blob: be65d16120c41a04d3f212f3c4ba0198a45e664b [file] [log] [blame]
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001//===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chandler Carruth1b398ae2012-09-14 09:22:59 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
9/// This transformation implements the well known scalar replacement of
10/// aggregates transformation. It tries to identify promotable elements of an
11/// aggregate alloca, and promote them to registers. It will also try to
12/// convert uses of an element (or set of elements) of an alloca into a vector
13/// or bitfield-style integer scalar if appropriate.
14///
15/// It works to do this with minimal slicing of the alloca so that regions
16/// which are merely transferred in and out of external memory remain unchanged
17/// and are not decomposed to scalar code.
18///
19/// Because this also performs alloca promotion, it can be thought of as also
20/// serving the purpose of SSA formation. The algorithm iterates on the
21/// function until all opportunities for promotion have been realized.
22///
23//===----------------------------------------------------------------------===//
24
Chandler Carruth29a18a42015-09-12 09:09:14 +000025#include "llvm/Transforms/Scalar/SROA.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000026#include "llvm/ADT/APInt.h"
27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/PointerIntPair.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/ADT/STLExtras.h"
Davide Italiano81a26da2017-04-27 23:09:01 +000031#include "llvm/ADT/SetVector.h"
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +000032#include "llvm/ADT/SmallBitVector.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000033#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/Statistic.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000036#include "llvm/ADT/StringRef.h"
37#include "llvm/ADT/Twine.h"
38#include "llvm/ADT/iterator.h"
39#include "llvm/ADT/iterator_range.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000040#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +000041#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000042#include "llvm/Analysis/Loads.h"
Chandler Carruthe41e7b72012-12-10 08:28:39 +000043#include "llvm/Analysis/PtrUseVisitor.h"
David Blaikie31b98d22018-06-04 21:23:21 +000044#include "llvm/Transforms/Utils/Local.h"
Nico Weber432a3882018-04-30 14:59:11 +000045#include "llvm/Config/llvm-config.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000046#include "llvm/IR/BasicBlock.h"
47#include "llvm/IR/Constant.h"
48#include "llvm/IR/ConstantFolder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000049#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000050#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/DataLayout.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000052#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000054#include "llvm/IR/Dominators.h"
55#include "llvm/IR/Function.h"
56#include "llvm/IR/GetElementPtrTypeIterator.h"
57#include "llvm/IR/GlobalAlias.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/IRBuilder.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000059#include "llvm/IR/InstVisitor.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000060#include "llvm/IR/InstrTypes.h"
61#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000062#include "llvm/IR/Instructions.h"
63#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000064#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000065#include "llvm/IR/LLVMContext.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000066#include "llvm/IR/Metadata.h"
67#include "llvm/IR/Module.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000068#include "llvm/IR/Operator.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000069#include "llvm/IR/PassManager.h"
70#include "llvm/IR/Type.h"
71#include "llvm/IR/Use.h"
72#include "llvm/IR/User.h"
73#include "llvm/IR/Value.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000074#include "llvm/Pass.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000075#include "llvm/Support/Casting.h"
Chandler Carruth70b44c52012-09-15 11:43:14 +000076#include "llvm/Support/CommandLine.h"
Chandler Carruthf0546402013-07-18 07:15:00 +000077#include "llvm/Support/Compiler.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000078#include "llvm/Support/Debug.h"
79#include "llvm/Support/ErrorHandling.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000080#include "llvm/Support/MathExtras.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000081#include "llvm/Support/raw_ostream.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +000082#include "llvm/Transforms/Scalar.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000083#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000084#include <algorithm>
85#include <cassert>
86#include <chrono>
87#include <cstddef>
88#include <cstdint>
89#include <cstring>
90#include <iterator>
91#include <string>
92#include <tuple>
93#include <utility>
94#include <vector>
Chandler Carruth83cee772014-02-25 03:59:29 +000095
Hal Finkel29f51312016-03-28 11:13:03 +000096#ifndef NDEBUG
97// We only use this for a debug check.
Chandler Carruth83cee772014-02-25 03:59:29 +000098#include <random>
99#endif
100
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000101using namespace llvm;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000102using namespace llvm::sroa;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000103
Chandler Carruth964daaa2014-04-22 02:55:47 +0000104#define DEBUG_TYPE "sroa"
105
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000106STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +0000107STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
Chandler Carruth6c321c12013-07-19 10:57:36 +0000108STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
109STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
110STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
Chandler Carruth5f5b6162013-03-20 06:30:46 +0000111STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
112STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000113STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +0000114STATISTIC(NumDeleted, "Number of instructions deleted");
115STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000116
Chandler Carruth83cee772014-02-25 03:59:29 +0000117/// Hidden option to enable randomly shuffling the slices to help uncover
118/// instability in their order.
119static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
120 cl::init(false), cl::Hidden);
121
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000122/// Hidden option to experiment with completely strict handling of inbounds
123/// GEPs.
Chandler Carruth113dc642014-12-20 02:39:18 +0000124static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
125 cl::Hidden);
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000126
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000127namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000128
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000129/// A custom IRBuilder inserter which prefixes all names, but only in
Mehdi Amini1e9c9252016-03-11 17:15:34 +0000130/// Assert builds.
Mehdi Aminiba9fba82016-03-13 21:05:13 +0000131class IRBuilderPrefixedInserter : public IRBuilderDefaultInserter {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000132 std::string Prefix;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000133
Zachary Turner41a9ee92017-10-11 23:54:34 +0000134 const Twine getNameWithPrefix(const Twine &Name) const {
135 return Name.isTriviallyEmpty() ? Name : Prefix + Name;
136 }
137
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000138public:
139 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
140
141protected:
142 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
143 BasicBlock::iterator InsertPt) const {
Zachary Turner41a9ee92017-10-11 23:54:34 +0000144 IRBuilderDefaultInserter::InsertHelper(I, getNameWithPrefix(Name), BB,
145 InsertPt);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000146 }
147};
148
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000149/// Provide a type for IRBuilder that drops names in release builds.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000150using IRBuilderTy = IRBuilder<ConstantFolder, IRBuilderPrefixedInserter>;
Chandler Carruthd177f862013-03-20 07:30:36 +0000151
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000152/// A used slice of an alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +0000153///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000154/// This structure represents a slice of an alloca used by some instruction. It
155/// stores both the begin and end offsets of this use, a pointer to the use
156/// itself, and a flag indicating whether we can classify the use as splittable
157/// or not when forming partitions of the alloca.
158class Slice {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000159 /// The beginning offset of the range.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000160 uint64_t BeginOffset = 0;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000161
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000162 /// The ending offset, not included in the range.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000163 uint64_t EndOffset = 0;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000164
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000165 /// Storage for both the use of this slice and whether it can be
Chandler Carruthf0546402013-07-18 07:15:00 +0000166 /// split.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000167 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
Chandler Carruthf0546402013-07-18 07:15:00 +0000168
169public:
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000170 Slice() = default;
171
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000172 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
Chandler Carruthf0546402013-07-18 07:15:00 +0000173 : BeginOffset(BeginOffset), EndOffset(EndOffset),
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000174 UseAndIsSplittable(U, IsSplittable) {}
Chandler Carruthf0546402013-07-18 07:15:00 +0000175
176 uint64_t beginOffset() const { return BeginOffset; }
177 uint64_t endOffset() const { return EndOffset; }
178
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000179 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
180 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000181
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000182 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000183
Craig Topperf40110f2014-04-25 05:29:35 +0000184 bool isDead() const { return getUse() == nullptr; }
185 void kill() { UseAndIsSplittable.setPointer(nullptr); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000186
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000187 /// Support for ordering ranges.
Chandler Carruthf74654d2013-03-18 08:36:46 +0000188 ///
189 /// This provides an ordering over ranges such that start offsets are
190 /// always increasing, and within equal start offsets, the end offsets are
191 /// decreasing. Thus the spanning range comes first in a cluster with the
192 /// same start position.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000193 bool operator<(const Slice &RHS) const {
Chandler Carruth113dc642014-12-20 02:39:18 +0000194 if (beginOffset() < RHS.beginOffset())
195 return true;
196 if (beginOffset() > RHS.beginOffset())
197 return false;
198 if (isSplittable() != RHS.isSplittable())
199 return !isSplittable();
200 if (endOffset() > RHS.endOffset())
201 return true;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000202 return false;
203 }
204
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000205 /// Support comparison with a single offset to allow binary searches.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000206 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
Chandler Carruthf0546402013-07-18 07:15:00 +0000207 uint64_t RHSOffset) {
208 return LHS.beginOffset() < RHSOffset;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000209 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000210 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000211 const Slice &RHS) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000212 return LHSOffset < RHS.beginOffset();
Chandler Carruthf74654d2013-03-18 08:36:46 +0000213 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000214
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000215 bool operator==(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000216 return isSplittable() == RHS.isSplittable() &&
217 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
Chandler Carruthe3899f22013-07-15 17:36:21 +0000218 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000219 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000220};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000221
Chandler Carruthf0546402013-07-18 07:15:00 +0000222} // end anonymous namespace
Chandler Carruthf74654d2013-03-18 08:36:46 +0000223
224namespace llvm {
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000225
Chandler Carruthf0546402013-07-18 07:15:00 +0000226template <typename T> struct isPodLike;
Chandler Carruth113dc642014-12-20 02:39:18 +0000227template <> struct isPodLike<Slice> { static const bool value = true; };
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000228
229} // end namespace llvm
Chandler Carruthf74654d2013-03-18 08:36:46 +0000230
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000231/// Representation of the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000232///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000233/// This class represents the slices of an alloca which are formed by its
234/// various uses. If a pointer escapes, we can't fully build a representation
235/// for the slices used and we reflect that in this structure. The uses are
236/// stored, sorted by increasing beginning offset and with unsplittable slices
237/// starting at a particular offset before splittable slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000238class llvm::sroa::AllocaSlices {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000239public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000240 /// Construct the slices of a particular alloca.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000241 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000242
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000243 /// Test whether a pointer to the allocation escapes our analysis.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000244 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000245 /// If this is true, the slices are never fully built and should be
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000246 /// ignored.
247 bool isEscaped() const { return PointerEscapingInstr; }
248
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000249 /// Support for iterating over the slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000250 /// @{
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000251 using iterator = SmallVectorImpl<Slice>::iterator;
252 using range = iterator_range<iterator>;
253
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000254 iterator begin() { return Slices.begin(); }
255 iterator end() { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000256
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000257 using const_iterator = SmallVectorImpl<Slice>::const_iterator;
258 using const_range = iterator_range<const_iterator>;
259
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000260 const_iterator begin() const { return Slices.begin(); }
261 const_iterator end() const { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000262 /// @}
263
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000264 /// Erase a range of slices.
Chandler Carruth994cde82015-01-01 12:01:03 +0000265 void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
Chandler Carruth0715cba2015-01-01 11:54:38 +0000266
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000267 /// Insert new slices for this alloca.
Chandler Carruth0715cba2015-01-01 11:54:38 +0000268 ///
269 /// This moves the slices into the alloca's slices collection, and re-sorts
270 /// everything so that the usual ordering properties of the alloca's slices
271 /// hold.
272 void insert(ArrayRef<Slice> NewSlices) {
273 int OldSize = Slices.size();
Benjamin Kramer4f6ac162015-02-28 10:11:12 +0000274 Slices.append(NewSlices.begin(), NewSlices.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +0000275 auto SliceI = Slices.begin() + OldSize;
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +0000276 llvm::sort(SliceI, Slices.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +0000277 std::inplace_merge(Slices.begin(), SliceI, Slices.end());
278 }
279
Chandler Carruth29a18a42015-09-12 09:09:14 +0000280 // Forward declare the iterator and range accessor for walking the
281 // partitions.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000282 class partition_iterator;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000283 iterator_range<partition_iterator> partitions();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000284
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000285 /// Access the dead users for this alloca.
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000286 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000287
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000288 /// Access the dead operands referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000289 ///
290 /// These are operands which have cannot actually be used to refer to the
291 /// alloca as they are outside its range and the user doesn't correct for
292 /// that. These mostly consist of PHI node inputs and the like which we just
293 /// need to replace with undef.
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000294 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000295
Aaron Ballman615eb472017-10-15 14:32:27 +0000296#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000297 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000298 void printSlice(raw_ostream &OS, const_iterator I,
299 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000300 void printUse(raw_ostream &OS, const_iterator I,
301 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000302 void print(raw_ostream &OS) const;
Alp Tokerf929e092014-01-04 22:47:48 +0000303 void dump(const_iterator I) const;
304 void dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000305#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000306
307private:
308 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000309 class SliceBuilder;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000310
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000311 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000312
Aaron Ballman615eb472017-10-15 14:32:27 +0000313#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000314 /// Handle to alloca instruction to simplify method interfaces.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000315 AllocaInst &AI;
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000316#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000317
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000318 /// The instruction responsible for this alloca not having a known set
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000319 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000320 ///
321 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000322 /// store a pointer to that here and abort trying to form slices of the
323 /// alloca. This will be null if the alloca slices are analyzed successfully.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000324 Instruction *PointerEscapingInstr;
325
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000326 /// The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000327 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000328 /// We store a vector of the slices formed by uses of the alloca here. This
329 /// vector is sorted by increasing begin offset, and then the unsplittable
330 /// slices before the splittable ones. See the Slice inner class for more
331 /// details.
332 SmallVector<Slice, 8> Slices;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000333
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000334 /// Instructions which will become dead if we rewrite the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000335 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000336 /// Note that these are not separated by slice. This is because we expect an
337 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
338 /// all these instructions can simply be removed and replaced with undef as
339 /// they come from outside of the allocated space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000340 SmallVector<Instruction *, 8> DeadUsers;
341
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000342 /// Operands which will become dead if we rewrite the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000343 ///
344 /// These are operands that in their particular use can be replaced with
345 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
346 /// to PHI nodes and the like. They aren't entirely dead (there might be
347 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
348 /// want to swap this particular input for undef to simplify the use lists of
349 /// the alloca.
350 SmallVector<Use *, 8> DeadOperands;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000351};
Chandler Carruth29a18a42015-09-12 09:09:14 +0000352
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000353/// A partition of the slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000354///
355/// An ephemeral representation for a range of slices which can be viewed as
356/// a partition of the alloca. This range represents a span of the alloca's
357/// memory which cannot be split, and provides access to all of the slices
358/// overlapping some part of the partition.
359///
360/// Objects of this type are produced by traversing the alloca's slices, but
361/// are only ephemeral and not persistent.
362class llvm::sroa::Partition {
363private:
364 friend class AllocaSlices;
365 friend class AllocaSlices::partition_iterator;
366
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000367 using iterator = AllocaSlices::iterator;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000368
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000369 /// The beginning and ending offsets of the alloca for this
Chandler Carruth29a18a42015-09-12 09:09:14 +0000370 /// partition.
371 uint64_t BeginOffset, EndOffset;
372
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000373 /// The start and end iterators of this partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000374 iterator SI, SJ;
375
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000376 /// A collection of split slice tails overlapping the partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000377 SmallVector<Slice *, 4> SplitTails;
378
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000379 /// Raw constructor builds an empty partition starting and ending at
Chandler Carruth29a18a42015-09-12 09:09:14 +0000380 /// the given iterator.
381 Partition(iterator SI) : SI(SI), SJ(SI) {}
382
383public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000384 /// The start offset of this partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000385 ///
386 /// All of the contained slices start at or after this offset.
387 uint64_t beginOffset() const { return BeginOffset; }
388
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000389 /// The end offset of this partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000390 ///
391 /// All of the contained slices end at or before this offset.
392 uint64_t endOffset() const { return EndOffset; }
393
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000394 /// The size of the partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000395 ///
396 /// Note that this can never be zero.
397 uint64_t size() const {
398 assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
399 return EndOffset - BeginOffset;
400 }
401
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000402 /// Test whether this partition contains no slices, and merely spans
Chandler Carruth29a18a42015-09-12 09:09:14 +0000403 /// a region occupied by split slices.
404 bool empty() const { return SI == SJ; }
405
406 /// \name Iterate slices that start within the partition.
407 /// These may be splittable or unsplittable. They have a begin offset >= the
408 /// partition begin offset.
409 /// @{
410 // FIXME: We should probably define a "concat_iterator" helper and use that
411 // to stitch together pointee_iterators over the split tails and the
412 // contiguous iterators of the partition. That would give a much nicer
413 // interface here. We could then additionally expose filtered iterators for
414 // split, unsplit, and unsplittable splices based on the usage patterns.
415 iterator begin() const { return SI; }
416 iterator end() const { return SJ; }
417 /// @}
418
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000419 /// Get the sequence of split slice tails.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000420 ///
421 /// These tails are of slices which start before this partition but are
422 /// split and overlap into the partition. We accumulate these while forming
423 /// partitions.
424 ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
425};
426
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000427/// An iterator over partitions of the alloca's slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000428///
429/// This iterator implements the core algorithm for partitioning the alloca's
430/// slices. It is a forward iterator as we don't support backtracking for
431/// efficiency reasons, and re-use a single storage area to maintain the
432/// current set of split slices.
433///
434/// It is templated on the slice iterator type to use so that it can operate
435/// with either const or non-const slice iterators.
436class AllocaSlices::partition_iterator
437 : public iterator_facade_base<partition_iterator, std::forward_iterator_tag,
438 Partition> {
439 friend class AllocaSlices;
440
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000441 /// Most of the state for walking the partitions is held in a class
Chandler Carruth29a18a42015-09-12 09:09:14 +0000442 /// with a nice interface for examining them.
443 Partition P;
444
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000445 /// We need to keep the end of the slices to know when to stop.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000446 AllocaSlices::iterator SE;
447
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000448 /// We also need to keep track of the maximum split end offset seen.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000449 /// FIXME: Do we really?
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000450 uint64_t MaxSplitSliceEndOffset = 0;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000451
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000452 /// Sets the partition to be empty at given iterator, and sets the
Chandler Carruth29a18a42015-09-12 09:09:14 +0000453 /// end iterator.
454 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000455 : P(SI), SE(SE) {
Chandler Carruth29a18a42015-09-12 09:09:14 +0000456 // If not already at the end, advance our state to form the initial
457 // partition.
458 if (SI != SE)
459 advance();
460 }
461
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000462 /// Advance the iterator to the next partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000463 ///
464 /// Requires that the iterator not be at the end of the slices.
465 void advance() {
466 assert((P.SI != SE || !P.SplitTails.empty()) &&
467 "Cannot advance past the end of the slices!");
468
469 // Clear out any split uses which have ended.
470 if (!P.SplitTails.empty()) {
471 if (P.EndOffset >= MaxSplitSliceEndOffset) {
472 // If we've finished all splits, this is easy.
473 P.SplitTails.clear();
474 MaxSplitSliceEndOffset = 0;
475 } else {
476 // Remove the uses which have ended in the prior partition. This
477 // cannot change the max split slice end because we just checked that
478 // the prior partition ended prior to that max.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000479 P.SplitTails.erase(llvm::remove_if(P.SplitTails,
480 [&](Slice *S) {
481 return S->endOffset() <=
482 P.EndOffset;
483 }),
484 P.SplitTails.end());
485 assert(llvm::any_of(P.SplitTails,
486 [&](Slice *S) {
487 return S->endOffset() == MaxSplitSliceEndOffset;
488 }) &&
Chandler Carruth29a18a42015-09-12 09:09:14 +0000489 "Could not find the current max split slice offset!");
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000490 assert(llvm::all_of(P.SplitTails,
491 [&](Slice *S) {
492 return S->endOffset() <= MaxSplitSliceEndOffset;
493 }) &&
Chandler Carruth29a18a42015-09-12 09:09:14 +0000494 "Max split slice end offset is not actually the max!");
495 }
496 }
497
498 // If P.SI is already at the end, then we've cleared the split tail and
499 // now have an end iterator.
500 if (P.SI == SE) {
501 assert(P.SplitTails.empty() && "Failed to clear the split slices!");
502 return;
503 }
504
505 // If we had a non-empty partition previously, set up the state for
506 // subsequent partitions.
507 if (P.SI != P.SJ) {
508 // Accumulate all the splittable slices which started in the old
509 // partition into the split list.
510 for (Slice &S : P)
511 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
512 P.SplitTails.push_back(&S);
513 MaxSplitSliceEndOffset =
514 std::max(S.endOffset(), MaxSplitSliceEndOffset);
515 }
516
517 // Start from the end of the previous partition.
518 P.SI = P.SJ;
519
520 // If P.SI is now at the end, we at most have a tail of split slices.
521 if (P.SI == SE) {
522 P.BeginOffset = P.EndOffset;
523 P.EndOffset = MaxSplitSliceEndOffset;
524 return;
525 }
526
527 // If the we have split slices and the next slice is after a gap and is
528 // not splittable immediately form an empty partition for the split
529 // slices up until the next slice begins.
530 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
531 !P.SI->isSplittable()) {
532 P.BeginOffset = P.EndOffset;
533 P.EndOffset = P.SI->beginOffset();
534 return;
535 }
536 }
537
538 // OK, we need to consume new slices. Set the end offset based on the
539 // current slice, and step SJ past it. The beginning offset of the
540 // partition is the beginning offset of the next slice unless we have
541 // pre-existing split slices that are continuing, in which case we begin
542 // at the prior end offset.
543 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
544 P.EndOffset = P.SI->endOffset();
545 ++P.SJ;
546
547 // There are two strategies to form a partition based on whether the
548 // partition starts with an unsplittable slice or a splittable slice.
549 if (!P.SI->isSplittable()) {
550 // When we're forming an unsplittable region, it must always start at
551 // the first slice and will extend through its end.
552 assert(P.BeginOffset == P.SI->beginOffset());
553
554 // Form a partition including all of the overlapping slices with this
555 // unsplittable slice.
556 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
557 if (!P.SJ->isSplittable())
558 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
559 ++P.SJ;
560 }
561
562 // We have a partition across a set of overlapping unsplittable
563 // partitions.
564 return;
565 }
566
567 // If we're starting with a splittable slice, then we need to form
568 // a synthetic partition spanning it and any other overlapping splittable
569 // splices.
570 assert(P.SI->isSplittable() && "Forming a splittable partition!");
571
572 // Collect all of the overlapping splittable slices.
573 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
574 P.SJ->isSplittable()) {
575 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
576 ++P.SJ;
577 }
578
579 // Back upiP.EndOffset if we ended the span early when encountering an
580 // unsplittable slice. This synthesizes the early end offset of
581 // a partition spanning only splittable slices.
582 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
583 assert(!P.SJ->isSplittable());
584 P.EndOffset = P.SJ->beginOffset();
585 }
586 }
587
588public:
589 bool operator==(const partition_iterator &RHS) const {
590 assert(SE == RHS.SE &&
591 "End iterators don't match between compared partition iterators!");
592
593 // The observed positions of partitions is marked by the P.SI iterator and
594 // the emptiness of the split slices. The latter is only relevant when
595 // P.SI == SE, as the end iterator will additionally have an empty split
596 // slices list, but the prior may have the same P.SI and a tail of split
597 // slices.
598 if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
599 assert(P.SJ == RHS.P.SJ &&
600 "Same set of slices formed two different sized partitions!");
601 assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
602 "Same slice position with differently sized non-empty split "
603 "slice tails!");
604 return true;
605 }
606 return false;
607 }
608
609 partition_iterator &operator++() {
610 advance();
611 return *this;
612 }
613
614 Partition &operator*() { return P; }
615};
616
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000617/// A forward range over the partitions of the alloca's slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000618///
619/// This accesses an iterator range over the partitions of the alloca's
620/// slices. It computes these partitions on the fly based on the overlapping
621/// offsets of the slices and the ability to split them. It will visit "empty"
622/// partitions to cover regions of the alloca only accessed via split
623/// slices.
624iterator_range<AllocaSlices::partition_iterator> AllocaSlices::partitions() {
625 return make_range(partition_iterator(begin(), end()),
626 partition_iterator(end(), end()));
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000627}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000628
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000629static Value *foldSelectInst(SelectInst &SI) {
630 // If the condition being selected on is a constant or the same value is
631 // being selected between, fold the select. Yes this does (rarely) happen
632 // early on.
633 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
Chandler Carruth113dc642014-12-20 02:39:18 +0000634 return SI.getOperand(1 + CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000635 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000636 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000637
Craig Topperf40110f2014-04-25 05:29:35 +0000638 return nullptr;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000639}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000640
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000641/// A helper that folds a PHI node or a select.
Jingyue Wuec33fa92014-08-22 22:45:57 +0000642static Value *foldPHINodeOrSelectInst(Instruction &I) {
643 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
644 // If PN merges together the same value, return that value.
645 return PN->hasConstantValue();
646 }
647 return foldSelectInst(cast<SelectInst>(I));
648}
649
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000650/// Builder for the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000651///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000652/// This class builds a set of alloca slices by recursively visiting the uses
653/// of an alloca and making a slice for each load and store at each offset.
654class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
655 friend class PtrUseVisitor<SliceBuilder>;
656 friend class InstVisitor<SliceBuilder>;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000657
658 using Base = PtrUseVisitor<SliceBuilder>;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000659
660 const uint64_t AllocSize;
Chandler Carruth83934062014-10-16 21:11:55 +0000661 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000662
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000663 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
Chandler Carruthf0546402013-07-18 07:15:00 +0000664 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
665
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000666 /// Set to de-duplicate dead instructions found in the use walk.
Chandler Carruthf0546402013-07-18 07:15:00 +0000667 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000668
669public:
Chandler Carruth83934062014-10-16 21:11:55 +0000670 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000671 : PtrUseVisitor<SliceBuilder>(DL),
Chandler Carruth83934062014-10-16 21:11:55 +0000672 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000673
674private:
Chandler Carruthf0546402013-07-18 07:15:00 +0000675 void markAsDead(Instruction &I) {
David Blaikie70573dc2014-11-19 07:49:26 +0000676 if (VisitedDeadInsts.insert(&I).second)
Chandler Carruth83934062014-10-16 21:11:55 +0000677 AS.DeadUsers.push_back(&I);
Chandler Carruthf0546402013-07-18 07:15:00 +0000678 }
679
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000680 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000681 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000682 // Completely skip uses which have a zero size or start either before or
683 // past the end of the allocation.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000684 if (Size == 0 || Offset.uge(AllocSize)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000685 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @"
686 << Offset
687 << " which has zero size or starts outside of the "
688 << AllocSize << " byte alloca:\n"
689 << " alloca: " << AS.AI << "\n"
690 << " use: " << I << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000691 return markAsDead(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000692 }
693
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000694 uint64_t BeginOffset = Offset.getZExtValue();
695 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000696
697 // Clamp the end offset to the end of the allocation. Note that this is
698 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000699 // This may appear superficially to be something we could ignore entirely,
700 // but that is not so! There may be widened loads or PHI-node uses where
701 // some instructions are dead but not others. We can't completely ignore
702 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000703 assert(AllocSize >= BeginOffset); // Established above.
704 if (Size > AllocSize - BeginOffset) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000705 LLVM_DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @"
706 << Offset << " to remain within the " << AllocSize
707 << " byte alloca:\n"
708 << " alloca: " << AS.AI << "\n"
709 << " use: " << I << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000710 EndOffset = AllocSize;
711 }
712
Chandler Carruth83934062014-10-16 21:11:55 +0000713 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
Chandler Carruthf0546402013-07-18 07:15:00 +0000714 }
715
716 void visitBitCastInst(BitCastInst &BC) {
717 if (BC.use_empty())
718 return markAsDead(BC);
719
720 return Base::visitBitCastInst(BC);
721 }
722
723 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
724 if (GEPI.use_empty())
725 return markAsDead(GEPI);
726
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000727 if (SROAStrictInbounds && GEPI.isInBounds()) {
728 // FIXME: This is a manually un-factored variant of the basic code inside
729 // of GEPs with checking of the inbounds invariant specified in the
730 // langref in a very strict sense. If we ever want to enable
731 // SROAStrictInbounds, this code should be factored cleanly into
732 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
Hal Finkel5c83a092016-03-28 11:23:21 +0000733 // by writing out the code here where we have the underlying allocation
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000734 // size readily available.
735 APInt GEPOffset = Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000736 const DataLayout &DL = GEPI.getModule()->getDataLayout();
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000737 for (gep_type_iterator GTI = gep_type_begin(GEPI),
738 GTE = gep_type_end(GEPI);
739 GTI != GTE; ++GTI) {
740 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
741 if (!OpC)
742 break;
743
744 // Handle a struct index, which adds its field offset to the pointer.
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000745 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000746 unsigned ElementIdx = OpC->getZExtValue();
747 const StructLayout *SL = DL.getStructLayout(STy);
748 GEPOffset +=
749 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
750 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +0000751 // For array or vector indices, scale the index by the size of the
752 // type.
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000753 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
754 GEPOffset += Index * APInt(Offset.getBitWidth(),
755 DL.getTypeAllocSize(GTI.getIndexedType()));
756 }
757
758 // If this index has computed an intermediate pointer which is not
759 // inbounds, then the result of the GEP is a poison value and we can
760 // delete it and all uses.
761 if (GEPOffset.ugt(AllocSize))
762 return markAsDead(GEPI);
763 }
764 }
765
Chandler Carruthf0546402013-07-18 07:15:00 +0000766 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000767 }
768
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000769 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000770 uint64_t Size, bool IsVolatile) {
Chandler Carruth24ac8302015-01-02 03:55:54 +0000771 // We allow splitting of non-volatile loads and stores where the type is an
772 // integer type. These may be used to implement 'memcpy' or other "transfer
773 // of bits" patterns.
774 bool IsSplittable = Ty->isIntegerTy() && !IsVolatile;
Chandler Carruth58d05562012-10-25 04:37:07 +0000775
776 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000777 }
778
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000779 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000780 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
781 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000782
783 if (!IsOffsetKnown)
784 return PI.setAborted(&LI);
785
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000786 const DataLayout &DL = LI.getModule()->getDataLayout();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000787 uint64_t Size = DL.getTypeStoreSize(LI.getType());
788 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000789 }
790
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000791 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000792 Value *ValOp = SI.getValueOperand();
793 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000794 return PI.setEscapedAndAborted(&SI);
795 if (!IsOffsetKnown)
796 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000797
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000798 const DataLayout &DL = SI.getModule()->getDataLayout();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000799 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
800
801 // If this memory access can be shown to *statically* extend outside the
Hiroshi Inoue0909ca12018-01-26 08:15:29 +0000802 // bounds of the allocation, it's behavior is undefined, so simply
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000803 // ignore it. Note that this is more strict than the generic clamping
804 // behavior of insertUse. We also try to handle cases which might run the
805 // risk of overflow.
806 // FIXME: We should instead consider the pointer to have escaped if this
807 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000808 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000809 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @"
810 << Offset << " which extends past the end of the "
811 << AllocSize << " byte alloca:\n"
812 << " alloca: " << AS.AI << "\n"
813 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000814 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000815 }
816
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000817 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
818 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000819 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000820 }
821
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000822 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000823 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000824 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000825 if ((Length && Length->getValue() == 0) ||
Chandler Carruth6aedc102014-02-26 03:14:14 +0000826 (IsOffsetKnown && Offset.uge(AllocSize)))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000827 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000828 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000829
830 if (!IsOffsetKnown)
831 return PI.setAborted(&II);
832
Chandler Carruth113dc642014-12-20 02:39:18 +0000833 insertUse(II, Offset, Length ? Length->getLimitedValue()
834 : AllocSize - Offset.getLimitedValue(),
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000835 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000836 }
837
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000838 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000839 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000840 if (Length && Length->getValue() == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000841 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000842 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000843
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000844 // Because we can visit these intrinsics twice, also check to see if the
845 // first time marked this instruction as dead. If so, skip it.
846 if (VisitedDeadInsts.count(&II))
847 return;
848
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000849 if (!IsOffsetKnown)
850 return PI.setAborted(&II);
851
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000852 // This side of the transfer is completely out-of-bounds, and so we can
853 // nuke the entire transfer. However, we also need to nuke the other side
854 // if already added to our partitions.
855 // FIXME: Yet another place we really should bypass this when
856 // instrumenting for ASan.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000857 if (Offset.uge(AllocSize)) {
Chandler Carruth113dc642014-12-20 02:39:18 +0000858 SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
859 MemTransferSliceMap.find(&II);
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000860 if (MTPI != MemTransferSliceMap.end())
Chandler Carruth83934062014-10-16 21:11:55 +0000861 AS.Slices[MTPI->second].kill();
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000862 return markAsDead(II);
863 }
864
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000865 uint64_t RawOffset = Offset.getLimitedValue();
Chandler Carruth113dc642014-12-20 02:39:18 +0000866 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000867
Chandler Carruthf0546402013-07-18 07:15:00 +0000868 // Check for the special case where the same exact value is used for both
869 // source and dest.
870 if (*U == II.getRawDest() && *U == II.getRawSource()) {
871 // For non-volatile transfers this is a no-op.
872 if (!II.isVolatile())
873 return markAsDead(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000874
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000875 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000876 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000877
Chandler Carruthf0546402013-07-18 07:15:00 +0000878 // If we have seen both source and destination for a mem transfer, then
879 // they both point to the same alloca.
880 bool Inserted;
881 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000882 std::tie(MTPI, Inserted) =
Chandler Carruth83934062014-10-16 21:11:55 +0000883 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000884 unsigned PrevIdx = MTPI->second;
885 if (!Inserted) {
Chandler Carruth83934062014-10-16 21:11:55 +0000886 Slice &PrevP = AS.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000887
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000888 // Check if the begin offsets match and this is a non-volatile transfer.
889 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000890 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
891 PrevP.kill();
892 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000893 }
894
895 // Otherwise we have an offset transfer within the same alloca. We can't
896 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000897 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000898 }
899
Chandler Carruthe3899f22013-07-15 17:36:21 +0000900 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000901 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000902
Chandler Carruthf0546402013-07-18 07:15:00 +0000903 // Check that we ended up with a valid index in the map.
Chandler Carruth83934062014-10-16 21:11:55 +0000904 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000905 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000906 }
907
908 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000909 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000910 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000911 void visitIntrinsicInst(IntrinsicInst &II) {
912 if (!IsOffsetKnown)
913 return PI.setAborted(&II);
914
Vedant Kumarb264d692018-12-21 21:49:40 +0000915 if (II.isLifetimeStartOrEnd()) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000916 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000917 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
918 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000919 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000920 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000921 }
922
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000923 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000924 }
925
926 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
927 // We consider any PHI or select that results in a direct load or store of
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000928 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000929 // are considered unsplittable and the size is the maximum loaded or stored
930 // size.
931 SmallPtrSet<Instruction *, 4> Visited;
932 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
933 Visited.insert(Root);
934 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000935 const DataLayout &DL = Root->getModule()->getDataLayout();
Chandler Carruth8b907e82012-09-25 10:03:40 +0000936 // If there are no loads or stores, the access is dead. We mark that as
937 // a size zero access.
938 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000939 do {
940 Instruction *I, *UsedI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000941 std::tie(UsedI, I) = Uses.pop_back_val();
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000942
943 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000944 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000945 continue;
946 }
947 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
948 Value *Op = SI->getOperand(0);
949 if (Op == UsedI)
950 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000951 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000952 continue;
953 }
954
955 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
956 if (!GEP->hasAllZeroIndices())
957 return GEP;
958 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
959 !isa<SelectInst>(I)) {
960 return I;
961 }
962
Chandler Carruthcdf47882014-03-09 03:16:01 +0000963 for (User *U : I->users())
David Blaikie70573dc2014-11-19 07:49:26 +0000964 if (Visited.insert(cast<Instruction>(U)).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000965 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000966 } while (!Uses.empty());
967
Craig Topperf40110f2014-04-25 05:29:35 +0000968 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000969 }
970
Jingyue Wuec33fa92014-08-22 22:45:57 +0000971 void visitPHINodeOrSelectInst(Instruction &I) {
972 assert(isa<PHINode>(I) || isa<SelectInst>(I));
973 if (I.use_empty())
974 return markAsDead(I);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000975
Jingyue Wuec33fa92014-08-22 22:45:57 +0000976 // TODO: We could use SimplifyInstruction here to fold PHINodes and
977 // SelectInsts. However, doing so requires to change the current
978 // dead-operand-tracking mechanism. For instance, suppose neither loading
979 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
980 // trap either. However, if we simply replace %U with undef using the
981 // current dead-operand-tracking mechanism, "load (select undef, undef,
982 // %other)" may trap because the select may return the first operand
983 // "undef".
984 if (Value *Result = foldPHINodeOrSelectInst(I)) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000985 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000986 // If the result of the constant fold will be the pointer, recurse
Jingyue Wuec33fa92014-08-22 22:45:57 +0000987 // through the PHI/select as if we had RAUW'ed it.
988 enqueueUsers(I);
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000989 else
Jingyue Wuec33fa92014-08-22 22:45:57 +0000990 // Otherwise the operand to the PHI/select is dead, and we can replace
991 // it with undef.
Chandler Carruth83934062014-10-16 21:11:55 +0000992 AS.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000993
994 return;
995 }
Jingyue Wuec33fa92014-08-22 22:45:57 +0000996
Chandler Carruthf0546402013-07-18 07:15:00 +0000997 if (!IsOffsetKnown)
Jingyue Wuec33fa92014-08-22 22:45:57 +0000998 return PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000999
Chandler Carruthf0546402013-07-18 07:15:00 +00001000 // See if we already have computed info on this node.
Jingyue Wuec33fa92014-08-22 22:45:57 +00001001 uint64_t &Size = PHIOrSelectSizes[&I];
1002 if (!Size) {
1003 // This is a new PHI/Select, check for an unsafe use of it.
1004 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
Chandler Carruthf0546402013-07-18 07:15:00 +00001005 return PI.setAborted(UnsafeI);
1006 }
1007
1008 // For PHI and select operands outside the alloca, we can't nuke the entire
1009 // phi or select -- the other side might still be relevant, so we special
1010 // case them here and use a separate structure to track the operands
1011 // themselves which should be replaced with undef.
1012 // FIXME: This should instead be escaped in the event we're instrumenting
1013 // for address sanitization.
Chandler Carruth6aedc102014-02-26 03:14:14 +00001014 if (Offset.uge(AllocSize)) {
Chandler Carruth83934062014-10-16 21:11:55 +00001015 AS.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +00001016 return;
1017 }
1018
Jingyue Wuec33fa92014-08-22 22:45:57 +00001019 insertUse(I, Offset, Size);
1020 }
1021
Chandler Carruth113dc642014-12-20 02:39:18 +00001022 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
Jingyue Wuec33fa92014-08-22 22:45:57 +00001023
Chandler Carruth113dc642014-12-20 02:39:18 +00001024 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001025
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001026 /// Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth113dc642014-12-20 02:39:18 +00001027 void visitInstruction(Instruction &I) { PI.setAborted(&I); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001028};
1029
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001030AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001031 :
Aaron Ballman615eb472017-10-15 14:32:27 +00001032#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001033 AI(AI),
1034#endif
Craig Topperf40110f2014-04-25 05:29:35 +00001035 PointerEscapingInstr(nullptr) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001036 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001037 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001038 if (PtrI.isEscaped() || PtrI.isAborted()) {
1039 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001040 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001041 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1042 : PtrI.getAbortingInst();
1043 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001044 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001045 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001046
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001047 Slices.erase(
1048 llvm::remove_if(Slices, [](const Slice &S) { return S.isDead(); }),
1049 Slices.end());
Benjamin Kramer08e50702013-07-20 08:38:34 +00001050
Hal Finkel29f51312016-03-28 11:13:03 +00001051#ifndef NDEBUG
Chandler Carruth83cee772014-02-25 03:59:29 +00001052 if (SROARandomShuffleSlices) {
Pavel Labathc207bec2016-11-09 12:07:12 +00001053 std::mt19937 MT(static_cast<unsigned>(
1054 std::chrono::system_clock::now().time_since_epoch().count()));
Chandler Carruth83cee772014-02-25 03:59:29 +00001055 std::shuffle(Slices.begin(), Slices.end(), MT);
1056 }
1057#endif
1058
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001059 // Sort the uses. This arranges for the offsets to be in ascending order,
1060 // and the sizes to be in descending order.
Fangrui Song0cac7262018-09-27 02:13:45 +00001061 llvm::sort(Slices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001062}
1063
Aaron Ballman615eb472017-10-15 14:32:27 +00001064#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001065
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001066void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1067 StringRef Indent) const {
1068 printSlice(OS, I, Indent);
Chandler Carruth0715cba2015-01-01 11:54:38 +00001069 OS << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001070 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001071}
1072
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001073void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1074 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001075 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001076 << " slice #" << (I - begin())
Chandler Carruth0715cba2015-01-01 11:54:38 +00001077 << (I->isSplittable() ? " (splittable)" : "");
Chandler Carruthf0546402013-07-18 07:15:00 +00001078}
1079
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001080void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1081 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001082 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001083}
1084
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001085void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001086 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001087 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001088 << " A pointer to this alloca escaped by:\n"
1089 << " " << *PointerEscapingInstr << "\n";
1090 return;
1091 }
1092
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001093 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001094 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001095 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001096}
1097
Alp Tokerf929e092014-01-04 22:47:48 +00001098LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1099 print(dbgs(), I);
1100}
1101LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001102
Aaron Ballman615eb472017-10-15 14:32:27 +00001103#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001104
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001105/// Walk the range of a partitioning looking for a common type to cover this
1106/// sequence of slices.
1107static Type *findCommonType(AllocaSlices::const_iterator B,
1108 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +00001109 uint64_t EndOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +00001110 Type *Ty = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001111 bool TyIsCommon = true;
Craig Topperf40110f2014-04-25 05:29:35 +00001112 IntegerType *ITy = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001113
1114 // Note that we need to look at *every* alloca slice's Use to ensure we
1115 // always get consistent results regardless of the order of slices.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001116 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001117 Use *U = I->getUse();
1118 if (isa<IntrinsicInst>(*U->getUser()))
1119 continue;
1120 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1121 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001122
Craig Topperf40110f2014-04-25 05:29:35 +00001123 Type *UserTy = nullptr;
Chandler Carrutha1262002013-11-19 09:03:18 +00001124 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001125 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001126 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001127 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001128 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001129
Chandler Carruth4de31542014-01-21 23:16:05 +00001130 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001131 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001132 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +00001133 // entity causing the split. Also skip if the type is not a byte width
1134 // multiple.
Chandler Carruth4de31542014-01-21 23:16:05 +00001135 if (UserITy->getBitWidth() % 8 != 0 ||
1136 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001137 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001138
Chandler Carruth4de31542014-01-21 23:16:05 +00001139 // Track the largest bitwidth integer type used in this way in case there
1140 // is no common type.
1141 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1142 ITy = UserITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001143 }
Duncan P. N. Exon Smith73686d32014-06-17 00:19:35 +00001144
1145 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1146 // depend on types skipped above.
1147 if (!UserTy || (Ty && Ty != UserTy))
1148 TyIsCommon = false; // Give up on anything but an iN type.
1149 else
1150 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001151 }
Chandler Carruth4de31542014-01-21 23:16:05 +00001152
1153 return TyIsCommon ? Ty : ITy;
Chandler Carruthf0546402013-07-18 07:15:00 +00001154}
Chandler Carruthe3899f22013-07-15 17:36:21 +00001155
Chandler Carruthf0546402013-07-18 07:15:00 +00001156/// PHI instructions that use an alloca and are subsequently loaded can be
1157/// rewritten to load both input pointers in the pred blocks and then PHI the
1158/// results, allowing the load of the alloca to be promoted.
1159/// From this:
1160/// %P2 = phi [i32* %Alloca, i32* %Other]
1161/// %V = load i32* %P2
1162/// to:
1163/// %V1 = load i32* %Alloca -> will be mem2reg'd
1164/// ...
1165/// %V2 = load i32* %Other
1166/// ...
1167/// %V = phi [i32 %V1, i32 %V2]
1168///
1169/// We can do this to a select if its only uses are loads and if the operands
1170/// to the select can be loaded unconditionally.
1171///
1172/// FIXME: This should be hoisted into a generic utility, likely in
1173/// Transforms/Util/Local.h
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001174static bool isSafePHIToSpeculate(PHINode &PN) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001175 // For now, we can only do this promotion if the load is in the same block
1176 // as the PHI, and if there are no stores between the phi and load.
1177 // TODO: Allow recursive phi users.
1178 // TODO: Allow stores.
1179 BasicBlock *BB = PN.getParent();
1180 unsigned MaxAlign = 0;
1181 bool HaveLoad = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001182 for (User *U : PN.users()) {
1183 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001184 if (!LI || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001185 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001186
Chandler Carruthf0546402013-07-18 07:15:00 +00001187 // For now we only allow loads in the same block as the PHI. This is
1188 // a common case that happens when instcombine merges two loads through
1189 // a PHI.
1190 if (LI->getParent() != BB)
1191 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001192
Chandler Carruthf0546402013-07-18 07:15:00 +00001193 // Ensure that there are no instructions between the PHI and the load that
1194 // could store.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001195 for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
Chandler Carruthf0546402013-07-18 07:15:00 +00001196 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001197 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001198
Chandler Carruthf0546402013-07-18 07:15:00 +00001199 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1200 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001201 }
1202
Chandler Carruthf0546402013-07-18 07:15:00 +00001203 if (!HaveLoad)
1204 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001205
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001206 const DataLayout &DL = PN.getModule()->getDataLayout();
1207
Chandler Carruthf0546402013-07-18 07:15:00 +00001208 // We can only transform this if it is safe to push the loads into the
1209 // predecessor blocks. The only thing to watch out for is that we can't put
1210 // a possibly trapping load in the predecessor if it is a critical edge.
1211 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001212 Instruction *TI = PN.getIncomingBlock(Idx)->getTerminator();
Chandler Carruthf0546402013-07-18 07:15:00 +00001213 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001214
Chandler Carruthf0546402013-07-18 07:15:00 +00001215 // If the value is produced by the terminator of the predecessor (an
1216 // invoke) or it has side-effects, there is no valid place to put a load
1217 // in the predecessor.
1218 if (TI == InVal || TI->mayHaveSideEffects())
1219 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001220
Chandler Carruthf0546402013-07-18 07:15:00 +00001221 // If the predecessor has a single successor, then the edge isn't
1222 // critical.
1223 if (TI->getNumSuccessors() == 1)
1224 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001225
Chandler Carruthf0546402013-07-18 07:15:00 +00001226 // If this pointer is always safe to load, or if we can prove that there
1227 // is already a load in the block, then we can move the load to the pred
1228 // block.
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001229 if (isSafeToLoadUnconditionally(InVal, MaxAlign, DL, TI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001230 continue;
1231
1232 return false;
1233 }
1234
1235 return true;
1236}
1237
1238static void speculatePHINodeLoads(PHINode &PN) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001239 LLVM_DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001240
1241 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1242 IRBuilderTy PHIBuilder(&PN);
1243 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1244 PN.getName() + ".sroa.speculated");
1245
Hal Finkelcc39b672014-07-24 12:16:19 +00001246 // Get the AA tags and alignment to use from one of the loads. It doesn't
Chandler Carruthf0546402013-07-18 07:15:00 +00001247 // matter which one we get and if any differ.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001248 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
Hal Finkelcc39b672014-07-24 12:16:19 +00001249
1250 AAMDNodes AATags;
1251 SomeLoad->getAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001252 unsigned Align = SomeLoad->getAlignment();
1253
1254 // Rewrite all loads of the PN to use the new PHI.
1255 while (!PN.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001256 LoadInst *LI = cast<LoadInst>(PN.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001257 LI->replaceAllUsesWith(NewPN);
1258 LI->eraseFromParent();
1259 }
1260
1261 // Inject loads into all of the pred blocks.
Bjorn Pettersson81a76a32018-05-17 07:21:41 +00001262 DenseMap<BasicBlock*, Value*> InjectedLoads;
Chandler Carruthf0546402013-07-18 07:15:00 +00001263 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1264 BasicBlock *Pred = PN.getIncomingBlock(Idx);
Chandler Carruthf0546402013-07-18 07:15:00 +00001265 Value *InVal = PN.getIncomingValue(Idx);
Bjorn Pettersson81a76a32018-05-17 07:21:41 +00001266
1267 // A PHI node is allowed to have multiple (duplicated) entries for the same
1268 // basic block, as long as the value is the same. So if we already injected
1269 // a load in the predecessor, then we should reuse the same load for all
1270 // duplicated entries.
1271 if (Value* V = InjectedLoads.lookup(Pred)) {
1272 NewPN->addIncoming(V, Pred);
1273 continue;
1274 }
1275
Chandler Carruthedb12a82018-10-15 10:04:59 +00001276 Instruction *TI = Pred->getTerminator();
Chandler Carruthf0546402013-07-18 07:15:00 +00001277 IRBuilderTy PredBuilder(TI);
1278
1279 LoadInst *Load = PredBuilder.CreateLoad(
1280 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1281 ++NumLoadsSpeculated;
1282 Load->setAlignment(Align);
Hal Finkelcc39b672014-07-24 12:16:19 +00001283 if (AATags)
1284 Load->setAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001285 NewPN->addIncoming(Load, Pred);
Bjorn Pettersson81a76a32018-05-17 07:21:41 +00001286 InjectedLoads[Pred] = Load;
Chandler Carruthf0546402013-07-18 07:15:00 +00001287 }
1288
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001289 LLVM_DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001290 PN.eraseFromParent();
1291}
1292
1293/// Select instructions that use an alloca and are subsequently loaded can be
1294/// rewritten to load both input pointers and then select between the result,
1295/// allowing the load of the alloca to be promoted.
1296/// From this:
1297/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1298/// %V = load i32* %P2
1299/// to:
1300/// %V1 = load i32* %Alloca -> will be mem2reg'd
1301/// %V2 = load i32* %Other
1302/// %V = select i1 %cond, i32 %V1, i32 %V2
1303///
1304/// We can do this to a select if its only uses are loads and if the operand
1305/// to the select can be loaded unconditionally.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001306static bool isSafeSelectToSpeculate(SelectInst &SI) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001307 Value *TValue = SI.getTrueValue();
1308 Value *FValue = SI.getFalseValue();
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001309 const DataLayout &DL = SI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00001310
Chandler Carruthcdf47882014-03-09 03:16:01 +00001311 for (User *U : SI.users()) {
1312 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001313 if (!LI || !LI->isSimple())
Chandler Carruthf0546402013-07-18 07:15:00 +00001314 return false;
1315
Hiroshi Inoueb3008242017-06-24 15:43:33 +00001316 // Both operands to the select need to be dereferenceable, either
Chandler Carruthf0546402013-07-18 07:15:00 +00001317 // absolutely (e.g. allocas) or at this point because we can see other
1318 // accesses to it.
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001319 if (!isSafeToLoadUnconditionally(TValue, LI->getAlignment(), DL, LI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001320 return false;
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001321 if (!isSafeToLoadUnconditionally(FValue, LI->getAlignment(), DL, LI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001322 return false;
1323 }
1324
1325 return true;
1326}
1327
1328static void speculateSelectInstLoads(SelectInst &SI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001329 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001330
1331 IRBuilderTy IRB(&SI);
1332 Value *TV = SI.getTrueValue();
1333 Value *FV = SI.getFalseValue();
1334 // Replace the loads of the select with a select of two loads.
1335 while (!SI.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001336 LoadInst *LI = cast<LoadInst>(SI.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001337 assert(LI->isSimple() && "We only speculate simple loads");
1338
1339 IRB.SetInsertPoint(LI);
1340 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001341 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001342 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001343 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001344 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001345
Hal Finkelcc39b672014-07-24 12:16:19 +00001346 // Transfer alignment and AA info if present.
Chandler Carruthf0546402013-07-18 07:15:00 +00001347 TL->setAlignment(LI->getAlignment());
1348 FL->setAlignment(LI->getAlignment());
Hal Finkelcc39b672014-07-24 12:16:19 +00001349
1350 AAMDNodes Tags;
1351 LI->getAAMetadata(Tags);
1352 if (Tags) {
1353 TL->setAAMetadata(Tags);
1354 FL->setAAMetadata(Tags);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001355 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001356
1357 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1358 LI->getName() + ".sroa.speculated");
1359
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001360 LLVM_DEBUG(dbgs() << " speculated to: " << *V << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001361 LI->replaceAllUsesWith(V);
1362 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001363 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001364 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001365}
1366
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001367/// Build a GEP out of a base pointer and indices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001368///
1369/// This will return the BasePtr if that is valid, or build a new GEP
1370/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001371static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001372 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001373 if (Indices.empty())
1374 return BasePtr;
1375
1376 // A single zero index is a no-op, so check for this and avoid building a GEP
1377 // in that case.
1378 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1379 return BasePtr;
1380
David Blaikieaa41cd52015-04-03 21:33:42 +00001381 return IRB.CreateInBoundsGEP(nullptr, BasePtr, Indices,
1382 NamePrefix + "sroa_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001383}
1384
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001385/// Get a natural GEP off of the BasePtr walking through Ty toward
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001386/// TargetTy without changing the offset of the pointer.
1387///
1388/// This routine assumes we've already established a properly offset GEP with
1389/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1390/// zero-indices down through type layers until we find one the same as
1391/// TargetTy. If we can't find one with the same type, we at least try to use
1392/// one with the same size. If none of that works, we just produce the GEP as
1393/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001394static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001395 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001396 SmallVectorImpl<Value *> &Indices,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001397 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001398 if (Ty == TargetTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001399 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001400
Nicola Zaghenf96383c2018-10-30 11:15:04 +00001401 // Offset size to use for the indices.
1402 unsigned OffsetSize = DL.getIndexTypeSizeInBits(BasePtr->getType());
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001403
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001404 // See if we can descend into a struct and locate a field with the correct
1405 // type.
1406 unsigned NumLayers = 0;
1407 Type *ElementTy = Ty;
1408 do {
1409 if (ElementTy->isPointerTy())
1410 break;
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001411
1412 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1413 ElementTy = ArrayTy->getElementType();
Nicola Zaghenf96383c2018-10-30 11:15:04 +00001414 Indices.push_back(IRB.getIntN(OffsetSize, 0));
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001415 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1416 ElementTy = VectorTy->getElementType();
1417 Indices.push_back(IRB.getInt32(0));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001418 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001419 if (STy->element_begin() == STy->element_end())
1420 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001421 ElementTy = *STy->element_begin();
1422 Indices.push_back(IRB.getInt32(0));
1423 } else {
1424 break;
1425 }
1426 ++NumLayers;
1427 } while (ElementTy != TargetTy);
1428 if (ElementTy != TargetTy)
1429 Indices.erase(Indices.end() - NumLayers, Indices.end());
1430
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001431 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001432}
1433
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001434/// Recursively compute indices for a natural GEP.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001435///
1436/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1437/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001438static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001439 Value *Ptr, Type *Ty, APInt &Offset,
1440 Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001441 SmallVectorImpl<Value *> &Indices,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001442 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001443 if (Offset == 0)
Chandler Carruth113dc642014-12-20 02:39:18 +00001444 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1445 NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001446
1447 // We can't recurse through pointer types.
1448 if (Ty->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001449 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001450
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001451 // We try to analyze GEPs over vectors here, but note that these GEPs are
1452 // extremely poorly defined currently. The long-term goal is to remove GEPing
1453 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001454 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001455 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Craig Topperf40110f2014-04-25 05:29:35 +00001456 if (ElementSizeInBits % 8 != 0) {
1457 // GEPs over non-multiple of 8 size vector elements are invalid.
1458 return nullptr;
1459 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001460 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001461 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001462 if (NumSkippedElements.ugt(VecTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001463 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001464 Offset -= NumSkippedElements * ElementSize;
1465 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001466 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001467 Offset, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001468 }
1469
1470 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1471 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001472 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001473 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001474 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001475 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001476
1477 Offset -= NumSkippedElements * ElementSize;
1478 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001479 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001480 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001481 }
1482
1483 StructType *STy = dyn_cast<StructType>(Ty);
1484 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00001485 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001486
Chandler Carruth90a735d2013-07-19 07:21:28 +00001487 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001488 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001489 if (StructOffset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00001490 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001491 unsigned Index = SL->getElementContainingOffset(StructOffset);
1492 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1493 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001494 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Craig Topperf40110f2014-04-25 05:29:35 +00001495 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001496
1497 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001498 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001499 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001500}
1501
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001502/// Get a natural GEP from a base pointer to a particular offset and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001503/// resulting in a particular type.
1504///
1505/// The goal is to produce a "natural" looking GEP that works with the existing
1506/// composite types to arrive at the appropriate offset and element type for
1507/// a pointer. TargetTy is the element type the returned GEP should point-to if
1508/// possible. We recurse by decreasing Offset, adding the appropriate index to
1509/// Indices, and setting Ty to the result subtype.
1510///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001511/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001512static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001513 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001514 SmallVectorImpl<Value *> &Indices,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001515 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001516 PointerType *Ty = cast<PointerType>(Ptr->getType());
1517
1518 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1519 // an i8.
Chandler Carruth286d87e2014-02-26 08:25:02 +00001520 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +00001521 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001522
1523 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001524 if (!ElementTy->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +00001525 return nullptr; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001526 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001527 if (ElementSize == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001528 return nullptr; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001529 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001530
1531 Offset -= NumSkippedElements * ElementSize;
1532 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001533 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001534 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001535}
1536
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001537/// Compute an adjusted pointer from Ptr by Offset bytes where the
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001538/// resulting pointer has PointerTy.
1539///
1540/// This tries very hard to compute a "natural" GEP which arrives at the offset
1541/// and produces the pointer type desired. Where it cannot, it will try to use
1542/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1543/// fails, it will try to use an existing i8* and GEP to the byte offset and
1544/// bitcast to the type.
1545///
1546/// The strategy for finding the more natural GEPs is to peel off layers of the
1547/// pointer, walking back through bit casts and GEPs, searching for a base
1548/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001549/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001550/// a single GEP as possible, thus making each GEP more independent of the
1551/// surrounding code.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001552static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001553 APInt Offset, Type *PointerTy, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001554 // Even though we don't look through PHI nodes, we could be called on an
1555 // instruction in an unreachable block, which may be on a cycle.
1556 SmallPtrSet<Value *, 4> Visited;
1557 Visited.insert(Ptr);
1558 SmallVector<Value *, 4> Indices;
1559
1560 // We may end up computing an offset pointer that has the wrong type. If we
1561 // never are able to compute one directly that has the correct type, we'll
Chandler Carruth5986b542015-01-02 02:47:38 +00001562 // fall back to it, so keep it and the base it was computed from around here.
Craig Topperf40110f2014-04-25 05:29:35 +00001563 Value *OffsetPtr = nullptr;
Chandler Carruth5986b542015-01-02 02:47:38 +00001564 Value *OffsetBasePtr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001565
1566 // Remember any i8 pointer we come across to re-use if we need to do a raw
1567 // byte offset.
Craig Topperf40110f2014-04-25 05:29:35 +00001568 Value *Int8Ptr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001569 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1570
1571 Type *TargetTy = PointerTy->getPointerElementType();
1572
1573 do {
1574 // First fold any existing GEPs into the offset.
1575 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1576 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001577 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001578 break;
1579 Offset += GEPOffset;
1580 Ptr = GEP->getPointerOperand();
David Blaikie70573dc2014-11-19 07:49:26 +00001581 if (!Visited.insert(Ptr).second)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001582 break;
1583 }
1584
1585 // See if we can perform a natural GEP here.
1586 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001587 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001588 Indices, NamePrefix)) {
Chandler Carruth5986b542015-01-02 02:47:38 +00001589 // If we have a new natural pointer at the offset, clear out any old
1590 // offset pointer we computed. Unless it is the base pointer or
1591 // a non-instruction, we built a GEP we don't need. Zap it.
1592 if (OffsetPtr && OffsetPtr != OffsetBasePtr)
1593 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1594 assert(I->use_empty() && "Built a GEP with uses some how!");
1595 I->eraseFromParent();
1596 }
1597 OffsetPtr = P;
1598 OffsetBasePtr = Ptr;
1599 // If we also found a pointer of the right type, we're done.
1600 if (P->getType() == PointerTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001601 return P;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001602 }
1603
1604 // Stash this pointer if we've found an i8*.
1605 if (Ptr->getType()->isIntegerTy(8)) {
1606 Int8Ptr = Ptr;
1607 Int8PtrOffset = Offset;
1608 }
1609
1610 // Peel off a layer of the pointer and update the offset appropriately.
1611 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1612 Ptr = cast<Operator>(Ptr)->getOperand(0);
1613 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001614 if (GA->isInterposable())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001615 break;
1616 Ptr = GA->getAliasee();
1617 } else {
1618 break;
1619 }
1620 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +00001621 } while (Visited.insert(Ptr).second);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001622
1623 if (!OffsetPtr) {
1624 if (!Int8Ptr) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00001625 Int8Ptr = IRB.CreateBitCast(
1626 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1627 NamePrefix + "sroa_raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001628 Int8PtrOffset = Offset;
1629 }
1630
Chandler Carruth113dc642014-12-20 02:39:18 +00001631 OffsetPtr = Int8PtrOffset == 0
1632 ? Int8Ptr
David Blaikieaa41cd52015-04-03 21:33:42 +00001633 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1634 IRB.getInt(Int8PtrOffset),
Chandler Carruth113dc642014-12-20 02:39:18 +00001635 NamePrefix + "sroa_raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001636 }
1637 Ptr = OffsetPtr;
1638
1639 // On the off chance we were targeting i8*, guard the bitcast here.
1640 if (Ptr->getType() != PointerTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001641 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001642
1643 return Ptr;
1644}
1645
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001646/// Compute the adjusted alignment for a load or store from an offset.
Chandler Carruth0715cba2015-01-01 11:54:38 +00001647static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset,
1648 const DataLayout &DL) {
1649 unsigned Alignment;
1650 Type *Ty;
1651 if (auto *LI = dyn_cast<LoadInst>(I)) {
1652 Alignment = LI->getAlignment();
1653 Ty = LI->getType();
1654 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
1655 Alignment = SI->getAlignment();
1656 Ty = SI->getValueOperand()->getType();
1657 } else {
1658 llvm_unreachable("Only loads and stores are allowed!");
1659 }
1660
1661 if (!Alignment)
1662 Alignment = DL.getABITypeAlignment(Ty);
1663
1664 return MinAlign(Alignment, Offset);
1665}
1666
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001667/// Test whether we can convert a value from the old to the new type.
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001668///
1669/// This predicate should be used to guard calls to convertValue in order to
1670/// ensure that we only try to convert viable values. The strategy is that we
1671/// will peel off single element struct and array wrappings to get to an
1672/// underlying value, and convert that value.
1673static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1674 if (OldTy == NewTy)
1675 return true;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001676
1677 // For integer types, we can't handle any bit-width differences. This would
1678 // break both vector conversions with extension and introduce endianness
1679 // issues when in conjunction with loads and stores.
1680 if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
1681 assert(cast<IntegerType>(OldTy)->getBitWidth() !=
1682 cast<IntegerType>(NewTy)->getBitWidth() &&
1683 "We can't have the same bitwidth for different int types");
1684 return false;
1685 }
1686
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001687 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1688 return false;
1689 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1690 return false;
1691
Benjamin Kramer56262592013-09-22 11:24:58 +00001692 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001693 // of pointers and integers.
1694 OldTy = OldTy->getScalarType();
1695 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001696 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
Jack Liuf101c0f2016-05-03 19:30:48 +00001697 if (NewTy->isPointerTy() && OldTy->isPointerTy()) {
1698 return cast<PointerType>(NewTy)->getPointerAddressSpace() ==
1699 cast<PointerType>(OldTy)->getPointerAddressSpace();
1700 }
Sanjoy Dasb70ddd82017-06-17 20:28:13 +00001701
1702 // We can convert integers to integral pointers, but not to non-integral
1703 // pointers.
1704 if (OldTy->isIntegerTy())
1705 return !DL.isNonIntegralPointerType(NewTy);
1706
1707 // We can convert integral pointers to integers, but non-integral pointers
1708 // need to remain pointers.
1709 if (!DL.isNonIntegralPointerType(OldTy))
1710 return NewTy->isIntegerTy();
1711
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001712 return false;
1713 }
1714
1715 return true;
1716}
1717
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001718/// Generic routine to convert an SSA value to a value of a different
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001719/// type.
1720///
1721/// This will try various different casting techniques, such as bitcasts,
1722/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1723/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001724static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001725 Type *NewTy) {
1726 Type *OldTy = V->getType();
1727 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1728
1729 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001730 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001731
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001732 assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
1733 "Integer types must be the exact same to convert.");
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001734
Benjamin Kramer90901a32013-09-21 20:36:04 +00001735 // See if we need inttoptr for this type pair. A cast involving both scalars
1736 // and vectors requires and additional bitcast.
Craig Topper95d23472017-07-09 07:04:00 +00001737 if (OldTy->isIntOrIntVectorTy() && NewTy->isPtrOrPtrVectorTy()) {
Benjamin Kramer90901a32013-09-21 20:36:04 +00001738 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1739 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1740 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1741 NewTy);
1742
1743 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1744 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1745 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1746 NewTy);
1747
1748 return IRB.CreateIntToPtr(V, NewTy);
1749 }
1750
1751 // See if we need ptrtoint for this type pair. A cast involving both scalars
1752 // and vectors requires and additional bitcast.
Craig Topper95d23472017-07-09 07:04:00 +00001753 if (OldTy->isPtrOrPtrVectorTy() && NewTy->isIntOrIntVectorTy()) {
Benjamin Kramer90901a32013-09-21 20:36:04 +00001754 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1755 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1756 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1757 NewTy);
1758
1759 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1760 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1761 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1762 NewTy);
1763
1764 return IRB.CreatePtrToInt(V, NewTy);
1765 }
1766
1767 return IRB.CreateBitCast(V, NewTy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001768}
1769
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001770/// Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001771///
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001772/// This function is called to test each entry in a partition which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001773/// for a single slice.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001774static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S,
1775 VectorType *Ty,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001776 uint64_t ElementSize,
1777 const DataLayout &DL) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001778 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001779 uint64_t BeginOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001780 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001781 uint64_t BeginIndex = BeginOffset / ElementSize;
1782 if (BeginIndex * ElementSize != BeginOffset ||
1783 BeginIndex >= Ty->getNumElements())
1784 return false;
1785 uint64_t EndOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001786 std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001787 uint64_t EndIndex = EndOffset / ElementSize;
1788 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1789 return false;
1790
1791 assert(EndIndex > BeginIndex && "Empty vector!");
1792 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruthc659df92014-10-16 20:24:07 +00001793 Type *SliceTy = (NumElements == 1)
1794 ? Ty->getElementType()
1795 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruthf0546402013-07-18 07:15:00 +00001796
1797 Type *SplitIntTy =
1798 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1799
Chandler Carruthc659df92014-10-16 20:24:07 +00001800 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001801
1802 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1803 if (MI->isVolatile())
1804 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00001805 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00001806 return false; // Skip any unsplittable intrinsics.
Owen Anderson6c19ab12014-08-07 21:07:35 +00001807 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
Vedant Kumarb264d692018-12-21 21:49:40 +00001808 if (!II->isLifetimeStartOrEnd())
Owen Anderson6c19ab12014-08-07 21:07:35 +00001809 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001810 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1811 // Disable vector promotion when there are loads or stores of an FCA.
1812 return false;
1813 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1814 if (LI->isVolatile())
1815 return false;
1816 Type *LTy = LI->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001817 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001818 assert(LTy->isIntegerTy());
1819 LTy = SplitIntTy;
1820 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001821 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001822 return false;
1823 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1824 if (SI->isVolatile())
1825 return false;
1826 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001827 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001828 assert(STy->isIntegerTy());
1829 STy = SplitIntTy;
1830 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001831 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001832 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001833 } else {
1834 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001835 }
1836
1837 return true;
1838}
1839
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001840/// Test whether the given alloca partitioning and range of slices can be
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001841/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001842///
1843/// This is a quick test to check whether we can rewrite a particular alloca
1844/// partition (and its newly formed alloca) into a vector alloca with only
1845/// whole-vector loads and stores such that it could be promoted to a vector
1846/// SSA value. We only can ensure this for a limited set of operations, and we
1847/// don't want to do the rewrites unless we are confident that the result will
1848/// be promotable, so we have an early test here.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001849static VectorType *isVectorPromotionViable(Partition &P, const DataLayout &DL) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001850 // Collect the candidate types for vector-based promotion. Also track whether
1851 // we have different element types.
1852 SmallVector<VectorType *, 4> CandidateTys;
1853 Type *CommonEltTy = nullptr;
1854 bool HaveCommonEltTy = true;
1855 auto CheckCandidateType = [&](Type *Ty) {
1856 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1857 CandidateTys.push_back(VTy);
1858 if (!CommonEltTy)
1859 CommonEltTy = VTy->getElementType();
1860 else if (CommonEltTy != VTy->getElementType())
1861 HaveCommonEltTy = false;
1862 }
1863 };
Chandler Carruth2dc96822014-10-18 00:44:02 +00001864 // Consider any loads or stores that are the exact size of the slice.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001865 for (const Slice &S : P)
1866 if (S.beginOffset() == P.beginOffset() &&
1867 S.endOffset() == P.endOffset()) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001868 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1869 CheckCandidateType(LI->getType());
1870 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1871 CheckCandidateType(SI->getValueOperand()->getType());
1872 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001873
Chandler Carruth2dc96822014-10-18 00:44:02 +00001874 // If we didn't find a vector type, nothing to do here.
1875 if (CandidateTys.empty())
1876 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001877
Chandler Carruth2dc96822014-10-18 00:44:02 +00001878 // Remove non-integer vector types if we had multiple common element types.
1879 // FIXME: It'd be nice to replace them with integer vector types, but we can't
1880 // do that until all the backends are known to produce good code for all
1881 // integer vector types.
1882 if (!HaveCommonEltTy) {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001883 CandidateTys.erase(
1884 llvm::remove_if(CandidateTys,
1885 [](VectorType *VTy) {
1886 return !VTy->getElementType()->isIntegerTy();
1887 }),
1888 CandidateTys.end());
Chandler Carruth2dc96822014-10-18 00:44:02 +00001889
1890 // If there were no integer vector types, give up.
1891 if (CandidateTys.empty())
1892 return nullptr;
1893
1894 // Rank the remaining candidate vector types. This is easy because we know
1895 // they're all integer vectors. We sort by ascending number of elements.
1896 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
David L. Jones41cecba2017-01-13 21:02:41 +00001897 (void)DL;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001898 assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
1899 "Cannot have vector types of different sizes!");
1900 assert(RHSTy->getElementType()->isIntegerTy() &&
1901 "All non-integer types eliminated!");
1902 assert(LHSTy->getElementType()->isIntegerTy() &&
1903 "All non-integer types eliminated!");
1904 return RHSTy->getNumElements() < LHSTy->getNumElements();
1905 };
Fangrui Song0cac7262018-09-27 02:13:45 +00001906 llvm::sort(CandidateTys, RankVectorTypes);
Chandler Carruth2dc96822014-10-18 00:44:02 +00001907 CandidateTys.erase(
1908 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
1909 CandidateTys.end());
1910 } else {
1911// The only way to have the same element type in every vector type is to
1912// have the same vector type. Check that and remove all but one.
1913#ifndef NDEBUG
1914 for (VectorType *VTy : CandidateTys) {
1915 assert(VTy->getElementType() == CommonEltTy &&
1916 "Unaccounted for element type!");
1917 assert(VTy == CandidateTys[0] &&
1918 "Different vector types with the same element type!");
1919 }
1920#endif
1921 CandidateTys.resize(1);
1922 }
1923
1924 // Try each vector type, and return the one which works.
1925 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
1926 uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
1927
1928 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1929 // that aren't byte sized.
1930 if (ElementSize % 8)
1931 return false;
1932 assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
1933 "vector size not a multiple of element size?");
1934 ElementSize /= 8;
1935
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001936 for (const Slice &S : P)
1937 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001938 return false;
1939
Chandler Carruthffb7ce52014-12-24 01:48:09 +00001940 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001941 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001942 return false;
1943
1944 return true;
1945 };
1946 for (VectorType *VTy : CandidateTys)
1947 if (CheckVectorTypeForPromotion(VTy))
1948 return VTy;
1949
1950 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001951}
1952
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001953/// Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001954///
1955/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001956/// test below on a single slice of the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001957static bool isIntegerWideningViableForSlice(const Slice &S,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001958 uint64_t AllocBeginOffset,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001959 Type *AllocaTy,
1960 const DataLayout &DL,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001961 bool &WholeAllocaOp) {
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001962 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
1963
Chandler Carruthc659df92014-10-16 20:24:07 +00001964 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
1965 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001966
1967 // We can't reasonably handle cases where the load or store extends past
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001968 // the end of the alloca's type and into its padding.
Chandler Carruthf0546402013-07-18 07:15:00 +00001969 if (RelEnd > Size)
1970 return false;
1971
Chandler Carruthc659df92014-10-16 20:24:07 +00001972 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001973
1974 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1975 if (LI->isVolatile())
1976 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001977 // We can't handle loads that extend past the allocated memory.
1978 if (DL.getTypeStoreSize(LI->getType()) > Size)
1979 return false;
Hiroshi Inouef5c0e6c2018-05-17 06:32:17 +00001980 // So far, AllocaSliceRewriter does not support widening split slice tails
1981 // in rewriteIntegerLoad.
1982 if (S.beginOffset() < AllocBeginOffset)
1983 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001984 // Note that we don't count vector loads or stores as whole-alloca
1985 // operations which enable integer widening because we would prefer to use
1986 // vector widening instead.
1987 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00001988 WholeAllocaOp = true;
1989 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001990 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001991 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001992 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001993 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001994 // Non-integer loads need to be convertible from the alloca type so that
1995 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001996 return false;
1997 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001998 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1999 Type *ValueTy = SI->getValueOperand()->getType();
2000 if (SI->isVolatile())
2001 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002002 // We can't handle stores that extend past the allocated memory.
2003 if (DL.getTypeStoreSize(ValueTy) > Size)
2004 return false;
Hiroshi Inouef5c0e6c2018-05-17 06:32:17 +00002005 // So far, AllocaSliceRewriter does not support widening split slice tails
2006 // in rewriteIntegerStore.
2007 if (S.beginOffset() < AllocBeginOffset)
2008 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00002009 // Note that we don't count vector loads or stores as whole-alloca
2010 // operations which enable integer widening because we would prefer to use
2011 // vector widening instead.
2012 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00002013 WholeAllocaOp = true;
2014 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002015 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00002016 return false;
2017 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002018 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002019 // Non-integer stores need to be convertible to the alloca type so that
2020 // they are promotable.
2021 return false;
2022 }
2023 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2024 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
2025 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00002026 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00002027 return false; // Skip any unsplittable intrinsics.
2028 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
Vedant Kumarb264d692018-12-21 21:49:40 +00002029 if (!II->isLifetimeStartOrEnd())
Chandler Carruthf0546402013-07-18 07:15:00 +00002030 return false;
2031 } else {
2032 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002033 }
Chandler Carruthf0546402013-07-18 07:15:00 +00002034
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002035 return true;
2036}
2037
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002038/// Test whether the given alloca partition's integer operations can be
Chandler Carruth435c4e02012-10-15 08:40:30 +00002039/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00002040///
Chandler Carruth435c4e02012-10-15 08:40:30 +00002041/// This is a quick test to check whether we can rewrite the integer loads and
2042/// stores to a particular alloca into wider loads and stores and be able to
2043/// promote the resulting alloca.
Chandler Carruth29a18a42015-09-12 09:09:14 +00002044static bool isIntegerWideningViable(Partition &P, Type *AllocaTy,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002045 const DataLayout &DL) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002046 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00002047 // Don't create integer types larger than the maximum bitwidth.
2048 if (SizeInBits > IntegerType::MAX_INT_BITS)
2049 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002050
2051 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002052 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002053 return false;
2054
Chandler Carruth58d05562012-10-25 04:37:07 +00002055 // We need to ensure that an integer type with the appropriate bitwidth can
2056 // be converted to the alloca type, whatever that is. We don't want to force
2057 // the alloca itself to have an integer type if there is a more suitable one.
2058 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002059 if (!canConvertValue(DL, AllocaTy, IntTy) ||
2060 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00002061 return false;
2062
Chandler Carruthf0546402013-07-18 07:15:00 +00002063 // While examining uses, we ensure that the alloca has a covering load or
2064 // store. We don't want to widen the integer operations only to fail to
2065 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00002066 // later). However, if there are only splittable uses, go ahead and assume
2067 // that we cover the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002068 // FIXME: We shouldn't consider split slices that happen to start in the
2069 // partition here...
Chandler Carruthc659df92014-10-16 20:24:07 +00002070 bool WholeAllocaOp =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002071 P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00002072
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002073 for (const Slice &S : P)
2074 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2075 WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00002076 return false;
2077
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002078 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002079 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2080 WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002081 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00002082
Chandler Carruth92924fd2012-09-24 00:34:20 +00002083 return WholeAllocaOp;
2084}
2085
Chandler Carruthd177f862013-03-20 07:30:36 +00002086static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002087 IntegerType *Ty, uint64_t Offset,
2088 const Twine &Name) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002089 LLVM_DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002090 IntegerType *IntTy = cast<IntegerType>(V->getType());
2091 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2092 "Element extends past full value");
Chandler Carruth113dc642014-12-20 02:39:18 +00002093 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002094 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002095 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002096 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002097 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002098 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002099 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002100 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2101 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002102 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002103 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002104 LLVM_DEBUG(dbgs() << " trunced: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002105 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002106 return V;
2107}
2108
Chandler Carruthd177f862013-03-20 07:30:36 +00002109static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002110 Value *V, uint64_t Offset, const Twine &Name) {
2111 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2112 IntegerType *Ty = cast<IntegerType>(V->getType());
2113 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2114 "Cannot insert a larger integer!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002115 LLVM_DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002116 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002117 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002118 LLVM_DEBUG(dbgs() << " extended: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002119 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002120 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2121 "Element store outside of alloca store");
Chandler Carruth113dc642014-12-20 02:39:18 +00002122 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002123 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002124 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002125 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002126 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002127 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002128 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002129
2130 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2131 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2132 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002133 LLVM_DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002134 V = IRB.CreateOr(Old, V, Name + ".insert");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002135 LLVM_DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002136 }
2137 return V;
2138}
2139
Chandler Carruth113dc642014-12-20 02:39:18 +00002140static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2141 unsigned EndIndex, const Twine &Name) {
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002142 VectorType *VecTy = cast<VectorType>(V->getType());
2143 unsigned NumElements = EndIndex - BeginIndex;
2144 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2145
2146 if (NumElements == VecTy->getNumElements())
2147 return V;
2148
2149 if (NumElements == 1) {
2150 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2151 Name + ".extract");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002152 LLVM_DEBUG(dbgs() << " extract: " << *V << "\n");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002153 return V;
2154 }
2155
Chandler Carruth113dc642014-12-20 02:39:18 +00002156 SmallVector<Constant *, 8> Mask;
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002157 Mask.reserve(NumElements);
2158 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2159 Mask.push_back(IRB.getInt32(i));
2160 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002161 ConstantVector::get(Mask), Name + ".extract");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002162 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002163 return V;
2164}
2165
Chandler Carruthd177f862013-03-20 07:30:36 +00002166static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00002167 unsigned BeginIndex, const Twine &Name) {
2168 VectorType *VecTy = cast<VectorType>(Old->getType());
2169 assert(VecTy && "Can only insert a vector into a vector");
2170
2171 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2172 if (!Ty) {
2173 // Single element to insert.
2174 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2175 Name + ".insert");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002176 LLVM_DEBUG(dbgs() << " insert: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002177 return V;
2178 }
2179
2180 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2181 "Too many elements!");
2182 if (Ty->getNumElements() == VecTy->getNumElements()) {
2183 assert(V->getType() == VecTy && "Vector type mismatch");
2184 return V;
2185 }
2186 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2187
2188 // When inserting a smaller vector into the larger to store, we first
2189 // use a shuffle vector to widen it with undef elements, and then
2190 // a second shuffle vector to select between the loaded vector and the
2191 // incoming vector.
Chandler Carruth113dc642014-12-20 02:39:18 +00002192 SmallVector<Constant *, 8> Mask;
Chandler Carruthce4562b2012-12-17 13:41:21 +00002193 Mask.reserve(VecTy->getNumElements());
2194 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2195 if (i >= BeginIndex && i < EndIndex)
2196 Mask.push_back(IRB.getInt32(i - BeginIndex));
2197 else
2198 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2199 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002200 ConstantVector::get(Mask), Name + ".expand");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002201 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002202
2203 Mask.clear();
2204 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00002205 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2206
2207 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2208
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002209 LLVM_DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002210 return V;
2211}
2212
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002213/// Visitor to rewrite instructions using p particular slice of an alloca
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002214/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002215///
2216/// Also implements the rewriting to vector-based accesses when the partition
2217/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2218/// lives here.
Chandler Carruth29a18a42015-09-12 09:09:14 +00002219class llvm::sroa::AllocaSliceRewriter
2220 : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002221 // Befriend the base class so it can delegate to private visit methods.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002222 friend class InstVisitor<AllocaSliceRewriter, bool>;
2223
2224 using Base = InstVisitor<AllocaSliceRewriter, bool>;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002225
Chandler Carruth90a735d2013-07-19 07:21:28 +00002226 const DataLayout &DL;
Chandler Carruth83934062014-10-16 21:11:55 +00002227 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002228 SROA &Pass;
2229 AllocaInst &OldAI, &NewAI;
2230 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00002231 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002232
Chandler Carruth2dc96822014-10-18 00:44:02 +00002233 // This is a convenience and flag variable that will be null unless the new
2234 // alloca's integer operations should be widened to this integer type due to
2235 // passing isIntegerWideningViable above. If it is non-null, the desired
2236 // integer type will be stored here for easy access during rewriting.
2237 IntegerType *IntTy;
2238
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002239 // If we are rewriting an alloca partition which can be written as pure
2240 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002241 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002242 // - The new alloca is exactly the size of the vector type here.
2243 // - The accesses all either map to the entire vector or to a single
2244 // element.
2245 // - The set of accessing instructions is only one of those handled above
2246 // in isVectorPromotionViable. Generally these are the same access kinds
2247 // which are promotable via mem2reg.
2248 VectorType *VecTy;
2249 Type *ElementTy;
2250 uint64_t ElementSize;
2251
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002252 // The original offset of the slice currently being rewritten relative to
2253 // the original alloca.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002254 uint64_t BeginOffset = 0;
2255 uint64_t EndOffset = 0;
2256
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002257 // The new offsets of the slice currently being rewritten relative to the
2258 // original alloca.
2259 uint64_t NewBeginOffset, NewEndOffset;
2260
2261 uint64_t SliceSize;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002262 bool IsSplittable = false;
2263 bool IsSplit = false;
2264 Use *OldUse = nullptr;
2265 Instruction *OldPtr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002266
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002267 // Track post-rewrite users which are PHI nodes and Selects.
Davide Italiano81a26da2017-04-27 23:09:01 +00002268 SmallSetVector<PHINode *, 8> &PHIUsers;
2269 SmallSetVector<SelectInst *, 8> &SelectUsers;
Chandler Carruth83ea1952013-07-24 09:47:28 +00002270
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002271 // Utility IR builder, whose name prefix is setup for each visited use, and
2272 // the insertion point is set to point to the user.
2273 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002274
2275public:
Chandler Carruth83934062014-10-16 21:11:55 +00002276 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002277 AllocaInst &OldAI, AllocaInst &NewAI,
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002278 uint64_t NewAllocaBeginOffset,
Chandler Carruth2dc96822014-10-18 00:44:02 +00002279 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2280 VectorType *PromotableVecTy,
Davide Italiano81a26da2017-04-27 23:09:01 +00002281 SmallSetVector<PHINode *, 8> &PHIUsers,
2282 SmallSetVector<SelectInst *, 8> &SelectUsers)
Chandler Carruth83934062014-10-16 21:11:55 +00002283 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002284 NewAllocaBeginOffset(NewAllocaBeginOffset),
2285 NewAllocaEndOffset(NewAllocaEndOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002286 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002287 IntTy(IsIntegerPromotable
2288 ? Type::getIntNTy(
2289 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002290 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Craig Topperf40110f2014-04-25 05:29:35 +00002291 : nullptr),
Chandler Carruth2dc96822014-10-18 00:44:02 +00002292 VecTy(PromotableVecTy),
2293 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2294 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002295 PHIUsers(PHIUsers), SelectUsers(SelectUsers),
Chandler Carruth83ea1952013-07-24 09:47:28 +00002296 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002297 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002298 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002299 "Only multiple-of-8 sized vector elements are viable");
2300 ++NumVectorized;
2301 }
Chandler Carruth2dc96822014-10-18 00:44:02 +00002302 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002303 }
2304
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002305 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002306 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002307 BeginOffset = I->beginOffset();
2308 EndOffset = I->endOffset();
2309 IsSplittable = I->isSplittable();
2310 IsSplit =
2311 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002312 LLVM_DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
2313 LLVM_DEBUG(AS.printSlice(dbgs(), I, ""));
2314 LLVM_DEBUG(dbgs() << "\n");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002315
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002316 // Compute the intersecting offset range.
2317 assert(BeginOffset < NewAllocaEndOffset);
2318 assert(EndOffset > NewAllocaBeginOffset);
2319 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2320 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2321
2322 SliceSize = NewEndOffset - NewBeginOffset;
2323
Chandler Carruthf0546402013-07-18 07:15:00 +00002324 OldUse = I->getUse();
2325 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002326
Chandler Carruthf0546402013-07-18 07:15:00 +00002327 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2328 IRB.SetInsertPoint(OldUserI);
2329 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2330 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2331
2332 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2333 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002334 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002335 return CanSROA;
2336 }
2337
2338private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002339 // Make sure the other visit overloads are visible.
2340 using Base::visit;
2341
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002342 // Every instruction which can end up as a user must have a rewrite rule.
2343 bool visitInstruction(Instruction &I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002344 LLVM_DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002345 llvm_unreachable("No rewrite rule for this instruction!");
2346 }
2347
Chandler Carruth47954c82014-02-26 05:12:43 +00002348 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2349 // Note that the offset computation can use BeginOffset or NewBeginOffset
2350 // interchangeably for unsplit slices.
2351 assert(IsSplit || BeginOffset == NewBeginOffset);
2352 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2353
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002354#ifndef NDEBUG
2355 StringRef OldName = OldPtr->getName();
2356 // Skip through the last '.sroa.' component of the name.
2357 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2358 if (LastSROAPrefix != StringRef::npos) {
2359 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2360 // Look for an SROA slice index.
2361 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2362 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2363 // Strip the index and look for the offset.
2364 OldName = OldName.substr(IndexEnd + 1);
2365 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2366 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2367 // Strip the offset.
2368 OldName = OldName.substr(OffsetEnd + 1);
2369 }
2370 }
2371 // Strip any SROA suffixes as well.
2372 OldName = OldName.substr(0, OldName.find(".sroa_"));
2373#endif
Chandler Carruth47954c82014-02-26 05:12:43 +00002374
2375 return getAdjustedPtr(IRB, DL, &NewAI,
Nicola Zaghenf96383c2018-10-30 11:15:04 +00002376 APInt(DL.getIndexTypeSizeInBits(PointerTy), Offset),
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002377 PointerTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002378#ifndef NDEBUG
2379 Twine(OldName) + "."
2380#else
2381 Twine()
2382#endif
2383 );
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002384 }
2385
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002386 /// Compute suitable alignment to access this slice of the *new*
Chandler Carruth113dc642014-12-20 02:39:18 +00002387 /// alloca.
Chandler Carruth2659e502014-02-26 05:02:19 +00002388 ///
2389 /// You can optionally pass a type to this routine and if that type's ABI
2390 /// alignment is itself suitable, this will return zero.
Craig Topperf40110f2014-04-25 05:29:35 +00002391 unsigned getSliceAlign(Type *Ty = nullptr) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002392 unsigned NewAIAlign = NewAI.getAlignment();
2393 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002394 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth113dc642014-12-20 02:39:18 +00002395 unsigned Align =
2396 MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
Chandler Carruth2659e502014-02-26 05:02:19 +00002397 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002398 }
2399
Chandler Carruth845b73c2012-11-21 08:16:30 +00002400 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002401 assert(VecTy && "Can only call getIndex when rewriting a vector");
2402 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2403 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2404 uint32_t Index = RelOffset / ElementSize;
2405 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002406 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002407 }
2408
2409 void deleteIfTriviallyDead(Value *V) {
2410 Instruction *I = cast<Instruction>(V);
2411 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002412 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002413 }
2414
Chandler Carruthea27cf02014-02-26 04:25:04 +00002415 Value *rewriteVectorizedLoadInst() {
Chandler Carruthf0546402013-07-18 07:15:00 +00002416 unsigned BeginIndex = getIndex(NewBeginOffset);
2417 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002418 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002419
Chandler Carruth113dc642014-12-20 02:39:18 +00002420 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002421 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002422 }
2423
Chandler Carruthea27cf02014-02-26 04:25:04 +00002424 Value *rewriteIntegerLoad(LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002425 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002426 assert(!LI.isVolatile());
Chandler Carruth113dc642014-12-20 02:39:18 +00002427 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002428 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002429 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2430 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth4b682f62015-08-28 09:03:52 +00002431 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
2432 IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8);
2433 V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract");
2434 }
2435 // It is possible that the extracted type is not the load type. This
2436 // happens if there is a load past the end of the alloca, and as
2437 // a consequence the slice is narrower but still a candidate for integer
2438 // lowering. To handle this case, we just zero extend the extracted
2439 // integer.
2440 assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 &&
2441 "Can only handle an extract for an overly wide load");
2442 if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8)
2443 V = IRB.CreateZExt(V, LI.getType());
Chandler Carruth18db7952012-11-20 01:12:50 +00002444 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002445 }
2446
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002447 bool visitLoadInst(LoadInst &LI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002448 LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002449 Value *OldOp = LI.getOperand(0);
2450 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002451
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002452 AAMDNodes AATags;
2453 LI.getAAMetadata(AATags);
2454
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002455 unsigned AS = LI.getPointerAddressSpace();
2456
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002457 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002458 : LI.getType();
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002459 const bool IsLoadPastEnd = DL.getTypeStoreSize(TargetTy) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002460 bool IsPtrAdjusted = false;
2461 Value *V;
2462 if (VecTy) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002463 V = rewriteVectorizedLoadInst();
Chandler Carruth18db7952012-11-20 01:12:50 +00002464 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002465 V = rewriteIntegerLoad(LI);
Chandler Carruthf0546402013-07-18 07:15:00 +00002466 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002467 NewEndOffset == NewAllocaEndOffset &&
2468 (canConvertValue(DL, NewAllocaTy, TargetTy) ||
2469 (IsLoadPastEnd && NewAllocaTy->isIntegerTy() &&
2470 TargetTy->isIntegerTy()))) {
David Majnemer62690b12015-07-14 06:19:58 +00002471 LoadInst *NewLI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2472 LI.isVolatile(), LI.getName());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002473 if (AATags)
2474 NewLI->setAAMetadata(AATags);
David Majnemer62690b12015-07-14 06:19:58 +00002475 if (LI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002476 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
Luqman Aden3f807c92017-03-22 19:16:39 +00002477
Chandler Carruth3f81d802017-06-27 08:32:03 +00002478 // Any !nonnull metadata or !range metadata on the old load is also valid
2479 // on the new load. This is even true in some cases even when the loads
2480 // are different types, for example by mapping !nonnull metadata to
2481 // !range metadata by modeling the null pointer constant converted to the
2482 // integer type.
Rafael Espindolac06f55e2017-11-28 01:25:38 +00002483 // FIXME: Add support for range metadata here. Currently the utilities
2484 // for this don't propagate range metadata in trivial cases from one
2485 // integer load to another, don't handle non-addrspace-0 null pointers
2486 // correctly, and don't have any support for mapping ranges as the
2487 // integer type becomes winder or narrower.
Chandler Carruth3f81d802017-06-27 08:32:03 +00002488 if (MDNode *N = LI.getMetadata(LLVMContext::MD_nonnull))
2489 copyNonnullMetadata(LI, N, *NewLI);
Rafael Espindolac06f55e2017-11-28 01:25:38 +00002490
2491 // Try to preserve nonnull metadata
David Majnemer62690b12015-07-14 06:19:58 +00002492 V = NewLI;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002493
2494 // If this is an integer load past the end of the slice (which means the
2495 // bytes outside the slice are undef or this load is dead) just forcibly
2496 // fix the integer size with correct handling of endianness.
2497 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2498 if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
2499 if (AITy->getBitWidth() < TITy->getBitWidth()) {
2500 V = IRB.CreateZExt(V, TITy, "load.ext");
2501 if (DL.isBigEndian())
2502 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
2503 "endian_shift");
2504 }
Chandler Carruth18db7952012-11-20 01:12:50 +00002505 } else {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002506 Type *LTy = TargetTy->getPointerTo(AS);
David Majnemer62690b12015-07-14 06:19:58 +00002507 LoadInst *NewLI = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
2508 getSliceAlign(TargetTy),
2509 LI.isVolatile(), LI.getName());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002510 if (AATags)
2511 NewLI->setAAMetadata(AATags);
David Majnemer62690b12015-07-14 06:19:58 +00002512 if (LI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002513 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
David Majnemer62690b12015-07-14 06:19:58 +00002514
2515 V = NewLI;
Chandler Carruth18db7952012-11-20 01:12:50 +00002516 IsPtrAdjusted = true;
2517 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002518 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002519
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002520 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002521 assert(!LI.isVolatile());
2522 assert(LI.getType()->isIntegerTy() &&
2523 "Only integer type loads and stores are split");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002524 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002525 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002526 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002527 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002528 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002529 // 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 +00002530 IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002531 // Create a placeholder value with the same type as LI to use as the
2532 // basis for the new value. This allows us to replace the uses of LI with
2533 // the computed value, and then replace the placeholder with LI, leaving
2534 // LI only used for this computation.
Chandler Carruth113dc642014-12-20 02:39:18 +00002535 Value *Placeholder =
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002536 new LoadInst(UndefValue::get(LI.getType()->getPointerTo(AS)));
Chandler Carruth24ac8302015-01-02 03:55:54 +00002537 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2538 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002539 LI.replaceAllUsesWith(V);
2540 Placeholder->replaceAllUsesWith(&LI);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002541 Placeholder->deleteValue();
Chandler Carruth18db7952012-11-20 01:12:50 +00002542 } else {
2543 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002544 }
2545
Chandler Carruth18db7952012-11-20 01:12:50 +00002546 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002547 deleteIfTriviallyDead(OldOp);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002548 LLVM_DEBUG(dbgs() << " to: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002549 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002550 }
2551
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002552 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2553 AAMDNodes AATags) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002554 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002555 unsigned BeginIndex = getIndex(NewBeginOffset);
2556 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002557 assert(EndIndex > BeginIndex && "Empty vector!");
2558 unsigned NumElements = EndIndex - BeginIndex;
2559 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth113dc642014-12-20 02:39:18 +00002560 Type *SliceTy = (NumElements == 1)
2561 ? ElementTy
2562 : VectorType::get(ElementTy, NumElements);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002563 if (V->getType() != SliceTy)
2564 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002565
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002566 // Mix in the existing elements.
Chandler Carruth113dc642014-12-20 02:39:18 +00002567 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002568 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2569 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002570 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002571 if (AATags)
2572 Store->setAAMetadata(AATags);
Chandler Carruth18db7952012-11-20 01:12:50 +00002573 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002574
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002575 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002576 return true;
2577 }
2578
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002579 bool rewriteIntegerStore(Value *V, StoreInst &SI, AAMDNodes AATags) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002580 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002581 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002582 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002583 Value *Old =
2584 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002585 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002586 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2587 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth113dc642014-12-20 02:39:18 +00002588 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002589 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002590 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002591 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Michael Kruse978ba612018-12-20 04:58:07 +00002592 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2593 LLVMContext::MD_access_group});
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002594 if (AATags)
2595 Store->setAAMetadata(AATags);
Chandler Carruth18db7952012-11-20 01:12:50 +00002596 Pass.DeadInsts.insert(&SI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002597 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002598 return true;
2599 }
2600
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002601 bool visitStoreInst(StoreInst &SI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002602 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002603 Value *OldOp = SI.getOperand(1);
2604 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002605
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002606 AAMDNodes AATags;
2607 SI.getAAMetadata(AATags);
2608
Chandler Carruth18db7952012-11-20 01:12:50 +00002609 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002610
Chandler Carruthac8317f2012-10-04 12:33:50 +00002611 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2612 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002613 if (V->getType()->isPointerTy())
2614 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002615 Pass.PostPromotionWorklist.insert(AI);
2616
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002617 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002618 assert(!SI.isVolatile());
2619 assert(V->getType()->isIntegerTy() &&
2620 "Only integer type loads and stores are split");
2621 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002622 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002623 "Non-byte-multiple bit width");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002624 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
Chandler Carruth24ac8302015-01-02 03:55:54 +00002625 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2626 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002627 }
2628
Chandler Carruth18db7952012-11-20 01:12:50 +00002629 if (VecTy)
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002630 return rewriteVectorizedStoreInst(V, SI, OldOp, AATags);
Chandler Carruth18db7952012-11-20 01:12:50 +00002631 if (IntTy && V->getType()->isIntegerTy())
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002632 return rewriteIntegerStore(V, SI, AATags);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002633
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002634 const bool IsStorePastEnd = DL.getTypeStoreSize(V->getType()) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002635 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002636 if (NewBeginOffset == NewAllocaBeginOffset &&
2637 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002638 (canConvertValue(DL, V->getType(), NewAllocaTy) ||
2639 (IsStorePastEnd && NewAllocaTy->isIntegerTy() &&
2640 V->getType()->isIntegerTy()))) {
2641 // If this is an integer store past the end of slice (and thus the bytes
2642 // past that point are irrelevant or this is unreachable), truncate the
2643 // value prior to storing.
2644 if (auto *VITy = dyn_cast<IntegerType>(V->getType()))
2645 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2646 if (VITy->getBitWidth() > AITy->getBitWidth()) {
2647 if (DL.isBigEndian())
2648 V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
2649 "endian_shift");
2650 V = IRB.CreateTrunc(V, AITy, "load.trunc");
2651 }
2652
Chandler Carruth90a735d2013-07-19 07:21:28 +00002653 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002654 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2655 SI.isVolatile());
2656 } else {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002657 unsigned AS = SI.getPointerAddressSpace();
2658 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo(AS));
Chandler Carruth2659e502014-02-26 05:02:19 +00002659 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2660 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002661 }
Michael Kruse978ba612018-12-20 04:58:07 +00002662 NewSI->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2663 LLVMContext::MD_access_group});
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002664 if (AATags)
2665 NewSI->setAAMetadata(AATags);
David Majnemer62690b12015-07-14 06:19:58 +00002666 if (SI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002667 NewSI->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
Chandler Carruth18db7952012-11-20 01:12:50 +00002668 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002669 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002670
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002671 LLVM_DEBUG(dbgs() << " to: " << *NewSI << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002672 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002673 }
2674
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002675 /// Compute an integer value from splatting an i8 across the given
Chandler Carruth514f34f2012-12-17 04:07:30 +00002676 /// number of bytes.
2677 ///
2678 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2679 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002680 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002681 ///
2682 /// \param V The i8 value to splat.
2683 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002684 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002685 assert(Size > 0 && "Expected a positive number of bytes.");
2686 IntegerType *VTy = cast<IntegerType>(V->getType());
2687 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2688 if (Size == 1)
2689 return V;
2690
Chandler Carruth113dc642014-12-20 02:39:18 +00002691 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2692 V = IRB.CreateMul(
2693 IRB.CreateZExt(V, SplatIntTy, "zext"),
2694 ConstantExpr::getUDiv(
2695 Constant::getAllOnesValue(SplatIntTy),
2696 ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2697 SplatIntTy)),
2698 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002699 return V;
2700 }
2701
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002702 /// Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002703 Value *getVectorSplat(Value *V, unsigned NumElements) {
2704 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002705 LLVM_DEBUG(dbgs() << " splat: " << *V << "\n");
Chandler Carruthccca5042012-12-17 04:07:37 +00002706 return V;
2707 }
2708
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002709 bool visitMemSetInst(MemSetInst &II) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002710 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002711 assert(II.getRawDest() == OldPtr);
2712
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002713 AAMDNodes AATags;
2714 II.getAAMetadata(AATags);
2715
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002716 // If the memset has a variable size, it cannot be split, just adjust the
2717 // pointer to the new alloca.
2718 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002719 assert(!IsSplit);
Chandler Carruth735d5be2014-02-26 04:45:24 +00002720 assert(NewBeginOffset == BeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002721 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
Daniel Neilson41e781d2018-03-13 14:25:33 +00002722 II.setDestAlignment(getSliceAlign());
Chandler Carruth208124f2012-09-26 10:59:22 +00002723
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002724 deleteIfTriviallyDead(OldPtr);
2725 return false;
2726 }
2727
2728 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002729 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002730
2731 Type *AllocaTy = NewAI.getAllocatedType();
2732 Type *ScalarTy = AllocaTy->getScalarType();
2733
2734 // If this doesn't map cleanly onto the alloca type, and that type isn't
2735 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002736 if (!VecTy && !IntTy &&
Chandler Carruth113dc642014-12-20 02:39:18 +00002737 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002738 SliceSize != DL.getTypeStoreSize(AllocaTy) ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002739 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002740 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
Chandler Carruth113dc642014-12-20 02:39:18 +00002741 DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002742 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002743 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2744 CallInst *New = IRB.CreateMemSet(
Chandler Carruth47954c82014-02-26 05:12:43 +00002745 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2746 getSliceAlign(), II.isVolatile());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002747 if (AATags)
2748 New->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002749 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002750 return false;
2751 }
2752
2753 // If we can represent this as a simple value, we have to build the actual
2754 // value to store, which requires expanding the byte present in memset to
2755 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002756 // splatting the byte to a sufficiently wide integer, splatting it across
2757 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002758 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002759
Chandler Carruthccca5042012-12-17 04:07:37 +00002760 if (VecTy) {
2761 // If this is a memset of a vectorized alloca, insert it.
2762 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002763
Chandler Carruthf0546402013-07-18 07:15:00 +00002764 unsigned BeginIndex = getIndex(NewBeginOffset);
2765 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002766 assert(EndIndex > BeginIndex && "Empty vector!");
2767 unsigned NumElements = EndIndex - BeginIndex;
2768 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2769
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002770 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002771 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2772 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002773 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002774 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002775
Chandler Carruth113dc642014-12-20 02:39:18 +00002776 Value *Old =
2777 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002778 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002779 } else if (IntTy) {
2780 // If this is a memset on an alloca where we can widen stores, insert the
2781 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002782 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002783
Chandler Carruthf0546402013-07-18 07:15:00 +00002784 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002785 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002786
2787 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2788 EndOffset != NewAllocaBeginOffset)) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002789 Value *Old =
2790 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002791 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002792 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002793 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002794 } else {
2795 assert(V->getType() == IntTy &&
2796 "Wrong type for an alloca wide integer!");
2797 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002798 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002799 } else {
2800 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002801 assert(NewBeginOffset == NewAllocaBeginOffset);
2802 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002803
Chandler Carruth90a735d2013-07-19 07:21:28 +00002804 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002805 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002806 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002807
Chandler Carruth90a735d2013-07-19 07:21:28 +00002808 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002809 }
2810
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002811 StoreInst *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2812 II.isVolatile());
2813 if (AATags)
2814 New->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002815 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002816 return !II.isVolatile();
2817 }
2818
2819 bool visitMemTransferInst(MemTransferInst &II) {
2820 // Rewriting of memory transfer instructions can be a bit tricky. We break
2821 // them into two categories: split intrinsics and unsplit intrinsics.
2822
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002823 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002824
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002825 AAMDNodes AATags;
2826 II.getAAMetadata(AATags);
2827
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002828 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002829 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002830 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002831
Chandler Carruthaa72b932014-02-26 07:29:54 +00002832 unsigned SliceAlign = getSliceAlign();
Chandler Carruth176ca712012-10-01 12:16:54 +00002833
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002834 // For unsplit intrinsics, we simply modify the source and destination
2835 // pointers in place. This isn't just an optimization, it is a matter of
2836 // correctness. With unsplit intrinsics we may be dealing with transfers
2837 // within a single alloca before SROA ran, or with transfers that have
2838 // a variable length. We may also be dealing with memmove instead of
2839 // memcpy, and so simply updating the pointers is the necessary for us to
2840 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002841 if (!IsSplittable) {
Chandler Carruth47954c82014-02-26 05:12:43 +00002842 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Daniel Neilson41e781d2018-03-13 14:25:33 +00002843 if (IsDest) {
Chandler Carruth8183a502014-02-25 11:08:02 +00002844 II.setDest(AdjustedPtr);
Daniel Neilson41e781d2018-03-13 14:25:33 +00002845 II.setDestAlignment(SliceAlign);
2846 }
2847 else {
Chandler Carruth8183a502014-02-25 11:08:02 +00002848 II.setSource(AdjustedPtr);
Daniel Neilson41e781d2018-03-13 14:25:33 +00002849 II.setSourceAlignment(SliceAlign);
Chandler Carruth181ed052014-02-26 05:33:36 +00002850 }
Chandler Carruth208124f2012-09-26 10:59:22 +00002851
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002852 LLVM_DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002853 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002854 return false;
2855 }
2856 // For split transfer intrinsics we have an incredibly useful assurance:
2857 // the source and destination do not reside within the same alloca, and at
2858 // least one of them does not escape. This means that we can replace
2859 // memmove with memcpy, and we don't need to worry about all manner of
2860 // downsides to splitting and transforming the operations.
2861
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002862 // If this doesn't map cleanly onto the alloca type, and that type isn't
2863 // a single value type, just emit a memcpy.
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002864 bool EmitMemCpy =
2865 !VecTy && !IntTy &&
2866 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2867 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2868 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002869
2870 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2871 // size hasn't been shrunk based on analysis of the viable range, this is
2872 // a no-op.
2873 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002874 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002875 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002876
2877 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002878 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002879 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002880 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002881 return false;
2882 }
2883 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002884 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002885
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002886 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2887 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002888 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth113dc642014-12-20 02:39:18 +00002889 if (AllocaInst *AI =
2890 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002891 assert(AI != &OldAI && AI != &NewAI &&
2892 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002893 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002894 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002895
Chandler Carruth286d87e2014-02-26 08:25:02 +00002896 Type *OtherPtrTy = OtherPtr->getType();
2897 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2898
Chandler Carruth181ed052014-02-26 05:33:36 +00002899 // Compute the relative offset for the other pointer within the transfer.
Nicola Zaghenf96383c2018-10-30 11:15:04 +00002900 unsigned OffsetWidth = DL.getIndexSizeInBits(OtherAS);
2901 APInt OtherOffset(OffsetWidth, NewBeginOffset - BeginOffset);
Daniel Neilson41e781d2018-03-13 14:25:33 +00002902 unsigned OtherAlign =
2903 IsDest ? II.getSourceAlignment() : II.getDestAlignment();
2904 OtherAlign = MinAlign(OtherAlign ? OtherAlign : 1,
2905 OtherOffset.zextOrTrunc(64).getZExtValue());
Chandler Carruth181ed052014-02-26 05:33:36 +00002906
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002907 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002908 // Compute the other pointer, folding as much as possible to produce
2909 // a single, simple GEP in most cases.
Chandler Carruth181ed052014-02-26 05:33:36 +00002910 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002911 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002912
Chandler Carruth47954c82014-02-26 05:12:43 +00002913 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002914 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002915 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002916
Daniel Neilson41e781d2018-03-13 14:25:33 +00002917 Value *DestPtr, *SrcPtr;
2918 unsigned DestAlign, SrcAlign;
2919 // Note: IsDest is true iff we're copying into the new alloca slice
2920 if (IsDest) {
2921 DestPtr = OurPtr;
2922 DestAlign = SliceAlign;
2923 SrcPtr = OtherPtr;
2924 SrcAlign = OtherAlign;
2925 } else {
2926 DestPtr = OtherPtr;
2927 DestAlign = OtherAlign;
2928 SrcPtr = OurPtr;
2929 SrcAlign = SliceAlign;
2930 }
2931 CallInst *New = IRB.CreateMemCpy(DestPtr, DestAlign, SrcPtr, SrcAlign,
2932 Size, II.isVolatile());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002933 if (AATags)
2934 New->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002935 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002936 return false;
2937 }
2938
Chandler Carruthf0546402013-07-18 07:15:00 +00002939 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2940 NewEndOffset == NewAllocaEndOffset;
2941 uint64_t Size = NewEndOffset - NewBeginOffset;
2942 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2943 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002944 unsigned NumElements = EndIndex - BeginIndex;
Chandler Carruth113dc642014-12-20 02:39:18 +00002945 IntegerType *SubIntTy =
2946 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002947
Chandler Carruth286d87e2014-02-26 08:25:02 +00002948 // Reset the other pointer type to match the register type we're going to
2949 // use, but using the address space of the original other pointer.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002950 if (VecTy && !IsWholeAlloca) {
2951 if (NumElements == 1)
2952 OtherPtrTy = VecTy->getElementType();
2953 else
2954 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2955
Chandler Carruth286d87e2014-02-26 08:25:02 +00002956 OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002957 } else if (IntTy && !IsWholeAlloca) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00002958 OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2959 } else {
2960 OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002961 }
2962
Chandler Carruth181ed052014-02-26 05:33:36 +00002963 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002964 OtherPtr->getName() + ".");
Pete Cooper67cf9a72015-11-19 05:56:52 +00002965 unsigned SrcAlign = OtherAlign;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002966 Value *DstPtr = &NewAI;
Chandler Carruthaa72b932014-02-26 07:29:54 +00002967 unsigned DstAlign = SliceAlign;
2968 if (!IsDest) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002969 std::swap(SrcPtr, DstPtr);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002970 std::swap(SrcAlign, DstAlign);
2971 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002972
2973 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002974 if (VecTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002975 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002976 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002977 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002978 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002979 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002980 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002981 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002982 } else {
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002983 LoadInst *Load = IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(),
2984 "copyload");
2985 if (AATags)
2986 Load->setAAMetadata(AATags);
2987 Src = Load;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002988 }
2989
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002990 if (VecTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002991 Value *Old =
2992 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002993 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002994 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002995 Value *Old =
2996 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002997 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002998 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002999 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
3000 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00003001 }
3002
Chandler Carruth871ba722012-09-26 10:27:46 +00003003 StoreInst *Store = cast<StoreInst>(
Chandler Carruthaa72b932014-02-26 07:29:54 +00003004 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003005 if (AATags)
3006 Store->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003007 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003008 return !II.isVolatile();
3009 }
3010
3011 bool visitIntrinsicInst(IntrinsicInst &II) {
Vedant Kumarb264d692018-12-21 21:49:40 +00003012 assert(II.isLifetimeStartOrEnd());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003013 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003014 assert(II.getArgOperand(1) == OldPtr);
3015
3016 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00003017 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003018
Eli Friedman50967752016-11-28 21:50:34 +00003019 // Lifetime intrinsics are only promotable if they cover the whole alloca.
3020 // Therefore, we drop lifetime intrinsics which don't cover the whole
3021 // alloca.
3022 // (In theory, intrinsics which partially cover an alloca could be
3023 // promoted, but PromoteMemToReg doesn't handle that case.)
3024 // FIXME: Check whether the alloca is promotable before dropping the
3025 // lifetime intrinsics?
3026 if (NewBeginOffset != NewAllocaBeginOffset ||
3027 NewEndOffset != NewAllocaEndOffset)
3028 return true;
3029
Chandler Carruth113dc642014-12-20 02:39:18 +00003030 ConstantInt *Size =
3031 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00003032 NewEndOffset - NewBeginOffset);
Gabor Buella3ec170c2019-01-16 12:06:17 +00003033 // Lifetime intrinsics always expect an i8* so directly get such a pointer
3034 // for the new alloca slice.
3035 Type *PointerTy = IRB.getInt8PtrTy(OldPtr->getType()->getPointerAddressSpace());
3036 Value *Ptr = getNewAllocaSlicePtr(IRB, PointerTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003037 Value *New;
3038 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
3039 New = IRB.CreateLifetimeStart(Ptr, Size);
3040 else
3041 New = IRB.CreateLifetimeEnd(Ptr, Size);
3042
Edwin Vane82f80d42013-01-29 17:42:24 +00003043 (void)New;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003044 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Eli Friedman2a65dd12016-08-08 01:30:53 +00003045
Eli Friedman50967752016-11-28 21:50:34 +00003046 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003047 }
3048
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003049 void fixLoadStoreAlign(Instruction &Root) {
3050 // This algorithm implements the same visitor loop as
3051 // hasUnsafePHIOrSelectUse, and fixes the alignment of each load
3052 // or store found.
3053 SmallPtrSet<Instruction *, 4> Visited;
3054 SmallVector<Instruction *, 4> Uses;
3055 Visited.insert(&Root);
3056 Uses.push_back(&Root);
3057 do {
3058 Instruction *I = Uses.pop_back_val();
3059
3060 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3061 unsigned LoadAlign = LI->getAlignment();
3062 if (!LoadAlign)
3063 LoadAlign = DL.getABITypeAlignment(LI->getType());
3064 LI->setAlignment(std::min(LoadAlign, getSliceAlign()));
3065 continue;
3066 }
3067 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3068 unsigned StoreAlign = SI->getAlignment();
3069 if (!StoreAlign) {
3070 Value *Op = SI->getOperand(0);
3071 StoreAlign = DL.getABITypeAlignment(Op->getType());
3072 }
3073 SI->setAlignment(std::min(StoreAlign, getSliceAlign()));
3074 continue;
3075 }
3076
3077 assert(isa<BitCastInst>(I) || isa<PHINode>(I) ||
3078 isa<SelectInst>(I) || isa<GetElementPtrInst>(I));
3079 for (User *U : I->users())
3080 if (Visited.insert(cast<Instruction>(U)).second)
3081 Uses.push_back(cast<Instruction>(U));
3082 } while (!Uses.empty());
3083 }
3084
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003085 bool visitPHINode(PHINode &PN) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003086 LLVM_DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00003087 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
3088 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003089
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003090 // We would like to compute a new pointer in only one place, but have it be
3091 // as local as possible to the PHI. To do that, we re-use the location of
3092 // the old pointer, which necessarily must be in the right position to
3093 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00003094 IRBuilderTy PtrBuilder(IRB);
David Majnemerd4cffcf2014-09-01 21:20:14 +00003095 if (isa<PHINode>(OldPtr))
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003096 PtrBuilder.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
David Majnemerd4cffcf2014-09-01 21:20:14 +00003097 else
3098 PtrBuilder.SetInsertPoint(OldPtr);
Chandler Carruth51175532014-02-25 11:12:04 +00003099 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003100
Chandler Carruth47954c82014-02-26 05:12:43 +00003101 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00003102 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003103 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003104
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003105 LLVM_DEBUG(dbgs() << " to: " << PN << "\n");
Chandler Carruth82a57542012-10-01 10:54:05 +00003106 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003107
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003108 // Fix the alignment of any loads or stores using this PHI node.
3109 fixLoadStoreAlign(PN);
3110
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003111 // PHIs can't be promoted on their own, but often can be speculated. We
3112 // check the speculation outside of the rewriter so that we see the
3113 // fully-rewritten alloca.
3114 PHIUsers.insert(&PN);
3115 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003116 }
3117
3118 bool visitSelectInst(SelectInst &SI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003119 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003120 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
3121 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00003122 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
3123 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003124
Chandler Carruth47954c82014-02-26 05:12:43 +00003125 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003126 // Replace the operands which were using the old pointer.
3127 if (SI.getOperand(1) == OldPtr)
3128 SI.setOperand(1, NewPtr);
3129 if (SI.getOperand(2) == OldPtr)
3130 SI.setOperand(2, NewPtr);
3131
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003132 LLVM_DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003133 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003134
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003135 // Fix the alignment of any loads or stores using this select.
3136 fixLoadStoreAlign(SI);
3137
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003138 // Selects can't be promoted on their own, but often can be speculated. We
3139 // check the speculation outside of the rewriter so that we see the
3140 // fully-rewritten alloca.
3141 SelectUsers.insert(&SI);
3142 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003143 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003144};
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003145
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003146namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003147
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003148/// Visitor to rewrite aggregate loads and stores as scalar.
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003149///
3150/// This pass aggressively rewrites all aggregate loads and stores on
3151/// a particular pointer (or any pointer derived from it which we can identify)
3152/// with scalar loads and stores.
3153class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3154 // Befriend the base class so it can delegate to private visit methods.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003155 friend class InstVisitor<AggLoadStoreRewriter, bool>;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003156
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003157 /// Queue of pointer uses to analyze and potentially rewrite.
3158 SmallVector<Use *, 8> Queue;
3159
3160 /// Set to prevent us from cycling with phi nodes and loops.
3161 SmallPtrSet<User *, 8> Visited;
3162
3163 /// The current pointer use being rewritten. This is used to dig up the used
3164 /// value (as opposed to the user).
3165 Use *U;
3166
Tim Northover856628f2018-12-18 09:29:39 +00003167 /// Used to calculate offsets, and hence alignment, of subobjects.
3168 const DataLayout &DL;
3169
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003170public:
Tim Northover856628f2018-12-18 09:29:39 +00003171 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
3172
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003173 /// Rewrite loads and stores through a pointer and all pointers derived from
3174 /// it.
3175 bool rewrite(Instruction &I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003176 LLVM_DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003177 enqueueUsers(I);
3178 bool Changed = false;
3179 while (!Queue.empty()) {
3180 U = Queue.pop_back_val();
3181 Changed |= visit(cast<Instruction>(U->getUser()));
3182 }
3183 return Changed;
3184 }
3185
3186private:
3187 /// Enqueue all the users of the given instruction for further processing.
3188 /// This uses a set to de-duplicate users.
3189 void enqueueUsers(Instruction &I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003190 for (Use &U : I.uses())
David Blaikie70573dc2014-11-19 07:49:26 +00003191 if (Visited.insert(U.getUser()).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00003192 Queue.push_back(&U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003193 }
3194
3195 // Conservative default is to not rewrite anything.
3196 bool visitInstruction(Instruction &I) { return false; }
3197
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003198 /// Generic recursive split emission class.
Chandler Carruth113dc642014-12-20 02:39:18 +00003199 template <typename Derived> class OpSplitter {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003200 protected:
3201 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00003202 IRBuilderTy IRB;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003203
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003204 /// The indices which to be used with insert- or extractvalue to select the
3205 /// appropriate value within the aggregate.
3206 SmallVector<unsigned, 4> Indices;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003207
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003208 /// The indices to a GEP instruction which will move Ptr to the correct slot
3209 /// within the aggregate.
3210 SmallVector<Value *, 4> GEPIndices;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003211
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003212 /// The base pointer of the original op, used as a base for GEPing the
3213 /// split operations.
3214 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003215
Tim Northover856628f2018-12-18 09:29:39 +00003216 /// The base pointee type being GEPed into.
3217 Type *BaseTy;
3218
3219 /// Known alignment of the base pointer.
3220 unsigned BaseAlign;
3221
3222 /// To calculate offset of each component so we can correctly deduce
3223 /// alignments.
3224 const DataLayout &DL;
3225
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003226 /// Initialize the splitter with an insertion point, Ptr and start with a
3227 /// single zero GEP index.
Tim Northover856628f2018-12-18 09:29:39 +00003228 OpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3229 unsigned BaseAlign, const DataLayout &DL)
3230 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr),
3231 BaseTy(BaseTy), BaseAlign(BaseAlign), DL(DL) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003232
3233 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003234 /// Generic recursive split emission routine.
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003235 ///
3236 /// This method recursively splits an aggregate op (load or store) into
3237 /// scalar or vector ops. It splits recursively until it hits a single value
3238 /// and emits that single value operation via the template argument.
3239 ///
3240 /// The logic of this routine relies on GEPs and insertvalue and
3241 /// extractvalue all operating with the same fundamental index list, merely
3242 /// formatted differently (GEPs need actual values).
3243 ///
3244 /// \param Ty The type being split recursively into smaller ops.
3245 /// \param Agg The aggregate value being built up or stored, depending on
3246 /// whether this is splitting a load or a store respectively.
3247 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
Tim Northover856628f2018-12-18 09:29:39 +00003248 if (Ty->isSingleValueType()) {
3249 unsigned Offset = DL.getIndexedOffsetInType(BaseTy, GEPIndices);
3250 return static_cast<Derived *>(this)->emitFunc(
3251 Ty, Agg, MinAlign(BaseAlign, Offset), Name);
3252 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003253
3254 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3255 unsigned OldSize = Indices.size();
3256 (void)OldSize;
3257 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3258 ++Idx) {
3259 assert(Indices.size() == OldSize && "Did not return to the old size");
3260 Indices.push_back(Idx);
3261 GEPIndices.push_back(IRB.getInt32(Idx));
3262 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3263 GEPIndices.pop_back();
3264 Indices.pop_back();
3265 }
3266 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003267 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003268
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003269 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3270 unsigned OldSize = Indices.size();
3271 (void)OldSize;
3272 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3273 ++Idx) {
3274 assert(Indices.size() == OldSize && "Did not return to the old size");
3275 Indices.push_back(Idx);
3276 GEPIndices.push_back(IRB.getInt32(Idx));
3277 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3278 GEPIndices.pop_back();
3279 Indices.pop_back();
3280 }
3281 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003282 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003283
3284 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003285 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003286 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003287
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003288 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003289 AAMDNodes AATags;
3290
Tim Northover856628f2018-12-18 09:29:39 +00003291 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3292 AAMDNodes AATags, unsigned BaseAlign, const DataLayout &DL)
3293 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
3294 DL), AATags(AATags) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003295
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003296 /// Emit a leaf load of a single value. This is called at the leaves of the
3297 /// recursive emission to actually load values.
Tim Northover856628f2018-12-18 09:29:39 +00003298 void emitFunc(Type *Ty, Value *&Agg, unsigned Align, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003299 assert(Ty->isSingleValueType());
3300 // Load the single value and insert it using the indices.
David Blaikieaa41cd52015-04-03 21:33:42 +00003301 Value *GEP =
3302 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
Tim Northover856628f2018-12-18 09:29:39 +00003303 LoadInst *Load = IRB.CreateAlignedLoad(GEP, Align, Name + ".load");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003304 if (AATags)
3305 Load->setAAMetadata(AATags);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003306 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003307 LLVM_DEBUG(dbgs() << " to: " << *Load << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003308 }
3309 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003310
3311 bool visitLoadInst(LoadInst &LI) {
3312 assert(LI.getPointerOperand() == *U);
3313 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3314 return false;
3315
3316 // We have an aggregate being loaded, split it apart.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003317 LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003318 AAMDNodes AATags;
3319 LI.getAAMetadata(AATags);
Tim Northover856628f2018-12-18 09:29:39 +00003320 LoadOpSplitter Splitter(&LI, *U, LI.getType(), AATags,
3321 getAdjustedAlignment(&LI, 0, DL), DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003322 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003323 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003324 LI.replaceAllUsesWith(V);
3325 LI.eraseFromParent();
3326 return true;
3327 }
3328
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003329 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Tim Northover856628f2018-12-18 09:29:39 +00003330 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3331 AAMDNodes AATags, unsigned BaseAlign, const DataLayout &DL)
3332 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
3333 DL),
3334 AATags(AATags) {}
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003335 AAMDNodes AATags;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003336 /// Emit a leaf store of a single value. This is called at the leaves of the
3337 /// recursive emission to actually produce stores.
Tim Northover856628f2018-12-18 09:29:39 +00003338 void emitFunc(Type *Ty, Value *&Agg, unsigned Align, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003339 assert(Ty->isSingleValueType());
3340 // Extract the single value and store it using the indices.
Patrik Hagglunda83706e2016-06-20 10:19:00 +00003341 //
3342 // The gep and extractvalue values are factored out of the CreateStore
3343 // call to make the output independent of the argument evaluation order.
Patrik Hagglund4e0bd842016-06-20 11:19:58 +00003344 Value *ExtractValue =
3345 IRB.CreateExtractValue(Agg, Indices, Name + ".extract");
3346 Value *InBoundsGEP =
3347 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
Tim Northover856628f2018-12-18 09:29:39 +00003348 StoreInst *Store =
3349 IRB.CreateAlignedStore(ExtractValue, InBoundsGEP, Align);
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003350 if (AATags)
3351 Store->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003352 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003353 }
3354 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003355
3356 bool visitStoreInst(StoreInst &SI) {
3357 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3358 return false;
3359 Value *V = SI.getValueOperand();
3360 if (V->getType()->isSingleValueType())
3361 return false;
3362
3363 // We have an aggregate being stored, split it apart.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003364 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003365 AAMDNodes AATags;
3366 SI.getAAMetadata(AATags);
Tim Northover856628f2018-12-18 09:29:39 +00003367 StoreOpSplitter Splitter(&SI, *U, V->getType(), AATags,
3368 getAdjustedAlignment(&SI, 0, DL), DL);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003369 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003370 SI.eraseFromParent();
3371 return true;
3372 }
3373
3374 bool visitBitCastInst(BitCastInst &BC) {
3375 enqueueUsers(BC);
3376 return false;
3377 }
3378
3379 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3380 enqueueUsers(GEPI);
3381 return false;
3382 }
3383
3384 bool visitPHINode(PHINode &PN) {
3385 enqueueUsers(PN);
3386 return false;
3387 }
3388
3389 bool visitSelectInst(SelectInst &SI) {
3390 enqueueUsers(SI);
3391 return false;
3392 }
3393};
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003394
3395} // end anonymous namespace
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003396
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003397/// Strip aggregate type wrapping.
Chandler Carruthba931992012-10-13 10:49:33 +00003398///
3399/// This removes no-op aggregate types wrapping an underlying type. It will
3400/// strip as many layers of types as it can without changing either the type
3401/// size or the allocated size.
3402static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3403 if (Ty->isSingleValueType())
3404 return Ty;
3405
3406 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3407 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3408
3409 Type *InnerTy;
3410 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3411 InnerTy = ArrTy->getElementType();
3412 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3413 const StructLayout *SL = DL.getStructLayout(STy);
3414 unsigned Index = SL->getElementContainingOffset(0);
3415 InnerTy = STy->getElementType(Index);
3416 } else {
3417 return Ty;
3418 }
3419
3420 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3421 TypeSize > DL.getTypeSizeInBits(InnerTy))
3422 return Ty;
3423
3424 return stripAggregateTypeWrapping(DL, InnerTy);
3425}
3426
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003427/// Try to find a partition of the aggregate type passed in for a given
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003428/// offset and size.
3429///
3430/// This recurses through the aggregate type and tries to compute a subtype
3431/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003432/// of an array, it will even compute a new array type for that sub-section,
3433/// and the same for structs.
3434///
3435/// Note that this routine is very strict and tries to find a partition of the
3436/// type which produces the *exact* right offset and size. It is not forgiving
3437/// when the size or offset cause either end of type-based partition to be off.
3438/// Also, this is a best-effort routine. It is reasonable to give up and not
3439/// return a type if necessary.
Chandler Carruth113dc642014-12-20 02:39:18 +00003440static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3441 uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00003442 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3443 return stripAggregateTypeWrapping(DL, Ty);
3444 if (Offset > DL.getTypeAllocSize(Ty) ||
3445 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003446 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003447
3448 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003449 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003450 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003451 uint64_t NumSkippedElements = Offset / ElementSize;
Peter Collingbournebc070522016-12-02 03:20:58 +00003452 if (NumSkippedElements >= SeqTy->getNumElements())
3453 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003454 Offset -= NumSkippedElements * ElementSize;
3455
3456 // First check if we need to recurse.
3457 if (Offset > 0 || Size < ElementSize) {
3458 // Bail if the partition ends in a different array element.
3459 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003460 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003461 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003462 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003463 }
3464 assert(Offset == 0);
3465
3466 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003467 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003468 assert(Size > ElementSize);
3469 uint64_t NumElements = Size / ElementSize;
3470 if (NumElements * ElementSize != Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003471 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003472 return ArrayType::get(ElementTy, NumElements);
3473 }
3474
3475 StructType *STy = dyn_cast<StructType>(Ty);
3476 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00003477 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003478
Chandler Carruth90a735d2013-07-19 07:21:28 +00003479 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003480 if (Offset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003481 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003482 uint64_t EndOffset = Offset + Size;
3483 if (EndOffset > SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003484 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003485
3486 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003487 Offset -= SL->getElementOffset(Index);
3488
3489 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003490 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003491 if (Offset >= ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003492 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003493
3494 // See if any partition must be contained by the element.
3495 if (Offset > 0 || Size < ElementSize) {
3496 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003497 return nullptr;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003498 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003499 }
3500 assert(Offset == 0);
3501
3502 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003503 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003504
3505 StructType::element_iterator EI = STy->element_begin() + Index,
3506 EE = STy->element_end();
3507 if (EndOffset < SL->getSizeInBytes()) {
3508 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3509 if (Index == EndIndex)
Craig Topperf40110f2014-04-25 05:29:35 +00003510 return nullptr; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003511
3512 // Don't try to form "natural" types if the elements don't line up with the
3513 // expected size.
3514 // FIXME: We could potentially recurse down through the last element in the
3515 // sub-struct to find a natural end point.
3516 if (SL->getElementOffset(EndIndex) != EndOffset)
Craig Topperf40110f2014-04-25 05:29:35 +00003517 return nullptr;
Chandler Carruth054a40a2012-09-14 11:08:31 +00003518
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003519 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003520 EE = STy->element_begin() + EndIndex;
3521 }
3522
3523 // Try to build up a sub-structure.
Chandler Carruth113dc642014-12-20 02:39:18 +00003524 StructType *SubTy =
3525 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003526 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003527 if (Size != SubSL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003528 return nullptr; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003529
Chandler Carruth054a40a2012-09-14 11:08:31 +00003530 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003531}
3532
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003533/// Pre-split loads and stores to simplify rewriting.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003534///
3535/// We want to break up the splittable load+store pairs as much as
3536/// possible. This is important to do as a preprocessing step, as once we
3537/// start rewriting the accesses to partitions of the alloca we lose the
3538/// necessary information to correctly split apart paired loads and stores
3539/// which both point into this alloca. The case to consider is something like
3540/// the following:
3541///
3542/// %a = alloca [12 x i8]
3543/// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3544/// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3545/// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3546/// %iptr1 = bitcast i8* %gep1 to i64*
3547/// %iptr2 = bitcast i8* %gep2 to i64*
3548/// %fptr1 = bitcast i8* %gep1 to float*
3549/// %fptr2 = bitcast i8* %gep2 to float*
3550/// %fptr3 = bitcast i8* %gep3 to float*
3551/// store float 0.0, float* %fptr1
3552/// store float 1.0, float* %fptr2
3553/// %v = load i64* %iptr1
3554/// store i64 %v, i64* %iptr2
3555/// %f1 = load float* %fptr2
3556/// %f2 = load float* %fptr3
3557///
3558/// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3559/// promote everything so we recover the 2 SSA values that should have been
3560/// there all along.
3561///
3562/// \returns true if any changes are made.
3563bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003564 LLVM_DEBUG(dbgs() << "Pre-splitting loads and stores\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003565
3566 // Track the loads and stores which are candidates for pre-splitting here, in
3567 // the order they first appear during the partition scan. These give stable
3568 // iteration order and a basis for tracking which loads and stores we
3569 // actually split.
3570 SmallVector<LoadInst *, 4> Loads;
3571 SmallVector<StoreInst *, 4> Stores;
3572
3573 // We need to accumulate the splits required of each load or store where we
3574 // can find them via a direct lookup. This is important to cross-check loads
3575 // and stores against each other. We also track the slice so that we can kill
3576 // all the slices that end up split.
3577 struct SplitOffsets {
3578 Slice *S;
3579 std::vector<uint64_t> Splits;
3580 };
3581 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3582
Chandler Carruth73b01642015-01-05 04:17:53 +00003583 // Track loads out of this alloca which cannot, for any reason, be pre-split.
3584 // This is important as we also cannot pre-split stores of those loads!
3585 // FIXME: This is all pretty gross. It means that we can be more aggressive
3586 // in pre-splitting when the load feeding the store happens to come from
3587 // a separate alloca. Put another way, the effectiveness of SROA would be
3588 // decreased by a frontend which just concatenated all of its local allocas
3589 // into one big flat alloca. But defeating such patterns is exactly the job
3590 // SROA is tasked with! Sadly, to not have this discrepancy we would have
3591 // change store pre-splitting to actually force pre-splitting of the load
3592 // that feeds it *and all stores*. That makes pre-splitting much harder, but
3593 // maybe it would make it more principled?
3594 SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
3595
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003596 LLVM_DEBUG(dbgs() << " Searching for candidate loads and stores\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003597 for (auto &P : AS.partitions()) {
3598 for (Slice &S : P) {
Chandler Carruth73b01642015-01-05 04:17:53 +00003599 Instruction *I = cast<Instruction>(S.getUse()->getUser());
Chandler Carruth37f1f122016-03-10 15:31:17 +00003600 if (!S.isSplittable() || S.endOffset() <= P.endOffset()) {
3601 // If this is a load we have to track that it can't participate in any
3602 // pre-splitting. If this is a store of a load we have to track that
3603 // that load also can't participate in any pre-splitting.
Chandler Carruth73b01642015-01-05 04:17:53 +00003604 if (auto *LI = dyn_cast<LoadInst>(I))
3605 UnsplittableLoads.insert(LI);
Chandler Carruth37f1f122016-03-10 15:31:17 +00003606 else if (auto *SI = dyn_cast<StoreInst>(I))
3607 if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
3608 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003609 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003610 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003611 assert(P.endOffset() > S.beginOffset() &&
3612 "Empty or backwards partition!");
3613
3614 // Determine if this is a pre-splittable slice.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003615 if (auto *LI = dyn_cast<LoadInst>(I)) {
3616 assert(!LI->isVolatile() && "Cannot split volatile loads!");
3617
3618 // The load must be used exclusively to store into other pointers for
3619 // us to be able to arbitrarily pre-split it. The stores must also be
3620 // simple to avoid changing semantics.
3621 auto IsLoadSimplyStored = [](LoadInst *LI) {
3622 for (User *LU : LI->users()) {
3623 auto *SI = dyn_cast<StoreInst>(LU);
3624 if (!SI || !SI->isSimple())
3625 return false;
3626 }
3627 return true;
3628 };
Chandler Carruth73b01642015-01-05 04:17:53 +00003629 if (!IsLoadSimplyStored(LI)) {
3630 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003631 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003632 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003633
3634 Loads.push_back(LI);
Chandler Carruthd94a5962016-03-10 14:16:18 +00003635 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
3636 if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3637 // Skip stores *of* pointers. FIXME: This shouldn't even be possible!
Chandler Carruth994cde82015-01-01 12:01:03 +00003638 continue;
3639 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3640 if (!StoredLoad || !StoredLoad->isSimple())
3641 continue;
3642 assert(!SI->isVolatile() && "Cannot split volatile stores!");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003643
Chandler Carruth994cde82015-01-01 12:01:03 +00003644 Stores.push_back(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003645 } else {
3646 // Other uses cannot be pre-split.
3647 continue;
3648 }
3649
3650 // Record the initial split.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003651 LLVM_DEBUG(dbgs() << " Candidate: " << *I << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003652 auto &Offsets = SplitOffsetsMap[I];
3653 assert(Offsets.Splits.empty() &&
3654 "Should not have splits the first time we see an instruction!");
3655 Offsets.S = &S;
Chandler Carruth24ac8302015-01-02 03:55:54 +00003656 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003657 }
3658
3659 // Now scan the already split slices, and add a split for any of them which
3660 // we're going to pre-split.
3661 for (Slice *S : P.splitSliceTails()) {
3662 auto SplitOffsetsMapI =
3663 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3664 if (SplitOffsetsMapI == SplitOffsetsMap.end())
3665 continue;
3666 auto &Offsets = SplitOffsetsMapI->second;
3667
3668 assert(Offsets.S == S && "Found a mismatched slice!");
3669 assert(!Offsets.Splits.empty() &&
3670 "Cannot have an empty set of splits on the second partition!");
Chandler Carruth24ac8302015-01-02 03:55:54 +00003671 assert(Offsets.Splits.back() ==
3672 P.beginOffset() - Offsets.S->beginOffset() &&
Chandler Carruth0715cba2015-01-01 11:54:38 +00003673 "Previous split does not end where this one begins!");
3674
3675 // Record each split. The last partition's end isn't needed as the size
3676 // of the slice dictates that.
3677 if (S->endOffset() > P.endOffset())
Chandler Carruth24ac8302015-01-02 03:55:54 +00003678 Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003679 }
3680 }
3681
3682 // We may have split loads where some of their stores are split stores. For
3683 // such loads and stores, we can only pre-split them if their splits exactly
3684 // match relative to their starting offset. We have to verify this prior to
3685 // any rewriting.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003686 Stores.erase(
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003687 llvm::remove_if(Stores,
3688 [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
3689 // Lookup the load we are storing in our map of split
3690 // offsets.
3691 auto *LI = cast<LoadInst>(SI->getValueOperand());
3692 // If it was completely unsplittable, then we're done,
3693 // and this store can't be pre-split.
3694 if (UnsplittableLoads.count(LI))
3695 return true;
Chandler Carruth73b01642015-01-05 04:17:53 +00003696
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003697 auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3698 if (LoadOffsetsI == SplitOffsetsMap.end())
3699 return false; // Unrelated loads are definitely safe.
3700 auto &LoadOffsets = LoadOffsetsI->second;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003701
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003702 // Now lookup the store's offsets.
3703 auto &StoreOffsets = SplitOffsetsMap[SI];
Chandler Carruth0715cba2015-01-01 11:54:38 +00003704
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003705 // If the relative offsets of each split in the load and
3706 // store match exactly, then we can split them and we
3707 // don't need to remove them here.
3708 if (LoadOffsets.Splits == StoreOffsets.Splits)
3709 return false;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003710
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003711 LLVM_DEBUG(
3712 dbgs()
3713 << " Mismatched splits for load and store:\n"
3714 << " " << *LI << "\n"
3715 << " " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003716
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003717 // We've found a store and load that we need to split
3718 // with mismatched relative splits. Just give up on them
3719 // and remove both instructions from our list of
3720 // candidates.
3721 UnsplittableLoads.insert(LI);
3722 return true;
3723 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003724 Stores.end());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003725 // Now we have to go *back* through all the stores, because a later store may
Chandler Carruth73b01642015-01-05 04:17:53 +00003726 // have caused an earlier store's load to become unsplittable and if it is
3727 // unsplittable for the later store, then we can't rely on it being split in
3728 // the earlier store either.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003729 Stores.erase(llvm::remove_if(Stores,
3730 [&UnsplittableLoads](StoreInst *SI) {
3731 auto *LI =
3732 cast<LoadInst>(SI->getValueOperand());
3733 return UnsplittableLoads.count(LI);
3734 }),
Chandler Carruth73b01642015-01-05 04:17:53 +00003735 Stores.end());
3736 // Once we've established all the loads that can't be split for some reason,
3737 // filter any that made it into our list out.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003738 Loads.erase(llvm::remove_if(Loads,
3739 [&UnsplittableLoads](LoadInst *LI) {
3740 return UnsplittableLoads.count(LI);
3741 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003742 Loads.end());
3743
3744 // If no loads or stores are left, there is no pre-splitting to be done for
3745 // this alloca.
3746 if (Loads.empty() && Stores.empty())
3747 return false;
3748
3749 // From here on, we can't fail and will be building new accesses, so rig up
3750 // an IR builder.
3751 IRBuilderTy IRB(&AI);
3752
3753 // Collect the new slices which we will merge into the alloca slices.
3754 SmallVector<Slice, 4> NewSlices;
3755
3756 // Track any allocas we end up splitting loads and stores for so we iterate
3757 // on them.
3758 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3759
3760 // At this point, we have collected all of the loads and stores we can
3761 // pre-split, and the specific splits needed for them. We actually do the
3762 // splitting in a specific order in order to handle when one of the loads in
3763 // the value operand to one of the stores.
3764 //
3765 // First, we rewrite all of the split loads, and just accumulate each split
3766 // load in a parallel structure. We also build the slices for them and append
3767 // them to the alloca slices.
3768 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3769 std::vector<LoadInst *> SplitLoads;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003770 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003771 for (LoadInst *LI : Loads) {
3772 SplitLoads.clear();
3773
3774 IntegerType *Ty = cast<IntegerType>(LI->getType());
3775 uint64_t LoadSize = Ty->getBitWidth() / 8;
3776 assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
3777
3778 auto &Offsets = SplitOffsetsMap[LI];
3779 assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3780 "Slice size should always match load size exactly!");
3781 uint64_t BaseOffset = Offsets.S->beginOffset();
3782 assert(BaseOffset + LoadSize > BaseOffset &&
3783 "Cannot represent alloca access size using 64-bit integers!");
3784
3785 Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003786 IRB.SetInsertPoint(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003787
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003788 LLVM_DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003789
3790 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3791 int Idx = 0, Size = Offsets.Splits.size();
3792 for (;;) {
3793 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
Yaxun Liu7c44f342017-06-27 18:26:06 +00003794 auto AS = LI->getPointerAddressSpace();
3795 auto *PartPtrTy = PartTy->getPointerTo(AS);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003796 LoadInst *PLoad = IRB.CreateAlignedLoad(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003797 getAdjustedPtr(IRB, DL, BasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003798 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Chandler Carruth994cde82015-01-01 12:01:03 +00003799 PartPtrTy, BasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003800 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003801 LI->getName());
Michael Kruse978ba612018-12-20 04:58:07 +00003802 PLoad->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
3803 LLVMContext::MD_access_group});
Chandler Carruth0715cba2015-01-01 11:54:38 +00003804
3805 // Append this load onto the list of split loads so we can find it later
3806 // to rewrite the stores.
3807 SplitLoads.push_back(PLoad);
3808
3809 // Now build a new slice for the alloca.
Chandler Carruth994cde82015-01-01 12:01:03 +00003810 NewSlices.push_back(
3811 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3812 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003813 /*IsSplittable*/ false));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003814 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3815 << ", " << NewSlices.back().endOffset()
3816 << "): " << *PLoad << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003817
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003818 // See if we've handled all the splits.
3819 if (Idx >= Size)
3820 break;
3821
Chandler Carruth0715cba2015-01-01 11:54:38 +00003822 // Setup the next partition.
3823 PartOffset = Offsets.Splits[Idx];
3824 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003825 PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
3826 }
3827
3828 // Now that we have the split loads, do the slow walk over all uses of the
3829 // load and rewrite them as split stores, or save the split loads to use
3830 // below if the store is going to be split there anyways.
3831 bool DeferredStores = false;
3832 for (User *LU : LI->users()) {
3833 StoreInst *SI = cast<StoreInst>(LU);
3834 if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
3835 DeferredStores = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003836 LLVM_DEBUG(dbgs() << " Deferred splitting of store: " << *SI
3837 << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003838 continue;
3839 }
3840
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003841 Value *StoreBasePtr = SI->getPointerOperand();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003842 IRB.SetInsertPoint(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003843
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003844 LLVM_DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003845
3846 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
3847 LoadInst *PLoad = SplitLoads[Idx];
3848 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
Chandler Carruth994cde82015-01-01 12:01:03 +00003849 auto *PartPtrTy =
3850 PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003851
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003852 auto AS = SI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003853 StoreInst *PStore = IRB.CreateAlignedStore(
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003854 PLoad,
3855 getAdjustedPtr(IRB, DL, StoreBasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003856 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003857 PartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003858 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Michael Kruse978ba612018-12-20 04:58:07 +00003859 PStore->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
3860 LLVMContext::MD_access_group});
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003861 LLVM_DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003862 }
3863
3864 // We want to immediately iterate on any allocas impacted by splitting
3865 // this store, and we have to track any promotable alloca (indicated by
3866 // a direct store) as needing to be resplit because it is no longer
3867 // promotable.
3868 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3869 ResplitPromotableAllocas.insert(OtherAI);
3870 Worklist.insert(OtherAI);
3871 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3872 StoreBasePtr->stripInBoundsOffsets())) {
3873 Worklist.insert(OtherAI);
3874 }
3875
3876 // Mark the original store as dead.
3877 DeadInsts.insert(SI);
3878 }
3879
3880 // Save the split loads if there are deferred stores among the users.
3881 if (DeferredStores)
3882 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
3883
3884 // Mark the original load as dead and kill the original slice.
3885 DeadInsts.insert(LI);
3886 Offsets.S->kill();
3887 }
3888
3889 // Second, we rewrite all of the split stores. At this point, we know that
3890 // all loads from this alloca have been split already. For stores of such
3891 // loads, we can simply look up the pre-existing split loads. For stores of
3892 // other loads, we split those loads first and then write split stores of
3893 // them.
3894 for (StoreInst *SI : Stores) {
3895 auto *LI = cast<LoadInst>(SI->getValueOperand());
3896 IntegerType *Ty = cast<IntegerType>(LI->getType());
3897 uint64_t StoreSize = Ty->getBitWidth() / 8;
3898 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
3899
3900 auto &Offsets = SplitOffsetsMap[SI];
3901 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3902 "Slice size should always match load size exactly!");
3903 uint64_t BaseOffset = Offsets.S->beginOffset();
3904 assert(BaseOffset + StoreSize > BaseOffset &&
3905 "Cannot represent alloca access size using 64-bit integers!");
3906
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003907 Value *LoadBasePtr = LI->getPointerOperand();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003908 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
3909
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003910 LLVM_DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003911
3912 // Check whether we have an already split load.
3913 auto SplitLoadsMapI = SplitLoadsMap.find(LI);
3914 std::vector<LoadInst *> *SplitLoads = nullptr;
3915 if (SplitLoadsMapI != SplitLoadsMap.end()) {
3916 SplitLoads = &SplitLoadsMapI->second;
3917 assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
3918 "Too few split loads for the number of splits in the store!");
3919 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003920 LLVM_DEBUG(dbgs() << " of load: " << *LI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003921 }
3922
Chandler Carruth0715cba2015-01-01 11:54:38 +00003923 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3924 int Idx = 0, Size = Offsets.Splits.size();
3925 for (;;) {
3926 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
Keno Fischer514a6a52017-06-02 19:04:17 +00003927 auto *LoadPartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
3928 auto *StorePartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003929
3930 // Either lookup a split load or create one.
3931 LoadInst *PLoad;
3932 if (SplitLoads) {
3933 PLoad = (*SplitLoads)[Idx];
3934 } else {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003935 IRB.SetInsertPoint(LI);
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003936 auto AS = LI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003937 PLoad = IRB.CreateAlignedLoad(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003938 getAdjustedPtr(IRB, DL, LoadBasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003939 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Keno Fischer514a6a52017-06-02 19:04:17 +00003940 LoadPartPtrTy, LoadBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003941 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003942 LI->getName());
3943 }
3944
3945 // And store this partition.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003946 IRB.SetInsertPoint(SI);
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003947 auto AS = SI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003948 StoreInst *PStore = IRB.CreateAlignedStore(
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003949 PLoad,
3950 getAdjustedPtr(IRB, DL, StoreBasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003951 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003952 StorePartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003953 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003954
3955 // Now build a new slice for the alloca.
3956 NewSlices.push_back(
3957 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3958 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003959 /*IsSplittable*/ false));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003960 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3961 << ", " << NewSlices.back().endOffset()
3962 << "): " << *PStore << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003963 if (!SplitLoads) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003964 LLVM_DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003965 }
3966
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003967 // See if we've finished all the splits.
3968 if (Idx >= Size)
3969 break;
3970
Chandler Carruth0715cba2015-01-01 11:54:38 +00003971 // Setup the next partition.
3972 PartOffset = Offsets.Splits[Idx];
3973 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003974 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
3975 }
3976
3977 // We want to immediately iterate on any allocas impacted by splitting
3978 // this load, which is only relevant if it isn't a load of this alloca and
3979 // thus we didn't already split the loads above. We also have to keep track
3980 // of any promotable allocas we split loads on as they can no longer be
3981 // promoted.
3982 if (!SplitLoads) {
3983 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
3984 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3985 ResplitPromotableAllocas.insert(OtherAI);
3986 Worklist.insert(OtherAI);
3987 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3988 LoadBasePtr->stripInBoundsOffsets())) {
3989 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3990 Worklist.insert(OtherAI);
3991 }
3992 }
3993
3994 // Mark the original store as dead now that we've split it up and kill its
Chandler Carruth24ac8302015-01-02 03:55:54 +00003995 // slice. Note that we leave the original load in place unless this store
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003996 // was its only use. It may in turn be split up if it is an alloca load
Chandler Carruth24ac8302015-01-02 03:55:54 +00003997 // for some other alloca, but it may be a normal load. This may introduce
3998 // redundant loads, but where those can be merged the rest of the optimizer
3999 // should handle the merging, and this uncovers SSA splits which is more
4000 // important. In practice, the original loads will almost always be fully
4001 // split and removed eventually, and the splits will be merged by any
4002 // trivial CSE, including instcombine.
4003 if (LI->hasOneUse()) {
4004 assert(*LI->user_begin() == SI && "Single use isn't this store!");
4005 DeadInsts.insert(LI);
4006 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00004007 DeadInsts.insert(SI);
4008 Offsets.S->kill();
4009 }
4010
Chandler Carruth24ac8302015-01-02 03:55:54 +00004011 // Remove the killed slices that have ben pre-split.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004012 AS.erase(llvm::remove_if(AS, [](const Slice &S) { return S.isDead(); }),
4013 AS.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +00004014
Chandler Carruth24ac8302015-01-02 03:55:54 +00004015 // Insert our new slices. This will sort and merge them into the sorted
4016 // sequence.
Chandler Carruth0715cba2015-01-01 11:54:38 +00004017 AS.insert(NewSlices);
4018
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004019 LLVM_DEBUG(dbgs() << " Pre-split slices:\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00004020#ifndef NDEBUG
4021 for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004022 LLVM_DEBUG(AS.print(dbgs(), I, " "));
Chandler Carruth0715cba2015-01-01 11:54:38 +00004023#endif
4024
4025 // Finally, don't try to promote any allocas that new require re-splitting.
4026 // They have already been added to the worklist above.
4027 PromotableAllocas.erase(
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004028 llvm::remove_if(
David Majnemerc7004902016-08-12 04:32:37 +00004029 PromotableAllocas,
Chandler Carruth0715cba2015-01-01 11:54:38 +00004030 [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
4031 PromotableAllocas.end());
4032
4033 return true;
4034}
4035
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004036/// Rewrite an alloca partition's users.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004037///
4038/// This routine drives both of the rewriting goals of the SROA pass. It tries
4039/// to rewrite uses of an alloca partition to be conducive for SSA value
4040/// promotion. If the partition needs a new, more refined alloca, this will
4041/// build that new alloca, preserving as much type information as possible, and
4042/// rewrite the uses of the old alloca to point at the new one and have the
4043/// appropriate new offsets. It also evaluates how successful the rewrite was
4044/// at enabling promotion and if it was successful queues the alloca to be
4045/// promoted.
Adrian Prantl565cc182015-01-20 19:42:22 +00004046AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
Chandler Carruth29a18a42015-09-12 09:09:14 +00004047 Partition &P) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004048 // Try to compute a friendly type for this partition of the alloca. This
4049 // won't always succeed, in which case we fall back to a legal integer type
4050 // or an i8 array of an appropriate size.
Craig Topperf40110f2014-04-25 05:29:35 +00004051 Type *SliceTy = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004052 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004053 if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004054 if (DL.getTypeAllocSize(CommonUseTy) >= P.size())
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004055 SliceTy = CommonUseTy;
4056 if (!SliceTy)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004057 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004058 P.beginOffset(), P.size()))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004059 SliceTy = TypePartitionTy;
4060 if ((!SliceTy || (SliceTy->isArrayTy() &&
4061 SliceTy->getArrayElementType()->isIntegerTy())) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004062 DL.isLegalInteger(P.size() * 8))
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004063 SliceTy = Type::getIntNTy(*C, P.size() * 8);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004064 if (!SliceTy)
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004065 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004066 assert(DL.getTypeAllocSize(SliceTy) >= P.size());
Chandler Carruthf0546402013-07-18 07:15:00 +00004067
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004068 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
Chandler Carruthf0546402013-07-18 07:15:00 +00004069
Chandler Carruth2dc96822014-10-18 00:44:02 +00004070 VectorType *VecTy =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004071 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
Chandler Carruth2dc96822014-10-18 00:44:02 +00004072 if (VecTy)
4073 SliceTy = VecTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004074
4075 // Check for the case where we're going to rewrite to a new alloca of the
4076 // exact same type as the original, and with the same access offsets. In that
4077 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00004078 // perform phi and select speculation.
Hiroshi Inoue99a8faa2018-01-16 06:23:05 +00004079 // P.beginOffset() can be non-zero even with the same type in a case with
4080 // out-of-bounds access (e.g. @PR35657 function in SROA/basictest.ll).
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004081 AllocaInst *NewAI;
Hiroshi Inoue99a8faa2018-01-16 06:23:05 +00004082 if (SliceTy == AI.getAllocatedType() && P.beginOffset() == 0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004083 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00004084 // FIXME: We should be able to bail at this point with "nothing changed".
4085 // FIXME: We might want to defer PHI speculation until after here.
Adrian Prantl565cc182015-01-20 19:42:22 +00004086 // FIXME: return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004087 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00004088 unsigned Alignment = AI.getAlignment();
4089 if (!Alignment) {
4090 // The minimum alignment which users can rely on when the explicit
4091 // alignment is omitted or zero is that required by the ABI for this
4092 // type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004093 Alignment = DL.getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00004094 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004095 Alignment = MinAlign(Alignment, P.beginOffset());
Chandler Carruth903790e2012-09-29 10:41:21 +00004096 // If we will get at least this much alignment from the type alone, leave
4097 // the alloca's alignment unconstrained.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004098 if (Alignment <= DL.getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00004099 Alignment = 0;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004100 NewAI = new AllocaInst(
Matt Arsenault3c1fc762017-04-10 22:27:50 +00004101 SliceTy, AI.getType()->getAddressSpace(), nullptr, Alignment,
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004102 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
Anastasis Grammenos425df222018-06-28 18:58:30 +00004103 // Copy the old AI debug location over to the new one.
4104 NewAI->setDebugLoc(AI.getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004105 ++NumNewAllocas;
4106 }
4107
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004108 LLVM_DEBUG(dbgs() << "Rewriting alloca partition "
4109 << "[" << P.beginOffset() << "," << P.endOffset()
4110 << ") to: " << *NewAI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004111
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004112 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00004113 // promoted allocas. We will reset it to this point if the alloca is not in
4114 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00004115 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00004116 unsigned NumUses = 0;
Davide Italiano81a26da2017-04-27 23:09:01 +00004117 SmallSetVector<PHINode *, 8> PHIUsers;
4118 SmallSetVector<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00004119
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004120 AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004121 P.endOffset(), IsIntegerPromotable, VecTy,
4122 PHIUsers, SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00004123 bool Promotable = true;
Chandler Carruthffb7ce52014-12-24 01:48:09 +00004124 for (Slice *S : P.splitSliceTails()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004125 Promotable &= Rewriter.visit(S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004126 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00004127 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004128 for (Slice &S : P) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004129 Promotable &= Rewriter.visit(&S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004130 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00004131 }
4132
Chandler Carruth6c321c12013-07-19 10:57:36 +00004133 NumAllocaPartitionUses += NumUses;
Craig Topper8a950272017-05-18 00:51:39 +00004134 MaxUsesPerAllocaPartition.updateMax(NumUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004135
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004136 // Now that we've processed all the slices in the new partition, check if any
4137 // PHIs or Selects would block promotion.
Davide Italiano81a26da2017-04-27 23:09:01 +00004138 for (PHINode *PHI : PHIUsers)
4139 if (!isSafePHIToSpeculate(*PHI)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004140 Promotable = false;
4141 PHIUsers.clear();
4142 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00004143 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004144 }
Davide Italiano81a26da2017-04-27 23:09:01 +00004145
4146 for (SelectInst *Sel : SelectUsers)
4147 if (!isSafeSelectToSpeculate(*Sel)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004148 Promotable = false;
4149 PHIUsers.clear();
4150 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00004151 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004152 }
4153
4154 if (Promotable) {
4155 if (PHIUsers.empty() && SelectUsers.empty()) {
4156 // Promote the alloca.
4157 PromotableAllocas.push_back(NewAI);
4158 } else {
4159 // If we have either PHIs or Selects to speculate, add them to those
4160 // worklists and re-queue the new alloca so that we promote in on the
4161 // next iteration.
Chandler Carruth61747042014-10-16 21:05:14 +00004162 for (PHINode *PHIUser : PHIUsers)
4163 SpeculatablePHIs.insert(PHIUser);
4164 for (SelectInst *SelectUser : SelectUsers)
4165 SpeculatableSelects.insert(SelectUser);
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004166 Worklist.insert(NewAI);
4167 }
4168 } else {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004169 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00004170 while (PostPromotionWorklist.size() > PPWOldSize)
4171 PostPromotionWorklist.pop_back();
David Majnemer30ffc4c2016-04-26 01:05:00 +00004172
4173 // We couldn't promote and we didn't create a new partition, nothing
4174 // happened.
4175 if (NewAI == &AI)
4176 return nullptr;
4177
4178 // If we can't promote the alloca, iterate on it to check for new
4179 // refinements exposed by splitting the current alloca. Don't iterate on an
4180 // alloca which didn't actually change and didn't get promoted.
4181 Worklist.insert(NewAI);
Chandler Carruthf0546402013-07-18 07:15:00 +00004182 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00004183
Adrian Prantl565cc182015-01-20 19:42:22 +00004184 return NewAI;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004185}
4186
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004187/// Walks the slices of an alloca and form partitions based on them,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004188/// rewriting each of their uses.
Chandler Carruth83934062014-10-16 21:11:55 +00004189bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
4190 if (AS.begin() == AS.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00004191 return false;
4192
Chandler Carruth6c321c12013-07-19 10:57:36 +00004193 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004194 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004195 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00004196
Chandler Carruth24ac8302015-01-02 03:55:54 +00004197 // First try to pre-split loads and stores.
Chandler Carruth0715cba2015-01-01 11:54:38 +00004198 Changed |= presplitLoadsAndStores(AI, AS);
4199
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004200 // Now that we have identified any pre-splitting opportunities,
4201 // mark loads and stores unsplittable except for the following case.
4202 // We leave a slice splittable if all other slices are disjoint or fully
4203 // included in the slice, such as whole-alloca loads and stores.
4204 // If we fail to split these during pre-splitting, we want to force them
4205 // to be rewritten into a partition.
Chandler Carruth24ac8302015-01-02 03:55:54 +00004206 bool IsSorted = true;
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004207
4208 uint64_t AllocaSize = DL.getTypeAllocSize(AI.getAllocatedType());
4209 const uint64_t MaxBitVectorSize = 1024;
Hiroshi Inoue99a8faa2018-01-16 06:23:05 +00004210 if (AllocaSize <= MaxBitVectorSize) {
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004211 // If a byte boundary is included in any load or store, a slice starting or
4212 // ending at the boundary is not splittable.
4213 SmallBitVector SplittableOffset(AllocaSize + 1, true);
4214 for (Slice &S : AS)
4215 for (unsigned O = S.beginOffset() + 1;
4216 O < S.endOffset() && O < AllocaSize; O++)
4217 SplittableOffset.reset(O);
4218
4219 for (Slice &S : AS) {
4220 if (!S.isSplittable())
4221 continue;
4222
4223 if ((S.beginOffset() > AllocaSize || SplittableOffset[S.beginOffset()]) &&
4224 (S.endOffset() > AllocaSize || SplittableOffset[S.endOffset()]))
4225 continue;
4226
4227 if (isa<LoadInst>(S.getUse()->getUser()) ||
4228 isa<StoreInst>(S.getUse()->getUser())) {
4229 S.makeUnsplittable();
4230 IsSorted = false;
4231 }
Chandler Carruth24ac8302015-01-02 03:55:54 +00004232 }
4233 }
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004234 else {
4235 // We only allow whole-alloca splittable loads and stores
4236 // for a large alloca to avoid creating too large BitVector.
4237 for (Slice &S : AS) {
4238 if (!S.isSplittable())
4239 continue;
4240
4241 if (S.beginOffset() == 0 && S.endOffset() >= AllocaSize)
4242 continue;
4243
4244 if (isa<LoadInst>(S.getUse()->getUser()) ||
4245 isa<StoreInst>(S.getUse()->getUser())) {
4246 S.makeUnsplittable();
4247 IsSorted = false;
4248 }
4249 }
4250 }
4251
Chandler Carruth24ac8302015-01-02 03:55:54 +00004252 if (!IsSorted)
Fangrui Song0cac7262018-09-27 02:13:45 +00004253 llvm::sort(AS);
Chandler Carruth24ac8302015-01-02 03:55:54 +00004254
Adrian Prantl941fa752016-12-05 18:04:47 +00004255 /// Describes the allocas introduced by rewritePartition in order to migrate
4256 /// the debug info.
4257 struct Fragment {
Adrian Prantl565cc182015-01-20 19:42:22 +00004258 AllocaInst *Alloca;
4259 uint64_t Offset;
4260 uint64_t Size;
Adrian Prantl941fa752016-12-05 18:04:47 +00004261 Fragment(AllocaInst *AI, uint64_t O, uint64_t S)
Adrian Prantl565cc182015-01-20 19:42:22 +00004262 : Alloca(AI), Offset(O), Size(S) {}
4263 };
Adrian Prantl941fa752016-12-05 18:04:47 +00004264 SmallVector<Fragment, 4> Fragments;
Adrian Prantl565cc182015-01-20 19:42:22 +00004265
Chandler Carruth0715cba2015-01-01 11:54:38 +00004266 // Rewrite each partition.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004267 for (auto &P : AS.partitions()) {
Adrian Prantl565cc182015-01-20 19:42:22 +00004268 if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4269 Changed = true;
Adrian Prantl34e75902015-02-09 23:57:22 +00004270 if (NewAI != &AI) {
4271 uint64_t SizeOfByte = 8;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004272 uint64_t AllocaSize = DL.getTypeSizeInBits(NewAI->getAllocatedType());
Adrian Prantl34e75902015-02-09 23:57:22 +00004273 // Don't include any padding.
4274 uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
Adrian Prantl941fa752016-12-05 18:04:47 +00004275 Fragments.push_back(Fragment(NewAI, P.beginOffset() * SizeOfByte, Size));
Adrian Prantl34e75902015-02-09 23:57:22 +00004276 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004277 }
Chandler Carruth6c321c12013-07-19 10:57:36 +00004278 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00004279 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004280
Chandler Carruth6c321c12013-07-19 10:57:36 +00004281 NumAllocaPartitions += NumPartitions;
Craig Topper8a950272017-05-18 00:51:39 +00004282 MaxPartitionsPerAlloca.updateMax(NumPartitions);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004283
Adrian Prantl565cc182015-01-20 19:42:22 +00004284 // Migrate debug information from the old alloca to the new alloca(s)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004285 // and the individual partitions.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00004286 TinyPtrVector<DbgVariableIntrinsic *> DbgDeclares = FindDbgAddrUses(&AI);
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004287 if (!DbgDeclares.empty()) {
4288 auto *Var = DbgDeclares.front()->getVariable();
4289 auto *Expr = DbgDeclares.front()->getExpression();
Adrian Prantld7f6f162017-11-28 00:57:53 +00004290 auto VarSize = Var->getSizeInBits();
Sanjay Patelaf674fb2015-12-14 17:24:23 +00004291 DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
Keno Fischerd5354fd2016-01-14 20:06:34 +00004292 uint64_t AllocaSize = DL.getTypeSizeInBits(AI.getAllocatedType());
Adrian Prantl941fa752016-12-05 18:04:47 +00004293 for (auto Fragment : Fragments) {
4294 // Create a fragment expression describing the new partition or reuse AI's
Adrian Prantl565cc182015-01-20 19:42:22 +00004295 // expression if there is only one partition.
Adrian Prantl941fa752016-12-05 18:04:47 +00004296 auto *FragmentExpr = Expr;
4297 if (Fragment.Size < AllocaSize || Expr->isFragment()) {
Adrian Prantl152ac392015-02-01 00:58:04 +00004298 // If this alloca is already a scalar replacement of a larger aggregate,
Adrian Prantl941fa752016-12-05 18:04:47 +00004299 // Fragment.Offset describes the offset inside the scalar.
Adrian Prantl49797ca2016-12-22 05:27:12 +00004300 auto ExprFragment = Expr->getFragmentInfo();
4301 uint64_t Offset = ExprFragment ? ExprFragment->OffsetInBits : 0;
Adrian Prantl941fa752016-12-05 18:04:47 +00004302 uint64_t Start = Offset + Fragment.Offset;
4303 uint64_t Size = Fragment.Size;
Adrian Prantl49797ca2016-12-22 05:27:12 +00004304 if (ExprFragment) {
Adrian Prantl941fa752016-12-05 18:04:47 +00004305 uint64_t AbsEnd =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00004306 ExprFragment->OffsetInBits + ExprFragment->SizeInBits;
Adrian Prantl34e75902015-02-09 23:57:22 +00004307 if (Start >= AbsEnd)
4308 // No need to describe a SROAed padding.
4309 continue;
4310 Size = std::min(Size, AbsEnd - Start);
4311 }
Adrian Prantlb192b542017-08-30 20:04:17 +00004312 // The new, smaller fragment is stenciled out from the old fragment.
4313 if (auto OrigFragment = FragmentExpr->getFragmentInfo()) {
4314 assert(Start >= OrigFragment->OffsetInBits &&
4315 "new fragment is outside of original fragment");
4316 Start -= OrigFragment->OffsetInBits;
4317 }
Adrian Prantl77d90b02017-11-28 21:30:38 +00004318
4319 // The alloca may be larger than the variable.
4320 if (VarSize) {
4321 if (Size > *VarSize)
4322 Size = *VarSize;
4323 if (Size == 0 || Start + Size > *VarSize)
4324 continue;
4325 }
4326
Adrian Prantld7f6f162017-11-28 00:57:53 +00004327 // Avoid creating a fragment expression that covers the entire variable.
4328 if (!VarSize || *VarSize != Size) {
4329 if (auto E =
4330 DIExpression::createFragmentExpression(Expr, Start, Size))
4331 FragmentExpr = *E;
4332 else
4333 continue;
4334 }
Adrian Prantl152ac392015-02-01 00:58:04 +00004335 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004336
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004337 // Remove any existing intrinsics describing the same alloca.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00004338 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(Fragment.Alloca))
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004339 OldDII->eraseFromParent();
Adrian Prantl565cc182015-01-20 19:42:22 +00004340
Adrian Prantl941fa752016-12-05 18:04:47 +00004341 DIB.insertDeclare(Fragment.Alloca, Var, FragmentExpr,
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004342 DbgDeclares.front()->getDebugLoc(), &AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004343 }
4344 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004345 return Changed;
4346}
4347
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004348/// Clobber a use with undef, deleting the used value if it becomes dead.
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004349void SROA::clobberUse(Use &U) {
4350 Value *OldV = U;
4351 // Replace the use with an undef value.
4352 U = UndefValue::get(OldV->getType());
4353
4354 // Check for this making an instruction dead. We have to garbage collect
4355 // all the dead instructions to ensure the uses of any alloca end up being
4356 // minimal.
4357 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4358 if (isInstructionTriviallyDead(OldI)) {
4359 DeadInsts.insert(OldI);
4360 }
4361}
4362
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004363/// Analyze an alloca for SROA.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004364///
4365/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004366/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004367/// rewritten as needed.
4368bool SROA::runOnAlloca(AllocaInst &AI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004369 LLVM_DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004370 ++NumAllocasAnalyzed;
4371
4372 // Special case dead allocas, as they're trivial.
4373 if (AI.use_empty()) {
4374 AI.eraseFromParent();
4375 return true;
4376 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004377 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004378
4379 // Skip alloca forms that this analysis can't handle.
4380 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004381 DL.getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004382 return false;
4383
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004384 bool Changed = false;
4385
4386 // First, split any FCA loads and stores touching this alloca to promote
4387 // better splitting and promotion opportunities.
Tim Northover856628f2018-12-18 09:29:39 +00004388 AggLoadStoreRewriter AggRewriter(DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004389 Changed |= AggRewriter.rewrite(AI);
4390
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004391 // Build the slices using a recursive instruction-visiting builder.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004392 AllocaSlices AS(DL, AI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004393 LLVM_DEBUG(AS.print(dbgs()));
Chandler Carruth83934062014-10-16 21:11:55 +00004394 if (AS.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004395 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004396
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004397 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth83934062014-10-16 21:11:55 +00004398 for (Instruction *DeadUser : AS.getDeadUsers()) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004399 // Free up everything used by this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004400 for (Use &DeadOp : DeadUser->operands())
Chandler Carruth1583e992014-03-03 10:42:58 +00004401 clobberUse(DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004402
4403 // Now replace the uses of this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004404 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004405
4406 // And mark it for deletion.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004407 DeadInsts.insert(DeadUser);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004408 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004409 }
Chandler Carruth83934062014-10-16 21:11:55 +00004410 for (Use *DeadOp : AS.getDeadOperands()) {
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004411 clobberUse(*DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004412 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004413 }
4414
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004415 // No slices to split. Leave the dead alloca for a later pass to clean up.
Chandler Carruth83934062014-10-16 21:11:55 +00004416 if (AS.begin() == AS.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00004417 return Changed;
4418
Chandler Carruth83934062014-10-16 21:11:55 +00004419 Changed |= splitAlloca(AI, AS);
Chandler Carruthf0546402013-07-18 07:15:00 +00004420
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004421 LLVM_DEBUG(dbgs() << " Speculating PHIs\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00004422 while (!SpeculatablePHIs.empty())
4423 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
4424
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004425 LLVM_DEBUG(dbgs() << " Speculating Selects\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00004426 while (!SpeculatableSelects.empty())
4427 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
4428
4429 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004430}
4431
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004432/// Delete the dead instructions accumulated in this run.
Chandler Carruth19450da2012-09-14 10:26:38 +00004433///
4434/// Recursively deletes the dead instructions we've accumulated. This is done
4435/// at the very end to maximize locality of the recursive delete and to
4436/// minimize the problems of invalidated instruction pointers as such pointers
4437/// are used heavily in the intermediate stages of the algorithm.
4438///
4439/// We also record the alloca instructions deleted here so that they aren't
4440/// subsequently handed to mem2reg to promote.
Teresa Johnson33090022017-11-20 18:33:38 +00004441bool SROA::deleteDeadInstructions(
Chandler Carruth113dc642014-12-20 02:39:18 +00004442 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
Teresa Johnson33090022017-11-20 18:33:38 +00004443 bool Changed = false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004444 while (!DeadInsts.empty()) {
4445 Instruction *I = DeadInsts.pop_back_val();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004446 LLVM_DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004447
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004448 // If the instruction is an alloca, find the possible dbg.declare connected
4449 // to it, and remove it too. We must do this before calling RAUW or we will
4450 // not be able to find it.
4451 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
4452 DeletedAllocas.insert(AI);
Hsiangkai Wangef72e482018-08-06 03:59:47 +00004453 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(AI))
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004454 OldDII->eraseFromParent();
4455 }
4456
Chandler Carruth58d05562012-10-25 04:37:07 +00004457 I->replaceAllUsesWith(UndefValue::get(I->getType()));
4458
Chandler Carruth1583e992014-03-03 10:42:58 +00004459 for (Use &Operand : I->operands())
4460 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004461 // Zero out the operand and see if it becomes trivially dead.
Craig Topperf40110f2014-04-25 05:29:35 +00004462 Operand = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004463 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00004464 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004465 }
4466
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004467 ++NumDeleted;
4468 I->eraseFromParent();
Teresa Johnson33090022017-11-20 18:33:38 +00004469 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004470 }
Teresa Johnson33090022017-11-20 18:33:38 +00004471 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004472}
4473
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004474/// Promote the allocas, using the best available technique.
Chandler Carruth70b44c52012-09-15 11:43:14 +00004475///
4476/// This attempts to promote whatever allocas have been identified as viable in
4477/// the PromotableAllocas list. If that list is empty, there is nothing to do.
Chandler Carruth748d0952015-08-26 09:09:29 +00004478/// This function returns whether any promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00004479bool SROA::promoteAllocas(Function &F) {
4480 if (PromotableAllocas.empty())
4481 return false;
4482
4483 NumPromoted += PromotableAllocas.size();
4484
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004485 LLVM_DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Davide Italiano612d5a92017-04-09 20:47:14 +00004486 PromoteMemToReg(PromotableAllocas, *DT, AC);
Chandler Carruth70b44c52012-09-15 11:43:14 +00004487 PromotableAllocas.clear();
4488 return true;
4489}
4490
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004491PreservedAnalyses SROA::runImpl(Function &F, DominatorTree &RunDT,
4492 AssumptionCache &RunAC) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004493 LLVM_DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004494 C = &F.getContext();
Chandler Carruth29a18a42015-09-12 09:09:14 +00004495 DT = &RunDT;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004496 AC = &RunAC;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004497
4498 BasicBlock &EntryBB = F.getEntryBlock();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00004499 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
Adrian Prantl565cc182015-01-20 19:42:22 +00004500 I != E; ++I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004501 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
4502 Worklist.insert(AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004503 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004504
4505 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00004506 // A set of deleted alloca instruction pointers which should be removed from
4507 // the list of promotable allocas.
4508 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4509
Chandler Carruthac8317f2012-10-04 12:33:50 +00004510 do {
4511 while (!Worklist.empty()) {
4512 Changed |= runOnAlloca(*Worklist.pop_back_val());
Teresa Johnson33090022017-11-20 18:33:38 +00004513 Changed |= deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00004514
Chandler Carruthac8317f2012-10-04 12:33:50 +00004515 // Remove the deleted allocas from various lists so that we don't try to
4516 // continue processing them.
4517 if (!DeletedAllocas.empty()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00004518 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00004519 Worklist.remove_if(IsInSet);
4520 PostPromotionWorklist.remove_if(IsInSet);
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004521 PromotableAllocas.erase(llvm::remove_if(PromotableAllocas, IsInSet),
Chandler Carruthac8317f2012-10-04 12:33:50 +00004522 PromotableAllocas.end());
4523 DeletedAllocas.clear();
4524 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004525 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004526
Chandler Carruthac8317f2012-10-04 12:33:50 +00004527 Changed |= promoteAllocas(F);
4528
4529 Worklist = PostPromotionWorklist;
4530 PostPromotionWorklist.clear();
4531 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004532
Davide Italiano16e96d42016-06-07 13:21:17 +00004533 if (!Changed)
4534 return PreservedAnalyses::all();
4535
Davide Italiano16e96d42016-06-07 13:21:17 +00004536 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00004537 PA.preserveSet<CFGAnalyses>();
Davide Italiano16e96d42016-06-07 13:21:17 +00004538 PA.preserve<GlobalsAA>();
4539 return PA;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004540}
4541
Sean Silva36e0d012016-08-09 00:28:15 +00004542PreservedAnalyses SROA::run(Function &F, FunctionAnalysisManager &AM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004543 return runImpl(F, AM.getResult<DominatorTreeAnalysis>(F),
4544 AM.getResult<AssumptionAnalysis>(F));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004545}
Chandler Carruth29a18a42015-09-12 09:09:14 +00004546
4547/// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
4548///
4549/// This is in the llvm namespace purely to allow it to be a friend of the \c
4550/// SROA pass.
4551class llvm::sroa::SROALegacyPass : public FunctionPass {
4552 /// The SROA implementation.
4553 SROA Impl;
4554
4555public:
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004556 static char ID;
4557
Chandler Carruth29a18a42015-09-12 09:09:14 +00004558 SROALegacyPass() : FunctionPass(ID) {
4559 initializeSROALegacyPassPass(*PassRegistry::getPassRegistry());
4560 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004561
Chandler Carruth29a18a42015-09-12 09:09:14 +00004562 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00004563 if (skipFunction(F))
Chandler Carruth29a18a42015-09-12 09:09:14 +00004564 return false;
4565
4566 auto PA = Impl.runImpl(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004567 F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4568 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
Chandler Carruth29a18a42015-09-12 09:09:14 +00004569 return !PA.areAllPreserved();
4570 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004571
Chandler Carruth29a18a42015-09-12 09:09:14 +00004572 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004573 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth29a18a42015-09-12 09:09:14 +00004574 AU.addRequired<DominatorTreeWrapperPass>();
4575 AU.addPreserved<GlobalsAAWrapperPass>();
4576 AU.setPreservesCFG();
4577 }
4578
Mehdi Amini117296c2016-10-01 02:56:57 +00004579 StringRef getPassName() const override { return "SROA"; }
Chandler Carruth29a18a42015-09-12 09:09:14 +00004580};
4581
4582char SROALegacyPass::ID = 0;
4583
4584FunctionPass *llvm::createSROAPass() { return new SROALegacyPass(); }
4585
4586INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",
4587 "Scalar Replacement Of Aggregates", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004588INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth29a18a42015-09-12 09:09:14 +00004589INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4590INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",
4591 false, false)