blob: d9f42b9d8555938014b1b977ba309efe9e578ad5 [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"
Nico Weber432a3882018-04-30 14:59:11 +000044#include "llvm/Config/llvm-config.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000045#include "llvm/IR/BasicBlock.h"
46#include "llvm/IR/Constant.h"
47#include "llvm/IR/ConstantFolder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000049#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000050#include "llvm/IR/DataLayout.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000051#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000052#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000053#include "llvm/IR/Dominators.h"
54#include "llvm/IR/Function.h"
55#include "llvm/IR/GetElementPtrTypeIterator.h"
56#include "llvm/IR/GlobalAlias.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000057#include "llvm/IR/IRBuilder.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000058#include "llvm/IR/InstVisitor.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000059#include "llvm/IR/InstrTypes.h"
60#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000061#include "llvm/IR/Instructions.h"
62#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000063#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000064#include "llvm/IR/LLVMContext.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000065#include "llvm/IR/Metadata.h"
66#include "llvm/IR/Module.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000067#include "llvm/IR/Operator.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000068#include "llvm/IR/PassManager.h"
69#include "llvm/IR/Type.h"
70#include "llvm/IR/Use.h"
71#include "llvm/IR/User.h"
72#include "llvm/IR/Value.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080073#include "llvm/InitializePasses.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"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080083#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000084#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000085#include <algorithm>
86#include <cassert>
87#include <chrono>
88#include <cstddef>
89#include <cstdint>
90#include <cstring>
91#include <iterator>
92#include <string>
93#include <tuple>
94#include <utility>
95#include <vector>
Chandler Carruth83cee772014-02-25 03:59:29 +000096
Hal Finkel29f51312016-03-28 11:13:03 +000097#ifndef NDEBUG
98// We only use this for a debug check.
Chandler Carruth83cee772014-02-25 03:59:29 +000099#include <random>
100#endif
101
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000102using namespace llvm;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000103using namespace llvm::sroa;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000104
Chandler Carruth964daaa2014-04-22 02:55:47 +0000105#define DEBUG_TYPE "sroa"
106
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000107STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +0000108STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
Chandler Carruth6c321c12013-07-19 10:57:36 +0000109STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
110STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
111STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
Chandler Carruth5f5b6162013-03-20 06:30:46 +0000112STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
113STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000114STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +0000115STATISTIC(NumDeleted, "Number of instructions deleted");
116STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000117
Chandler Carruth83cee772014-02-25 03:59:29 +0000118/// Hidden option to enable randomly shuffling the slices to help uncover
119/// instability in their order.
120static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
121 cl::init(false), cl::Hidden);
122
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000123/// Hidden option to experiment with completely strict handling of inbounds
124/// GEPs.
Chandler Carruth113dc642014-12-20 02:39:18 +0000125static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
126 cl::Hidden);
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000127
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000128namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000129
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000130/// A custom IRBuilder inserter which prefixes all names, but only in
Mehdi Amini1e9c9252016-03-11 17:15:34 +0000131/// Assert builds.
Mehdi Aminiba9fba82016-03-13 21:05:13 +0000132class IRBuilderPrefixedInserter : public IRBuilderDefaultInserter {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000133 std::string Prefix;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000134
Zachary Turner41a9ee92017-10-11 23:54:34 +0000135 const Twine getNameWithPrefix(const Twine &Name) const {
136 return Name.isTriviallyEmpty() ? Name : Prefix + Name;
137 }
138
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000139public:
140 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
141
142protected:
143 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
144 BasicBlock::iterator InsertPt) const {
Zachary Turner41a9ee92017-10-11 23:54:34 +0000145 IRBuilderDefaultInserter::InsertHelper(I, getNameWithPrefix(Name), BB,
146 InsertPt);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000147 }
148};
149
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000150/// Provide a type for IRBuilder that drops names in release builds.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000151using IRBuilderTy = IRBuilder<ConstantFolder, IRBuilderPrefixedInserter>;
Chandler Carruthd177f862013-03-20 07:30:36 +0000152
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000153/// A used slice of an alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +0000154///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000155/// This structure represents a slice of an alloca used by some instruction. It
156/// stores both the begin and end offsets of this use, a pointer to the use
157/// itself, and a flag indicating whether we can classify the use as splittable
158/// or not when forming partitions of the alloca.
159class Slice {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000160 /// The beginning offset of the range.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000161 uint64_t BeginOffset = 0;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000162
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000163 /// The ending offset, not included in the range.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000164 uint64_t EndOffset = 0;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000165
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000166 /// Storage for both the use of this slice and whether it can be
Chandler Carruthf0546402013-07-18 07:15:00 +0000167 /// split.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000168 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
Chandler Carruthf0546402013-07-18 07:15:00 +0000169
170public:
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000171 Slice() = default;
172
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000173 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
Chandler Carruthf0546402013-07-18 07:15:00 +0000174 : BeginOffset(BeginOffset), EndOffset(EndOffset),
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000175 UseAndIsSplittable(U, IsSplittable) {}
Chandler Carruthf0546402013-07-18 07:15:00 +0000176
177 uint64_t beginOffset() const { return BeginOffset; }
178 uint64_t endOffset() const { return EndOffset; }
179
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000180 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
181 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000182
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000183 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000184
Craig Topperf40110f2014-04-25 05:29:35 +0000185 bool isDead() const { return getUse() == nullptr; }
186 void kill() { UseAndIsSplittable.setPointer(nullptr); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000187
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000188 /// Support for ordering ranges.
Chandler Carruthf74654d2013-03-18 08:36:46 +0000189 ///
190 /// This provides an ordering over ranges such that start offsets are
191 /// always increasing, and within equal start offsets, the end offsets are
192 /// decreasing. Thus the spanning range comes first in a cluster with the
193 /// same start position.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000194 bool operator<(const Slice &RHS) const {
Chandler Carruth113dc642014-12-20 02:39:18 +0000195 if (beginOffset() < RHS.beginOffset())
196 return true;
197 if (beginOffset() > RHS.beginOffset())
198 return false;
199 if (isSplittable() != RHS.isSplittable())
200 return !isSplittable();
201 if (endOffset() > RHS.endOffset())
202 return true;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000203 return false;
204 }
205
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000206 /// Support comparison with a single offset to allow binary searches.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000207 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
Chandler Carruthf0546402013-07-18 07:15:00 +0000208 uint64_t RHSOffset) {
209 return LHS.beginOffset() < RHSOffset;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000210 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000211 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000212 const Slice &RHS) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000213 return LHSOffset < RHS.beginOffset();
Chandler Carruthf74654d2013-03-18 08:36:46 +0000214 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000215
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000216 bool operator==(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000217 return isSplittable() == RHS.isSplittable() &&
218 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
Chandler Carruthe3899f22013-07-15 17:36:21 +0000219 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000220 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000221};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000222
Chandler Carruthf0546402013-07-18 07:15:00 +0000223} // end anonymous namespace
Chandler Carruthf74654d2013-03-18 08:36:46 +0000224
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000225/// Representation of the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000226///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000227/// This class represents the slices of an alloca which are formed by its
228/// various uses. If a pointer escapes, we can't fully build a representation
229/// for the slices used and we reflect that in this structure. The uses are
230/// stored, sorted by increasing beginning offset and with unsplittable slices
231/// starting at a particular offset before splittable slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000232class llvm::sroa::AllocaSlices {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000233public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000234 /// Construct the slices of a particular alloca.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000235 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000236
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000237 /// Test whether a pointer to the allocation escapes our analysis.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000238 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000239 /// If this is true, the slices are never fully built and should be
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000240 /// ignored.
241 bool isEscaped() const { return PointerEscapingInstr; }
242
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000243 /// Support for iterating over the slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000244 /// @{
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000245 using iterator = SmallVectorImpl<Slice>::iterator;
246 using range = iterator_range<iterator>;
247
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000248 iterator begin() { return Slices.begin(); }
249 iterator end() { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000250
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000251 using const_iterator = SmallVectorImpl<Slice>::const_iterator;
252 using const_range = iterator_range<const_iterator>;
253
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000254 const_iterator begin() const { return Slices.begin(); }
255 const_iterator end() const { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000256 /// @}
257
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000258 /// Erase a range of slices.
Chandler Carruth994cde82015-01-01 12:01:03 +0000259 void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
Chandler Carruth0715cba2015-01-01 11:54:38 +0000260
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000261 /// Insert new slices for this alloca.
Chandler Carruth0715cba2015-01-01 11:54:38 +0000262 ///
263 /// This moves the slices into the alloca's slices collection, and re-sorts
264 /// everything so that the usual ordering properties of the alloca's slices
265 /// hold.
266 void insert(ArrayRef<Slice> NewSlices) {
267 int OldSize = Slices.size();
Benjamin Kramer4f6ac162015-02-28 10:11:12 +0000268 Slices.append(NewSlices.begin(), NewSlices.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +0000269 auto SliceI = Slices.begin() + OldSize;
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +0000270 llvm::sort(SliceI, Slices.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +0000271 std::inplace_merge(Slices.begin(), SliceI, Slices.end());
272 }
273
Chandler Carruth29a18a42015-09-12 09:09:14 +0000274 // Forward declare the iterator and range accessor for walking the
275 // partitions.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000276 class partition_iterator;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000277 iterator_range<partition_iterator> partitions();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000278
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000279 /// Access the dead users for this alloca.
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000280 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000281
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000282 /// Access the dead operands referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000283 ///
284 /// These are operands which have cannot actually be used to refer to the
285 /// alloca as they are outside its range and the user doesn't correct for
286 /// that. These mostly consist of PHI node inputs and the like which we just
287 /// need to replace with undef.
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000288 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000289
Aaron Ballman615eb472017-10-15 14:32:27 +0000290#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000291 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000292 void printSlice(raw_ostream &OS, const_iterator I,
293 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000294 void printUse(raw_ostream &OS, const_iterator I,
295 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000296 void print(raw_ostream &OS) const;
Alp Tokerf929e092014-01-04 22:47:48 +0000297 void dump(const_iterator I) const;
298 void dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000299#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000300
301private:
302 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000303 class SliceBuilder;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000304
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000305 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000306
Aaron Ballman615eb472017-10-15 14:32:27 +0000307#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000308 /// Handle to alloca instruction to simplify method interfaces.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000309 AllocaInst &AI;
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000310#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000311
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000312 /// The instruction responsible for this alloca not having a known set
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000313 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000314 ///
315 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000316 /// store a pointer to that here and abort trying to form slices of the
317 /// alloca. This will be null if the alloca slices are analyzed successfully.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000318 Instruction *PointerEscapingInstr;
319
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000320 /// The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000321 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000322 /// We store a vector of the slices formed by uses of the alloca here. This
323 /// vector is sorted by increasing begin offset, and then the unsplittable
324 /// slices before the splittable ones. See the Slice inner class for more
325 /// details.
326 SmallVector<Slice, 8> Slices;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000327
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000328 /// Instructions which will become dead if we rewrite the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000329 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000330 /// Note that these are not separated by slice. This is because we expect an
331 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
332 /// all these instructions can simply be removed and replaced with undef as
333 /// they come from outside of the allocated space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000334 SmallVector<Instruction *, 8> DeadUsers;
335
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000336 /// Operands which will become dead if we rewrite the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000337 ///
338 /// These are operands that in their particular use can be replaced with
339 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
340 /// to PHI nodes and the like. They aren't entirely dead (there might be
341 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
342 /// want to swap this particular input for undef to simplify the use lists of
343 /// the alloca.
344 SmallVector<Use *, 8> DeadOperands;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000345};
Chandler Carruth29a18a42015-09-12 09:09:14 +0000346
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000347/// A partition of the slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000348///
349/// An ephemeral representation for a range of slices which can be viewed as
350/// a partition of the alloca. This range represents a span of the alloca's
351/// memory which cannot be split, and provides access to all of the slices
352/// overlapping some part of the partition.
353///
354/// Objects of this type are produced by traversing the alloca's slices, but
355/// are only ephemeral and not persistent.
356class llvm::sroa::Partition {
357private:
358 friend class AllocaSlices;
359 friend class AllocaSlices::partition_iterator;
360
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000361 using iterator = AllocaSlices::iterator;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000362
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000363 /// The beginning and ending offsets of the alloca for this
Chandler Carruth29a18a42015-09-12 09:09:14 +0000364 /// partition.
365 uint64_t BeginOffset, EndOffset;
366
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000367 /// The start and end iterators of this partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000368 iterator SI, SJ;
369
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000370 /// A collection of split slice tails overlapping the partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000371 SmallVector<Slice *, 4> SplitTails;
372
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000373 /// Raw constructor builds an empty partition starting and ending at
Chandler Carruth29a18a42015-09-12 09:09:14 +0000374 /// the given iterator.
375 Partition(iterator SI) : SI(SI), SJ(SI) {}
376
377public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000378 /// The start offset of this partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000379 ///
380 /// All of the contained slices start at or after this offset.
381 uint64_t beginOffset() const { return BeginOffset; }
382
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000383 /// The end offset of this partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000384 ///
385 /// All of the contained slices end at or before this offset.
386 uint64_t endOffset() const { return EndOffset; }
387
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000388 /// The size of the partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000389 ///
390 /// Note that this can never be zero.
391 uint64_t size() const {
392 assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
393 return EndOffset - BeginOffset;
394 }
395
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000396 /// Test whether this partition contains no slices, and merely spans
Chandler Carruth29a18a42015-09-12 09:09:14 +0000397 /// a region occupied by split slices.
398 bool empty() const { return SI == SJ; }
399
400 /// \name Iterate slices that start within the partition.
401 /// These may be splittable or unsplittable. They have a begin offset >= the
402 /// partition begin offset.
403 /// @{
404 // FIXME: We should probably define a "concat_iterator" helper and use that
405 // to stitch together pointee_iterators over the split tails and the
406 // contiguous iterators of the partition. That would give a much nicer
407 // interface here. We could then additionally expose filtered iterators for
408 // split, unsplit, and unsplittable splices based on the usage patterns.
409 iterator begin() const { return SI; }
410 iterator end() const { return SJ; }
411 /// @}
412
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000413 /// Get the sequence of split slice tails.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000414 ///
415 /// These tails are of slices which start before this partition but are
416 /// split and overlap into the partition. We accumulate these while forming
417 /// partitions.
418 ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
419};
420
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000421/// An iterator over partitions of the alloca's slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000422///
423/// This iterator implements the core algorithm for partitioning the alloca's
424/// slices. It is a forward iterator as we don't support backtracking for
425/// efficiency reasons, and re-use a single storage area to maintain the
426/// current set of split slices.
427///
428/// It is templated on the slice iterator type to use so that it can operate
429/// with either const or non-const slice iterators.
430class AllocaSlices::partition_iterator
431 : public iterator_facade_base<partition_iterator, std::forward_iterator_tag,
432 Partition> {
433 friend class AllocaSlices;
434
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000435 /// Most of the state for walking the partitions is held in a class
Chandler Carruth29a18a42015-09-12 09:09:14 +0000436 /// with a nice interface for examining them.
437 Partition P;
438
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000439 /// We need to keep the end of the slices to know when to stop.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000440 AllocaSlices::iterator SE;
441
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000442 /// We also need to keep track of the maximum split end offset seen.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000443 /// FIXME: Do we really?
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000444 uint64_t MaxSplitSliceEndOffset = 0;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000445
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000446 /// Sets the partition to be empty at given iterator, and sets the
Chandler Carruth29a18a42015-09-12 09:09:14 +0000447 /// end iterator.
448 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000449 : P(SI), SE(SE) {
Chandler Carruth29a18a42015-09-12 09:09:14 +0000450 // If not already at the end, advance our state to form the initial
451 // partition.
452 if (SI != SE)
453 advance();
454 }
455
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000456 /// Advance the iterator to the next partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000457 ///
458 /// Requires that the iterator not be at the end of the slices.
459 void advance() {
460 assert((P.SI != SE || !P.SplitTails.empty()) &&
461 "Cannot advance past the end of the slices!");
462
463 // Clear out any split uses which have ended.
464 if (!P.SplitTails.empty()) {
465 if (P.EndOffset >= MaxSplitSliceEndOffset) {
466 // If we've finished all splits, this is easy.
467 P.SplitTails.clear();
468 MaxSplitSliceEndOffset = 0;
469 } else {
470 // Remove the uses which have ended in the prior partition. This
471 // cannot change the max split slice end because we just checked that
472 // the prior partition ended prior to that max.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000473 P.SplitTails.erase(llvm::remove_if(P.SplitTails,
474 [&](Slice *S) {
475 return S->endOffset() <=
476 P.EndOffset;
477 }),
478 P.SplitTails.end());
479 assert(llvm::any_of(P.SplitTails,
480 [&](Slice *S) {
481 return S->endOffset() == MaxSplitSliceEndOffset;
482 }) &&
Chandler Carruth29a18a42015-09-12 09:09:14 +0000483 "Could not find the current max split slice offset!");
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000484 assert(llvm::all_of(P.SplitTails,
485 [&](Slice *S) {
486 return S->endOffset() <= MaxSplitSliceEndOffset;
487 }) &&
Chandler Carruth29a18a42015-09-12 09:09:14 +0000488 "Max split slice end offset is not actually the max!");
489 }
490 }
491
492 // If P.SI is already at the end, then we've cleared the split tail and
493 // now have an end iterator.
494 if (P.SI == SE) {
495 assert(P.SplitTails.empty() && "Failed to clear the split slices!");
496 return;
497 }
498
499 // If we had a non-empty partition previously, set up the state for
500 // subsequent partitions.
501 if (P.SI != P.SJ) {
502 // Accumulate all the splittable slices which started in the old
503 // partition into the split list.
504 for (Slice &S : P)
505 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
506 P.SplitTails.push_back(&S);
507 MaxSplitSliceEndOffset =
508 std::max(S.endOffset(), MaxSplitSliceEndOffset);
509 }
510
511 // Start from the end of the previous partition.
512 P.SI = P.SJ;
513
514 // If P.SI is now at the end, we at most have a tail of split slices.
515 if (P.SI == SE) {
516 P.BeginOffset = P.EndOffset;
517 P.EndOffset = MaxSplitSliceEndOffset;
518 return;
519 }
520
521 // If the we have split slices and the next slice is after a gap and is
522 // not splittable immediately form an empty partition for the split
523 // slices up until the next slice begins.
524 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
525 !P.SI->isSplittable()) {
526 P.BeginOffset = P.EndOffset;
527 P.EndOffset = P.SI->beginOffset();
528 return;
529 }
530 }
531
532 // OK, we need to consume new slices. Set the end offset based on the
533 // current slice, and step SJ past it. The beginning offset of the
534 // partition is the beginning offset of the next slice unless we have
535 // pre-existing split slices that are continuing, in which case we begin
536 // at the prior end offset.
537 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
538 P.EndOffset = P.SI->endOffset();
539 ++P.SJ;
540
541 // There are two strategies to form a partition based on whether the
542 // partition starts with an unsplittable slice or a splittable slice.
543 if (!P.SI->isSplittable()) {
544 // When we're forming an unsplittable region, it must always start at
545 // the first slice and will extend through its end.
546 assert(P.BeginOffset == P.SI->beginOffset());
547
548 // Form a partition including all of the overlapping slices with this
549 // unsplittable slice.
550 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
551 if (!P.SJ->isSplittable())
552 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
553 ++P.SJ;
554 }
555
556 // We have a partition across a set of overlapping unsplittable
557 // partitions.
558 return;
559 }
560
561 // If we're starting with a splittable slice, then we need to form
562 // a synthetic partition spanning it and any other overlapping splittable
563 // splices.
564 assert(P.SI->isSplittable() && "Forming a splittable partition!");
565
566 // Collect all of the overlapping splittable slices.
567 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
568 P.SJ->isSplittable()) {
569 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
570 ++P.SJ;
571 }
572
573 // Back upiP.EndOffset if we ended the span early when encountering an
574 // unsplittable slice. This synthesizes the early end offset of
575 // a partition spanning only splittable slices.
576 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
577 assert(!P.SJ->isSplittable());
578 P.EndOffset = P.SJ->beginOffset();
579 }
580 }
581
582public:
583 bool operator==(const partition_iterator &RHS) const {
584 assert(SE == RHS.SE &&
585 "End iterators don't match between compared partition iterators!");
586
587 // The observed positions of partitions is marked by the P.SI iterator and
588 // the emptiness of the split slices. The latter is only relevant when
589 // P.SI == SE, as the end iterator will additionally have an empty split
590 // slices list, but the prior may have the same P.SI and a tail of split
591 // slices.
592 if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
593 assert(P.SJ == RHS.P.SJ &&
594 "Same set of slices formed two different sized partitions!");
595 assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
596 "Same slice position with differently sized non-empty split "
597 "slice tails!");
598 return true;
599 }
600 return false;
601 }
602
603 partition_iterator &operator++() {
604 advance();
605 return *this;
606 }
607
608 Partition &operator*() { return P; }
609};
610
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000611/// A forward range over the partitions of the alloca's slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000612///
613/// This accesses an iterator range over the partitions of the alloca's
614/// slices. It computes these partitions on the fly based on the overlapping
615/// offsets of the slices and the ability to split them. It will visit "empty"
616/// partitions to cover regions of the alloca only accessed via split
617/// slices.
618iterator_range<AllocaSlices::partition_iterator> AllocaSlices::partitions() {
619 return make_range(partition_iterator(begin(), end()),
620 partition_iterator(end(), end()));
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000621}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000622
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000623static Value *foldSelectInst(SelectInst &SI) {
624 // If the condition being selected on is a constant or the same value is
625 // being selected between, fold the select. Yes this does (rarely) happen
626 // early on.
627 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
Chandler Carruth113dc642014-12-20 02:39:18 +0000628 return SI.getOperand(1 + CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000629 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000630 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000631
Craig Topperf40110f2014-04-25 05:29:35 +0000632 return nullptr;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000633}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000634
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000635/// A helper that folds a PHI node or a select.
Jingyue Wuec33fa92014-08-22 22:45:57 +0000636static Value *foldPHINodeOrSelectInst(Instruction &I) {
637 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
638 // If PN merges together the same value, return that value.
639 return PN->hasConstantValue();
640 }
641 return foldSelectInst(cast<SelectInst>(I));
642}
643
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000644/// Builder for the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000645///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000646/// This class builds a set of alloca slices by recursively visiting the uses
647/// of an alloca and making a slice for each load and store at each offset.
648class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
649 friend class PtrUseVisitor<SliceBuilder>;
650 friend class InstVisitor<SliceBuilder>;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000651
652 using Base = PtrUseVisitor<SliceBuilder>;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000653
654 const uint64_t AllocSize;
Chandler Carruth83934062014-10-16 21:11:55 +0000655 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000656
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000657 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
Chandler Carruthf0546402013-07-18 07:15:00 +0000658 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
659
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000660 /// Set to de-duplicate dead instructions found in the use walk.
Chandler Carruthf0546402013-07-18 07:15:00 +0000661 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000662
663public:
Chandler Carruth83934062014-10-16 21:11:55 +0000664 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000665 : PtrUseVisitor<SliceBuilder>(DL),
Chandler Carruth83934062014-10-16 21:11:55 +0000666 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000667
668private:
Chandler Carruthf0546402013-07-18 07:15:00 +0000669 void markAsDead(Instruction &I) {
David Blaikie70573dc2014-11-19 07:49:26 +0000670 if (VisitedDeadInsts.insert(&I).second)
Chandler Carruth83934062014-10-16 21:11:55 +0000671 AS.DeadUsers.push_back(&I);
Chandler Carruthf0546402013-07-18 07:15:00 +0000672 }
673
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000674 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000675 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000676 // Completely skip uses which have a zero size or start either before or
677 // past the end of the allocation.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000678 if (Size == 0 || Offset.uge(AllocSize)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000679 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @"
680 << Offset
681 << " which has zero size or starts outside of the "
682 << AllocSize << " byte alloca:\n"
683 << " alloca: " << AS.AI << "\n"
684 << " use: " << I << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000685 return markAsDead(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000686 }
687
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000688 uint64_t BeginOffset = Offset.getZExtValue();
689 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000690
691 // Clamp the end offset to the end of the allocation. Note that this is
692 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000693 // This may appear superficially to be something we could ignore entirely,
694 // but that is not so! There may be widened loads or PHI-node uses where
695 // some instructions are dead but not others. We can't completely ignore
696 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000697 assert(AllocSize >= BeginOffset); // Established above.
698 if (Size > AllocSize - BeginOffset) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000699 LLVM_DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @"
700 << Offset << " to remain within the " << AllocSize
701 << " byte alloca:\n"
702 << " alloca: " << AS.AI << "\n"
703 << " use: " << I << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000704 EndOffset = AllocSize;
705 }
706
Chandler Carruth83934062014-10-16 21:11:55 +0000707 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
Chandler Carruthf0546402013-07-18 07:15:00 +0000708 }
709
710 void visitBitCastInst(BitCastInst &BC) {
711 if (BC.use_empty())
712 return markAsDead(BC);
713
714 return Base::visitBitCastInst(BC);
715 }
716
Matt Arsenault282dac72019-06-14 21:38:31 +0000717 void visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
718 if (ASC.use_empty())
719 return markAsDead(ASC);
720
721 return Base::visitAddrSpaceCastInst(ASC);
722 }
723
Chandler Carruthf0546402013-07-18 07:15:00 +0000724 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
725 if (GEPI.use_empty())
726 return markAsDead(GEPI);
727
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000728 if (SROAStrictInbounds && GEPI.isInBounds()) {
729 // FIXME: This is a manually un-factored variant of the basic code inside
730 // of GEPs with checking of the inbounds invariant specified in the
731 // langref in a very strict sense. If we ever want to enable
732 // SROAStrictInbounds, this code should be factored cleanly into
733 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
Hal Finkel5c83a092016-03-28 11:23:21 +0000734 // by writing out the code here where we have the underlying allocation
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000735 // size readily available.
736 APInt GEPOffset = Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000737 const DataLayout &DL = GEPI.getModule()->getDataLayout();
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000738 for (gep_type_iterator GTI = gep_type_begin(GEPI),
739 GTE = gep_type_end(GEPI);
740 GTI != GTE; ++GTI) {
741 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
742 if (!OpC)
743 break;
744
745 // Handle a struct index, which adds its field offset to the pointer.
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000746 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000747 unsigned ElementIdx = OpC->getZExtValue();
748 const StructLayout *SL = DL.getStructLayout(STy);
749 GEPOffset +=
750 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
751 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +0000752 // For array or vector indices, scale the index by the size of the
753 // type.
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000754 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
755 GEPOffset += Index * APInt(Offset.getBitWidth(),
756 DL.getTypeAllocSize(GTI.getIndexedType()));
757 }
758
759 // If this index has computed an intermediate pointer which is not
760 // inbounds, then the result of the GEP is a poison value and we can
761 // delete it and all uses.
762 if (GEPOffset.ugt(AllocSize))
763 return markAsDead(GEPI);
764 }
765 }
766
Chandler Carruthf0546402013-07-18 07:15:00 +0000767 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000768 }
769
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000770 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000771 uint64_t Size, bool IsVolatile) {
Chandler Carruth24ac8302015-01-02 03:55:54 +0000772 // We allow splitting of non-volatile loads and stores where the type is an
773 // integer type. These may be used to implement 'memcpy' or other "transfer
774 // of bits" patterns.
775 bool IsSplittable = Ty->isIntegerTy() && !IsVolatile;
Chandler Carruth58d05562012-10-25 04:37:07 +0000776
777 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000778 }
779
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000780 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000781 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
782 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000783
784 if (!IsOffsetKnown)
785 return PI.setAborted(&LI);
786
Matt Arsenault282dac72019-06-14 21:38:31 +0000787 if (LI.isVolatile() &&
788 LI.getPointerAddressSpace() != DL.getAllocaAddrSpace())
789 return PI.setAborted(&LI);
790
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000791 uint64_t Size = DL.getTypeStoreSize(LI.getType());
792 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000793 }
794
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000795 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000796 Value *ValOp = SI.getValueOperand();
797 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000798 return PI.setEscapedAndAborted(&SI);
799 if (!IsOffsetKnown)
800 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000801
Matt Arsenault282dac72019-06-14 21:38:31 +0000802 if (SI.isVolatile() &&
803 SI.getPointerAddressSpace() != DL.getAllocaAddrSpace())
804 return PI.setAborted(&SI);
805
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000806 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
807
808 // If this memory access can be shown to *statically* extend outside the
Hiroshi Inoue0909ca12018-01-26 08:15:29 +0000809 // bounds of the allocation, it's behavior is undefined, so simply
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000810 // ignore it. Note that this is more strict than the generic clamping
811 // behavior of insertUse. We also try to handle cases which might run the
812 // risk of overflow.
813 // FIXME: We should instead consider the pointer to have escaped if this
814 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000815 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000816 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @"
817 << Offset << " which extends past the end of the "
818 << AllocSize << " byte alloca:\n"
819 << " alloca: " << AS.AI << "\n"
820 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000821 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000822 }
823
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000824 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
825 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000826 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000827 }
828
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000829 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000830 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000831 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000832 if ((Length && Length->getValue() == 0) ||
Chandler Carruth6aedc102014-02-26 03:14:14 +0000833 (IsOffsetKnown && Offset.uge(AllocSize)))
Chandler Carruthe41e7b72012-12-10 08:28:39 +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
837 if (!IsOffsetKnown)
838 return PI.setAborted(&II);
839
Matt Arsenault282dac72019-06-14 21:38:31 +0000840 // Don't replace this with a store with a different address space. TODO:
841 // Use a store with the casted new alloca?
842 if (II.isVolatile() && II.getDestAddressSpace() != DL.getAllocaAddrSpace())
843 return PI.setAborted(&II);
844
Chandler Carruth113dc642014-12-20 02:39:18 +0000845 insertUse(II, Offset, Length ? Length->getLimitedValue()
846 : AllocSize - Offset.getLimitedValue(),
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000847 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000848 }
849
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000850 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000851 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000852 if (Length && Length->getValue() == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000853 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000854 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000855
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000856 // Because we can visit these intrinsics twice, also check to see if the
857 // first time marked this instruction as dead. If so, skip it.
858 if (VisitedDeadInsts.count(&II))
859 return;
860
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000861 if (!IsOffsetKnown)
862 return PI.setAborted(&II);
863
Matt Arsenault282dac72019-06-14 21:38:31 +0000864 // Don't replace this with a load/store with a different address space.
865 // TODO: Use a store with the casted new alloca?
866 if (II.isVolatile() &&
867 (II.getDestAddressSpace() != DL.getAllocaAddrSpace() ||
868 II.getSourceAddressSpace() != DL.getAllocaAddrSpace()))
869 return PI.setAborted(&II);
870
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000871 // This side of the transfer is completely out-of-bounds, and so we can
872 // nuke the entire transfer. However, we also need to nuke the other side
873 // if already added to our partitions.
874 // FIXME: Yet another place we really should bypass this when
875 // instrumenting for ASan.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000876 if (Offset.uge(AllocSize)) {
Chandler Carruth113dc642014-12-20 02:39:18 +0000877 SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
878 MemTransferSliceMap.find(&II);
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000879 if (MTPI != MemTransferSliceMap.end())
Chandler Carruth83934062014-10-16 21:11:55 +0000880 AS.Slices[MTPI->second].kill();
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000881 return markAsDead(II);
882 }
883
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000884 uint64_t RawOffset = Offset.getLimitedValue();
Chandler Carruth113dc642014-12-20 02:39:18 +0000885 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000886
Chandler Carruthf0546402013-07-18 07:15:00 +0000887 // Check for the special case where the same exact value is used for both
888 // source and dest.
889 if (*U == II.getRawDest() && *U == II.getRawSource()) {
890 // For non-volatile transfers this is a no-op.
891 if (!II.isVolatile())
892 return markAsDead(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000893
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000894 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000895 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000896
Chandler Carruthf0546402013-07-18 07:15:00 +0000897 // If we have seen both source and destination for a mem transfer, then
898 // they both point to the same alloca.
899 bool Inserted;
900 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000901 std::tie(MTPI, Inserted) =
Chandler Carruth83934062014-10-16 21:11:55 +0000902 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000903 unsigned PrevIdx = MTPI->second;
904 if (!Inserted) {
Chandler Carruth83934062014-10-16 21:11:55 +0000905 Slice &PrevP = AS.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000906
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000907 // Check if the begin offsets match and this is a non-volatile transfer.
908 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000909 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
910 PrevP.kill();
911 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000912 }
913
914 // Otherwise we have an offset transfer within the same alloca. We can't
915 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000916 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000917 }
918
Chandler Carruthe3899f22013-07-15 17:36:21 +0000919 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000920 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000921
Chandler Carruthf0546402013-07-18 07:15:00 +0000922 // Check that we ended up with a valid index in the map.
Chandler Carruth83934062014-10-16 21:11:55 +0000923 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000924 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000925 }
926
927 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000928 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000929 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000930 void visitIntrinsicInst(IntrinsicInst &II) {
931 if (!IsOffsetKnown)
932 return PI.setAborted(&II);
933
Vedant Kumarb264d692018-12-21 21:49:40 +0000934 if (II.isLifetimeStartOrEnd()) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000935 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000936 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
937 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000938 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000939 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000940 }
941
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000942 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000943 }
944
945 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
946 // We consider any PHI or select that results in a direct load or store of
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000947 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000948 // are considered unsplittable and the size is the maximum loaded or stored
949 // size.
950 SmallPtrSet<Instruction *, 4> Visited;
951 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
952 Visited.insert(Root);
953 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000954 const DataLayout &DL = Root->getModule()->getDataLayout();
Chandler Carruth8b907e82012-09-25 10:03:40 +0000955 // If there are no loads or stores, the access is dead. We mark that as
956 // a size zero access.
957 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000958 do {
959 Instruction *I, *UsedI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000960 std::tie(UsedI, I) = Uses.pop_back_val();
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000961
962 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Graham Hunterb3025612019-10-08 12:53:54 +0000963 Size = std::max(Size,
964 DL.getTypeStoreSize(LI->getType()).getFixedSize());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000965 continue;
966 }
967 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
968 Value *Op = SI->getOperand(0);
969 if (Op == UsedI)
970 return SI;
Graham Hunterb3025612019-10-08 12:53:54 +0000971 Size = std::max(Size,
972 DL.getTypeStoreSize(Op->getType()).getFixedSize());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000973 continue;
974 }
975
976 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
977 if (!GEP->hasAllZeroIndices())
978 return GEP;
979 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
Matt Arsenault282dac72019-06-14 21:38:31 +0000980 !isa<SelectInst>(I) && !isa<AddrSpaceCastInst>(I)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000981 return I;
982 }
983
Chandler Carruthcdf47882014-03-09 03:16:01 +0000984 for (User *U : I->users())
David Blaikie70573dc2014-11-19 07:49:26 +0000985 if (Visited.insert(cast<Instruction>(U)).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000986 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000987 } while (!Uses.empty());
988
Craig Topperf40110f2014-04-25 05:29:35 +0000989 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000990 }
991
Jingyue Wuec33fa92014-08-22 22:45:57 +0000992 void visitPHINodeOrSelectInst(Instruction &I) {
993 assert(isa<PHINode>(I) || isa<SelectInst>(I));
994 if (I.use_empty())
995 return markAsDead(I);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000996
Jingyue Wuec33fa92014-08-22 22:45:57 +0000997 // TODO: We could use SimplifyInstruction here to fold PHINodes and
998 // SelectInsts. However, doing so requires to change the current
999 // dead-operand-tracking mechanism. For instance, suppose neither loading
1000 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
1001 // trap either. However, if we simply replace %U with undef using the
1002 // current dead-operand-tracking mechanism, "load (select undef, undef,
1003 // %other)" may trap because the select may return the first operand
1004 // "undef".
1005 if (Value *Result = foldPHINodeOrSelectInst(I)) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001006 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001007 // If the result of the constant fold will be the pointer, recurse
Jingyue Wuec33fa92014-08-22 22:45:57 +00001008 // through the PHI/select as if we had RAUW'ed it.
1009 enqueueUsers(I);
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001010 else
Jingyue Wuec33fa92014-08-22 22:45:57 +00001011 // Otherwise the operand to the PHI/select is dead, and we can replace
1012 // it with undef.
Chandler Carruth83934062014-10-16 21:11:55 +00001013 AS.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001014
1015 return;
1016 }
Jingyue Wuec33fa92014-08-22 22:45:57 +00001017
Chandler Carruthf0546402013-07-18 07:15:00 +00001018 if (!IsOffsetKnown)
Jingyue Wuec33fa92014-08-22 22:45:57 +00001019 return PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001020
Chandler Carruthf0546402013-07-18 07:15:00 +00001021 // See if we already have computed info on this node.
Jingyue Wuec33fa92014-08-22 22:45:57 +00001022 uint64_t &Size = PHIOrSelectSizes[&I];
1023 if (!Size) {
1024 // This is a new PHI/Select, check for an unsafe use of it.
1025 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
Chandler Carruthf0546402013-07-18 07:15:00 +00001026 return PI.setAborted(UnsafeI);
1027 }
1028
1029 // For PHI and select operands outside the alloca, we can't nuke the entire
1030 // phi or select -- the other side might still be relevant, so we special
1031 // case them here and use a separate structure to track the operands
1032 // themselves which should be replaced with undef.
1033 // FIXME: This should instead be escaped in the event we're instrumenting
1034 // for address sanitization.
Chandler Carruth6aedc102014-02-26 03:14:14 +00001035 if (Offset.uge(AllocSize)) {
Chandler Carruth83934062014-10-16 21:11:55 +00001036 AS.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +00001037 return;
1038 }
1039
Jingyue Wuec33fa92014-08-22 22:45:57 +00001040 insertUse(I, Offset, Size);
1041 }
1042
Chandler Carruth113dc642014-12-20 02:39:18 +00001043 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
Jingyue Wuec33fa92014-08-22 22:45:57 +00001044
Chandler Carruth113dc642014-12-20 02:39:18 +00001045 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001046
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001047 /// Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth113dc642014-12-20 02:39:18 +00001048 void visitInstruction(Instruction &I) { PI.setAborted(&I); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001049};
1050
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001051AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001052 :
Aaron Ballman615eb472017-10-15 14:32:27 +00001053#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001054 AI(AI),
1055#endif
Craig Topperf40110f2014-04-25 05:29:35 +00001056 PointerEscapingInstr(nullptr) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001057 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001058 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001059 if (PtrI.isEscaped() || PtrI.isAborted()) {
1060 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001061 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001062 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1063 : PtrI.getAbortingInst();
1064 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001065 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001066 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001067
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001068 Slices.erase(
1069 llvm::remove_if(Slices, [](const Slice &S) { return S.isDead(); }),
1070 Slices.end());
Benjamin Kramer08e50702013-07-20 08:38:34 +00001071
Hal Finkel29f51312016-03-28 11:13:03 +00001072#ifndef NDEBUG
Chandler Carruth83cee772014-02-25 03:59:29 +00001073 if (SROARandomShuffleSlices) {
Pavel Labathc207bec2016-11-09 12:07:12 +00001074 std::mt19937 MT(static_cast<unsigned>(
1075 std::chrono::system_clock::now().time_since_epoch().count()));
Chandler Carruth83cee772014-02-25 03:59:29 +00001076 std::shuffle(Slices.begin(), Slices.end(), MT);
1077 }
1078#endif
1079
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001080 // Sort the uses. This arranges for the offsets to be in ascending order,
1081 // and the sizes to be in descending order.
Fangrui Song0cac7262018-09-27 02:13:45 +00001082 llvm::sort(Slices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001083}
1084
Aaron Ballman615eb472017-10-15 14:32:27 +00001085#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001086
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001087void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1088 StringRef Indent) const {
1089 printSlice(OS, I, Indent);
Chandler Carruth0715cba2015-01-01 11:54:38 +00001090 OS << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001091 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001092}
1093
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001094void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1095 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001096 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001097 << " slice #" << (I - begin())
Chandler Carruth0715cba2015-01-01 11:54:38 +00001098 << (I->isSplittable() ? " (splittable)" : "");
Chandler Carruthf0546402013-07-18 07:15:00 +00001099}
1100
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001101void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1102 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001103 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001104}
1105
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001106void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001107 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001108 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001109 << " A pointer to this alloca escaped by:\n"
1110 << " " << *PointerEscapingInstr << "\n";
1111 return;
1112 }
1113
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001114 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001115 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001116 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001117}
1118
Alp Tokerf929e092014-01-04 22:47:48 +00001119LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1120 print(dbgs(), I);
1121}
1122LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001123
Aaron Ballman615eb472017-10-15 14:32:27 +00001124#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001125
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001126/// Walk the range of a partitioning looking for a common type to cover this
1127/// sequence of slices.
1128static Type *findCommonType(AllocaSlices::const_iterator B,
1129 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +00001130 uint64_t EndOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +00001131 Type *Ty = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001132 bool TyIsCommon = true;
Craig Topperf40110f2014-04-25 05:29:35 +00001133 IntegerType *ITy = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001134
1135 // Note that we need to look at *every* alloca slice's Use to ensure we
1136 // always get consistent results regardless of the order of slices.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001137 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001138 Use *U = I->getUse();
1139 if (isa<IntrinsicInst>(*U->getUser()))
1140 continue;
1141 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1142 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001143
Craig Topperf40110f2014-04-25 05:29:35 +00001144 Type *UserTy = nullptr;
Chandler Carrutha1262002013-11-19 09:03:18 +00001145 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001146 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001147 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001148 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001149 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001150
Chandler Carruth4de31542014-01-21 23:16:05 +00001151 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001152 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001153 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +00001154 // entity causing the split. Also skip if the type is not a byte width
1155 // multiple.
Chandler Carruth4de31542014-01-21 23:16:05 +00001156 if (UserITy->getBitWidth() % 8 != 0 ||
1157 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001158 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001159
Chandler Carruth4de31542014-01-21 23:16:05 +00001160 // Track the largest bitwidth integer type used in this way in case there
1161 // is no common type.
1162 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1163 ITy = UserITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001164 }
Duncan P. N. Exon Smith73686d32014-06-17 00:19:35 +00001165
1166 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1167 // depend on types skipped above.
1168 if (!UserTy || (Ty && Ty != UserTy))
1169 TyIsCommon = false; // Give up on anything but an iN type.
1170 else
1171 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001172 }
Chandler Carruth4de31542014-01-21 23:16:05 +00001173
1174 return TyIsCommon ? Ty : ITy;
Chandler Carruthf0546402013-07-18 07:15:00 +00001175}
Chandler Carruthe3899f22013-07-15 17:36:21 +00001176
Chandler Carruthf0546402013-07-18 07:15:00 +00001177/// PHI instructions that use an alloca and are subsequently loaded can be
1178/// rewritten to load both input pointers in the pred blocks and then PHI the
1179/// results, allowing the load of the alloca to be promoted.
1180/// From this:
1181/// %P2 = phi [i32* %Alloca, i32* %Other]
1182/// %V = load i32* %P2
1183/// to:
1184/// %V1 = load i32* %Alloca -> will be mem2reg'd
1185/// ...
1186/// %V2 = load i32* %Other
1187/// ...
1188/// %V = phi [i32 %V1, i32 %V2]
1189///
1190/// We can do this to a select if its only uses are loads and if the operands
1191/// to the select can be loaded unconditionally.
1192///
1193/// FIXME: This should be hoisted into a generic utility, likely in
1194/// Transforms/Util/Local.h
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001195static bool isSafePHIToSpeculate(PHINode &PN) {
Tim Northover60afa492019-07-09 11:35:35 +00001196 const DataLayout &DL = PN.getModule()->getDataLayout();
1197
Chandler Carruthf0546402013-07-18 07:15:00 +00001198 // For now, we can only do this promotion if the load is in the same block
1199 // as the PHI, and if there are no stores between the phi and load.
1200 // TODO: Allow recursive phi users.
1201 // TODO: Allow stores.
1202 BasicBlock *BB = PN.getParent();
Guillaume Chatelet301b4122019-10-21 15:10:26 +00001203 MaybeAlign MaxAlign;
Tim Northover60afa492019-07-09 11:35:35 +00001204 uint64_t APWidth = DL.getIndexTypeSizeInBits(PN.getType());
1205 APInt MaxSize(APWidth, 0);
Chandler Carruthf0546402013-07-18 07:15:00 +00001206 bool HaveLoad = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001207 for (User *U : PN.users()) {
1208 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001209 if (!LI || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001210 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001211
Chandler Carruthf0546402013-07-18 07:15:00 +00001212 // For now we only allow loads in the same block as the PHI. This is
1213 // a common case that happens when instcombine merges two loads through
1214 // a PHI.
1215 if (LI->getParent() != BB)
1216 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001217
Chandler Carruthf0546402013-07-18 07:15:00 +00001218 // Ensure that there are no instructions between the PHI and the load that
1219 // could store.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001220 for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
Chandler Carruthf0546402013-07-18 07:15:00 +00001221 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001222 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001223
Philip Reames26945222019-08-27 19:34:43 +00001224 uint64_t Size = DL.getTypeStoreSize(LI->getType());
Guillaume Chatelet301b4122019-10-21 15:10:26 +00001225 MaxAlign = std::max(MaxAlign, MaybeAlign(LI->getAlignment()));
Tim Northover60afa492019-07-09 11:35:35 +00001226 MaxSize = MaxSize.ult(Size) ? APInt(APWidth, Size) : MaxSize;
Chandler Carruthf0546402013-07-18 07:15:00 +00001227 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001228 }
1229
Chandler Carruthf0546402013-07-18 07:15:00 +00001230 if (!HaveLoad)
1231 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001232
Chandler Carruthf0546402013-07-18 07:15:00 +00001233 // We can only transform this if it is safe to push the loads into the
1234 // predecessor blocks. The only thing to watch out for is that we can't put
1235 // a possibly trapping load in the predecessor if it is a critical edge.
1236 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001237 Instruction *TI = PN.getIncomingBlock(Idx)->getTerminator();
Chandler Carruthf0546402013-07-18 07:15:00 +00001238 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001239
Chandler Carruthf0546402013-07-18 07:15:00 +00001240 // If the value is produced by the terminator of the predecessor (an
1241 // invoke) or it has side-effects, there is no valid place to put a load
1242 // in the predecessor.
1243 if (TI == InVal || TI->mayHaveSideEffects())
1244 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001245
Chandler Carruthf0546402013-07-18 07:15:00 +00001246 // If the predecessor has a single successor, then the edge isn't
1247 // critical.
1248 if (TI->getNumSuccessors() == 1)
1249 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001250
Chandler Carruthf0546402013-07-18 07:15:00 +00001251 // If this pointer is always safe to load, or if we can prove that there
1252 // is already a load in the block, then we can move the load to the pred
1253 // block.
Tim Northover60afa492019-07-09 11:35:35 +00001254 if (isSafeToLoadUnconditionally(InVal, MaxAlign, MaxSize, DL, TI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001255 continue;
1256
1257 return false;
1258 }
1259
1260 return true;
1261}
1262
1263static void speculatePHINodeLoads(PHINode &PN) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001264 LLVM_DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001265
James Y Knight14359ef2019-02-01 20:44:24 +00001266 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
1267 Type *LoadTy = SomeLoad->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00001268 IRBuilderTy PHIBuilder(&PN);
1269 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1270 PN.getName() + ".sroa.speculated");
1271
Suyog Sardac62136e2019-09-21 18:03:30 +00001272 // Get the AA tags and alignment to use from one of the loads. It does not
Chandler Carruthf0546402013-07-18 07:15:00 +00001273 // matter which one we get and if any differ.
Hal Finkelcc39b672014-07-24 12:16:19 +00001274 AAMDNodes AATags;
1275 SomeLoad->getAAMetadata(AATags);
Guillaume Chatelet17380222019-09-30 09:37:05 +00001276 const MaybeAlign Align = MaybeAlign(SomeLoad->getAlignment());
Chandler Carruthf0546402013-07-18 07:15:00 +00001277
1278 // Rewrite all loads of the PN to use the new PHI.
1279 while (!PN.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001280 LoadInst *LI = cast<LoadInst>(PN.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001281 LI->replaceAllUsesWith(NewPN);
1282 LI->eraseFromParent();
1283 }
1284
1285 // Inject loads into all of the pred blocks.
Bjorn Pettersson81a76a32018-05-17 07:21:41 +00001286 DenseMap<BasicBlock*, Value*> InjectedLoads;
Chandler Carruthf0546402013-07-18 07:15:00 +00001287 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1288 BasicBlock *Pred = PN.getIncomingBlock(Idx);
Chandler Carruthf0546402013-07-18 07:15:00 +00001289 Value *InVal = PN.getIncomingValue(Idx);
Bjorn Pettersson81a76a32018-05-17 07:21:41 +00001290
1291 // A PHI node is allowed to have multiple (duplicated) entries for the same
1292 // basic block, as long as the value is the same. So if we already injected
1293 // a load in the predecessor, then we should reuse the same load for all
1294 // duplicated entries.
1295 if (Value* V = InjectedLoads.lookup(Pred)) {
1296 NewPN->addIncoming(V, Pred);
1297 continue;
1298 }
1299
Chandler Carruthedb12a82018-10-15 10:04:59 +00001300 Instruction *TI = Pred->getTerminator();
Chandler Carruthf0546402013-07-18 07:15:00 +00001301 IRBuilderTy PredBuilder(TI);
1302
1303 LoadInst *Load = PredBuilder.CreateLoad(
James Y Knight14359ef2019-02-01 20:44:24 +00001304 LoadTy, InVal,
1305 (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
Chandler Carruthf0546402013-07-18 07:15:00 +00001306 ++NumLoadsSpeculated;
1307 Load->setAlignment(Align);
Hal Finkelcc39b672014-07-24 12:16:19 +00001308 if (AATags)
1309 Load->setAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001310 NewPN->addIncoming(Load, Pred);
Bjorn Pettersson81a76a32018-05-17 07:21:41 +00001311 InjectedLoads[Pred] = Load;
Chandler Carruthf0546402013-07-18 07:15:00 +00001312 }
1313
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001314 LLVM_DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001315 PN.eraseFromParent();
1316}
1317
1318/// Select instructions that use an alloca and are subsequently loaded can be
1319/// rewritten to load both input pointers and then select between the result,
1320/// allowing the load of the alloca to be promoted.
1321/// From this:
1322/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1323/// %V = load i32* %P2
1324/// to:
1325/// %V1 = load i32* %Alloca -> will be mem2reg'd
1326/// %V2 = load i32* %Other
1327/// %V = select i1 %cond, i32 %V1, i32 %V2
1328///
1329/// We can do this to a select if its only uses are loads and if the operand
1330/// to the select can be loaded unconditionally.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001331static bool isSafeSelectToSpeculate(SelectInst &SI) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001332 Value *TValue = SI.getTrueValue();
1333 Value *FValue = SI.getFalseValue();
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001334 const DataLayout &DL = SI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00001335
Chandler Carruthcdf47882014-03-09 03:16:01 +00001336 for (User *U : SI.users()) {
1337 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001338 if (!LI || !LI->isSimple())
Chandler Carruthf0546402013-07-18 07:15:00 +00001339 return false;
1340
Hiroshi Inoueb3008242017-06-24 15:43:33 +00001341 // Both operands to the select need to be dereferenceable, either
Chandler Carruthf0546402013-07-18 07:15:00 +00001342 // absolutely (e.g. allocas) or at this point because we can see other
1343 // accesses to it.
Guillaume Chatelet301b4122019-10-21 15:10:26 +00001344 if (!isSafeToLoadUnconditionally(TValue, LI->getType(),
1345 MaybeAlign(LI->getAlignment()), DL, LI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001346 return false;
Guillaume Chatelet301b4122019-10-21 15:10:26 +00001347 if (!isSafeToLoadUnconditionally(FValue, LI->getType(),
1348 MaybeAlign(LI->getAlignment()), DL, LI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001349 return false;
1350 }
1351
1352 return true;
1353}
1354
1355static void speculateSelectInstLoads(SelectInst &SI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001356 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001357
1358 IRBuilderTy IRB(&SI);
1359 Value *TV = SI.getTrueValue();
1360 Value *FV = SI.getFalseValue();
1361 // Replace the loads of the select with a select of two loads.
1362 while (!SI.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001363 LoadInst *LI = cast<LoadInst>(SI.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001364 assert(LI->isSimple() && "We only speculate simple loads");
1365
1366 IRB.SetInsertPoint(LI);
James Y Knight14359ef2019-02-01 20:44:24 +00001367 LoadInst *TL = IRB.CreateLoad(LI->getType(), TV,
1368 LI->getName() + ".sroa.speculate.load.true");
1369 LoadInst *FL = IRB.CreateLoad(LI->getType(), FV,
1370 LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001371 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001372
Hal Finkelcc39b672014-07-24 12:16:19 +00001373 // Transfer alignment and AA info if present.
Guillaume Chatelet17380222019-09-30 09:37:05 +00001374 TL->setAlignment(MaybeAlign(LI->getAlignment()));
1375 FL->setAlignment(MaybeAlign(LI->getAlignment()));
Hal Finkelcc39b672014-07-24 12:16:19 +00001376
1377 AAMDNodes Tags;
1378 LI->getAAMetadata(Tags);
1379 if (Tags) {
1380 TL->setAAMetadata(Tags);
1381 FL->setAAMetadata(Tags);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001382 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001383
1384 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1385 LI->getName() + ".sroa.speculated");
1386
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001387 LLVM_DEBUG(dbgs() << " speculated to: " << *V << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001388 LI->replaceAllUsesWith(V);
1389 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001390 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001391 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001392}
1393
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001394/// Build a GEP out of a base pointer and indices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001395///
1396/// This will return the BasePtr if that is valid, or build a new GEP
1397/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001398static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001399 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001400 if (Indices.empty())
1401 return BasePtr;
1402
1403 // A single zero index is a no-op, so check for this and avoid building a GEP
1404 // in that case.
1405 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1406 return BasePtr;
1407
James Y Knight77160752019-02-01 20:44:47 +00001408 return IRB.CreateInBoundsGEP(BasePtr->getType()->getPointerElementType(),
1409 BasePtr, Indices, NamePrefix + "sroa_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001410}
1411
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001412/// Get a natural GEP off of the BasePtr walking through Ty toward
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001413/// TargetTy without changing the offset of the pointer.
1414///
1415/// This routine assumes we've already established a properly offset GEP with
1416/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1417/// zero-indices down through type layers until we find one the same as
1418/// TargetTy. If we can't find one with the same type, we at least try to use
1419/// one with the same size. If none of that works, we just produce the GEP as
1420/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001421static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001422 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001423 SmallVectorImpl<Value *> &Indices,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001424 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001425 if (Ty == TargetTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001426 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001427
Nicola Zaghenf96383c2018-10-30 11:15:04 +00001428 // Offset size to use for the indices.
1429 unsigned OffsetSize = DL.getIndexTypeSizeInBits(BasePtr->getType());
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001430
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001431 // See if we can descend into a struct and locate a field with the correct
1432 // type.
1433 unsigned NumLayers = 0;
1434 Type *ElementTy = Ty;
1435 do {
1436 if (ElementTy->isPointerTy())
1437 break;
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001438
1439 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1440 ElementTy = ArrayTy->getElementType();
Nicola Zaghenf96383c2018-10-30 11:15:04 +00001441 Indices.push_back(IRB.getIntN(OffsetSize, 0));
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001442 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1443 ElementTy = VectorTy->getElementType();
1444 Indices.push_back(IRB.getInt32(0));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001445 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001446 if (STy->element_begin() == STy->element_end())
1447 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001448 ElementTy = *STy->element_begin();
1449 Indices.push_back(IRB.getInt32(0));
1450 } else {
1451 break;
1452 }
1453 ++NumLayers;
1454 } while (ElementTy != TargetTy);
1455 if (ElementTy != TargetTy)
1456 Indices.erase(Indices.end() - NumLayers, Indices.end());
1457
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001458 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001459}
1460
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001461/// Recursively compute indices for a natural GEP.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001462///
1463/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1464/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001465static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001466 Value *Ptr, Type *Ty, APInt &Offset,
1467 Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001468 SmallVectorImpl<Value *> &Indices,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001469 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001470 if (Offset == 0)
Chandler Carruth113dc642014-12-20 02:39:18 +00001471 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1472 NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001473
1474 // We can't recurse through pointer types.
1475 if (Ty->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001476 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001477
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001478 // We try to analyze GEPs over vectors here, but note that these GEPs are
1479 // extremely poorly defined currently. The long-term goal is to remove GEPing
1480 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001481 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001482 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Craig Topperf40110f2014-04-25 05:29:35 +00001483 if (ElementSizeInBits % 8 != 0) {
1484 // GEPs over non-multiple of 8 size vector elements are invalid.
1485 return nullptr;
1486 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001487 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001488 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001489 if (NumSkippedElements.ugt(VecTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001490 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001491 Offset -= NumSkippedElements * ElementSize;
1492 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001493 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001494 Offset, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001495 }
1496
1497 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1498 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001499 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001500 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001501 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001502 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001503
1504 Offset -= NumSkippedElements * ElementSize;
1505 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001506 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001507 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001508 }
1509
1510 StructType *STy = dyn_cast<StructType>(Ty);
1511 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00001512 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001513
Chandler Carruth90a735d2013-07-19 07:21:28 +00001514 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001515 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001516 if (StructOffset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00001517 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001518 unsigned Index = SL->getElementContainingOffset(StructOffset);
1519 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1520 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001521 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Craig Topperf40110f2014-04-25 05:29:35 +00001522 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001523
1524 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001525 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001526 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001527}
1528
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001529/// Get a natural GEP from a base pointer to a particular offset and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001530/// resulting in a particular type.
1531///
1532/// The goal is to produce a "natural" looking GEP that works with the existing
1533/// composite types to arrive at the appropriate offset and element type for
1534/// a pointer. TargetTy is the element type the returned GEP should point-to if
1535/// possible. We recurse by decreasing Offset, adding the appropriate index to
1536/// Indices, and setting Ty to the result subtype.
1537///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001538/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001539static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001540 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001541 SmallVectorImpl<Value *> &Indices,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001542 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001543 PointerType *Ty = cast<PointerType>(Ptr->getType());
1544
1545 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1546 // an i8.
Chandler Carruth286d87e2014-02-26 08:25:02 +00001547 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +00001548 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001549
1550 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001551 if (!ElementTy->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +00001552 return nullptr; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001553 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001554 if (ElementSize == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001555 return nullptr; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001556 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001557
1558 Offset -= NumSkippedElements * ElementSize;
1559 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001560 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001561 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001562}
1563
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001564/// Compute an adjusted pointer from Ptr by Offset bytes where the
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001565/// resulting pointer has PointerTy.
1566///
1567/// This tries very hard to compute a "natural" GEP which arrives at the offset
1568/// and produces the pointer type desired. Where it cannot, it will try to use
1569/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1570/// fails, it will try to use an existing i8* and GEP to the byte offset and
1571/// bitcast to the type.
1572///
1573/// The strategy for finding the more natural GEPs is to peel off layers of the
1574/// pointer, walking back through bit casts and GEPs, searching for a base
1575/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001576/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001577/// a single GEP as possible, thus making each GEP more independent of the
1578/// surrounding code.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001579static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001580 APInt Offset, Type *PointerTy, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001581 // Even though we don't look through PHI nodes, we could be called on an
1582 // instruction in an unreachable block, which may be on a cycle.
1583 SmallPtrSet<Value *, 4> Visited;
1584 Visited.insert(Ptr);
1585 SmallVector<Value *, 4> Indices;
1586
1587 // We may end up computing an offset pointer that has the wrong type. If we
1588 // never are able to compute one directly that has the correct type, we'll
Chandler Carruth5986b542015-01-02 02:47:38 +00001589 // fall back to it, so keep it and the base it was computed from around here.
Craig Topperf40110f2014-04-25 05:29:35 +00001590 Value *OffsetPtr = nullptr;
Chandler Carruth5986b542015-01-02 02:47:38 +00001591 Value *OffsetBasePtr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001592
1593 // Remember any i8 pointer we come across to re-use if we need to do a raw
1594 // byte offset.
Craig Topperf40110f2014-04-25 05:29:35 +00001595 Value *Int8Ptr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001596 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1597
Matt Arsenault282dac72019-06-14 21:38:31 +00001598 PointerType *TargetPtrTy = cast<PointerType>(PointerTy);
1599 Type *TargetTy = TargetPtrTy->getElementType();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001600
Michael Liao4f7f70e2019-06-18 21:41:13 +00001601 // As `addrspacecast` is , `Ptr` (the storage pointer) may have different
1602 // address space from the expected `PointerTy` (the pointer to be used).
1603 // Adjust the pointer type based the original storage pointer.
1604 auto AS = cast<PointerType>(Ptr->getType())->getAddressSpace();
1605 PointerTy = TargetTy->getPointerTo(AS);
1606
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001607 do {
1608 // First fold any existing GEPs into the offset.
1609 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1610 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001611 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001612 break;
1613 Offset += GEPOffset;
1614 Ptr = GEP->getPointerOperand();
David Blaikie70573dc2014-11-19 07:49:26 +00001615 if (!Visited.insert(Ptr).second)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001616 break;
1617 }
1618
1619 // See if we can perform a natural GEP here.
1620 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001621 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001622 Indices, NamePrefix)) {
Chandler Carruth5986b542015-01-02 02:47:38 +00001623 // If we have a new natural pointer at the offset, clear out any old
1624 // offset pointer we computed. Unless it is the base pointer or
1625 // a non-instruction, we built a GEP we don't need. Zap it.
1626 if (OffsetPtr && OffsetPtr != OffsetBasePtr)
1627 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1628 assert(I->use_empty() && "Built a GEP with uses some how!");
1629 I->eraseFromParent();
1630 }
1631 OffsetPtr = P;
1632 OffsetBasePtr = Ptr;
1633 // If we also found a pointer of the right type, we're done.
1634 if (P->getType() == PointerTy)
Michael Liao4f7f70e2019-06-18 21:41:13 +00001635 break;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001636 }
1637
1638 // Stash this pointer if we've found an i8*.
1639 if (Ptr->getType()->isIntegerTy(8)) {
1640 Int8Ptr = Ptr;
1641 Int8PtrOffset = Offset;
1642 }
1643
1644 // Peel off a layer of the pointer and update the offset appropriately.
1645 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1646 Ptr = cast<Operator>(Ptr)->getOperand(0);
1647 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001648 if (GA->isInterposable())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001649 break;
1650 Ptr = GA->getAliasee();
1651 } else {
1652 break;
1653 }
1654 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +00001655 } while (Visited.insert(Ptr).second);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001656
1657 if (!OffsetPtr) {
1658 if (!Int8Ptr) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00001659 Int8Ptr = IRB.CreateBitCast(
1660 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1661 NamePrefix + "sroa_raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001662 Int8PtrOffset = Offset;
1663 }
1664
Chandler Carruth113dc642014-12-20 02:39:18 +00001665 OffsetPtr = Int8PtrOffset == 0
1666 ? Int8Ptr
David Blaikieaa41cd52015-04-03 21:33:42 +00001667 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1668 IRB.getInt(Int8PtrOffset),
Chandler Carruth113dc642014-12-20 02:39:18 +00001669 NamePrefix + "sroa_raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001670 }
1671 Ptr = OffsetPtr;
1672
1673 // On the off chance we were targeting i8*, guard the bitcast here.
Matt Arsenault282dac72019-06-14 21:38:31 +00001674 if (cast<PointerType>(Ptr->getType()) != TargetPtrTy) {
1675 Ptr = IRB.CreatePointerBitCastOrAddrSpaceCast(Ptr,
1676 TargetPtrTy,
1677 NamePrefix + "sroa_cast");
1678 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001679
1680 return Ptr;
1681}
1682
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001683/// Compute the adjusted alignment for a load or store from an offset.
Chandler Carruth0715cba2015-01-01 11:54:38 +00001684static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset,
1685 const DataLayout &DL) {
1686 unsigned Alignment;
1687 Type *Ty;
1688 if (auto *LI = dyn_cast<LoadInst>(I)) {
1689 Alignment = LI->getAlignment();
1690 Ty = LI->getType();
1691 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
1692 Alignment = SI->getAlignment();
1693 Ty = SI->getValueOperand()->getType();
1694 } else {
1695 llvm_unreachable("Only loads and stores are allowed!");
1696 }
1697
1698 if (!Alignment)
1699 Alignment = DL.getABITypeAlignment(Ty);
1700
1701 return MinAlign(Alignment, Offset);
1702}
1703
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001704/// Test whether we can convert a value from the old to the new type.
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001705///
1706/// This predicate should be used to guard calls to convertValue in order to
1707/// ensure that we only try to convert viable values. The strategy is that we
1708/// will peel off single element struct and array wrappings to get to an
1709/// underlying value, and convert that value.
1710static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1711 if (OldTy == NewTy)
1712 return true;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001713
1714 // For integer types, we can't handle any bit-width differences. This would
1715 // break both vector conversions with extension and introduce endianness
1716 // issues when in conjunction with loads and stores.
1717 if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
1718 assert(cast<IntegerType>(OldTy)->getBitWidth() !=
1719 cast<IntegerType>(NewTy)->getBitWidth() &&
1720 "We can't have the same bitwidth for different int types");
1721 return false;
1722 }
1723
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001724 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1725 return false;
1726 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1727 return false;
1728
Benjamin Kramer56262592013-09-22 11:24:58 +00001729 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001730 // of pointers and integers.
1731 OldTy = OldTy->getScalarType();
1732 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001733 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
Jack Liuf101c0f2016-05-03 19:30:48 +00001734 if (NewTy->isPointerTy() && OldTy->isPointerTy()) {
1735 return cast<PointerType>(NewTy)->getPointerAddressSpace() ==
1736 cast<PointerType>(OldTy)->getPointerAddressSpace();
1737 }
Sanjoy Dasb70ddd82017-06-17 20:28:13 +00001738
1739 // We can convert integers to integral pointers, but not to non-integral
1740 // pointers.
1741 if (OldTy->isIntegerTy())
1742 return !DL.isNonIntegralPointerType(NewTy);
1743
1744 // We can convert integral pointers to integers, but non-integral pointers
1745 // need to remain pointers.
1746 if (!DL.isNonIntegralPointerType(OldTy))
1747 return NewTy->isIntegerTy();
1748
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001749 return false;
1750 }
1751
1752 return true;
1753}
1754
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001755/// Generic routine to convert an SSA value to a value of a different
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001756/// type.
1757///
1758/// This will try various different casting techniques, such as bitcasts,
1759/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1760/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001761static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001762 Type *NewTy) {
1763 Type *OldTy = V->getType();
1764 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1765
1766 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001767 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001768
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001769 assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
1770 "Integer types must be the exact same to convert.");
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001771
Benjamin Kramer90901a32013-09-21 20:36:04 +00001772 // See if we need inttoptr for this type pair. A cast involving both scalars
1773 // and vectors requires and additional bitcast.
Craig Topper95d23472017-07-09 07:04:00 +00001774 if (OldTy->isIntOrIntVectorTy() && NewTy->isPtrOrPtrVectorTy()) {
Benjamin Kramer90901a32013-09-21 20:36:04 +00001775 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1776 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1777 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1778 NewTy);
1779
1780 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1781 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1782 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1783 NewTy);
1784
1785 return IRB.CreateIntToPtr(V, NewTy);
1786 }
1787
1788 // See if we need ptrtoint for this type pair. A cast involving both scalars
1789 // and vectors requires and additional bitcast.
Craig Topper95d23472017-07-09 07:04:00 +00001790 if (OldTy->isPtrOrPtrVectorTy() && NewTy->isIntOrIntVectorTy()) {
Benjamin Kramer90901a32013-09-21 20:36:04 +00001791 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1792 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1793 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1794 NewTy);
1795
1796 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1797 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1798 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1799 NewTy);
1800
1801 return IRB.CreatePtrToInt(V, NewTy);
1802 }
1803
1804 return IRB.CreateBitCast(V, NewTy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001805}
1806
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001807/// Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001808///
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001809/// This function is called to test each entry in a partition which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001810/// for a single slice.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001811static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S,
1812 VectorType *Ty,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001813 uint64_t ElementSize,
1814 const DataLayout &DL) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001815 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001816 uint64_t BeginOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001817 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001818 uint64_t BeginIndex = BeginOffset / ElementSize;
1819 if (BeginIndex * ElementSize != BeginOffset ||
1820 BeginIndex >= Ty->getNumElements())
1821 return false;
1822 uint64_t EndOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001823 std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001824 uint64_t EndIndex = EndOffset / ElementSize;
1825 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1826 return false;
1827
1828 assert(EndIndex > BeginIndex && "Empty vector!");
1829 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruthc659df92014-10-16 20:24:07 +00001830 Type *SliceTy = (NumElements == 1)
1831 ? Ty->getElementType()
1832 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruthf0546402013-07-18 07:15:00 +00001833
1834 Type *SplitIntTy =
1835 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1836
Chandler Carruthc659df92014-10-16 20:24:07 +00001837 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001838
1839 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1840 if (MI->isVolatile())
1841 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00001842 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00001843 return false; // Skip any unsplittable intrinsics.
Owen Anderson6c19ab12014-08-07 21:07:35 +00001844 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
Vedant Kumarb264d692018-12-21 21:49:40 +00001845 if (!II->isLifetimeStartOrEnd())
Owen Anderson6c19ab12014-08-07 21:07:35 +00001846 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001847 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1848 // Disable vector promotion when there are loads or stores of an FCA.
1849 return false;
1850 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1851 if (LI->isVolatile())
1852 return false;
1853 Type *LTy = LI->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001854 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001855 assert(LTy->isIntegerTy());
1856 LTy = SplitIntTy;
1857 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001858 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001859 return false;
1860 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1861 if (SI->isVolatile())
1862 return false;
1863 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001864 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001865 assert(STy->isIntegerTy());
1866 STy = SplitIntTy;
1867 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001868 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001869 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001870 } else {
1871 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001872 }
1873
1874 return true;
1875}
1876
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001877/// Test whether the given alloca partitioning and range of slices can be
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001878/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001879///
1880/// This is a quick test to check whether we can rewrite a particular alloca
1881/// partition (and its newly formed alloca) into a vector alloca with only
1882/// whole-vector loads and stores such that it could be promoted to a vector
1883/// SSA value. We only can ensure this for a limited set of operations, and we
1884/// don't want to do the rewrites unless we are confident that the result will
1885/// be promotable, so we have an early test here.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001886static VectorType *isVectorPromotionViable(Partition &P, const DataLayout &DL) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001887 // Collect the candidate types for vector-based promotion. Also track whether
1888 // we have different element types.
1889 SmallVector<VectorType *, 4> CandidateTys;
1890 Type *CommonEltTy = nullptr;
1891 bool HaveCommonEltTy = true;
1892 auto CheckCandidateType = [&](Type *Ty) {
1893 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
Suyog Sardacd629ea2019-09-21 18:16:37 +00001894 // Return if bitcast to vectors is different for total size in bits.
1895 if (!CandidateTys.empty()) {
1896 VectorType *V = CandidateTys[0];
1897 if (DL.getTypeSizeInBits(VTy) != DL.getTypeSizeInBits(V)) {
1898 CandidateTys.clear();
1899 return;
1900 }
1901 }
Chandler Carruth2dc96822014-10-18 00:44:02 +00001902 CandidateTys.push_back(VTy);
1903 if (!CommonEltTy)
1904 CommonEltTy = VTy->getElementType();
1905 else if (CommonEltTy != VTy->getElementType())
1906 HaveCommonEltTy = false;
1907 }
1908 };
Chandler Carruth2dc96822014-10-18 00:44:02 +00001909 // Consider any loads or stores that are the exact size of the slice.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001910 for (const Slice &S : P)
1911 if (S.beginOffset() == P.beginOffset() &&
1912 S.endOffset() == P.endOffset()) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001913 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1914 CheckCandidateType(LI->getType());
1915 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1916 CheckCandidateType(SI->getValueOperand()->getType());
1917 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001918
Chandler Carruth2dc96822014-10-18 00:44:02 +00001919 // If we didn't find a vector type, nothing to do here.
1920 if (CandidateTys.empty())
1921 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001922
Chandler Carruth2dc96822014-10-18 00:44:02 +00001923 // Remove non-integer vector types if we had multiple common element types.
1924 // FIXME: It'd be nice to replace them with integer vector types, but we can't
1925 // do that until all the backends are known to produce good code for all
1926 // integer vector types.
1927 if (!HaveCommonEltTy) {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001928 CandidateTys.erase(
1929 llvm::remove_if(CandidateTys,
1930 [](VectorType *VTy) {
1931 return !VTy->getElementType()->isIntegerTy();
1932 }),
1933 CandidateTys.end());
Chandler Carruth2dc96822014-10-18 00:44:02 +00001934
1935 // If there were no integer vector types, give up.
1936 if (CandidateTys.empty())
1937 return nullptr;
1938
1939 // Rank the remaining candidate vector types. This is easy because we know
1940 // they're all integer vectors. We sort by ascending number of elements.
1941 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
David L. Jones41cecba2017-01-13 21:02:41 +00001942 (void)DL;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001943 assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
1944 "Cannot have vector types of different sizes!");
1945 assert(RHSTy->getElementType()->isIntegerTy() &&
1946 "All non-integer types eliminated!");
1947 assert(LHSTy->getElementType()->isIntegerTy() &&
1948 "All non-integer types eliminated!");
1949 return RHSTy->getNumElements() < LHSTy->getNumElements();
1950 };
Fangrui Song0cac7262018-09-27 02:13:45 +00001951 llvm::sort(CandidateTys, RankVectorTypes);
Chandler Carruth2dc96822014-10-18 00:44:02 +00001952 CandidateTys.erase(
1953 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
1954 CandidateTys.end());
1955 } else {
1956// The only way to have the same element type in every vector type is to
1957// have the same vector type. Check that and remove all but one.
1958#ifndef NDEBUG
1959 for (VectorType *VTy : CandidateTys) {
1960 assert(VTy->getElementType() == CommonEltTy &&
1961 "Unaccounted for element type!");
1962 assert(VTy == CandidateTys[0] &&
1963 "Different vector types with the same element type!");
1964 }
1965#endif
1966 CandidateTys.resize(1);
1967 }
1968
1969 // Try each vector type, and return the one which works.
1970 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
1971 uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
1972
1973 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1974 // that aren't byte sized.
1975 if (ElementSize % 8)
1976 return false;
1977 assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
1978 "vector size not a multiple of element size?");
1979 ElementSize /= 8;
1980
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001981 for (const Slice &S : P)
1982 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001983 return false;
1984
Chandler Carruthffb7ce52014-12-24 01:48:09 +00001985 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001986 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001987 return false;
1988
1989 return true;
1990 };
1991 for (VectorType *VTy : CandidateTys)
1992 if (CheckVectorTypeForPromotion(VTy))
1993 return VTy;
1994
1995 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001996}
1997
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001998/// Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001999///
2000/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002001/// test below on a single slice of the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002002static bool isIntegerWideningViableForSlice(const Slice &S,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002003 uint64_t AllocBeginOffset,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002004 Type *AllocaTy,
2005 const DataLayout &DL,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002006 bool &WholeAllocaOp) {
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002007 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
2008
Chandler Carruthc659df92014-10-16 20:24:07 +00002009 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
2010 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00002011
2012 // We can't reasonably handle cases where the load or store extends past
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002013 // the end of the alloca's type and into its padding.
Chandler Carruthf0546402013-07-18 07:15:00 +00002014 if (RelEnd > Size)
2015 return false;
2016
Chandler Carruthc659df92014-10-16 20:24:07 +00002017 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00002018
2019 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2020 if (LI->isVolatile())
2021 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002022 // We can't handle loads that extend past the allocated memory.
2023 if (DL.getTypeStoreSize(LI->getType()) > Size)
2024 return false;
Hiroshi Inouef5c0e6c2018-05-17 06:32:17 +00002025 // So far, AllocaSliceRewriter does not support widening split slice tails
2026 // in rewriteIntegerLoad.
2027 if (S.beginOffset() < AllocBeginOffset)
2028 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00002029 // Note that we don't count vector loads or stores as whole-alloca
2030 // operations which enable integer widening because we would prefer to use
2031 // vector widening instead.
2032 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00002033 WholeAllocaOp = true;
2034 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002035 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00002036 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00002037 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002038 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002039 // Non-integer loads need to be convertible from the alloca type so that
2040 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002041 return false;
2042 }
Chandler Carruthf0546402013-07-18 07:15:00 +00002043 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2044 Type *ValueTy = SI->getValueOperand()->getType();
2045 if (SI->isVolatile())
2046 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002047 // We can't handle stores that extend past the allocated memory.
2048 if (DL.getTypeStoreSize(ValueTy) > Size)
2049 return false;
Hiroshi Inouef5c0e6c2018-05-17 06:32:17 +00002050 // So far, AllocaSliceRewriter does not support widening split slice tails
2051 // in rewriteIntegerStore.
2052 if (S.beginOffset() < AllocBeginOffset)
2053 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00002054 // Note that we don't count vector loads or stores as whole-alloca
2055 // operations which enable integer widening because we would prefer to use
2056 // vector widening instead.
2057 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00002058 WholeAllocaOp = true;
2059 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002060 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00002061 return false;
2062 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002063 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002064 // Non-integer stores need to be convertible to the alloca type so that
2065 // they are promotable.
2066 return false;
2067 }
2068 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2069 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
2070 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00002071 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00002072 return false; // Skip any unsplittable intrinsics.
2073 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
Vedant Kumarb264d692018-12-21 21:49:40 +00002074 if (!II->isLifetimeStartOrEnd())
Chandler Carruthf0546402013-07-18 07:15:00 +00002075 return false;
2076 } else {
2077 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002078 }
Chandler Carruthf0546402013-07-18 07:15:00 +00002079
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002080 return true;
2081}
2082
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002083/// Test whether the given alloca partition's integer operations can be
Chandler Carruth435c4e02012-10-15 08:40:30 +00002084/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00002085///
Chandler Carruth435c4e02012-10-15 08:40:30 +00002086/// This is a quick test to check whether we can rewrite the integer loads and
2087/// stores to a particular alloca into wider loads and stores and be able to
2088/// promote the resulting alloca.
Chandler Carruth29a18a42015-09-12 09:09:14 +00002089static bool isIntegerWideningViable(Partition &P, Type *AllocaTy,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002090 const DataLayout &DL) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002091 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00002092 // Don't create integer types larger than the maximum bitwidth.
2093 if (SizeInBits > IntegerType::MAX_INT_BITS)
2094 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002095
2096 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002097 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002098 return false;
2099
Chandler Carruth58d05562012-10-25 04:37:07 +00002100 // We need to ensure that an integer type with the appropriate bitwidth can
2101 // be converted to the alloca type, whatever that is. We don't want to force
2102 // the alloca itself to have an integer type if there is a more suitable one.
2103 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002104 if (!canConvertValue(DL, AllocaTy, IntTy) ||
2105 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00002106 return false;
2107
Chandler Carruthf0546402013-07-18 07:15:00 +00002108 // While examining uses, we ensure that the alloca has a covering load or
2109 // store. We don't want to widen the integer operations only to fail to
2110 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00002111 // later). However, if there are only splittable uses, go ahead and assume
2112 // that we cover the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002113 // FIXME: We shouldn't consider split slices that happen to start in the
2114 // partition here...
Chandler Carruthc659df92014-10-16 20:24:07 +00002115 bool WholeAllocaOp =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002116 P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00002117
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002118 for (const Slice &S : P)
2119 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2120 WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00002121 return false;
2122
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002123 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002124 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2125 WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002126 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00002127
Chandler Carruth92924fd2012-09-24 00:34:20 +00002128 return WholeAllocaOp;
2129}
2130
Chandler Carruthd177f862013-03-20 07:30:36 +00002131static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002132 IntegerType *Ty, uint64_t Offset,
2133 const Twine &Name) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002134 LLVM_DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002135 IntegerType *IntTy = cast<IntegerType>(V->getType());
2136 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2137 "Element extends past full value");
Chandler Carruth113dc642014-12-20 02:39:18 +00002138 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002139 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002140 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002141 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002142 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002143 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002144 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002145 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2146 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002147 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002148 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002149 LLVM_DEBUG(dbgs() << " trunced: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002150 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002151 return V;
2152}
2153
Chandler Carruthd177f862013-03-20 07:30:36 +00002154static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002155 Value *V, uint64_t Offset, const Twine &Name) {
2156 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2157 IntegerType *Ty = cast<IntegerType>(V->getType());
2158 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2159 "Cannot insert a larger integer!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002160 LLVM_DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002161 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002162 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002163 LLVM_DEBUG(dbgs() << " extended: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002164 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002165 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2166 "Element store outside of alloca store");
Chandler Carruth113dc642014-12-20 02:39:18 +00002167 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002168 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002169 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002170 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002171 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002172 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002173 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002174
2175 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2176 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2177 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002178 LLVM_DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002179 V = IRB.CreateOr(Old, V, Name + ".insert");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002180 LLVM_DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002181 }
2182 return V;
2183}
2184
Chandler Carruth113dc642014-12-20 02:39:18 +00002185static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2186 unsigned EndIndex, const Twine &Name) {
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002187 VectorType *VecTy = cast<VectorType>(V->getType());
2188 unsigned NumElements = EndIndex - BeginIndex;
2189 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2190
2191 if (NumElements == VecTy->getNumElements())
2192 return V;
2193
2194 if (NumElements == 1) {
2195 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2196 Name + ".extract");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002197 LLVM_DEBUG(dbgs() << " extract: " << *V << "\n");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002198 return V;
2199 }
2200
Chandler Carruth113dc642014-12-20 02:39:18 +00002201 SmallVector<Constant *, 8> Mask;
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002202 Mask.reserve(NumElements);
2203 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2204 Mask.push_back(IRB.getInt32(i));
2205 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002206 ConstantVector::get(Mask), Name + ".extract");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002207 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002208 return V;
2209}
2210
Chandler Carruthd177f862013-03-20 07:30:36 +00002211static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00002212 unsigned BeginIndex, const Twine &Name) {
2213 VectorType *VecTy = cast<VectorType>(Old->getType());
2214 assert(VecTy && "Can only insert a vector into a vector");
2215
2216 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2217 if (!Ty) {
2218 // Single element to insert.
2219 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2220 Name + ".insert");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002221 LLVM_DEBUG(dbgs() << " insert: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002222 return V;
2223 }
2224
2225 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2226 "Too many elements!");
2227 if (Ty->getNumElements() == VecTy->getNumElements()) {
2228 assert(V->getType() == VecTy && "Vector type mismatch");
2229 return V;
2230 }
2231 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2232
2233 // When inserting a smaller vector into the larger to store, we first
2234 // use a shuffle vector to widen it with undef elements, and then
2235 // a second shuffle vector to select between the loaded vector and the
2236 // incoming vector.
Chandler Carruth113dc642014-12-20 02:39:18 +00002237 SmallVector<Constant *, 8> Mask;
Chandler Carruthce4562b2012-12-17 13:41:21 +00002238 Mask.reserve(VecTy->getNumElements());
2239 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2240 if (i >= BeginIndex && i < EndIndex)
2241 Mask.push_back(IRB.getInt32(i - BeginIndex));
2242 else
2243 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2244 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002245 ConstantVector::get(Mask), Name + ".expand");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002246 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002247
2248 Mask.clear();
2249 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00002250 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2251
2252 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2253
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002254 LLVM_DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002255 return V;
2256}
2257
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002258/// Visitor to rewrite instructions using p particular slice of an alloca
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002259/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002260///
2261/// Also implements the rewriting to vector-based accesses when the partition
2262/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2263/// lives here.
Chandler Carruth29a18a42015-09-12 09:09:14 +00002264class llvm::sroa::AllocaSliceRewriter
2265 : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002266 // Befriend the base class so it can delegate to private visit methods.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002267 friend class InstVisitor<AllocaSliceRewriter, bool>;
2268
2269 using Base = InstVisitor<AllocaSliceRewriter, bool>;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002270
Chandler Carruth90a735d2013-07-19 07:21:28 +00002271 const DataLayout &DL;
Chandler Carruth83934062014-10-16 21:11:55 +00002272 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002273 SROA &Pass;
2274 AllocaInst &OldAI, &NewAI;
2275 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00002276 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002277
Chandler Carruth2dc96822014-10-18 00:44:02 +00002278 // This is a convenience and flag variable that will be null unless the new
2279 // alloca's integer operations should be widened to this integer type due to
2280 // passing isIntegerWideningViable above. If it is non-null, the desired
2281 // integer type will be stored here for easy access during rewriting.
2282 IntegerType *IntTy;
2283
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002284 // If we are rewriting an alloca partition which can be written as pure
2285 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002286 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002287 // - The new alloca is exactly the size of the vector type here.
2288 // - The accesses all either map to the entire vector or to a single
2289 // element.
2290 // - The set of accessing instructions is only one of those handled above
2291 // in isVectorPromotionViable. Generally these are the same access kinds
2292 // which are promotable via mem2reg.
2293 VectorType *VecTy;
2294 Type *ElementTy;
2295 uint64_t ElementSize;
2296
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002297 // The original offset of the slice currently being rewritten relative to
2298 // the original alloca.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002299 uint64_t BeginOffset = 0;
2300 uint64_t EndOffset = 0;
2301
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002302 // The new offsets of the slice currently being rewritten relative to the
2303 // original alloca.
2304 uint64_t NewBeginOffset, NewEndOffset;
2305
2306 uint64_t SliceSize;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002307 bool IsSplittable = false;
2308 bool IsSplit = false;
2309 Use *OldUse = nullptr;
2310 Instruction *OldPtr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002311
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002312 // Track post-rewrite users which are PHI nodes and Selects.
Davide Italiano81a26da2017-04-27 23:09:01 +00002313 SmallSetVector<PHINode *, 8> &PHIUsers;
2314 SmallSetVector<SelectInst *, 8> &SelectUsers;
Chandler Carruth83ea1952013-07-24 09:47:28 +00002315
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002316 // Utility IR builder, whose name prefix is setup for each visited use, and
2317 // the insertion point is set to point to the user.
2318 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002319
2320public:
Chandler Carruth83934062014-10-16 21:11:55 +00002321 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002322 AllocaInst &OldAI, AllocaInst &NewAI,
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002323 uint64_t NewAllocaBeginOffset,
Chandler Carruth2dc96822014-10-18 00:44:02 +00002324 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2325 VectorType *PromotableVecTy,
Davide Italiano81a26da2017-04-27 23:09:01 +00002326 SmallSetVector<PHINode *, 8> &PHIUsers,
2327 SmallSetVector<SelectInst *, 8> &SelectUsers)
Chandler Carruth83934062014-10-16 21:11:55 +00002328 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002329 NewAllocaBeginOffset(NewAllocaBeginOffset),
2330 NewAllocaEndOffset(NewAllocaEndOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002331 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002332 IntTy(IsIntegerPromotable
2333 ? Type::getIntNTy(
2334 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002335 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Craig Topperf40110f2014-04-25 05:29:35 +00002336 : nullptr),
Chandler Carruth2dc96822014-10-18 00:44:02 +00002337 VecTy(PromotableVecTy),
2338 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2339 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002340 PHIUsers(PHIUsers), SelectUsers(SelectUsers),
Chandler Carruth83ea1952013-07-24 09:47:28 +00002341 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002342 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002343 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002344 "Only multiple-of-8 sized vector elements are viable");
2345 ++NumVectorized;
2346 }
Chandler Carruth2dc96822014-10-18 00:44:02 +00002347 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002348 }
2349
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002350 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002351 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002352 BeginOffset = I->beginOffset();
2353 EndOffset = I->endOffset();
2354 IsSplittable = I->isSplittable();
2355 IsSplit =
2356 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002357 LLVM_DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
2358 LLVM_DEBUG(AS.printSlice(dbgs(), I, ""));
2359 LLVM_DEBUG(dbgs() << "\n");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002360
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002361 // Compute the intersecting offset range.
2362 assert(BeginOffset < NewAllocaEndOffset);
2363 assert(EndOffset > NewAllocaBeginOffset);
2364 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2365 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2366
2367 SliceSize = NewEndOffset - NewBeginOffset;
2368
Chandler Carruthf0546402013-07-18 07:15:00 +00002369 OldUse = I->getUse();
2370 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002371
Chandler Carruthf0546402013-07-18 07:15:00 +00002372 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2373 IRB.SetInsertPoint(OldUserI);
2374 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2375 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2376
2377 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2378 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002379 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002380 return CanSROA;
2381 }
2382
2383private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002384 // Make sure the other visit overloads are visible.
2385 using Base::visit;
2386
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002387 // Every instruction which can end up as a user must have a rewrite rule.
2388 bool visitInstruction(Instruction &I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002389 LLVM_DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002390 llvm_unreachable("No rewrite rule for this instruction!");
2391 }
2392
Chandler Carruth47954c82014-02-26 05:12:43 +00002393 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2394 // Note that the offset computation can use BeginOffset or NewBeginOffset
2395 // interchangeably for unsplit slices.
2396 assert(IsSplit || BeginOffset == NewBeginOffset);
2397 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2398
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002399#ifndef NDEBUG
2400 StringRef OldName = OldPtr->getName();
2401 // Skip through the last '.sroa.' component of the name.
2402 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2403 if (LastSROAPrefix != StringRef::npos) {
2404 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2405 // Look for an SROA slice index.
2406 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2407 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2408 // Strip the index and look for the offset.
2409 OldName = OldName.substr(IndexEnd + 1);
2410 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2411 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2412 // Strip the offset.
2413 OldName = OldName.substr(OffsetEnd + 1);
2414 }
2415 }
2416 // Strip any SROA suffixes as well.
2417 OldName = OldName.substr(0, OldName.find(".sroa_"));
2418#endif
Chandler Carruth47954c82014-02-26 05:12:43 +00002419
2420 return getAdjustedPtr(IRB, DL, &NewAI,
Nicola Zaghenf96383c2018-10-30 11:15:04 +00002421 APInt(DL.getIndexTypeSizeInBits(PointerTy), Offset),
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002422 PointerTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002423#ifndef NDEBUG
2424 Twine(OldName) + "."
2425#else
2426 Twine()
2427#endif
2428 );
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002429 }
2430
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002431 /// Compute suitable alignment to access this slice of the *new*
Chandler Carruth113dc642014-12-20 02:39:18 +00002432 /// alloca.
Chandler Carruth2659e502014-02-26 05:02:19 +00002433 ///
2434 /// You can optionally pass a type to this routine and if that type's ABI
2435 /// alignment is itself suitable, this will return zero.
Craig Topperf40110f2014-04-25 05:29:35 +00002436 unsigned getSliceAlign(Type *Ty = nullptr) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002437 unsigned NewAIAlign = NewAI.getAlignment();
2438 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002439 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth113dc642014-12-20 02:39:18 +00002440 unsigned Align =
2441 MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
Chandler Carruth2659e502014-02-26 05:02:19 +00002442 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002443 }
2444
Chandler Carruth845b73c2012-11-21 08:16:30 +00002445 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002446 assert(VecTy && "Can only call getIndex when rewriting a vector");
2447 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2448 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2449 uint32_t Index = RelOffset / ElementSize;
2450 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002451 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002452 }
2453
2454 void deleteIfTriviallyDead(Value *V) {
2455 Instruction *I = cast<Instruction>(V);
2456 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002457 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002458 }
2459
Chandler Carruthea27cf02014-02-26 04:25:04 +00002460 Value *rewriteVectorizedLoadInst() {
Chandler Carruthf0546402013-07-18 07:15:00 +00002461 unsigned BeginIndex = getIndex(NewBeginOffset);
2462 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002463 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002464
James Y Knight14359ef2019-02-01 20:44:24 +00002465 Value *V = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2466 NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002467 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002468 }
2469
Chandler Carruthea27cf02014-02-26 04:25:04 +00002470 Value *rewriteIntegerLoad(LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002471 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002472 assert(!LI.isVolatile());
James Y Knight14359ef2019-02-01 20:44:24 +00002473 Value *V = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2474 NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002475 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002476 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2477 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth4b682f62015-08-28 09:03:52 +00002478 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
2479 IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8);
2480 V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract");
2481 }
2482 // It is possible that the extracted type is not the load type. This
2483 // happens if there is a load past the end of the alloca, and as
2484 // a consequence the slice is narrower but still a candidate for integer
2485 // lowering. To handle this case, we just zero extend the extracted
2486 // integer.
2487 assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 &&
2488 "Can only handle an extract for an overly wide load");
2489 if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8)
2490 V = IRB.CreateZExt(V, LI.getType());
Chandler Carruth18db7952012-11-20 01:12:50 +00002491 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002492 }
2493
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002494 bool visitLoadInst(LoadInst &LI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002495 LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002496 Value *OldOp = LI.getOperand(0);
2497 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002498
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002499 AAMDNodes AATags;
2500 LI.getAAMetadata(AATags);
2501
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002502 unsigned AS = LI.getPointerAddressSpace();
2503
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002504 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002505 : LI.getType();
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002506 const bool IsLoadPastEnd = DL.getTypeStoreSize(TargetTy) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002507 bool IsPtrAdjusted = false;
2508 Value *V;
2509 if (VecTy) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002510 V = rewriteVectorizedLoadInst();
Chandler Carruth18db7952012-11-20 01:12:50 +00002511 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002512 V = rewriteIntegerLoad(LI);
Chandler Carruthf0546402013-07-18 07:15:00 +00002513 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002514 NewEndOffset == NewAllocaEndOffset &&
2515 (canConvertValue(DL, NewAllocaTy, TargetTy) ||
2516 (IsLoadPastEnd && NewAllocaTy->isIntegerTy() &&
2517 TargetTy->isIntegerTy()))) {
James Y Knight14359ef2019-02-01 20:44:24 +00002518 LoadInst *NewLI = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2519 NewAI.getAlignment(),
David Majnemer62690b12015-07-14 06:19:58 +00002520 LI.isVolatile(), LI.getName());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002521 if (AATags)
2522 NewLI->setAAMetadata(AATags);
David Majnemer62690b12015-07-14 06:19:58 +00002523 if (LI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002524 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
Luqman Aden3f807c92017-03-22 19:16:39 +00002525
Chandler Carruth3f81d802017-06-27 08:32:03 +00002526 // Any !nonnull metadata or !range metadata on the old load is also valid
2527 // on the new load. This is even true in some cases even when the loads
2528 // are different types, for example by mapping !nonnull metadata to
2529 // !range metadata by modeling the null pointer constant converted to the
2530 // integer type.
Rafael Espindolac06f55e2017-11-28 01:25:38 +00002531 // FIXME: Add support for range metadata here. Currently the utilities
2532 // for this don't propagate range metadata in trivial cases from one
2533 // integer load to another, don't handle non-addrspace-0 null pointers
2534 // correctly, and don't have any support for mapping ranges as the
2535 // integer type becomes winder or narrower.
Chandler Carruth3f81d802017-06-27 08:32:03 +00002536 if (MDNode *N = LI.getMetadata(LLVMContext::MD_nonnull))
2537 copyNonnullMetadata(LI, N, *NewLI);
Rafael Espindolac06f55e2017-11-28 01:25:38 +00002538
2539 // Try to preserve nonnull metadata
David Majnemer62690b12015-07-14 06:19:58 +00002540 V = NewLI;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002541
2542 // If this is an integer load past the end of the slice (which means the
2543 // bytes outside the slice are undef or this load is dead) just forcibly
2544 // fix the integer size with correct handling of endianness.
2545 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2546 if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
2547 if (AITy->getBitWidth() < TITy->getBitWidth()) {
2548 V = IRB.CreateZExt(V, TITy, "load.ext");
2549 if (DL.isBigEndian())
2550 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
2551 "endian_shift");
2552 }
Chandler Carruth18db7952012-11-20 01:12:50 +00002553 } else {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002554 Type *LTy = TargetTy->getPointerTo(AS);
James Y Knight14359ef2019-02-01 20:44:24 +00002555 LoadInst *NewLI = IRB.CreateAlignedLoad(
2556 TargetTy, getNewAllocaSlicePtr(IRB, LTy), getSliceAlign(TargetTy),
2557 LI.isVolatile(), LI.getName());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002558 if (AATags)
2559 NewLI->setAAMetadata(AATags);
David Majnemer62690b12015-07-14 06:19:58 +00002560 if (LI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002561 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
David Majnemer62690b12015-07-14 06:19:58 +00002562
2563 V = NewLI;
Chandler Carruth18db7952012-11-20 01:12:50 +00002564 IsPtrAdjusted = true;
2565 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002566 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002567
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002568 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002569 assert(!LI.isVolatile());
2570 assert(LI.getType()->isIntegerTy() &&
2571 "Only integer type loads and stores are split");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002572 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002573 "Split load isn't smaller than original load");
Bjorn Petterssonb4771422019-05-24 09:20:20 +00002574 assert(DL.typeSizeEqualsStoreSize(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002575 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002576 // 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 +00002577 IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002578 // Create a placeholder value with the same type as LI to use as the
2579 // basis for the new value. This allows us to replace the uses of LI with
2580 // the computed value, and then replace the placeholder with LI, leaving
2581 // LI only used for this computation.
James Y Knight14359ef2019-02-01 20:44:24 +00002582 Value *Placeholder = new LoadInst(
2583 LI.getType(), UndefValue::get(LI.getType()->getPointerTo(AS)));
Chandler Carruth24ac8302015-01-02 03:55:54 +00002584 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2585 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002586 LI.replaceAllUsesWith(V);
2587 Placeholder->replaceAllUsesWith(&LI);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002588 Placeholder->deleteValue();
Chandler Carruth18db7952012-11-20 01:12:50 +00002589 } else {
2590 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002591 }
2592
Chandler Carruth18db7952012-11-20 01:12:50 +00002593 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002594 deleteIfTriviallyDead(OldOp);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002595 LLVM_DEBUG(dbgs() << " to: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002596 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002597 }
2598
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002599 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2600 AAMDNodes AATags) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002601 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002602 unsigned BeginIndex = getIndex(NewBeginOffset);
2603 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002604 assert(EndIndex > BeginIndex && "Empty vector!");
2605 unsigned NumElements = EndIndex - BeginIndex;
2606 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth113dc642014-12-20 02:39:18 +00002607 Type *SliceTy = (NumElements == 1)
2608 ? ElementTy
2609 : VectorType::get(ElementTy, NumElements);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002610 if (V->getType() != SliceTy)
2611 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002612
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002613 // Mix in the existing elements.
James Y Knight14359ef2019-02-01 20:44:24 +00002614 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2615 NewAI.getAlignment(), "load");
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002616 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2617 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002618 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002619 if (AATags)
2620 Store->setAAMetadata(AATags);
Chandler Carruth18db7952012-11-20 01:12:50 +00002621 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002622
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002623 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002624 return true;
2625 }
2626
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002627 bool rewriteIntegerStore(Value *V, StoreInst &SI, AAMDNodes AATags) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002628 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002629 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002630 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
James Y Knight14359ef2019-02-01 20:44:24 +00002631 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2632 NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002633 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002634 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2635 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth113dc642014-12-20 02:39:18 +00002636 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002637 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002638 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002639 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Michael Kruse978ba612018-12-20 04:58:07 +00002640 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2641 LLVMContext::MD_access_group});
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002642 if (AATags)
2643 Store->setAAMetadata(AATags);
Chandler Carruth18db7952012-11-20 01:12:50 +00002644 Pass.DeadInsts.insert(&SI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002645 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002646 return true;
2647 }
2648
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002649 bool visitStoreInst(StoreInst &SI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002650 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002651 Value *OldOp = SI.getOperand(1);
2652 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002653
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002654 AAMDNodes AATags;
2655 SI.getAAMetadata(AATags);
2656
Chandler Carruth18db7952012-11-20 01:12:50 +00002657 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002658
Chandler Carruthac8317f2012-10-04 12:33:50 +00002659 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2660 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002661 if (V->getType()->isPointerTy())
2662 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002663 Pass.PostPromotionWorklist.insert(AI);
2664
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002665 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002666 assert(!SI.isVolatile());
2667 assert(V->getType()->isIntegerTy() &&
2668 "Only integer type loads and stores are split");
Bjorn Petterssonb4771422019-05-24 09:20:20 +00002669 assert(DL.typeSizeEqualsStoreSize(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002670 "Non-byte-multiple bit width");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002671 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
Chandler Carruth24ac8302015-01-02 03:55:54 +00002672 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2673 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002674 }
2675
Chandler Carruth18db7952012-11-20 01:12:50 +00002676 if (VecTy)
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002677 return rewriteVectorizedStoreInst(V, SI, OldOp, AATags);
Chandler Carruth18db7952012-11-20 01:12:50 +00002678 if (IntTy && V->getType()->isIntegerTy())
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002679 return rewriteIntegerStore(V, SI, AATags);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002680
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002681 const bool IsStorePastEnd = DL.getTypeStoreSize(V->getType()) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002682 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002683 if (NewBeginOffset == NewAllocaBeginOffset &&
2684 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002685 (canConvertValue(DL, V->getType(), NewAllocaTy) ||
2686 (IsStorePastEnd && NewAllocaTy->isIntegerTy() &&
2687 V->getType()->isIntegerTy()))) {
2688 // If this is an integer store past the end of slice (and thus the bytes
2689 // past that point are irrelevant or this is unreachable), truncate the
2690 // value prior to storing.
2691 if (auto *VITy = dyn_cast<IntegerType>(V->getType()))
2692 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2693 if (VITy->getBitWidth() > AITy->getBitWidth()) {
2694 if (DL.isBigEndian())
2695 V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
2696 "endian_shift");
2697 V = IRB.CreateTrunc(V, AITy, "load.trunc");
2698 }
2699
Chandler Carruth90a735d2013-07-19 07:21:28 +00002700 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002701 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2702 SI.isVolatile());
2703 } else {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002704 unsigned AS = SI.getPointerAddressSpace();
2705 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo(AS));
Chandler Carruth2659e502014-02-26 05:02:19 +00002706 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2707 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002708 }
Michael Kruse978ba612018-12-20 04:58:07 +00002709 NewSI->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2710 LLVMContext::MD_access_group});
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002711 if (AATags)
2712 NewSI->setAAMetadata(AATags);
David Majnemer62690b12015-07-14 06:19:58 +00002713 if (SI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002714 NewSI->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
Chandler Carruth18db7952012-11-20 01:12:50 +00002715 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002716 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002717
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002718 LLVM_DEBUG(dbgs() << " to: " << *NewSI << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002719 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002720 }
2721
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002722 /// Compute an integer value from splatting an i8 across the given
Chandler Carruth514f34f2012-12-17 04:07:30 +00002723 /// number of bytes.
2724 ///
2725 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2726 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002727 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002728 ///
2729 /// \param V The i8 value to splat.
2730 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002731 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002732 assert(Size > 0 && "Expected a positive number of bytes.");
2733 IntegerType *VTy = cast<IntegerType>(V->getType());
2734 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2735 if (Size == 1)
2736 return V;
2737
Chandler Carruth113dc642014-12-20 02:39:18 +00002738 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2739 V = IRB.CreateMul(
2740 IRB.CreateZExt(V, SplatIntTy, "zext"),
2741 ConstantExpr::getUDiv(
2742 Constant::getAllOnesValue(SplatIntTy),
2743 ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2744 SplatIntTy)),
2745 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002746 return V;
2747 }
2748
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002749 /// Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002750 Value *getVectorSplat(Value *V, unsigned NumElements) {
2751 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002752 LLVM_DEBUG(dbgs() << " splat: " << *V << "\n");
Chandler Carruthccca5042012-12-17 04:07:37 +00002753 return V;
2754 }
2755
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002756 bool visitMemSetInst(MemSetInst &II) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002757 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002758 assert(II.getRawDest() == OldPtr);
2759
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002760 AAMDNodes AATags;
2761 II.getAAMetadata(AATags);
2762
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002763 // If the memset has a variable size, it cannot be split, just adjust the
2764 // pointer to the new alloca.
2765 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002766 assert(!IsSplit);
Chandler Carruth735d5be2014-02-26 04:45:24 +00002767 assert(NewBeginOffset == BeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002768 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
Daniel Neilson41e781d2018-03-13 14:25:33 +00002769 II.setDestAlignment(getSliceAlign());
Chandler Carruth208124f2012-09-26 10:59:22 +00002770
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002771 deleteIfTriviallyDead(OldPtr);
2772 return false;
2773 }
2774
2775 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002776 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002777
2778 Type *AllocaTy = NewAI.getAllocatedType();
2779 Type *ScalarTy = AllocaTy->getScalarType();
Philip Reames9b6b4fa2019-03-12 20:15:05 +00002780
2781 const bool CanContinue = [&]() {
2782 if (VecTy || IntTy)
2783 return true;
2784 if (BeginOffset > NewAllocaBeginOffset ||
2785 EndOffset < NewAllocaEndOffset)
2786 return false;
2787 auto *C = cast<ConstantInt>(II.getLength());
2788 if (C->getBitWidth() > 64)
2789 return false;
2790 const auto Len = C->getZExtValue();
2791 auto *Int8Ty = IntegerType::getInt8Ty(NewAI.getContext());
2792 auto *SrcTy = VectorType::get(Int8Ty, Len);
2793 return canConvertValue(DL, SrcTy, AllocaTy) &&
2794 DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy));
2795 }();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002796
2797 // If this doesn't map cleanly onto the alloca type, and that type isn't
2798 // a single value type, just emit a memset.
Philip Reames9b6b4fa2019-03-12 20:15:05 +00002799 if (!CanContinue) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002800 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002801 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2802 CallInst *New = IRB.CreateMemSet(
Chandler Carruth47954c82014-02-26 05:12:43 +00002803 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2804 getSliceAlign(), II.isVolatile());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002805 if (AATags)
2806 New->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002807 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002808 return false;
2809 }
2810
2811 // If we can represent this as a simple value, we have to build the actual
2812 // value to store, which requires expanding the byte present in memset to
2813 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002814 // splatting the byte to a sufficiently wide integer, splatting it across
2815 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002816 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002817
Chandler Carruthccca5042012-12-17 04:07:37 +00002818 if (VecTy) {
2819 // If this is a memset of a vectorized alloca, insert it.
2820 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002821
Chandler Carruthf0546402013-07-18 07:15:00 +00002822 unsigned BeginIndex = getIndex(NewBeginOffset);
2823 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002824 assert(EndIndex > BeginIndex && "Empty vector!");
2825 unsigned NumElements = EndIndex - BeginIndex;
2826 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2827
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002828 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002829 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2830 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002831 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002832 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002833
James Y Knight14359ef2019-02-01 20:44:24 +00002834 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2835 NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002836 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002837 } else if (IntTy) {
2838 // If this is a memset on an alloca where we can widen stores, insert the
2839 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002840 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002841
Chandler Carruthf0546402013-07-18 07:15:00 +00002842 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002843 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002844
2845 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2846 EndOffset != NewAllocaBeginOffset)) {
James Y Knight14359ef2019-02-01 20:44:24 +00002847 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2848 NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002849 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002850 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002851 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002852 } else {
2853 assert(V->getType() == IntTy &&
2854 "Wrong type for an alloca wide integer!");
2855 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002856 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002857 } else {
2858 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002859 assert(NewBeginOffset == NewAllocaBeginOffset);
2860 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002861
Chandler Carruth90a735d2013-07-19 07:21:28 +00002862 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002863 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002864 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002865
Chandler Carruth90a735d2013-07-19 07:21:28 +00002866 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002867 }
2868
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002869 StoreInst *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2870 II.isVolatile());
2871 if (AATags)
2872 New->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002873 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002874 return !II.isVolatile();
2875 }
2876
2877 bool visitMemTransferInst(MemTransferInst &II) {
2878 // Rewriting of memory transfer instructions can be a bit tricky. We break
2879 // them into two categories: split intrinsics and unsplit intrinsics.
2880
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002881 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002882
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002883 AAMDNodes AATags;
2884 II.getAAMetadata(AATags);
2885
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002886 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002887 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002888 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002889
Chandler Carruthaa72b932014-02-26 07:29:54 +00002890 unsigned SliceAlign = getSliceAlign();
Chandler Carruth176ca712012-10-01 12:16:54 +00002891
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002892 // For unsplit intrinsics, we simply modify the source and destination
2893 // pointers in place. This isn't just an optimization, it is a matter of
2894 // correctness. With unsplit intrinsics we may be dealing with transfers
2895 // within a single alloca before SROA ran, or with transfers that have
2896 // a variable length. We may also be dealing with memmove instead of
2897 // memcpy, and so simply updating the pointers is the necessary for us to
2898 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002899 if (!IsSplittable) {
Chandler Carruth47954c82014-02-26 05:12:43 +00002900 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Daniel Neilson41e781d2018-03-13 14:25:33 +00002901 if (IsDest) {
Chandler Carruth8183a502014-02-25 11:08:02 +00002902 II.setDest(AdjustedPtr);
Daniel Neilson41e781d2018-03-13 14:25:33 +00002903 II.setDestAlignment(SliceAlign);
2904 }
2905 else {
Chandler Carruth8183a502014-02-25 11:08:02 +00002906 II.setSource(AdjustedPtr);
Daniel Neilson41e781d2018-03-13 14:25:33 +00002907 II.setSourceAlignment(SliceAlign);
Chandler Carruth181ed052014-02-26 05:33:36 +00002908 }
Chandler Carruth208124f2012-09-26 10:59:22 +00002909
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002910 LLVM_DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002911 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002912 return false;
2913 }
2914 // For split transfer intrinsics we have an incredibly useful assurance:
2915 // the source and destination do not reside within the same alloca, and at
2916 // least one of them does not escape. This means that we can replace
2917 // memmove with memcpy, and we don't need to worry about all manner of
2918 // downsides to splitting and transforming the operations.
2919
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002920 // If this doesn't map cleanly onto the alloca type, and that type isn't
2921 // a single value type, just emit a memcpy.
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002922 bool EmitMemCpy =
2923 !VecTy && !IntTy &&
2924 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2925 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2926 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002927
2928 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2929 // size hasn't been shrunk based on analysis of the viable range, this is
2930 // a no-op.
2931 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002932 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002933 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002934
2935 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002936 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002937 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002938 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002939 return false;
2940 }
2941 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002942 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002943
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002944 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2945 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002946 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth113dc642014-12-20 02:39:18 +00002947 if (AllocaInst *AI =
2948 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002949 assert(AI != &OldAI && AI != &NewAI &&
2950 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002951 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002952 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002953
Chandler Carruth286d87e2014-02-26 08:25:02 +00002954 Type *OtherPtrTy = OtherPtr->getType();
2955 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2956
Chandler Carruth181ed052014-02-26 05:33:36 +00002957 // Compute the relative offset for the other pointer within the transfer.
Nicola Zaghenf96383c2018-10-30 11:15:04 +00002958 unsigned OffsetWidth = DL.getIndexSizeInBits(OtherAS);
2959 APInt OtherOffset(OffsetWidth, NewBeginOffset - BeginOffset);
Daniel Neilson41e781d2018-03-13 14:25:33 +00002960 unsigned OtherAlign =
2961 IsDest ? II.getSourceAlignment() : II.getDestAlignment();
2962 OtherAlign = MinAlign(OtherAlign ? OtherAlign : 1,
2963 OtherOffset.zextOrTrunc(64).getZExtValue());
Chandler Carruth181ed052014-02-26 05:33:36 +00002964
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002965 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002966 // Compute the other pointer, folding as much as possible to produce
2967 // a single, simple GEP in most cases.
Chandler Carruth181ed052014-02-26 05:33:36 +00002968 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002969 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002970
Chandler Carruth47954c82014-02-26 05:12:43 +00002971 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002972 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002973 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002974
Daniel Neilson41e781d2018-03-13 14:25:33 +00002975 Value *DestPtr, *SrcPtr;
2976 unsigned DestAlign, SrcAlign;
2977 // Note: IsDest is true iff we're copying into the new alloca slice
2978 if (IsDest) {
2979 DestPtr = OurPtr;
2980 DestAlign = SliceAlign;
2981 SrcPtr = OtherPtr;
2982 SrcAlign = OtherAlign;
2983 } else {
2984 DestPtr = OtherPtr;
2985 DestAlign = OtherAlign;
2986 SrcPtr = OurPtr;
2987 SrcAlign = SliceAlign;
2988 }
2989 CallInst *New = IRB.CreateMemCpy(DestPtr, DestAlign, SrcPtr, SrcAlign,
2990 Size, II.isVolatile());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002991 if (AATags)
2992 New->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002993 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002994 return false;
2995 }
2996
Chandler Carruthf0546402013-07-18 07:15:00 +00002997 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2998 NewEndOffset == NewAllocaEndOffset;
2999 uint64_t Size = NewEndOffset - NewBeginOffset;
3000 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
3001 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003002 unsigned NumElements = EndIndex - BeginIndex;
Chandler Carruth113dc642014-12-20 02:39:18 +00003003 IntegerType *SubIntTy =
3004 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003005
Chandler Carruth286d87e2014-02-26 08:25:02 +00003006 // Reset the other pointer type to match the register type we're going to
3007 // use, but using the address space of the original other pointer.
James Y Knight14359ef2019-02-01 20:44:24 +00003008 Type *OtherTy;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003009 if (VecTy && !IsWholeAlloca) {
3010 if (NumElements == 1)
James Y Knight14359ef2019-02-01 20:44:24 +00003011 OtherTy = VecTy->getElementType();
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003012 else
James Y Knight14359ef2019-02-01 20:44:24 +00003013 OtherTy = VectorType::get(VecTy->getElementType(), NumElements);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003014 } else if (IntTy && !IsWholeAlloca) {
James Y Knight14359ef2019-02-01 20:44:24 +00003015 OtherTy = SubIntTy;
Chandler Carruth286d87e2014-02-26 08:25:02 +00003016 } else {
James Y Knight14359ef2019-02-01 20:44:24 +00003017 OtherTy = NewAllocaTy;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003018 }
James Y Knight14359ef2019-02-01 20:44:24 +00003019 OtherPtrTy = OtherTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003020
Chandler Carruth181ed052014-02-26 05:33:36 +00003021 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00003022 OtherPtr->getName() + ".");
Pete Cooper67cf9a72015-11-19 05:56:52 +00003023 unsigned SrcAlign = OtherAlign;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003024 Value *DstPtr = &NewAI;
Chandler Carruthaa72b932014-02-26 07:29:54 +00003025 unsigned DstAlign = SliceAlign;
3026 if (!IsDest) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003027 std::swap(SrcPtr, DstPtr);
Chandler Carruthaa72b932014-02-26 07:29:54 +00003028 std::swap(SrcAlign, DstAlign);
3029 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003030
3031 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003032 if (VecTy && !IsWholeAlloca && !IsDest) {
James Y Knight14359ef2019-02-01 20:44:24 +00003033 Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3034 NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00003035 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00003036 } else if (IntTy && !IsWholeAlloca && !IsDest) {
James Y Knight14359ef2019-02-01 20:44:24 +00003037 Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3038 NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00003039 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00003040 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003041 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003042 } else {
James Y Knight14359ef2019-02-01 20:44:24 +00003043 LoadInst *Load = IRB.CreateAlignedLoad(OtherTy, SrcPtr, SrcAlign,
3044 II.isVolatile(), "copyload");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003045 if (AATags)
3046 Load->setAAMetadata(AATags);
3047 Src = Load;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003048 }
3049
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003050 if (VecTy && !IsWholeAlloca && IsDest) {
James Y Knight14359ef2019-02-01 20:44:24 +00003051 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3052 NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00003053 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003054 } else if (IntTy && !IsWholeAlloca && IsDest) {
James Y Knight14359ef2019-02-01 20:44:24 +00003055 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3056 NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00003057 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00003058 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003059 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
3060 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00003061 }
3062
Chandler Carruth871ba722012-09-26 10:27:46 +00003063 StoreInst *Store = cast<StoreInst>(
Chandler Carruthaa72b932014-02-26 07:29:54 +00003064 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003065 if (AATags)
3066 Store->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003067 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003068 return !II.isVolatile();
3069 }
3070
3071 bool visitIntrinsicInst(IntrinsicInst &II) {
Vedant Kumarb264d692018-12-21 21:49:40 +00003072 assert(II.isLifetimeStartOrEnd());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003073 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003074 assert(II.getArgOperand(1) == OldPtr);
3075
3076 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00003077 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003078
Eli Friedman50967752016-11-28 21:50:34 +00003079 // Lifetime intrinsics are only promotable if they cover the whole alloca.
3080 // Therefore, we drop lifetime intrinsics which don't cover the whole
3081 // alloca.
3082 // (In theory, intrinsics which partially cover an alloca could be
3083 // promoted, but PromoteMemToReg doesn't handle that case.)
3084 // FIXME: Check whether the alloca is promotable before dropping the
3085 // lifetime intrinsics?
David L. Jones6bfdebb2019-10-15 04:32:07 +00003086 if (NewBeginOffset != NewAllocaBeginOffset ||
3087 NewEndOffset != NewAllocaEndOffset)
Eli Friedman50967752016-11-28 21:50:34 +00003088 return true;
3089
Chandler Carruth113dc642014-12-20 02:39:18 +00003090 ConstantInt *Size =
3091 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00003092 NewEndOffset - NewBeginOffset);
Gabor Buella3ec170c2019-01-16 12:06:17 +00003093 // Lifetime intrinsics always expect an i8* so directly get such a pointer
3094 // for the new alloca slice.
3095 Type *PointerTy = IRB.getInt8PtrTy(OldPtr->getType()->getPointerAddressSpace());
3096 Value *Ptr = getNewAllocaSlicePtr(IRB, PointerTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003097 Value *New;
3098 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
3099 New = IRB.CreateLifetimeStart(Ptr, Size);
3100 else
3101 New = IRB.CreateLifetimeEnd(Ptr, Size);
3102
Edwin Vane82f80d42013-01-29 17:42:24 +00003103 (void)New;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003104 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Eli Friedman2a65dd12016-08-08 01:30:53 +00003105
Eli Friedman50967752016-11-28 21:50:34 +00003106 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003107 }
3108
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003109 void fixLoadStoreAlign(Instruction &Root) {
3110 // This algorithm implements the same visitor loop as
3111 // hasUnsafePHIOrSelectUse, and fixes the alignment of each load
3112 // or store found.
3113 SmallPtrSet<Instruction *, 4> Visited;
3114 SmallVector<Instruction *, 4> Uses;
3115 Visited.insert(&Root);
3116 Uses.push_back(&Root);
3117 do {
3118 Instruction *I = Uses.pop_back_val();
3119
3120 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3121 unsigned LoadAlign = LI->getAlignment();
3122 if (!LoadAlign)
3123 LoadAlign = DL.getABITypeAlignment(LI->getType());
Guillaume Chatelet17380222019-09-30 09:37:05 +00003124 LI->setAlignment(MaybeAlign(std::min(LoadAlign, getSliceAlign())));
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003125 continue;
3126 }
3127 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3128 unsigned StoreAlign = SI->getAlignment();
3129 if (!StoreAlign) {
3130 Value *Op = SI->getOperand(0);
3131 StoreAlign = DL.getABITypeAlignment(Op->getType());
3132 }
Guillaume Chateletd400d452019-10-03 13:17:21 +00003133 SI->setAlignment(MaybeAlign(std::min(StoreAlign, getSliceAlign())));
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003134 continue;
3135 }
3136
Matt Arsenault282dac72019-06-14 21:38:31 +00003137 assert(isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I) ||
3138 isa<PHINode>(I) || isa<SelectInst>(I) ||
3139 isa<GetElementPtrInst>(I));
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003140 for (User *U : I->users())
3141 if (Visited.insert(cast<Instruction>(U)).second)
3142 Uses.push_back(cast<Instruction>(U));
3143 } while (!Uses.empty());
3144 }
3145
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003146 bool visitPHINode(PHINode &PN) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003147 LLVM_DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00003148 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
3149 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003150
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003151 // We would like to compute a new pointer in only one place, but have it be
3152 // as local as possible to the PHI. To do that, we re-use the location of
3153 // the old pointer, which necessarily must be in the right position to
3154 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00003155 IRBuilderTy PtrBuilder(IRB);
David Majnemerd4cffcf2014-09-01 21:20:14 +00003156 if (isa<PHINode>(OldPtr))
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003157 PtrBuilder.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
David Majnemerd4cffcf2014-09-01 21:20:14 +00003158 else
3159 PtrBuilder.SetInsertPoint(OldPtr);
Chandler Carruth51175532014-02-25 11:12:04 +00003160 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003161
Chandler Carruth47954c82014-02-26 05:12:43 +00003162 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00003163 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003164 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003165
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003166 LLVM_DEBUG(dbgs() << " to: " << PN << "\n");
Chandler Carruth82a57542012-10-01 10:54:05 +00003167 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003168
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003169 // Fix the alignment of any loads or stores using this PHI node.
3170 fixLoadStoreAlign(PN);
3171
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003172 // PHIs can't be promoted on their own, but often can be speculated. We
3173 // check the speculation outside of the rewriter so that we see the
3174 // fully-rewritten alloca.
3175 PHIUsers.insert(&PN);
3176 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003177 }
3178
3179 bool visitSelectInst(SelectInst &SI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003180 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003181 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
3182 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00003183 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
3184 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003185
Chandler Carruth47954c82014-02-26 05:12:43 +00003186 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003187 // Replace the operands which were using the old pointer.
3188 if (SI.getOperand(1) == OldPtr)
3189 SI.setOperand(1, NewPtr);
3190 if (SI.getOperand(2) == OldPtr)
3191 SI.setOperand(2, NewPtr);
3192
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003193 LLVM_DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003194 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003195
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003196 // Fix the alignment of any loads or stores using this select.
3197 fixLoadStoreAlign(SI);
3198
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003199 // Selects can't be promoted on their own, but often can be speculated. We
3200 // check the speculation outside of the rewriter so that we see the
3201 // fully-rewritten alloca.
3202 SelectUsers.insert(&SI);
3203 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003204 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003205};
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003206
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003207namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003208
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003209/// Visitor to rewrite aggregate loads and stores as scalar.
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003210///
3211/// This pass aggressively rewrites all aggregate loads and stores on
3212/// a particular pointer (or any pointer derived from it which we can identify)
3213/// with scalar loads and stores.
3214class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3215 // Befriend the base class so it can delegate to private visit methods.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003216 friend class InstVisitor<AggLoadStoreRewriter, bool>;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003217
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003218 /// Queue of pointer uses to analyze and potentially rewrite.
3219 SmallVector<Use *, 8> Queue;
3220
3221 /// Set to prevent us from cycling with phi nodes and loops.
3222 SmallPtrSet<User *, 8> Visited;
3223
3224 /// The current pointer use being rewritten. This is used to dig up the used
3225 /// value (as opposed to the user).
3226 Use *U;
3227
Tim Northover856628f2018-12-18 09:29:39 +00003228 /// Used to calculate offsets, and hence alignment, of subobjects.
3229 const DataLayout &DL;
3230
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003231public:
Tim Northover856628f2018-12-18 09:29:39 +00003232 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
3233
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003234 /// Rewrite loads and stores through a pointer and all pointers derived from
3235 /// it.
3236 bool rewrite(Instruction &I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003237 LLVM_DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003238 enqueueUsers(I);
3239 bool Changed = false;
3240 while (!Queue.empty()) {
3241 U = Queue.pop_back_val();
3242 Changed |= visit(cast<Instruction>(U->getUser()));
3243 }
3244 return Changed;
3245 }
3246
3247private:
3248 /// Enqueue all the users of the given instruction for further processing.
3249 /// This uses a set to de-duplicate users.
3250 void enqueueUsers(Instruction &I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003251 for (Use &U : I.uses())
David Blaikie70573dc2014-11-19 07:49:26 +00003252 if (Visited.insert(U.getUser()).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00003253 Queue.push_back(&U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003254 }
3255
3256 // Conservative default is to not rewrite anything.
3257 bool visitInstruction(Instruction &I) { return false; }
3258
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003259 /// Generic recursive split emission class.
Chandler Carruth113dc642014-12-20 02:39:18 +00003260 template <typename Derived> class OpSplitter {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003261 protected:
3262 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00003263 IRBuilderTy IRB;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003264
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003265 /// The indices which to be used with insert- or extractvalue to select the
3266 /// appropriate value within the aggregate.
3267 SmallVector<unsigned, 4> Indices;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003268
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003269 /// The indices to a GEP instruction which will move Ptr to the correct slot
3270 /// within the aggregate.
3271 SmallVector<Value *, 4> GEPIndices;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003272
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003273 /// The base pointer of the original op, used as a base for GEPing the
3274 /// split operations.
3275 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003276
Tim Northover856628f2018-12-18 09:29:39 +00003277 /// The base pointee type being GEPed into.
3278 Type *BaseTy;
3279
3280 /// Known alignment of the base pointer.
3281 unsigned BaseAlign;
3282
3283 /// To calculate offset of each component so we can correctly deduce
3284 /// alignments.
3285 const DataLayout &DL;
3286
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003287 /// Initialize the splitter with an insertion point, Ptr and start with a
3288 /// single zero GEP index.
Tim Northover856628f2018-12-18 09:29:39 +00003289 OpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3290 unsigned BaseAlign, const DataLayout &DL)
3291 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr),
3292 BaseTy(BaseTy), BaseAlign(BaseAlign), DL(DL) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003293
3294 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003295 /// Generic recursive split emission routine.
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003296 ///
3297 /// This method recursively splits an aggregate op (load or store) into
3298 /// scalar or vector ops. It splits recursively until it hits a single value
3299 /// and emits that single value operation via the template argument.
3300 ///
3301 /// The logic of this routine relies on GEPs and insertvalue and
3302 /// extractvalue all operating with the same fundamental index list, merely
3303 /// formatted differently (GEPs need actual values).
3304 ///
3305 /// \param Ty The type being split recursively into smaller ops.
3306 /// \param Agg The aggregate value being built up or stored, depending on
3307 /// whether this is splitting a load or a store respectively.
3308 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
Tim Northover856628f2018-12-18 09:29:39 +00003309 if (Ty->isSingleValueType()) {
3310 unsigned Offset = DL.getIndexedOffsetInType(BaseTy, GEPIndices);
3311 return static_cast<Derived *>(this)->emitFunc(
3312 Ty, Agg, MinAlign(BaseAlign, Offset), Name);
3313 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003314
3315 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3316 unsigned OldSize = Indices.size();
3317 (void)OldSize;
3318 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3319 ++Idx) {
3320 assert(Indices.size() == OldSize && "Did not return to the old size");
3321 Indices.push_back(Idx);
3322 GEPIndices.push_back(IRB.getInt32(Idx));
3323 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3324 GEPIndices.pop_back();
3325 Indices.pop_back();
3326 }
3327 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003328 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003329
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003330 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3331 unsigned OldSize = Indices.size();
3332 (void)OldSize;
3333 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3334 ++Idx) {
3335 assert(Indices.size() == OldSize && "Did not return to the old size");
3336 Indices.push_back(Idx);
3337 GEPIndices.push_back(IRB.getInt32(Idx));
3338 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3339 GEPIndices.pop_back();
3340 Indices.pop_back();
3341 }
3342 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003343 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003344
3345 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003346 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003347 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003348
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003349 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003350 AAMDNodes AATags;
3351
Tim Northover856628f2018-12-18 09:29:39 +00003352 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3353 AAMDNodes AATags, unsigned BaseAlign, const DataLayout &DL)
3354 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
3355 DL), AATags(AATags) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003356
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003357 /// Emit a leaf load of a single value. This is called at the leaves of the
3358 /// recursive emission to actually load values.
Tim Northover856628f2018-12-18 09:29:39 +00003359 void emitFunc(Type *Ty, Value *&Agg, unsigned Align, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003360 assert(Ty->isSingleValueType());
3361 // Load the single value and insert it using the indices.
David Blaikieaa41cd52015-04-03 21:33:42 +00003362 Value *GEP =
James Y Knight77160752019-02-01 20:44:47 +00003363 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
James Y Knight14359ef2019-02-01 20:44:24 +00003364 LoadInst *Load = IRB.CreateAlignedLoad(Ty, GEP, Align, Name + ".load");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003365 if (AATags)
3366 Load->setAAMetadata(AATags);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003367 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003368 LLVM_DEBUG(dbgs() << " to: " << *Load << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003369 }
3370 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003371
3372 bool visitLoadInst(LoadInst &LI) {
3373 assert(LI.getPointerOperand() == *U);
3374 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3375 return false;
3376
3377 // We have an aggregate being loaded, split it apart.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003378 LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003379 AAMDNodes AATags;
3380 LI.getAAMetadata(AATags);
Tim Northover856628f2018-12-18 09:29:39 +00003381 LoadOpSplitter Splitter(&LI, *U, LI.getType(), AATags,
3382 getAdjustedAlignment(&LI, 0, DL), DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003383 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003384 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003385 LI.replaceAllUsesWith(V);
3386 LI.eraseFromParent();
3387 return true;
3388 }
3389
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003390 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Tim Northover856628f2018-12-18 09:29:39 +00003391 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3392 AAMDNodes AATags, unsigned BaseAlign, const DataLayout &DL)
3393 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
3394 DL),
3395 AATags(AATags) {}
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003396 AAMDNodes AATags;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003397 /// Emit a leaf store of a single value. This is called at the leaves of the
3398 /// recursive emission to actually produce stores.
Tim Northover856628f2018-12-18 09:29:39 +00003399 void emitFunc(Type *Ty, Value *&Agg, unsigned Align, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003400 assert(Ty->isSingleValueType());
3401 // Extract the single value and store it using the indices.
Patrik Hagglunda83706e2016-06-20 10:19:00 +00003402 //
3403 // The gep and extractvalue values are factored out of the CreateStore
3404 // call to make the output independent of the argument evaluation order.
Patrik Hagglund4e0bd842016-06-20 11:19:58 +00003405 Value *ExtractValue =
3406 IRB.CreateExtractValue(Agg, Indices, Name + ".extract");
3407 Value *InBoundsGEP =
James Y Knight77160752019-02-01 20:44:47 +00003408 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
Tim Northover856628f2018-12-18 09:29:39 +00003409 StoreInst *Store =
3410 IRB.CreateAlignedStore(ExtractValue, InBoundsGEP, Align);
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003411 if (AATags)
3412 Store->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003413 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003414 }
3415 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003416
3417 bool visitStoreInst(StoreInst &SI) {
3418 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3419 return false;
3420 Value *V = SI.getValueOperand();
3421 if (V->getType()->isSingleValueType())
3422 return false;
3423
3424 // We have an aggregate being stored, split it apart.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003425 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003426 AAMDNodes AATags;
3427 SI.getAAMetadata(AATags);
Tim Northover856628f2018-12-18 09:29:39 +00003428 StoreOpSplitter Splitter(&SI, *U, V->getType(), AATags,
3429 getAdjustedAlignment(&SI, 0, DL), DL);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003430 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003431 SI.eraseFromParent();
3432 return true;
3433 }
3434
3435 bool visitBitCastInst(BitCastInst &BC) {
3436 enqueueUsers(BC);
3437 return false;
3438 }
3439
Matt Arsenault282dac72019-06-14 21:38:31 +00003440 bool visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
3441 enqueueUsers(ASC);
3442 return false;
3443 }
3444
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003445 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3446 enqueueUsers(GEPI);
3447 return false;
3448 }
3449
3450 bool visitPHINode(PHINode &PN) {
3451 enqueueUsers(PN);
3452 return false;
3453 }
3454
3455 bool visitSelectInst(SelectInst &SI) {
3456 enqueueUsers(SI);
3457 return false;
3458 }
3459};
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003460
3461} // end anonymous namespace
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003462
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003463/// Strip aggregate type wrapping.
Chandler Carruthba931992012-10-13 10:49:33 +00003464///
3465/// This removes no-op aggregate types wrapping an underlying type. It will
3466/// strip as many layers of types as it can without changing either the type
3467/// size or the allocated size.
3468static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3469 if (Ty->isSingleValueType())
3470 return Ty;
3471
3472 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3473 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3474
3475 Type *InnerTy;
3476 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3477 InnerTy = ArrTy->getElementType();
3478 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3479 const StructLayout *SL = DL.getStructLayout(STy);
3480 unsigned Index = SL->getElementContainingOffset(0);
3481 InnerTy = STy->getElementType(Index);
3482 } else {
3483 return Ty;
3484 }
3485
3486 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3487 TypeSize > DL.getTypeSizeInBits(InnerTy))
3488 return Ty;
3489
3490 return stripAggregateTypeWrapping(DL, InnerTy);
3491}
3492
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003493/// Try to find a partition of the aggregate type passed in for a given
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003494/// offset and size.
3495///
3496/// This recurses through the aggregate type and tries to compute a subtype
3497/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003498/// of an array, it will even compute a new array type for that sub-section,
3499/// and the same for structs.
3500///
3501/// Note that this routine is very strict and tries to find a partition of the
3502/// type which produces the *exact* right offset and size. It is not forgiving
3503/// when the size or offset cause either end of type-based partition to be off.
3504/// Also, this is a best-effort routine. It is reasonable to give up and not
3505/// return a type if necessary.
Chandler Carruth113dc642014-12-20 02:39:18 +00003506static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3507 uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00003508 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3509 return stripAggregateTypeWrapping(DL, Ty);
3510 if (Offset > DL.getTypeAllocSize(Ty) ||
3511 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003512 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003513
3514 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003515 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003516 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003517 uint64_t NumSkippedElements = Offset / ElementSize;
Peter Collingbournebc070522016-12-02 03:20:58 +00003518 if (NumSkippedElements >= SeqTy->getNumElements())
3519 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003520 Offset -= NumSkippedElements * ElementSize;
3521
3522 // First check if we need to recurse.
3523 if (Offset > 0 || Size < ElementSize) {
3524 // Bail if the partition ends in a different array element.
3525 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003526 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003527 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003528 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003529 }
3530 assert(Offset == 0);
3531
3532 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003533 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003534 assert(Size > ElementSize);
3535 uint64_t NumElements = Size / ElementSize;
3536 if (NumElements * ElementSize != Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003537 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003538 return ArrayType::get(ElementTy, NumElements);
3539 }
3540
3541 StructType *STy = dyn_cast<StructType>(Ty);
3542 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00003543 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003544
Chandler Carruth90a735d2013-07-19 07:21:28 +00003545 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003546 if (Offset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003547 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003548 uint64_t EndOffset = Offset + Size;
3549 if (EndOffset > SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003550 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003551
3552 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003553 Offset -= SL->getElementOffset(Index);
3554
3555 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003556 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003557 if (Offset >= ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003558 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003559
3560 // See if any partition must be contained by the element.
3561 if (Offset > 0 || Size < ElementSize) {
3562 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003563 return nullptr;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003564 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003565 }
3566 assert(Offset == 0);
3567
3568 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003569 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003570
3571 StructType::element_iterator EI = STy->element_begin() + Index,
3572 EE = STy->element_end();
3573 if (EndOffset < SL->getSizeInBytes()) {
3574 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3575 if (Index == EndIndex)
Craig Topperf40110f2014-04-25 05:29:35 +00003576 return nullptr; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003577
3578 // Don't try to form "natural" types if the elements don't line up with the
3579 // expected size.
3580 // FIXME: We could potentially recurse down through the last element in the
3581 // sub-struct to find a natural end point.
3582 if (SL->getElementOffset(EndIndex) != EndOffset)
Craig Topperf40110f2014-04-25 05:29:35 +00003583 return nullptr;
Chandler Carruth054a40a2012-09-14 11:08:31 +00003584
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003585 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003586 EE = STy->element_begin() + EndIndex;
3587 }
3588
3589 // Try to build up a sub-structure.
Chandler Carruth113dc642014-12-20 02:39:18 +00003590 StructType *SubTy =
3591 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003592 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003593 if (Size != SubSL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003594 return nullptr; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003595
Chandler Carruth054a40a2012-09-14 11:08:31 +00003596 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003597}
3598
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003599/// Pre-split loads and stores to simplify rewriting.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003600///
3601/// We want to break up the splittable load+store pairs as much as
3602/// possible. This is important to do as a preprocessing step, as once we
3603/// start rewriting the accesses to partitions of the alloca we lose the
3604/// necessary information to correctly split apart paired loads and stores
3605/// which both point into this alloca. The case to consider is something like
3606/// the following:
3607///
3608/// %a = alloca [12 x i8]
3609/// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3610/// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3611/// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3612/// %iptr1 = bitcast i8* %gep1 to i64*
3613/// %iptr2 = bitcast i8* %gep2 to i64*
3614/// %fptr1 = bitcast i8* %gep1 to float*
3615/// %fptr2 = bitcast i8* %gep2 to float*
3616/// %fptr3 = bitcast i8* %gep3 to float*
3617/// store float 0.0, float* %fptr1
3618/// store float 1.0, float* %fptr2
3619/// %v = load i64* %iptr1
3620/// store i64 %v, i64* %iptr2
3621/// %f1 = load float* %fptr2
3622/// %f2 = load float* %fptr3
3623///
3624/// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3625/// promote everything so we recover the 2 SSA values that should have been
3626/// there all along.
3627///
3628/// \returns true if any changes are made.
3629bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003630 LLVM_DEBUG(dbgs() << "Pre-splitting loads and stores\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003631
3632 // Track the loads and stores which are candidates for pre-splitting here, in
3633 // the order they first appear during the partition scan. These give stable
3634 // iteration order and a basis for tracking which loads and stores we
3635 // actually split.
3636 SmallVector<LoadInst *, 4> Loads;
3637 SmallVector<StoreInst *, 4> Stores;
3638
3639 // We need to accumulate the splits required of each load or store where we
3640 // can find them via a direct lookup. This is important to cross-check loads
3641 // and stores against each other. We also track the slice so that we can kill
3642 // all the slices that end up split.
3643 struct SplitOffsets {
3644 Slice *S;
3645 std::vector<uint64_t> Splits;
3646 };
3647 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3648
Chandler Carruth73b01642015-01-05 04:17:53 +00003649 // Track loads out of this alloca which cannot, for any reason, be pre-split.
3650 // This is important as we also cannot pre-split stores of those loads!
3651 // FIXME: This is all pretty gross. It means that we can be more aggressive
3652 // in pre-splitting when the load feeding the store happens to come from
3653 // a separate alloca. Put another way, the effectiveness of SROA would be
3654 // decreased by a frontend which just concatenated all of its local allocas
3655 // into one big flat alloca. But defeating such patterns is exactly the job
3656 // SROA is tasked with! Sadly, to not have this discrepancy we would have
3657 // change store pre-splitting to actually force pre-splitting of the load
3658 // that feeds it *and all stores*. That makes pre-splitting much harder, but
3659 // maybe it would make it more principled?
3660 SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
3661
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003662 LLVM_DEBUG(dbgs() << " Searching for candidate loads and stores\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003663 for (auto &P : AS.partitions()) {
3664 for (Slice &S : P) {
Chandler Carruth73b01642015-01-05 04:17:53 +00003665 Instruction *I = cast<Instruction>(S.getUse()->getUser());
Chandler Carruth37f1f122016-03-10 15:31:17 +00003666 if (!S.isSplittable() || S.endOffset() <= P.endOffset()) {
3667 // If this is a load we have to track that it can't participate in any
3668 // pre-splitting. If this is a store of a load we have to track that
3669 // that load also can't participate in any pre-splitting.
Chandler Carruth73b01642015-01-05 04:17:53 +00003670 if (auto *LI = dyn_cast<LoadInst>(I))
3671 UnsplittableLoads.insert(LI);
Chandler Carruth37f1f122016-03-10 15:31:17 +00003672 else if (auto *SI = dyn_cast<StoreInst>(I))
3673 if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
3674 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003675 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003676 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003677 assert(P.endOffset() > S.beginOffset() &&
3678 "Empty or backwards partition!");
3679
3680 // Determine if this is a pre-splittable slice.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003681 if (auto *LI = dyn_cast<LoadInst>(I)) {
3682 assert(!LI->isVolatile() && "Cannot split volatile loads!");
3683
3684 // The load must be used exclusively to store into other pointers for
3685 // us to be able to arbitrarily pre-split it. The stores must also be
3686 // simple to avoid changing semantics.
3687 auto IsLoadSimplyStored = [](LoadInst *LI) {
3688 for (User *LU : LI->users()) {
3689 auto *SI = dyn_cast<StoreInst>(LU);
3690 if (!SI || !SI->isSimple())
3691 return false;
3692 }
3693 return true;
3694 };
Chandler Carruth73b01642015-01-05 04:17:53 +00003695 if (!IsLoadSimplyStored(LI)) {
3696 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003697 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003698 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003699
3700 Loads.push_back(LI);
Chandler Carruthd94a5962016-03-10 14:16:18 +00003701 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
3702 if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3703 // Skip stores *of* pointers. FIXME: This shouldn't even be possible!
Chandler Carruth994cde82015-01-01 12:01:03 +00003704 continue;
3705 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3706 if (!StoredLoad || !StoredLoad->isSimple())
3707 continue;
3708 assert(!SI->isVolatile() && "Cannot split volatile stores!");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003709
Chandler Carruth994cde82015-01-01 12:01:03 +00003710 Stores.push_back(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003711 } else {
3712 // Other uses cannot be pre-split.
3713 continue;
3714 }
3715
3716 // Record the initial split.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003717 LLVM_DEBUG(dbgs() << " Candidate: " << *I << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003718 auto &Offsets = SplitOffsetsMap[I];
3719 assert(Offsets.Splits.empty() &&
3720 "Should not have splits the first time we see an instruction!");
3721 Offsets.S = &S;
Chandler Carruth24ac8302015-01-02 03:55:54 +00003722 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003723 }
3724
3725 // Now scan the already split slices, and add a split for any of them which
3726 // we're going to pre-split.
3727 for (Slice *S : P.splitSliceTails()) {
3728 auto SplitOffsetsMapI =
3729 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3730 if (SplitOffsetsMapI == SplitOffsetsMap.end())
3731 continue;
3732 auto &Offsets = SplitOffsetsMapI->second;
3733
3734 assert(Offsets.S == S && "Found a mismatched slice!");
3735 assert(!Offsets.Splits.empty() &&
3736 "Cannot have an empty set of splits on the second partition!");
Chandler Carruth24ac8302015-01-02 03:55:54 +00003737 assert(Offsets.Splits.back() ==
3738 P.beginOffset() - Offsets.S->beginOffset() &&
Chandler Carruth0715cba2015-01-01 11:54:38 +00003739 "Previous split does not end where this one begins!");
3740
3741 // Record each split. The last partition's end isn't needed as the size
3742 // of the slice dictates that.
3743 if (S->endOffset() > P.endOffset())
Chandler Carruth24ac8302015-01-02 03:55:54 +00003744 Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003745 }
3746 }
3747
3748 // We may have split loads where some of their stores are split stores. For
3749 // such loads and stores, we can only pre-split them if their splits exactly
3750 // match relative to their starting offset. We have to verify this prior to
3751 // any rewriting.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003752 Stores.erase(
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003753 llvm::remove_if(Stores,
3754 [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
3755 // Lookup the load we are storing in our map of split
3756 // offsets.
3757 auto *LI = cast<LoadInst>(SI->getValueOperand());
3758 // If it was completely unsplittable, then we're done,
3759 // and this store can't be pre-split.
3760 if (UnsplittableLoads.count(LI))
3761 return true;
Chandler Carruth73b01642015-01-05 04:17:53 +00003762
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003763 auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3764 if (LoadOffsetsI == SplitOffsetsMap.end())
3765 return false; // Unrelated loads are definitely safe.
3766 auto &LoadOffsets = LoadOffsetsI->second;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003767
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003768 // Now lookup the store's offsets.
3769 auto &StoreOffsets = SplitOffsetsMap[SI];
Chandler Carruth0715cba2015-01-01 11:54:38 +00003770
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003771 // If the relative offsets of each split in the load and
3772 // store match exactly, then we can split them and we
3773 // don't need to remove them here.
3774 if (LoadOffsets.Splits == StoreOffsets.Splits)
3775 return false;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003776
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003777 LLVM_DEBUG(
3778 dbgs()
3779 << " Mismatched splits for load and store:\n"
3780 << " " << *LI << "\n"
3781 << " " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003782
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003783 // We've found a store and load that we need to split
3784 // with mismatched relative splits. Just give up on them
3785 // and remove both instructions from our list of
3786 // candidates.
3787 UnsplittableLoads.insert(LI);
3788 return true;
3789 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003790 Stores.end());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003791 // Now we have to go *back* through all the stores, because a later store may
Chandler Carruth73b01642015-01-05 04:17:53 +00003792 // have caused an earlier store's load to become unsplittable and if it is
3793 // unsplittable for the later store, then we can't rely on it being split in
3794 // the earlier store either.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003795 Stores.erase(llvm::remove_if(Stores,
3796 [&UnsplittableLoads](StoreInst *SI) {
3797 auto *LI =
3798 cast<LoadInst>(SI->getValueOperand());
3799 return UnsplittableLoads.count(LI);
3800 }),
Chandler Carruth73b01642015-01-05 04:17:53 +00003801 Stores.end());
3802 // Once we've established all the loads that can't be split for some reason,
3803 // filter any that made it into our list out.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003804 Loads.erase(llvm::remove_if(Loads,
3805 [&UnsplittableLoads](LoadInst *LI) {
3806 return UnsplittableLoads.count(LI);
3807 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003808 Loads.end());
3809
3810 // If no loads or stores are left, there is no pre-splitting to be done for
3811 // this alloca.
3812 if (Loads.empty() && Stores.empty())
3813 return false;
3814
3815 // From here on, we can't fail and will be building new accesses, so rig up
3816 // an IR builder.
3817 IRBuilderTy IRB(&AI);
3818
3819 // Collect the new slices which we will merge into the alloca slices.
3820 SmallVector<Slice, 4> NewSlices;
3821
3822 // Track any allocas we end up splitting loads and stores for so we iterate
3823 // on them.
3824 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3825
3826 // At this point, we have collected all of the loads and stores we can
3827 // pre-split, and the specific splits needed for them. We actually do the
3828 // splitting in a specific order in order to handle when one of the loads in
3829 // the value operand to one of the stores.
3830 //
3831 // First, we rewrite all of the split loads, and just accumulate each split
3832 // load in a parallel structure. We also build the slices for them and append
3833 // them to the alloca slices.
3834 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3835 std::vector<LoadInst *> SplitLoads;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003836 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003837 for (LoadInst *LI : Loads) {
3838 SplitLoads.clear();
3839
3840 IntegerType *Ty = cast<IntegerType>(LI->getType());
3841 uint64_t LoadSize = Ty->getBitWidth() / 8;
3842 assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
3843
3844 auto &Offsets = SplitOffsetsMap[LI];
3845 assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3846 "Slice size should always match load size exactly!");
3847 uint64_t BaseOffset = Offsets.S->beginOffset();
3848 assert(BaseOffset + LoadSize > BaseOffset &&
3849 "Cannot represent alloca access size using 64-bit integers!");
3850
3851 Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003852 IRB.SetInsertPoint(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003853
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003854 LLVM_DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003855
3856 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3857 int Idx = 0, Size = Offsets.Splits.size();
3858 for (;;) {
3859 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
Yaxun Liu7c44f342017-06-27 18:26:06 +00003860 auto AS = LI->getPointerAddressSpace();
3861 auto *PartPtrTy = PartTy->getPointerTo(AS);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003862 LoadInst *PLoad = IRB.CreateAlignedLoad(
James Y Knight14359ef2019-02-01 20:44:24 +00003863 PartTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003864 getAdjustedPtr(IRB, DL, BasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003865 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Chandler Carruth994cde82015-01-01 12:01:03 +00003866 PartPtrTy, BasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003867 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003868 LI->getName());
Michael Kruse978ba612018-12-20 04:58:07 +00003869 PLoad->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
3870 LLVMContext::MD_access_group});
Chandler Carruth0715cba2015-01-01 11:54:38 +00003871
3872 // Append this load onto the list of split loads so we can find it later
3873 // to rewrite the stores.
3874 SplitLoads.push_back(PLoad);
3875
3876 // Now build a new slice for the alloca.
Chandler Carruth994cde82015-01-01 12:01:03 +00003877 NewSlices.push_back(
3878 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3879 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003880 /*IsSplittable*/ false));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003881 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3882 << ", " << NewSlices.back().endOffset()
3883 << "): " << *PLoad << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003884
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003885 // See if we've handled all the splits.
3886 if (Idx >= Size)
3887 break;
3888
Chandler Carruth0715cba2015-01-01 11:54:38 +00003889 // Setup the next partition.
3890 PartOffset = Offsets.Splits[Idx];
3891 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003892 PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
3893 }
3894
3895 // Now that we have the split loads, do the slow walk over all uses of the
3896 // load and rewrite them as split stores, or save the split loads to use
3897 // below if the store is going to be split there anyways.
3898 bool DeferredStores = false;
3899 for (User *LU : LI->users()) {
3900 StoreInst *SI = cast<StoreInst>(LU);
3901 if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
3902 DeferredStores = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003903 LLVM_DEBUG(dbgs() << " Deferred splitting of store: " << *SI
3904 << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003905 continue;
3906 }
3907
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003908 Value *StoreBasePtr = SI->getPointerOperand();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003909 IRB.SetInsertPoint(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003910
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003911 LLVM_DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003912
3913 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
3914 LoadInst *PLoad = SplitLoads[Idx];
3915 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
Chandler Carruth994cde82015-01-01 12:01:03 +00003916 auto *PartPtrTy =
3917 PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003918
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003919 auto AS = SI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003920 StoreInst *PStore = IRB.CreateAlignedStore(
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003921 PLoad,
3922 getAdjustedPtr(IRB, DL, StoreBasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003923 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003924 PartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003925 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Michael Kruse978ba612018-12-20 04:58:07 +00003926 PStore->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
3927 LLVMContext::MD_access_group});
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003928 LLVM_DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003929 }
3930
3931 // We want to immediately iterate on any allocas impacted by splitting
3932 // this store, and we have to track any promotable alloca (indicated by
3933 // a direct store) as needing to be resplit because it is no longer
3934 // promotable.
3935 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3936 ResplitPromotableAllocas.insert(OtherAI);
3937 Worklist.insert(OtherAI);
3938 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3939 StoreBasePtr->stripInBoundsOffsets())) {
3940 Worklist.insert(OtherAI);
3941 }
3942
3943 // Mark the original store as dead.
3944 DeadInsts.insert(SI);
3945 }
3946
3947 // Save the split loads if there are deferred stores among the users.
3948 if (DeferredStores)
3949 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
3950
3951 // Mark the original load as dead and kill the original slice.
3952 DeadInsts.insert(LI);
3953 Offsets.S->kill();
3954 }
3955
3956 // Second, we rewrite all of the split stores. At this point, we know that
3957 // all loads from this alloca have been split already. For stores of such
3958 // loads, we can simply look up the pre-existing split loads. For stores of
3959 // other loads, we split those loads first and then write split stores of
3960 // them.
3961 for (StoreInst *SI : Stores) {
3962 auto *LI = cast<LoadInst>(SI->getValueOperand());
3963 IntegerType *Ty = cast<IntegerType>(LI->getType());
3964 uint64_t StoreSize = Ty->getBitWidth() / 8;
3965 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
3966
3967 auto &Offsets = SplitOffsetsMap[SI];
3968 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3969 "Slice size should always match load size exactly!");
3970 uint64_t BaseOffset = Offsets.S->beginOffset();
3971 assert(BaseOffset + StoreSize > BaseOffset &&
3972 "Cannot represent alloca access size using 64-bit integers!");
3973
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003974 Value *LoadBasePtr = LI->getPointerOperand();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003975 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
3976
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003977 LLVM_DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003978
3979 // Check whether we have an already split load.
3980 auto SplitLoadsMapI = SplitLoadsMap.find(LI);
3981 std::vector<LoadInst *> *SplitLoads = nullptr;
3982 if (SplitLoadsMapI != SplitLoadsMap.end()) {
3983 SplitLoads = &SplitLoadsMapI->second;
3984 assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
3985 "Too few split loads for the number of splits in the store!");
3986 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003987 LLVM_DEBUG(dbgs() << " of load: " << *LI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003988 }
3989
Chandler Carruth0715cba2015-01-01 11:54:38 +00003990 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3991 int Idx = 0, Size = Offsets.Splits.size();
3992 for (;;) {
3993 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
Keno Fischer514a6a52017-06-02 19:04:17 +00003994 auto *LoadPartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
3995 auto *StorePartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003996
3997 // Either lookup a split load or create one.
3998 LoadInst *PLoad;
3999 if (SplitLoads) {
4000 PLoad = (*SplitLoads)[Idx];
4001 } else {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00004002 IRB.SetInsertPoint(LI);
Yaxun Liu6455b0d2017-06-09 20:46:29 +00004003 auto AS = LI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00004004 PLoad = IRB.CreateAlignedLoad(
James Y Knight14359ef2019-02-01 20:44:24 +00004005 PartTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004006 getAdjustedPtr(IRB, DL, LoadBasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00004007 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Keno Fischer514a6a52017-06-02 19:04:17 +00004008 LoadPartPtrTy, LoadBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004009 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00004010 LI->getName());
4011 }
4012
4013 // And store this partition.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00004014 IRB.SetInsertPoint(SI);
Yaxun Liu6455b0d2017-06-09 20:46:29 +00004015 auto AS = SI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00004016 StoreInst *PStore = IRB.CreateAlignedStore(
Yaxun Liu6455b0d2017-06-09 20:46:29 +00004017 PLoad,
4018 getAdjustedPtr(IRB, DL, StoreBasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00004019 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Yaxun Liu6455b0d2017-06-09 20:46:29 +00004020 StorePartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004021 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Chandler Carruth0715cba2015-01-01 11:54:38 +00004022
4023 // Now build a new slice for the alloca.
4024 NewSlices.push_back(
4025 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
4026 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00004027 /*IsSplittable*/ false));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004028 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
4029 << ", " << NewSlices.back().endOffset()
4030 << "): " << *PStore << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00004031 if (!SplitLoads) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004032 LLVM_DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00004033 }
4034
Chandler Carruth29c22fa2015-01-02 00:10:22 +00004035 // See if we've finished all the splits.
4036 if (Idx >= Size)
4037 break;
4038
Chandler Carruth0715cba2015-01-01 11:54:38 +00004039 // Setup the next partition.
4040 PartOffset = Offsets.Splits[Idx];
4041 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00004042 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
4043 }
4044
4045 // We want to immediately iterate on any allocas impacted by splitting
4046 // this load, which is only relevant if it isn't a load of this alloca and
4047 // thus we didn't already split the loads above. We also have to keep track
4048 // of any promotable allocas we split loads on as they can no longer be
4049 // promoted.
4050 if (!SplitLoads) {
4051 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
4052 assert(OtherAI != &AI && "We can't re-split our own alloca!");
4053 ResplitPromotableAllocas.insert(OtherAI);
4054 Worklist.insert(OtherAI);
4055 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
4056 LoadBasePtr->stripInBoundsOffsets())) {
4057 assert(OtherAI != &AI && "We can't re-split our own alloca!");
4058 Worklist.insert(OtherAI);
4059 }
4060 }
4061
4062 // Mark the original store as dead now that we've split it up and kill its
Chandler Carruth24ac8302015-01-02 03:55:54 +00004063 // slice. Note that we leave the original load in place unless this store
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004064 // was its only use. It may in turn be split up if it is an alloca load
Chandler Carruth24ac8302015-01-02 03:55:54 +00004065 // for some other alloca, but it may be a normal load. This may introduce
4066 // redundant loads, but where those can be merged the rest of the optimizer
4067 // should handle the merging, and this uncovers SSA splits which is more
4068 // important. In practice, the original loads will almost always be fully
4069 // split and removed eventually, and the splits will be merged by any
4070 // trivial CSE, including instcombine.
4071 if (LI->hasOneUse()) {
4072 assert(*LI->user_begin() == SI && "Single use isn't this store!");
4073 DeadInsts.insert(LI);
4074 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00004075 DeadInsts.insert(SI);
4076 Offsets.S->kill();
4077 }
4078
Chandler Carruth24ac8302015-01-02 03:55:54 +00004079 // Remove the killed slices that have ben pre-split.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004080 AS.erase(llvm::remove_if(AS, [](const Slice &S) { return S.isDead(); }),
4081 AS.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +00004082
Chandler Carruth24ac8302015-01-02 03:55:54 +00004083 // Insert our new slices. This will sort and merge them into the sorted
4084 // sequence.
Chandler Carruth0715cba2015-01-01 11:54:38 +00004085 AS.insert(NewSlices);
4086
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004087 LLVM_DEBUG(dbgs() << " Pre-split slices:\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00004088#ifndef NDEBUG
4089 for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004090 LLVM_DEBUG(AS.print(dbgs(), I, " "));
Chandler Carruth0715cba2015-01-01 11:54:38 +00004091#endif
4092
4093 // Finally, don't try to promote any allocas that new require re-splitting.
4094 // They have already been added to the worklist above.
4095 PromotableAllocas.erase(
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004096 llvm::remove_if(
David Majnemerc7004902016-08-12 04:32:37 +00004097 PromotableAllocas,
Chandler Carruth0715cba2015-01-01 11:54:38 +00004098 [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
4099 PromotableAllocas.end());
4100
4101 return true;
4102}
4103
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004104/// Rewrite an alloca partition's users.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004105///
4106/// This routine drives both of the rewriting goals of the SROA pass. It tries
4107/// to rewrite uses of an alloca partition to be conducive for SSA value
4108/// promotion. If the partition needs a new, more refined alloca, this will
4109/// build that new alloca, preserving as much type information as possible, and
4110/// rewrite the uses of the old alloca to point at the new one and have the
4111/// appropriate new offsets. It also evaluates how successful the rewrite was
4112/// at enabling promotion and if it was successful queues the alloca to be
4113/// promoted.
Adrian Prantl565cc182015-01-20 19:42:22 +00004114AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
Chandler Carruth29a18a42015-09-12 09:09:14 +00004115 Partition &P) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004116 // Try to compute a friendly type for this partition of the alloca. This
4117 // won't always succeed, in which case we fall back to a legal integer type
4118 // or an i8 array of an appropriate size.
Craig Topperf40110f2014-04-25 05:29:35 +00004119 Type *SliceTy = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004120 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004121 if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004122 if (DL.getTypeAllocSize(CommonUseTy) >= P.size())
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004123 SliceTy = CommonUseTy;
4124 if (!SliceTy)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004125 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004126 P.beginOffset(), P.size()))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004127 SliceTy = TypePartitionTy;
4128 if ((!SliceTy || (SliceTy->isArrayTy() &&
4129 SliceTy->getArrayElementType()->isIntegerTy())) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004130 DL.isLegalInteger(P.size() * 8))
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004131 SliceTy = Type::getIntNTy(*C, P.size() * 8);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004132 if (!SliceTy)
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004133 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004134 assert(DL.getTypeAllocSize(SliceTy) >= P.size());
Chandler Carruthf0546402013-07-18 07:15:00 +00004135
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004136 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
Chandler Carruthf0546402013-07-18 07:15:00 +00004137
Chandler Carruth2dc96822014-10-18 00:44:02 +00004138 VectorType *VecTy =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004139 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
Chandler Carruth2dc96822014-10-18 00:44:02 +00004140 if (VecTy)
4141 SliceTy = VecTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004142
4143 // Check for the case where we're going to rewrite to a new alloca of the
4144 // exact same type as the original, and with the same access offsets. In that
4145 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00004146 // perform phi and select speculation.
Hiroshi Inoue99a8faa2018-01-16 06:23:05 +00004147 // P.beginOffset() can be non-zero even with the same type in a case with
4148 // out-of-bounds access (e.g. @PR35657 function in SROA/basictest.ll).
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004149 AllocaInst *NewAI;
Hiroshi Inoue99a8faa2018-01-16 06:23:05 +00004150 if (SliceTy == AI.getAllocatedType() && P.beginOffset() == 0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004151 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00004152 // FIXME: We should be able to bail at this point with "nothing changed".
4153 // FIXME: We might want to defer PHI speculation until after here.
Adrian Prantl565cc182015-01-20 19:42:22 +00004154 // FIXME: return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004155 } else {
Guillaume Chatelete8a0a092019-10-25 22:26:23 +02004156 // If alignment is unspecified we fallback on the one required by the ABI
4157 // for this type. We also make sure the alignment is compatible with
4158 // P.beginOffset().
4159 const Align Alignment = commonAlignment(
4160 DL.getValueOrABITypeAlignment(MaybeAlign(AI.getAlignment()),
4161 AI.getAllocatedType()),
4162 P.beginOffset());
Chandler Carruth903790e2012-09-29 10:41:21 +00004163 // If we will get at least this much alignment from the type alone, leave
4164 // the alloca's alignment unconstrained.
Guillaume Chatelete8a0a092019-10-25 22:26:23 +02004165 const bool IsUnconstrained = Alignment <= DL.getABITypeAlignment(SliceTy);
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004166 NewAI = new AllocaInst(
Guillaume Chatelete8a0a092019-10-25 22:26:23 +02004167 SliceTy, AI.getType()->getAddressSpace(), nullptr,
4168 IsUnconstrained ? MaybeAlign() : Alignment,
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004169 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
Anastasis Grammenos425df222018-06-28 18:58:30 +00004170 // Copy the old AI debug location over to the new one.
4171 NewAI->setDebugLoc(AI.getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004172 ++NumNewAllocas;
4173 }
4174
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004175 LLVM_DEBUG(dbgs() << "Rewriting alloca partition "
4176 << "[" << P.beginOffset() << "," << P.endOffset()
4177 << ") to: " << *NewAI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004178
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004179 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00004180 // promoted allocas. We will reset it to this point if the alloca is not in
4181 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00004182 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00004183 unsigned NumUses = 0;
Davide Italiano81a26da2017-04-27 23:09:01 +00004184 SmallSetVector<PHINode *, 8> PHIUsers;
4185 SmallSetVector<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00004186
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004187 AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004188 P.endOffset(), IsIntegerPromotable, VecTy,
4189 PHIUsers, SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00004190 bool Promotable = true;
Chandler Carruthffb7ce52014-12-24 01:48:09 +00004191 for (Slice *S : P.splitSliceTails()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004192 Promotable &= Rewriter.visit(S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004193 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00004194 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004195 for (Slice &S : P) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004196 Promotable &= Rewriter.visit(&S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004197 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00004198 }
4199
Chandler Carruth6c321c12013-07-19 10:57:36 +00004200 NumAllocaPartitionUses += NumUses;
Craig Topper8a950272017-05-18 00:51:39 +00004201 MaxUsesPerAllocaPartition.updateMax(NumUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004202
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004203 // Now that we've processed all the slices in the new partition, check if any
4204 // PHIs or Selects would block promotion.
Davide Italiano81a26da2017-04-27 23:09:01 +00004205 for (PHINode *PHI : PHIUsers)
4206 if (!isSafePHIToSpeculate(*PHI)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004207 Promotable = false;
4208 PHIUsers.clear();
4209 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00004210 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004211 }
Davide Italiano81a26da2017-04-27 23:09:01 +00004212
4213 for (SelectInst *Sel : SelectUsers)
4214 if (!isSafeSelectToSpeculate(*Sel)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004215 Promotable = false;
4216 PHIUsers.clear();
4217 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00004218 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004219 }
4220
4221 if (Promotable) {
4222 if (PHIUsers.empty() && SelectUsers.empty()) {
4223 // Promote the alloca.
4224 PromotableAllocas.push_back(NewAI);
4225 } else {
4226 // If we have either PHIs or Selects to speculate, add them to those
4227 // worklists and re-queue the new alloca so that we promote in on the
4228 // next iteration.
Chandler Carruth61747042014-10-16 21:05:14 +00004229 for (PHINode *PHIUser : PHIUsers)
4230 SpeculatablePHIs.insert(PHIUser);
4231 for (SelectInst *SelectUser : SelectUsers)
4232 SpeculatableSelects.insert(SelectUser);
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004233 Worklist.insert(NewAI);
4234 }
4235 } else {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004236 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00004237 while (PostPromotionWorklist.size() > PPWOldSize)
4238 PostPromotionWorklist.pop_back();
David Majnemer30ffc4c2016-04-26 01:05:00 +00004239
4240 // We couldn't promote and we didn't create a new partition, nothing
4241 // happened.
4242 if (NewAI == &AI)
4243 return nullptr;
4244
4245 // If we can't promote the alloca, iterate on it to check for new
4246 // refinements exposed by splitting the current alloca. Don't iterate on an
4247 // alloca which didn't actually change and didn't get promoted.
4248 Worklist.insert(NewAI);
Chandler Carruthf0546402013-07-18 07:15:00 +00004249 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00004250
Adrian Prantl565cc182015-01-20 19:42:22 +00004251 return NewAI;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004252}
4253
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004254/// Walks the slices of an alloca and form partitions based on them,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004255/// rewriting each of their uses.
Chandler Carruth83934062014-10-16 21:11:55 +00004256bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
4257 if (AS.begin() == AS.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00004258 return false;
4259
Chandler Carruth6c321c12013-07-19 10:57:36 +00004260 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004261 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004262 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00004263
Chandler Carruth24ac8302015-01-02 03:55:54 +00004264 // First try to pre-split loads and stores.
Chandler Carruth0715cba2015-01-01 11:54:38 +00004265 Changed |= presplitLoadsAndStores(AI, AS);
4266
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004267 // Now that we have identified any pre-splitting opportunities,
4268 // mark loads and stores unsplittable except for the following case.
4269 // We leave a slice splittable if all other slices are disjoint or fully
4270 // included in the slice, such as whole-alloca loads and stores.
4271 // If we fail to split these during pre-splitting, we want to force them
4272 // to be rewritten into a partition.
Chandler Carruth24ac8302015-01-02 03:55:54 +00004273 bool IsSorted = true;
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004274
4275 uint64_t AllocaSize = DL.getTypeAllocSize(AI.getAllocatedType());
4276 const uint64_t MaxBitVectorSize = 1024;
Hiroshi Inoue99a8faa2018-01-16 06:23:05 +00004277 if (AllocaSize <= MaxBitVectorSize) {
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004278 // If a byte boundary is included in any load or store, a slice starting or
4279 // ending at the boundary is not splittable.
4280 SmallBitVector SplittableOffset(AllocaSize + 1, true);
4281 for (Slice &S : AS)
4282 for (unsigned O = S.beginOffset() + 1;
4283 O < S.endOffset() && O < AllocaSize; O++)
4284 SplittableOffset.reset(O);
4285
4286 for (Slice &S : AS) {
4287 if (!S.isSplittable())
4288 continue;
4289
4290 if ((S.beginOffset() > AllocaSize || SplittableOffset[S.beginOffset()]) &&
4291 (S.endOffset() > AllocaSize || SplittableOffset[S.endOffset()]))
4292 continue;
4293
4294 if (isa<LoadInst>(S.getUse()->getUser()) ||
4295 isa<StoreInst>(S.getUse()->getUser())) {
4296 S.makeUnsplittable();
4297 IsSorted = false;
4298 }
Chandler Carruth24ac8302015-01-02 03:55:54 +00004299 }
4300 }
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004301 else {
4302 // We only allow whole-alloca splittable loads and stores
4303 // for a large alloca to avoid creating too large BitVector.
4304 for (Slice &S : AS) {
4305 if (!S.isSplittable())
4306 continue;
4307
4308 if (S.beginOffset() == 0 && S.endOffset() >= AllocaSize)
4309 continue;
4310
4311 if (isa<LoadInst>(S.getUse()->getUser()) ||
4312 isa<StoreInst>(S.getUse()->getUser())) {
4313 S.makeUnsplittable();
4314 IsSorted = false;
4315 }
4316 }
4317 }
4318
Chandler Carruth24ac8302015-01-02 03:55:54 +00004319 if (!IsSorted)
Fangrui Song0cac7262018-09-27 02:13:45 +00004320 llvm::sort(AS);
Chandler Carruth24ac8302015-01-02 03:55:54 +00004321
Adrian Prantl941fa752016-12-05 18:04:47 +00004322 /// Describes the allocas introduced by rewritePartition in order to migrate
4323 /// the debug info.
4324 struct Fragment {
Adrian Prantl565cc182015-01-20 19:42:22 +00004325 AllocaInst *Alloca;
4326 uint64_t Offset;
4327 uint64_t Size;
Adrian Prantl941fa752016-12-05 18:04:47 +00004328 Fragment(AllocaInst *AI, uint64_t O, uint64_t S)
Adrian Prantl565cc182015-01-20 19:42:22 +00004329 : Alloca(AI), Offset(O), Size(S) {}
4330 };
Adrian Prantl941fa752016-12-05 18:04:47 +00004331 SmallVector<Fragment, 4> Fragments;
Adrian Prantl565cc182015-01-20 19:42:22 +00004332
Chandler Carruth0715cba2015-01-01 11:54:38 +00004333 // Rewrite each partition.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004334 for (auto &P : AS.partitions()) {
Adrian Prantl565cc182015-01-20 19:42:22 +00004335 if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4336 Changed = true;
Adrian Prantl34e75902015-02-09 23:57:22 +00004337 if (NewAI != &AI) {
4338 uint64_t SizeOfByte = 8;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004339 uint64_t AllocaSize = DL.getTypeSizeInBits(NewAI->getAllocatedType());
Adrian Prantl34e75902015-02-09 23:57:22 +00004340 // Don't include any padding.
4341 uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
Adrian Prantl941fa752016-12-05 18:04:47 +00004342 Fragments.push_back(Fragment(NewAI, P.beginOffset() * SizeOfByte, Size));
Adrian Prantl34e75902015-02-09 23:57:22 +00004343 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004344 }
Chandler Carruth6c321c12013-07-19 10:57:36 +00004345 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00004346 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004347
Chandler Carruth6c321c12013-07-19 10:57:36 +00004348 NumAllocaPartitions += NumPartitions;
Craig Topper8a950272017-05-18 00:51:39 +00004349 MaxPartitionsPerAlloca.updateMax(NumPartitions);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004350
Adrian Prantl565cc182015-01-20 19:42:22 +00004351 // Migrate debug information from the old alloca to the new alloca(s)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004352 // and the individual partitions.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00004353 TinyPtrVector<DbgVariableIntrinsic *> DbgDeclares = FindDbgAddrUses(&AI);
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004354 if (!DbgDeclares.empty()) {
4355 auto *Var = DbgDeclares.front()->getVariable();
4356 auto *Expr = DbgDeclares.front()->getExpression();
Adrian Prantld7f6f162017-11-28 00:57:53 +00004357 auto VarSize = Var->getSizeInBits();
Sanjay Patelaf674fb2015-12-14 17:24:23 +00004358 DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
Keno Fischerd5354fd2016-01-14 20:06:34 +00004359 uint64_t AllocaSize = DL.getTypeSizeInBits(AI.getAllocatedType());
Adrian Prantl941fa752016-12-05 18:04:47 +00004360 for (auto Fragment : Fragments) {
4361 // Create a fragment expression describing the new partition or reuse AI's
Adrian Prantl565cc182015-01-20 19:42:22 +00004362 // expression if there is only one partition.
Adrian Prantl941fa752016-12-05 18:04:47 +00004363 auto *FragmentExpr = Expr;
4364 if (Fragment.Size < AllocaSize || Expr->isFragment()) {
Adrian Prantl152ac392015-02-01 00:58:04 +00004365 // If this alloca is already a scalar replacement of a larger aggregate,
Adrian Prantl941fa752016-12-05 18:04:47 +00004366 // Fragment.Offset describes the offset inside the scalar.
Adrian Prantl49797ca2016-12-22 05:27:12 +00004367 auto ExprFragment = Expr->getFragmentInfo();
4368 uint64_t Offset = ExprFragment ? ExprFragment->OffsetInBits : 0;
Adrian Prantl941fa752016-12-05 18:04:47 +00004369 uint64_t Start = Offset + Fragment.Offset;
4370 uint64_t Size = Fragment.Size;
Adrian Prantl49797ca2016-12-22 05:27:12 +00004371 if (ExprFragment) {
Adrian Prantl941fa752016-12-05 18:04:47 +00004372 uint64_t AbsEnd =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00004373 ExprFragment->OffsetInBits + ExprFragment->SizeInBits;
Adrian Prantl34e75902015-02-09 23:57:22 +00004374 if (Start >= AbsEnd)
4375 // No need to describe a SROAed padding.
4376 continue;
4377 Size = std::min(Size, AbsEnd - Start);
4378 }
Adrian Prantlb192b542017-08-30 20:04:17 +00004379 // The new, smaller fragment is stenciled out from the old fragment.
4380 if (auto OrigFragment = FragmentExpr->getFragmentInfo()) {
4381 assert(Start >= OrigFragment->OffsetInBits &&
4382 "new fragment is outside of original fragment");
4383 Start -= OrigFragment->OffsetInBits;
4384 }
Adrian Prantl77d90b02017-11-28 21:30:38 +00004385
4386 // The alloca may be larger than the variable.
4387 if (VarSize) {
4388 if (Size > *VarSize)
4389 Size = *VarSize;
4390 if (Size == 0 || Start + Size > *VarSize)
4391 continue;
4392 }
4393
Adrian Prantld7f6f162017-11-28 00:57:53 +00004394 // Avoid creating a fragment expression that covers the entire variable.
4395 if (!VarSize || *VarSize != Size) {
4396 if (auto E =
4397 DIExpression::createFragmentExpression(Expr, Start, Size))
4398 FragmentExpr = *E;
4399 else
4400 continue;
4401 }
Adrian Prantl152ac392015-02-01 00:58:04 +00004402 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004403
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004404 // Remove any existing intrinsics describing the same alloca.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00004405 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(Fragment.Alloca))
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004406 OldDII->eraseFromParent();
Adrian Prantl565cc182015-01-20 19:42:22 +00004407
Adrian Prantl941fa752016-12-05 18:04:47 +00004408 DIB.insertDeclare(Fragment.Alloca, Var, FragmentExpr,
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004409 DbgDeclares.front()->getDebugLoc(), &AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004410 }
4411 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004412 return Changed;
4413}
4414
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004415/// Clobber a use with undef, deleting the used value if it becomes dead.
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004416void SROA::clobberUse(Use &U) {
4417 Value *OldV = U;
4418 // Replace the use with an undef value.
4419 U = UndefValue::get(OldV->getType());
4420
4421 // Check for this making an instruction dead. We have to garbage collect
4422 // all the dead instructions to ensure the uses of any alloca end up being
4423 // minimal.
4424 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4425 if (isInstructionTriviallyDead(OldI)) {
4426 DeadInsts.insert(OldI);
4427 }
4428}
4429
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004430/// Analyze an alloca for SROA.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004431///
4432/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004433/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004434/// rewritten as needed.
4435bool SROA::runOnAlloca(AllocaInst &AI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004436 LLVM_DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004437 ++NumAllocasAnalyzed;
4438
4439 // Special case dead allocas, as they're trivial.
4440 if (AI.use_empty()) {
4441 AI.eraseFromParent();
4442 return true;
4443 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004444 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004445
4446 // Skip alloca forms that this analysis can't handle.
4447 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004448 DL.getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004449 return false;
4450
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004451 bool Changed = false;
4452
4453 // First, split any FCA loads and stores touching this alloca to promote
4454 // better splitting and promotion opportunities.
Tim Northover856628f2018-12-18 09:29:39 +00004455 AggLoadStoreRewriter AggRewriter(DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004456 Changed |= AggRewriter.rewrite(AI);
4457
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004458 // Build the slices using a recursive instruction-visiting builder.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004459 AllocaSlices AS(DL, AI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004460 LLVM_DEBUG(AS.print(dbgs()));
Chandler Carruth83934062014-10-16 21:11:55 +00004461 if (AS.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004462 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004463
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004464 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth83934062014-10-16 21:11:55 +00004465 for (Instruction *DeadUser : AS.getDeadUsers()) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004466 // Free up everything used by this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004467 for (Use &DeadOp : DeadUser->operands())
Chandler Carruth1583e992014-03-03 10:42:58 +00004468 clobberUse(DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004469
4470 // Now replace the uses of this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004471 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004472
4473 // And mark it for deletion.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004474 DeadInsts.insert(DeadUser);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004475 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004476 }
Chandler Carruth83934062014-10-16 21:11:55 +00004477 for (Use *DeadOp : AS.getDeadOperands()) {
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004478 clobberUse(*DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004479 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004480 }
4481
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004482 // No slices to split. Leave the dead alloca for a later pass to clean up.
Chandler Carruth83934062014-10-16 21:11:55 +00004483 if (AS.begin() == AS.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00004484 return Changed;
4485
Chandler Carruth83934062014-10-16 21:11:55 +00004486 Changed |= splitAlloca(AI, AS);
Chandler Carruthf0546402013-07-18 07:15:00 +00004487
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004488 LLVM_DEBUG(dbgs() << " Speculating PHIs\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00004489 while (!SpeculatablePHIs.empty())
4490 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
4491
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004492 LLVM_DEBUG(dbgs() << " Speculating Selects\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00004493 while (!SpeculatableSelects.empty())
4494 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
4495
4496 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004497}
4498
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004499/// Delete the dead instructions accumulated in this run.
Chandler Carruth19450da2012-09-14 10:26:38 +00004500///
4501/// Recursively deletes the dead instructions we've accumulated. This is done
4502/// at the very end to maximize locality of the recursive delete and to
4503/// minimize the problems of invalidated instruction pointers as such pointers
4504/// are used heavily in the intermediate stages of the algorithm.
4505///
4506/// We also record the alloca instructions deleted here so that they aren't
4507/// subsequently handed to mem2reg to promote.
Teresa Johnson33090022017-11-20 18:33:38 +00004508bool SROA::deleteDeadInstructions(
Chandler Carruth113dc642014-12-20 02:39:18 +00004509 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
Teresa Johnson33090022017-11-20 18:33:38 +00004510 bool Changed = false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004511 while (!DeadInsts.empty()) {
4512 Instruction *I = DeadInsts.pop_back_val();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004513 LLVM_DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004514
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004515 // If the instruction is an alloca, find the possible dbg.declare connected
4516 // to it, and remove it too. We must do this before calling RAUW or we will
4517 // not be able to find it.
4518 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
4519 DeletedAllocas.insert(AI);
Hsiangkai Wangef72e482018-08-06 03:59:47 +00004520 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(AI))
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004521 OldDII->eraseFromParent();
4522 }
4523
Chandler Carruth58d05562012-10-25 04:37:07 +00004524 I->replaceAllUsesWith(UndefValue::get(I->getType()));
4525
Chandler Carruth1583e992014-03-03 10:42:58 +00004526 for (Use &Operand : I->operands())
4527 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004528 // Zero out the operand and see if it becomes trivially dead.
Craig Topperf40110f2014-04-25 05:29:35 +00004529 Operand = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004530 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00004531 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004532 }
4533
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004534 ++NumDeleted;
4535 I->eraseFromParent();
Teresa Johnson33090022017-11-20 18:33:38 +00004536 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004537 }
Teresa Johnson33090022017-11-20 18:33:38 +00004538 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004539}
4540
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004541/// Promote the allocas, using the best available technique.
Chandler Carruth70b44c52012-09-15 11:43:14 +00004542///
4543/// This attempts to promote whatever allocas have been identified as viable in
4544/// the PromotableAllocas list. If that list is empty, there is nothing to do.
Chandler Carruth748d0952015-08-26 09:09:29 +00004545/// This function returns whether any promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00004546bool SROA::promoteAllocas(Function &F) {
4547 if (PromotableAllocas.empty())
4548 return false;
4549
4550 NumPromoted += PromotableAllocas.size();
4551
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004552 LLVM_DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Davide Italiano612d5a92017-04-09 20:47:14 +00004553 PromoteMemToReg(PromotableAllocas, *DT, AC);
Chandler Carruth70b44c52012-09-15 11:43:14 +00004554 PromotableAllocas.clear();
4555 return true;
4556}
4557
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004558PreservedAnalyses SROA::runImpl(Function &F, DominatorTree &RunDT,
4559 AssumptionCache &RunAC) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004560 LLVM_DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004561 C = &F.getContext();
Chandler Carruth29a18a42015-09-12 09:09:14 +00004562 DT = &RunDT;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004563 AC = &RunAC;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004564
4565 BasicBlock &EntryBB = F.getEntryBlock();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00004566 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
Adrian Prantl565cc182015-01-20 19:42:22 +00004567 I != E; ++I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004568 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
4569 Worklist.insert(AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004570 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004571
4572 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00004573 // A set of deleted alloca instruction pointers which should be removed from
4574 // the list of promotable allocas.
4575 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4576
Chandler Carruthac8317f2012-10-04 12:33:50 +00004577 do {
4578 while (!Worklist.empty()) {
4579 Changed |= runOnAlloca(*Worklist.pop_back_val());
Teresa Johnson33090022017-11-20 18:33:38 +00004580 Changed |= deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00004581
Chandler Carruthac8317f2012-10-04 12:33:50 +00004582 // Remove the deleted allocas from various lists so that we don't try to
4583 // continue processing them.
4584 if (!DeletedAllocas.empty()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00004585 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00004586 Worklist.remove_if(IsInSet);
4587 PostPromotionWorklist.remove_if(IsInSet);
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004588 PromotableAllocas.erase(llvm::remove_if(PromotableAllocas, IsInSet),
Chandler Carruthac8317f2012-10-04 12:33:50 +00004589 PromotableAllocas.end());
4590 DeletedAllocas.clear();
4591 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004592 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004593
Chandler Carruthac8317f2012-10-04 12:33:50 +00004594 Changed |= promoteAllocas(F);
4595
4596 Worklist = PostPromotionWorklist;
4597 PostPromotionWorklist.clear();
4598 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004599
Davide Italiano16e96d42016-06-07 13:21:17 +00004600 if (!Changed)
4601 return PreservedAnalyses::all();
4602
Davide Italiano16e96d42016-06-07 13:21:17 +00004603 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00004604 PA.preserveSet<CFGAnalyses>();
Davide Italiano16e96d42016-06-07 13:21:17 +00004605 PA.preserve<GlobalsAA>();
4606 return PA;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004607}
4608
Sean Silva36e0d012016-08-09 00:28:15 +00004609PreservedAnalyses SROA::run(Function &F, FunctionAnalysisManager &AM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004610 return runImpl(F, AM.getResult<DominatorTreeAnalysis>(F),
4611 AM.getResult<AssumptionAnalysis>(F));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004612}
Chandler Carruth29a18a42015-09-12 09:09:14 +00004613
4614/// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
4615///
4616/// This is in the llvm namespace purely to allow it to be a friend of the \c
4617/// SROA pass.
4618class llvm::sroa::SROALegacyPass : public FunctionPass {
4619 /// The SROA implementation.
4620 SROA Impl;
4621
4622public:
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004623 static char ID;
4624
Chandler Carruth29a18a42015-09-12 09:09:14 +00004625 SROALegacyPass() : FunctionPass(ID) {
4626 initializeSROALegacyPassPass(*PassRegistry::getPassRegistry());
4627 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004628
Chandler Carruth29a18a42015-09-12 09:09:14 +00004629 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00004630 if (skipFunction(F))
Chandler Carruth29a18a42015-09-12 09:09:14 +00004631 return false;
4632
4633 auto PA = Impl.runImpl(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004634 F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4635 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
Chandler Carruth29a18a42015-09-12 09:09:14 +00004636 return !PA.areAllPreserved();
4637 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004638
Chandler Carruth29a18a42015-09-12 09:09:14 +00004639 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004640 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth29a18a42015-09-12 09:09:14 +00004641 AU.addRequired<DominatorTreeWrapperPass>();
4642 AU.addPreserved<GlobalsAAWrapperPass>();
4643 AU.setPreservesCFG();
4644 }
4645
Mehdi Amini117296c2016-10-01 02:56:57 +00004646 StringRef getPassName() const override { return "SROA"; }
Chandler Carruth29a18a42015-09-12 09:09:14 +00004647};
4648
4649char SROALegacyPass::ID = 0;
4650
4651FunctionPass *llvm::createSROAPass() { return new SROALegacyPass(); }
4652
4653INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",
4654 "Scalar Replacement Of Aggregates", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004655INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth29a18a42015-09-12 09:09:14 +00004656INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4657INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",
4658 false, false)