blob: 5b47ef9d7307a59a0c784212050f0de2d870a41d [file] [log] [blame]
Chris Lattnerfb41a502003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerfb41a502003-05-27 15:45:27 +00009//
10// This transformation implements the well known scalar replacement of
11// aggregates transformation. This xform breaks up alloca instructions of
12// aggregate type (structure or array) into individual alloca instructions for
Chris Lattner5d8a12e2003-09-11 16:45:55 +000013// each member (if possible). Then, if possible, it transforms the individual
14// alloca instructions into nice clean scalar SSA form.
15//
Chad Rosiercc899f32012-04-11 19:21:58 +000016// This combines a simple SRoA algorithm with the Mem2Reg algorithm because they
Chris Lattner5d8a12e2003-09-11 16:45:55 +000017// often interact, especially for C++ programs. As such, iterating between
18// SRoA, then Mem2Reg until we run out of things to promote works well.
Chris Lattnerfb41a502003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
22#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/ADT/SetVector.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/Statistic.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000026#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/Loads.h"
28#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000029#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000031#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000033#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000035#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000037#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/GlobalVariable.h"
39#include "llvm/IR/IRBuilder.h"
40#include "llvm/IR/Instructions.h"
41#include "llvm/IR/IntrinsicInst.h"
42#include "llvm/IR/LLVMContext.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IR/Operator.h"
Chris Lattner66e6a822007-03-05 07:52:57 +000045#include "llvm/Pass.h"
Chris Lattner996795b2006-06-28 23:17:24 +000046#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000047#include "llvm/Support/ErrorHandling.h"
Chris Lattner3b0a62d2005-12-12 07:19:13 +000048#include "llvm/Support/MathExtras.h"
Chris Lattnerb25de3f2009-08-23 04:37:46 +000049#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000050#include "llvm/Transforms/Utils/Local.h"
51#include "llvm/Transforms/Utils/PromoteMemToReg.h"
52#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner40d2aeb2003-12-02 17:43:55 +000053using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000054
Chandler Carruth964daaa2014-04-22 02:55:47 +000055#define DEBUG_TYPE "scalarrepl"
56
Chris Lattner79a42ac2006-12-19 21:40:18 +000057STATISTIC(NumReplaced, "Number of allocas broken up");
58STATISTIC(NumPromoted, "Number of allocas promoted");
Chris Lattnera9607252011-01-23 22:04:55 +000059STATISTIC(NumAdjusted, "Number of scalar allocas adjusted to allow promotion");
Chris Lattner79a42ac2006-12-19 21:40:18 +000060STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattnerfb41a502003-05-27 15:45:27 +000061
Chris Lattner79a42ac2006-12-19 21:40:18 +000062namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +000063 struct SROA : public FunctionPass {
Nadav Rotem4e9012c2012-06-21 13:44:31 +000064 SROA(int T, bool hasDT, char &ID, int ST, int AT, int SLT)
Cameron Zwarich4694e692011-01-18 03:53:26 +000065 : FunctionPass(ID), HasDomTree(hasDT) {
Devang Patele8ec7662007-07-09 21:19:23 +000066 if (T == -1)
Chris Lattner1f708162007-08-02 21:33:36 +000067 SRThreshold = 128;
Devang Patele8ec7662007-07-09 21:19:23 +000068 else
69 SRThreshold = T;
Nadav Rotem4e9012c2012-06-21 13:44:31 +000070 if (ST == -1)
71 StructMemberThreshold = 32;
72 else
73 StructMemberThreshold = ST;
74 if (AT == -1)
75 ArrayElementThreshold = 8;
76 else
77 ArrayElementThreshold = AT;
78 if (SLT == -1)
79 // Do not limit the scalar integer load size if no threshold is given.
80 ScalarLoadThreshold = -1;
81 else
82 ScalarLoadThreshold = SLT;
Devang Patele8ec7662007-07-09 21:19:23 +000083 }
Devang Patel09f162c2007-05-01 21:15:47 +000084
Craig Topper3e4c6972014-03-05 09:10:37 +000085 bool runOnFunction(Function &F) override;
Chris Lattnerfb41a502003-05-27 15:45:27 +000086
Chris Lattner5d8a12e2003-09-11 16:45:55 +000087 bool performScalarRepl(Function &F);
88 bool performPromotion(Function &F);
89
Chris Lattnerfb41a502003-05-27 15:45:27 +000090 private:
Cameron Zwarich4694e692011-01-18 03:53:26 +000091 bool HasDomTree;
Bob Wilson328e91b2011-01-13 20:59:44 +000092
Bob Wilson532cd232009-12-18 20:14:40 +000093 /// DeadInsts - Keep track of instructions we have made dead, so that
94 /// we can remove them after we are done working.
95 SmallVector<Value*, 32> DeadInsts;
96
Chris Lattner87679202007-05-30 06:11:23 +000097 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
98 /// information about the uses. All these fields are initialized to false
99 /// and set to true when something is learned.
100 struct AllocaInfo {
Chris Lattner8acbb792011-01-23 07:29:29 +0000101 /// The alloca to promote.
102 AllocaInst *AI;
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000103
Chris Lattner9491dee2011-01-23 08:27:54 +0000104 /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
105 /// looping and avoid redundant work.
106 SmallPtrSet<PHINode*, 8> CheckedPHIs;
Nadav Rotem465834c2012-07-24 10:51:42 +0000107
Chris Lattner87679202007-05-30 06:11:23 +0000108 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
109 bool isUnsafe : 1;
Bob Wilson328e91b2011-01-13 20:59:44 +0000110
Chris Lattner87679202007-05-30 06:11:23 +0000111 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
112 bool isMemCpySrc : 1;
113
Zhou Sheng1ee941d2007-07-06 06:01:16 +0000114 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner87679202007-05-30 06:11:23 +0000115 bool isMemCpyDst : 1;
116
Chris Lattner6fab2e92011-01-16 06:18:28 +0000117 /// hasSubelementAccess - This is true if a subelement of the alloca is
118 /// ever accessed, or false if the alloca is only accessed with mem
119 /// intrinsics or load/store that only access the entire alloca at once.
120 bool hasSubelementAccess : 1;
Nadav Rotem465834c2012-07-24 10:51:42 +0000121
Chris Lattner6fab2e92011-01-16 06:18:28 +0000122 /// hasALoadOrStore - This is true if there are any loads or stores to it.
123 /// The alloca may just be accessed with memcpy, for example, which would
124 /// not set this.
125 bool hasALoadOrStore : 1;
Nadav Rotem465834c2012-07-24 10:51:42 +0000126
Chris Lattner8acbb792011-01-23 07:29:29 +0000127 explicit AllocaInfo(AllocaInst *ai)
128 : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
Chris Lattner6fab2e92011-01-16 06:18:28 +0000129 hasSubelementAccess(false), hasALoadOrStore(false) {}
Chris Lattner87679202007-05-30 06:11:23 +0000130 };
Bob Wilson328e91b2011-01-13 20:59:44 +0000131
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000132 /// SRThreshold - The maximum alloca size to considered for SROA.
Devang Patele8ec7662007-07-09 21:19:23 +0000133 unsigned SRThreshold;
134
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000135 /// StructMemberThreshold - The maximum number of members a struct can
136 /// contain to be considered for SROA.
137 unsigned StructMemberThreshold;
138
139 /// ArrayElementThreshold - The maximum number of elements an array can
140 /// have to be considered for SROA.
141 unsigned ArrayElementThreshold;
142
143 /// ScalarLoadThreshold - The maximum size in bits of scalars to load when
144 /// converting to scalar
145 unsigned ScalarLoadThreshold;
146
Chris Lattner3e56c292011-01-23 07:05:44 +0000147 void MarkUnsafe(AllocaInfo &I, Instruction *User) {
148 I.isUnsafe = true;
149 DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
150 }
Chris Lattner87679202007-05-30 06:11:23 +0000151
Victor Hernandez1df65182010-01-21 23:05:53 +0000152 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner87679202007-05-30 06:11:23 +0000153
Chris Lattner8acbb792011-01-23 07:29:29 +0000154 void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
Chris Lattner9491dee2011-01-23 08:27:54 +0000155 void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
156 AllocaInfo &Info);
Chris Lattner8acbb792011-01-23 07:29:29 +0000157 void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
158 void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattner229907c2011-07-18 04:54:35 +0000159 Type *MemOpType, bool isStore, AllocaInfo &Info,
Chris Lattner9491dee2011-01-23 08:27:54 +0000160 Instruction *TheAccess, bool AllowWholeAccess);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000161 bool TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size,
162 const DataLayout &DL);
163 uint64_t FindElementAndOffset(Type *&T, uint64_t &Offset, Type *&IdxTy,
164 const DataLayout &DL);
Bob Wilson328e91b2011-01-13 20:59:44 +0000165
166 void DoScalarReplacement(AllocaInst *AI,
Victor Hernandez8acf2952009-10-23 21:09:37 +0000167 std::vector<AllocaInst*> &WorkList);
Bob Wilson532cd232009-12-18 20:14:40 +0000168 void DeleteDeadInstructions();
Bob Wilson328e91b2011-01-13 20:59:44 +0000169
Bob Wilson532cd232009-12-18 20:14:40 +0000170 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +0000171 SmallVectorImpl<AllocaInst *> &NewElts);
Bob Wilson532cd232009-12-18 20:14:40 +0000172 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +0000173 SmallVectorImpl<AllocaInst *> &NewElts);
Bob Wilson532cd232009-12-18 20:14:40 +0000174 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +0000175 SmallVectorImpl<AllocaInst *> &NewElts);
Nick Lewycky15e2d902011-07-25 23:14:22 +0000176 void RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
177 uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +0000178 SmallVectorImpl<AllocaInst *> &NewElts);
Bob Wilson532cd232009-12-18 20:14:40 +0000179 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez8acf2952009-10-23 21:09:37 +0000180 AllocaInst *AI,
Craig Topperb94011f2013-07-14 04:42:23 +0000181 SmallVectorImpl<AllocaInst *> &NewElts);
Victor Hernandez8acf2952009-10-23 21:09:37 +0000182 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Craig Topperb94011f2013-07-14 04:42:23 +0000183 SmallVectorImpl<AllocaInst *> &NewElts);
Victor Hernandez8acf2952009-10-23 21:09:37 +0000184 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Craig Topperb94011f2013-07-14 04:42:23 +0000185 SmallVectorImpl<AllocaInst *> &NewElts);
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000186 bool ShouldAttemptScalarRepl(AllocaInst *AI);
Chris Lattnerfb41a502003-05-27 15:45:27 +0000187 };
Nadav Rotem465834c2012-07-24 10:51:42 +0000188
Cameron Zwarich4694e692011-01-18 03:53:26 +0000189 // SROA_DT - SROA that uses DominatorTree.
190 struct SROA_DT : public SROA {
Chris Lattner9987a6f2011-01-14 08:13:00 +0000191 static char ID;
192 public:
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000193 SROA_DT(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
194 SROA(T, true, ID, ST, AT, SLT) {
Cameron Zwarich4694e692011-01-18 03:53:26 +0000195 initializeSROA_DTPass(*PassRegistry::getPassRegistry());
Chris Lattner9987a6f2011-01-14 08:13:00 +0000196 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000197
Chris Lattner9987a6f2011-01-14 08:13:00 +0000198 // getAnalysisUsage - This pass does not require any passes, but we know it
199 // will not alter the CFG, so say so.
Craig Topper3e4c6972014-03-05 09:10:37 +0000200 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth66b31302015-01-04 12:03:27 +0000201 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth73523022014-01-13 13:07:17 +0000202 AU.addRequired<DominatorTreeWrapperPass>();
Chris Lattner9987a6f2011-01-14 08:13:00 +0000203 AU.setPreservesCFG();
204 }
205 };
Nadav Rotem465834c2012-07-24 10:51:42 +0000206
Chris Lattner9987a6f2011-01-14 08:13:00 +0000207 // SROA_SSAUp - SROA that uses SSAUpdater.
208 struct SROA_SSAUp : public SROA {
209 static char ID;
210 public:
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000211 SROA_SSAUp(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
212 SROA(T, false, ID, ST, AT, SLT) {
Chris Lattner9987a6f2011-01-14 08:13:00 +0000213 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
214 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000215
Chris Lattner9987a6f2011-01-14 08:13:00 +0000216 // getAnalysisUsage - This pass does not require any passes, but we know it
217 // will not alter the CFG, so say so.
Craig Topper3e4c6972014-03-05 09:10:37 +0000218 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth66b31302015-01-04 12:03:27 +0000219 AU.addRequired<AssumptionCacheTracker>();
Chris Lattner9987a6f2011-01-14 08:13:00 +0000220 AU.setPreservesCFG();
221 }
222 };
Nadav Rotem465834c2012-07-24 10:51:42 +0000223
Chris Lattnerfb41a502003-05-27 15:45:27 +0000224}
225
Cameron Zwarich4694e692011-01-18 03:53:26 +0000226char SROA_DT::ID = 0;
Chris Lattner9987a6f2011-01-14 08:13:00 +0000227char SROA_SSAUp::ID = 0;
228
Cameron Zwarich4694e692011-01-18 03:53:26 +0000229INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
230 "Scalar Replacement of Aggregates (DT)", false, false)
Chandler Carruth66b31302015-01-04 12:03:27 +0000231INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth73523022014-01-13 13:07:17 +0000232INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Cameron Zwarich4694e692011-01-18 03:53:26 +0000233INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
234 "Scalar Replacement of Aggregates (DT)", false, false)
Chris Lattner9987a6f2011-01-14 08:13:00 +0000235
236INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
237 "Scalar Replacement of Aggregates (SSAUp)", false, false)
Chandler Carruth66b31302015-01-04 12:03:27 +0000238INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chris Lattner9987a6f2011-01-14 08:13:00 +0000239INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
240 "Scalar Replacement of Aggregates (SSAUp)", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000241
Brian Gaeke960707c2003-11-11 22:41:34 +0000242// Public interface to the ScalarReplAggregates pass
Chris Lattner9987a6f2011-01-14 08:13:00 +0000243FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000244 bool UseDomTree,
245 int StructMemberThreshold,
246 int ArrayElementThreshold,
247 int ScalarLoadThreshold) {
Cameron Zwarich4694e692011-01-18 03:53:26 +0000248 if (UseDomTree)
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000249 return new SROA_DT(Threshold, StructMemberThreshold, ArrayElementThreshold,
250 ScalarLoadThreshold);
251 return new SROA_SSAUp(Threshold, StructMemberThreshold,
252 ArrayElementThreshold, ScalarLoadThreshold);
Devang Patele8ec7662007-07-09 21:19:23 +0000253}
Chris Lattnerfb41a502003-05-27 15:45:27 +0000254
255
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000256//===----------------------------------------------------------------------===//
257// Convert To Scalar Optimization.
258//===----------------------------------------------------------------------===//
259
260namespace {
Chris Lattnerb7355292010-04-16 00:38:19 +0000261/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
262/// optimization, which scans the uses of an alloca and determines if it can
263/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000264class ConvertToScalarInfo {
Cameron Zwarich63062cc2011-03-16 00:13:35 +0000265 /// AllocaSize - The size of the alloca being considered in bytes.
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000266 unsigned AllocaSize;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000267 const DataLayout &DL;
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000268 unsigned ScalarLoadThreshold;
Bob Wilson328e91b2011-01-13 20:59:44 +0000269
Chris Lattnerbd2d9432010-04-16 02:32:17 +0000270 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnerb7355292010-04-16 00:38:19 +0000271 /// which means that mem2reg can't promote it.
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000272 bool IsNotTrivial;
Bob Wilson328e91b2011-01-13 20:59:44 +0000273
Cameron Zwarich5e9a0be2011-06-13 21:44:35 +0000274 /// ScalarKind - Tracks the kind of alloca being considered for promotion,
275 /// computed based on the uses of the alloca rather than the LLVM type system.
276 enum {
277 Unknown,
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000278
Cameron Zwarich922e4942011-06-13 23:39:23 +0000279 // Accesses via GEPs that are consistent with element access of a vector
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000280 // type. This will not be converted into a vector unless there is a later
281 // access using an actual vector type.
282 ImplicitVector,
283
Cameron Zwarich922e4942011-06-13 23:39:23 +0000284 // Accesses via vector operations and GEPs that are consistent with the
285 // layout of a vector type.
Cameron Zwarich5e9a0be2011-06-13 21:44:35 +0000286 Vector,
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000287
288 // An integer bag-of-bits with bitwise operations for insertion and
289 // extraction. Any combination of types can be converted into this kind
290 // of scalar.
Cameron Zwarich5e9a0be2011-06-13 21:44:35 +0000291 Integer
292 } ScalarKind;
293
Chris Lattnerb7355292010-04-16 00:38:19 +0000294 /// VectorTy - This tracks the type that we should promote the vector to if
295 /// it is possible to turn it into a vector. This starts out null, and if it
296 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Chris Lattner229907c2011-07-18 04:54:35 +0000297 VectorType *VectorTy;
Bob Wilson328e91b2011-01-13 20:59:44 +0000298
Nadav Rotem465834c2012-07-24 10:51:42 +0000299 /// HadNonMemTransferAccess - True if there is at least one access to the
Cameron Zwarich7599b102011-03-16 08:13:42 +0000300 /// alloca that is not a MemTransferInst. We don't want to turn structs into
301 /// large integers unless there is some potential for optimization.
Cameron Zwarich04542532011-03-16 00:13:44 +0000302 bool HadNonMemTransferAccess;
303
Pete Cooper33ee6c92012-06-17 03:58:26 +0000304 /// HadDynamicAccess - True if some element of this alloca was dynamic.
305 /// We don't yet have support for turning a dynamic access into a large
306 /// integer.
307 bool HadDynamicAccess;
308
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000309public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000310 explicit ConvertToScalarInfo(unsigned Size, const DataLayout &DL,
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000311 unsigned SLT)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000312 : AllocaSize(Size), DL(DL), ScalarLoadThreshold(SLT), IsNotTrivial(false),
Craig Topperf40110f2014-04-25 05:29:35 +0000313 ScalarKind(Unknown), VectorTy(nullptr), HadNonMemTransferAccess(false),
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000314 HadDynamicAccess(false) { }
Bob Wilson328e91b2011-01-13 20:59:44 +0000315
Chris Lattnerb7355292010-04-16 00:38:19 +0000316 AllocaInst *TryConvert(AllocaInst *AI);
Bob Wilson328e91b2011-01-13 20:59:44 +0000317
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000318private:
Pete Cooper33ee6c92012-06-17 03:58:26 +0000319 bool CanConvertToScalar(Value *V, uint64_t Offset, Value* NonConstantIdx);
Chris Lattner229907c2011-07-18 04:54:35 +0000320 void MergeInTypeForLoadOrStore(Type *In, uint64_t Offset);
321 bool MergeInVectorType(VectorType *VInTy, uint64_t Offset);
Pete Cooper33ee6c92012-06-17 03:58:26 +0000322 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset,
323 Value *NonConstantIdx);
Bob Wilson328e91b2011-01-13 20:59:44 +0000324
Chris Lattner229907c2011-07-18 04:54:35 +0000325 Value *ConvertScalar_ExtractValue(Value *NV, Type *ToType,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000326 uint64_t Offset, Value* NonConstantIdx,
327 IRBuilder<> &Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000328 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000329 uint64_t Offset, Value* NonConstantIdx,
330 IRBuilder<> &Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000331};
332} // end anonymous namespace.
333
Chris Lattner34e53612010-09-01 05:14:33 +0000334
Chris Lattnerb7355292010-04-16 00:38:19 +0000335/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
336/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
337/// alloca if possible or null if not.
338AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
339 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
340 // out.
Craig Topperf40110f2014-04-25 05:29:35 +0000341 if (!CanConvertToScalar(AI, 0, nullptr) || !IsNotTrivial)
342 return nullptr;
Bob Wilson328e91b2011-01-13 20:59:44 +0000343
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000344 // If an alloca has only memset / memcpy uses, it may still have an Unknown
345 // ScalarKind. Treat it as an Integer below.
346 if (ScalarKind == Unknown)
347 ScalarKind = Integer;
348
Cameron Zwarich9601ddb2011-06-18 06:17:51 +0000349 if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
350 ScalarKind = Integer;
351
Chris Lattnerb7355292010-04-16 00:38:19 +0000352 // If we were able to find a vector type that can handle this with
353 // insert/extract elements, and if there was at least one use that had
354 // a vector type, promote this to a vector. We don't want to promote
355 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
356 // we just get a lot of insert/extracts. If at least one vector is
357 // involved, then we probably really do have a union of vector/array.
Chris Lattner229907c2011-07-18 04:54:35 +0000358 Type *NewTy;
Cameron Zwarichb5f19d92011-06-14 06:33:51 +0000359 if (ScalarKind == Vector) {
360 assert(VectorTy && "Missing type for vector scalar.");
Chris Lattnerb7355292010-04-16 00:38:19 +0000361 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
362 << *VectorTy << '\n');
363 NewTy = VectorTy; // Use the vector type.
364 } else {
Cameron Zwarich04542532011-03-16 00:13:44 +0000365 unsigned BitWidth = AllocaSize * 8;
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000366
367 // Do not convert to scalar integer if the alloca size exceeds the
368 // scalar load threshold.
369 if (BitWidth > ScalarLoadThreshold)
Craig Topperf40110f2014-04-25 05:29:35 +0000370 return nullptr;
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000371
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000372 if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000373 !HadNonMemTransferAccess && !DL.fitsInLegalInteger(BitWidth))
Craig Topperf40110f2014-04-25 05:29:35 +0000374 return nullptr;
Pete Cooper33ee6c92012-06-17 03:58:26 +0000375 // Dynamic accesses on integers aren't yet supported. They need us to shift
376 // by a dynamic amount which could be difficult to work out as we might not
377 // know whether to use a left or right shift.
378 if (ScalarKind == Integer && HadDynamicAccess)
Craig Topperf40110f2014-04-25 05:29:35 +0000379 return nullptr;
Cameron Zwarich04542532011-03-16 00:13:44 +0000380
Chris Lattnerb7355292010-04-16 00:38:19 +0000381 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
382 // Create and insert the integer alloca.
Cameron Zwarich04542532011-03-16 00:13:44 +0000383 NewTy = IntegerType::get(AI->getContext(), BitWidth);
Chris Lattnerb7355292010-04-16 00:38:19 +0000384 }
Craig Topperf40110f2014-04-25 05:29:35 +0000385 AllocaInst *NewAI = new AllocaInst(NewTy, nullptr, "",
386 AI->getParent()->begin());
387 ConvertUsesToScalar(AI, NewAI, 0, nullptr);
Chris Lattnerb7355292010-04-16 00:38:19 +0000388 return NewAI;
389}
390
Cameron Zwarich3ecbd592011-06-13 21:44:43 +0000391/// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
392/// (VectorTy) so far at the offset specified by Offset (which is specified in
393/// bytes).
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000394///
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000395/// There are two cases we handle here:
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000396/// 1) A union of vector types of the same size and potentially its elements.
397/// Here we turn element accesses into insert/extract element operations.
398/// This promotes a <4 x float> with a store of float to the third element
399/// into a <4 x float> that uses insert element.
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000400/// 2) A fully general blob of memory, which we turn into some (potentially
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000401/// large) integer type with extract and insert operations where the loads
Chris Lattnerb7355292010-04-16 00:38:19 +0000402/// and stores would mutate the memory. We mark this by setting VectorTy
403/// to VoidTy.
Chris Lattner229907c2011-07-18 04:54:35 +0000404void ConvertToScalarInfo::MergeInTypeForLoadOrStore(Type *In,
Cameron Zwarich3ecbd592011-06-13 21:44:43 +0000405 uint64_t Offset) {
Chris Lattnerb7355292010-04-16 00:38:19 +0000406 // If we already decided to turn this into a blob of integer memory, there is
407 // nothing to be done.
Cameron Zwarich5e9a0be2011-06-13 21:44:35 +0000408 if (ScalarKind == Integer)
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000409 return;
Bob Wilson328e91b2011-01-13 20:59:44 +0000410
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000411 // If this could be contributing to a vector, analyze it.
412
413 // If the In type is a vector that is the same size as the alloca, see if it
414 // matches the existing VecTy.
Chris Lattner229907c2011-07-18 04:54:35 +0000415 if (VectorType *VInTy = dyn_cast<VectorType>(In)) {
Cameron Zwarich43a241f2011-03-09 05:43:01 +0000416 if (MergeInVectorType(VInTy, Offset))
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000417 return;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000418 } else if (In->isFloatTy() || In->isDoubleTy() ||
419 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
420 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
Cameron Zwarichff811cc2011-03-29 05:19:52 +0000421 // Full width accesses can be ignored, because they can always be turned
422 // into bitcasts.
423 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
Cameron Zwarich8deb6152011-06-13 21:44:31 +0000424 if (EltSize == AllocaSize)
Cameron Zwarichff811cc2011-03-29 05:19:52 +0000425 return;
Cameron Zwarich4cd9a4a2011-04-20 21:48:16 +0000426
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000427 // If we're accessing something that could be an element of a vector, see
428 // if the implied vector agrees with what we already have and if Offset is
429 // compatible with it.
Cameron Zwarich77a699a2011-06-09 01:45:33 +0000430 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000431 (!VectorTy || EltSize == VectorTy->getElementType()
432 ->getPrimitiveSizeInBits()/8)) {
Cameron Zwarich4cd9a4a2011-04-20 21:48:16 +0000433 if (!VectorTy) {
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000434 ScalarKind = ImplicitVector;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000435 VectorTy = VectorType::get(In, AllocaSize/EltSize);
Cameron Zwarich4cd9a4a2011-04-20 21:48:16 +0000436 }
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000437 return;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000438 }
439 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000440
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000441 // Otherwise, we have a case that we can't handle with an optimized vector
442 // form. We can still turn this into a large integer.
Cameron Zwarich5e9a0be2011-06-13 21:44:35 +0000443 ScalarKind = Integer;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000444}
445
Cameron Zwarich3ecbd592011-06-13 21:44:43 +0000446/// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
447/// returning true if the type was successfully merged and false otherwise.
Chris Lattner229907c2011-07-18 04:54:35 +0000448bool ConvertToScalarInfo::MergeInVectorType(VectorType *VInTy,
Cameron Zwarich43a241f2011-03-09 05:43:01 +0000449 uint64_t Offset) {
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000450 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
451 // If we're storing/loading a vector of the right size, allow it as a
452 // vector. If this the first vector we see, remember the type so that
453 // we know the element size. If this is a subsequent access, ignore it
454 // even if it is a differing type but the same size. Worst case we can
455 // bitcast the resultant vectors.
456 if (!VectorTy)
457 VectorTy = VInTy;
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000458 ScalarKind = Vector;
Cameron Zwarich3b649f42011-03-09 05:43:05 +0000459 return true;
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000460 }
Cameron Zwarich3b649f42011-03-09 05:43:05 +0000461
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000462 return false;
Cameron Zwarich43a241f2011-03-09 05:43:01 +0000463}
464
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000465/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
466/// its accesses to a single vector type, return true and set VecTy to
467/// the new type. If we could convert the alloca into a single promotable
468/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
469/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
470/// is the current offset from the base of the alloca being analyzed.
471///
472/// If we see at least one access to the value that is as a vector type, set the
473/// SawVec flag.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000474bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset,
475 Value* NonConstantIdx) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000476 for (User *U : V->users()) {
477 Instruction *UI = cast<Instruction>(U);
Bob Wilson328e91b2011-01-13 20:59:44 +0000478
Chandler Carruthcdf47882014-03-09 03:16:01 +0000479 if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000480 // Don't break volatile loads.
Eli Friedman7c5dc122011-09-12 20:23:13 +0000481 if (!LI->isSimple())
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000482 return false;
Dale Johannesendd224d22010-09-30 23:57:10 +0000483 // Don't touch MMX operations.
484 if (LI->getType()->isX86_MMXTy())
485 return false;
Cameron Zwarich04542532011-03-16 00:13:44 +0000486 HadNonMemTransferAccess = true;
Cameron Zwarich3ecbd592011-06-13 21:44:43 +0000487 MergeInTypeForLoadOrStore(LI->getType(), Offset);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000488 continue;
489 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000490
Chandler Carruthcdf47882014-03-09 03:16:01 +0000491 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000492 // Storing the pointer, not into the value?
Eli Friedman7c5dc122011-09-12 20:23:13 +0000493 if (SI->getOperand(0) == V || !SI->isSimple()) return false;
Dale Johannesendd224d22010-09-30 23:57:10 +0000494 // Don't touch MMX operations.
495 if (SI->getOperand(0)->getType()->isX86_MMXTy())
496 return false;
Cameron Zwarich04542532011-03-16 00:13:44 +0000497 HadNonMemTransferAccess = true;
Cameron Zwarich3ecbd592011-06-13 21:44:43 +0000498 MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000499 continue;
500 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000501
Chandler Carruthcdf47882014-03-09 03:16:01 +0000502 if (BitCastInst *BCI = dyn_cast<BitCastInst>(UI)) {
Nick Lewycky15e2d902011-07-25 23:14:22 +0000503 if (!onlyUsedByLifetimeMarkers(BCI))
504 IsNotTrivial = true; // Can't be mem2reg'd.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000505 if (!CanConvertToScalar(BCI, Offset, NonConstantIdx))
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000506 return false;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000507 continue;
508 }
509
Chandler Carruthcdf47882014-03-09 03:16:01 +0000510 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UI)) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000511 // If this is a GEP with a variable indices, we can't handle it.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000512 PointerType* PtrTy = dyn_cast<PointerType>(GEP->getPointerOperandType());
513 if (!PtrTy)
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000514 return false;
Bob Wilson328e91b2011-01-13 20:59:44 +0000515
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000516 // Compute the offset that this GEP adds to the pointer.
517 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Craig Topperf40110f2014-04-25 05:29:35 +0000518 Value *GEPNonConstantIdx = nullptr;
Pete Cooper33ee6c92012-06-17 03:58:26 +0000519 if (!GEP->hasAllConstantIndices()) {
520 if (!isa<VectorType>(PtrTy->getElementType()))
521 return false;
522 if (NonConstantIdx)
523 return false;
524 GEPNonConstantIdx = Indices.pop_back_val();
525 if (!GEPNonConstantIdx->getType()->isIntegerTy(32))
526 return false;
527 HadDynamicAccess = true;
528 } else
529 GEPNonConstantIdx = NonConstantIdx;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000530 uint64_t GEPOffset = DL.getIndexedOffset(PtrTy,
Jay Foadbf904772011-07-19 14:01:37 +0000531 Indices);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000532 // See if all uses can be converted.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000533 if (!CanConvertToScalar(GEP, Offset+GEPOffset, GEPNonConstantIdx))
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000534 return false;
Chris Lattnerb7355292010-04-16 00:38:19 +0000535 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich04542532011-03-16 00:13:44 +0000536 HadNonMemTransferAccess = true;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000537 continue;
538 }
539
540 // If this is a constant sized memset of a constant value (e.g. 0) we can
541 // handle it.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000542 if (MemSetInst *MSI = dyn_cast<MemSetInst>(UI)) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000543 // Store to dynamic index.
544 if (NonConstantIdx)
545 return false;
Cameron Zwarich2a261002011-06-18 05:47:49 +0000546 // Store of constant value.
547 if (!isa<ConstantInt>(MSI->getValue()))
Chris Lattnerb7355292010-04-16 00:38:19 +0000548 return false;
Cameron Zwarich2a261002011-06-18 05:47:49 +0000549
550 // Store of constant size.
551 ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
552 if (!Len)
553 return false;
554
555 // If the size differs from the alloca, we can only convert the alloca to
556 // an integer bag-of-bits.
557 // FIXME: This should handle all of the cases that are currently accepted
558 // as vector element insertions.
559 if (Len->getZExtValue() != AllocaSize || Offset != 0)
560 ScalarKind = Integer;
561
Chris Lattnerb7355292010-04-16 00:38:19 +0000562 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich04542532011-03-16 00:13:44 +0000563 HadNonMemTransferAccess = true;
Chris Lattnerb7355292010-04-16 00:38:19 +0000564 continue;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000565 }
566
567 // If this is a memcpy or memmove into or out of the whole allocation, we
568 // can handle it like a load or store of the scalar type.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000569 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(UI)) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000570 // Store to dynamic index.
571 if (NonConstantIdx)
572 return false;
Chris Lattnerb7355292010-04-16 00:38:19 +0000573 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +0000574 if (!Len || Len->getZExtValue() != AllocaSize || Offset != 0)
Chris Lattnerb7355292010-04-16 00:38:19 +0000575 return false;
Bob Wilson328e91b2011-01-13 20:59:44 +0000576
Chris Lattnerb7355292010-04-16 00:38:19 +0000577 IsNotTrivial = true; // Can't be mem2reg'd.
578 continue;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000579 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000580
Nick Lewycky15e2d902011-07-25 23:14:22 +0000581 // If this is a lifetime intrinsic, we can handle it.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000582 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(UI)) {
Nick Lewycky15e2d902011-07-25 23:14:22 +0000583 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
584 II->getIntrinsicID() == Intrinsic::lifetime_end) {
585 continue;
586 }
587 }
588
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000589 // Otherwise, we cannot handle this!
590 return false;
591 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000592
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000593 return true;
594}
595
596/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
597/// directly. This happens when we are converting an "integer union" to a
598/// single integer scalar, or when we are converting a "vector union" to a
599/// vector with insert/extractelement instructions.
600///
601/// Offset is an offset from the original alloca, in bits that need to be
602/// shifted to the right. By the end of this, there should be no uses of Ptr.
603void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000604 uint64_t Offset,
605 Value* NonConstantIdx) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000606 while (!Ptr->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000607 Instruction *User = cast<Instruction>(Ptr->user_back());
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000608
609 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000610 ConvertUsesToScalar(CI, NewAI, Offset, NonConstantIdx);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000611 CI->eraseFromParent();
612 continue;
613 }
614
615 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
616 // Compute the offset that this GEP adds to the pointer.
617 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Craig Topperf40110f2014-04-25 05:29:35 +0000618 Value* GEPNonConstantIdx = nullptr;
Pete Cooper0deca6b2012-08-10 03:26:36 +0000619 if (!GEP->hasAllConstantIndices()) {
620 assert(!NonConstantIdx &&
621 "Dynamic GEP reading from dynamic GEP unsupported");
622 GEPNonConstantIdx = Indices.pop_back_val();
623 } else
624 GEPNonConstantIdx = NonConstantIdx;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000625 uint64_t GEPOffset = DL.getIndexedOffset(GEP->getPointerOperandType(),
Jay Foadbf904772011-07-19 14:01:37 +0000626 Indices);
Pete Cooper0deca6b2012-08-10 03:26:36 +0000627 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8, GEPNonConstantIdx);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000628 GEP->eraseFromParent();
629 continue;
630 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000631
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000632 IRBuilder<> Builder(User);
Bob Wilson328e91b2011-01-13 20:59:44 +0000633
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000634 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
635 // The load is a bit extract from NewAI shifted right by Offset bits.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000636 Value *LoadedVal = Builder.CreateLoad(NewAI);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000637 Value *NewLoadVal
Pete Cooper33ee6c92012-06-17 03:58:26 +0000638 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset,
639 NonConstantIdx, Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000640 LI->replaceAllUsesWith(NewLoadVal);
641 LI->eraseFromParent();
642 continue;
643 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000644
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000645 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
646 assert(SI->getOperand(0) != Ptr && "Consistency error!");
647 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
648 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000649 NonConstantIdx, Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000650 Builder.CreateStore(New, NewAI);
651 SI->eraseFromParent();
Bob Wilson328e91b2011-01-13 20:59:44 +0000652
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000653 // If the load we just inserted is now dead, then the inserted store
654 // overwrote the entire thing.
655 if (Old->use_empty())
656 Old->eraseFromParent();
657 continue;
658 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000659
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000660 // If this is a constant sized memset of a constant value (e.g. 0) we can
661 // transform it into a store of the expanded constant value.
662 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
663 assert(MSI->getRawDest() == Ptr && "Consistency error!");
Pete Cooper33ee6c92012-06-17 03:58:26 +0000664 assert(!NonConstantIdx && "Cannot replace dynamic memset with insert");
Duncan Sands8f897dc2012-03-23 08:29:04 +0000665 int64_t SNumBytes = cast<ConstantInt>(MSI->getLength())->getSExtValue();
Chris Lattner7d7dba32012-03-22 03:46:58 +0000666 if (SNumBytes > 0 && (SNumBytes >> 32) == 0) {
Aaron Ballmana7332972012-03-15 00:05:31 +0000667 unsigned NumBytes = static_cast<unsigned>(SNumBytes);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000668 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
Bob Wilson328e91b2011-01-13 20:59:44 +0000669
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000670 // Compute the value replicated the right number of times.
671 APInt APVal(NumBytes*8, Val);
672
673 // Splat the value if non-zero.
674 if (Val)
675 for (unsigned i = 1; i != NumBytes; ++i)
676 APVal |= APVal << 8;
Bob Wilson328e91b2011-01-13 20:59:44 +0000677
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000678 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
679 Value *New = ConvertScalar_InsertValue(
680 ConstantInt::get(User->getContext(), APVal),
Craig Topperf40110f2014-04-25 05:29:35 +0000681 Old, Offset, nullptr, Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000682 Builder.CreateStore(New, NewAI);
Bob Wilson328e91b2011-01-13 20:59:44 +0000683
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000684 // If the load we just inserted is now dead, then the memset overwrote
685 // the entire thing.
686 if (Old->use_empty())
Bob Wilson328e91b2011-01-13 20:59:44 +0000687 Old->eraseFromParent();
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000688 }
689 MSI->eraseFromParent();
690 continue;
691 }
692
693 // If this is a memcpy or memmove into or out of the whole allocation, we
694 // can handle it like a load or store of the scalar type.
695 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
696 assert(Offset == 0 && "must be store to start of alloca");
Pete Cooper33ee6c92012-06-17 03:58:26 +0000697 assert(!NonConstantIdx && "Cannot replace dynamic transfer with insert");
Bob Wilson328e91b2011-01-13 20:59:44 +0000698
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000699 // If the source and destination are both to the same alloca, then this is
700 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
701 // as appropriate.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000702 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, DL, 0));
Bob Wilson328e91b2011-01-13 20:59:44 +0000703
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000704 if (GetUnderlyingObject(MTI->getSource(), DL, 0) != OrigAI) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000705 // Dest must be OrigAI, change this to be a load from the original
706 // pointer (bitcasted), then a store to our new alloca.
707 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
708 Value *SrcPtr = MTI->getSource();
Chris Lattner229907c2011-07-18 04:54:35 +0000709 PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
710 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
Mon P Wang18b762a2010-12-23 01:41:32 +0000711 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
712 AIPTy = PointerType::get(AIPTy->getElementType(),
713 SPTy->getAddressSpace());
714 }
715 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
716
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000717 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
718 SrcVal->setAlignment(MTI->getAlignment());
719 Builder.CreateStore(SrcVal, NewAI);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000720 } else if (GetUnderlyingObject(MTI->getDest(), DL, 0) != OrigAI) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000721 // Src must be OrigAI, change this to be a load from NewAI then a store
722 // through the original dest pointer (bitcasted).
723 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
724 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
725
Chris Lattner229907c2011-07-18 04:54:35 +0000726 PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
727 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
Mon P Wang18b762a2010-12-23 01:41:32 +0000728 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
729 AIPTy = PointerType::get(AIPTy->getElementType(),
730 DPTy->getAddressSpace());
731 }
732 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
733
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000734 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
735 NewStore->setAlignment(MTI->getAlignment());
736 } else {
737 // Noop transfer. Src == Dst
738 }
739
740 MTI->eraseFromParent();
741 continue;
742 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000743
Nick Lewycky15e2d902011-07-25 23:14:22 +0000744 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
745 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
746 II->getIntrinsicID() == Intrinsic::lifetime_end) {
747 // There's no need to preserve these, as the resulting alloca will be
748 // converted to a register anyways.
749 II->eraseFromParent();
750 continue;
751 }
752 }
753
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000754 llvm_unreachable("Unsupported operation!");
755 }
756}
757
758/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
759/// or vector value FromVal, extracting the bits from the offset specified by
760/// Offset. This returns the value, which is of type ToType.
761///
762/// This happens when we are converting an "integer union" to a single
763/// integer scalar, or when we are converting a "vector union" to a vector with
764/// insert/extractelement instructions.
765///
766/// Offset is an offset from the original alloca, in bits that need to be
767/// shifted to the right.
768Value *ConvertToScalarInfo::
Chris Lattner229907c2011-07-18 04:54:35 +0000769ConvertScalar_ExtractValue(Value *FromVal, Type *ToType,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000770 uint64_t Offset, Value* NonConstantIdx,
771 IRBuilder<> &Builder) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000772 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattner229907c2011-07-18 04:54:35 +0000773 Type *FromType = FromVal->getType();
Mon P Wang2e5528f2011-04-13 21:40:02 +0000774 if (FromType == ToType && Offset == 0)
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000775 return FromVal;
776
777 // If the result alloca is a vector type, this is either an element
778 // access or a bitcast to another vector type of the same size.
Chris Lattner229907c2011-07-18 04:54:35 +0000779 if (VectorType *VTy = dyn_cast<VectorType>(FromType)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000780 unsigned FromTypeSize = DL.getTypeAllocSize(FromType);
781 unsigned ToTypeSize = DL.getTypeAllocSize(ToType);
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000782 if (FromTypeSize == ToTypeSize)
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000783 return Builder.CreateBitCast(FromVal, ToType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000784
785 // Otherwise it must be an element access.
786 unsigned Elt = 0;
787 if (Offset) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000788 unsigned EltSize = DL.getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000789 Elt = Offset/EltSize;
790 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
791 }
792 // Return the element extracted out of it.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000793 Value *Idx;
794 if (NonConstantIdx) {
795 if (Elt)
796 Idx = Builder.CreateAdd(NonConstantIdx,
797 Builder.getInt32(Elt),
798 "dyn.offset");
799 else
800 Idx = NonConstantIdx;
801 } else
802 Idx = Builder.getInt32(Elt);
803 Value *V = Builder.CreateExtractElement(FromVal, Idx);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000804 if (V->getType() != ToType)
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000805 V = Builder.CreateBitCast(V, ToType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000806 return V;
807 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000808
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000809 // If ToType is a first class aggregate, extract out each of the pieces and
810 // use insertvalue's to form the FCA.
Chris Lattner229907c2011-07-18 04:54:35 +0000811 if (StructType *ST = dyn_cast<StructType>(ToType)) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000812 assert(!NonConstantIdx &&
813 "Dynamic indexing into struct types not supported");
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000814 const StructLayout &Layout = *DL.getStructLayout(ST);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000815 Value *Res = UndefValue::get(ST);
816 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
817 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
818 Offset+Layout.getElementOffsetInBits(i),
Craig Topperf40110f2014-04-25 05:29:35 +0000819 nullptr, Builder);
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000820 Res = Builder.CreateInsertValue(Res, Elt, i);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000821 }
822 return Res;
823 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000824
Chris Lattner229907c2011-07-18 04:54:35 +0000825 if (ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000826 assert(!NonConstantIdx &&
827 "Dynamic indexing into array types not supported");
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000828 uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000829 Value *Res = UndefValue::get(AT);
830 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
831 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
Craig Topperf40110f2014-04-25 05:29:35 +0000832 Offset+i*EltSize, nullptr,
833 Builder);
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000834 Res = Builder.CreateInsertValue(Res, Elt, i);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000835 }
836 return Res;
837 }
838
839 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattner229907c2011-07-18 04:54:35 +0000840 IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000841
842 // If this is a big-endian system and the load is narrower than the
843 // full alloca type, we need to do a shift to get the right bits.
844 int ShAmt = 0;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000845 if (DL.isBigEndian()) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000846 // On big-endian machines, the lowest bit is stored at the bit offset
847 // from the pointer given by getTypeStoreSizeInBits. This matters for
848 // integers with a bitwidth that is not a multiple of 8.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000849 ShAmt = DL.getTypeStoreSizeInBits(NTy) -
850 DL.getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000851 } else {
852 ShAmt = Offset;
853 }
854
855 // Note: we support negative bitwidths (with shl) which are not defined.
856 // We do this to support (f.e.) loads off the end of a structure where
857 // only some bits are used.
858 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
859 FromVal = Builder.CreateLShr(FromVal,
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000860 ConstantInt::get(FromVal->getType(), ShAmt));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000861 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Bob Wilson328e91b2011-01-13 20:59:44 +0000862 FromVal = Builder.CreateShl(FromVal,
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000863 ConstantInt::get(FromVal->getType(), -ShAmt));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000864
865 // Finally, unconditionally truncate the integer to the right width.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000866 unsigned LIBitWidth = DL.getTypeSizeInBits(ToType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000867 if (LIBitWidth < NTy->getBitWidth())
868 FromVal =
Bob Wilson328e91b2011-01-13 20:59:44 +0000869 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000870 LIBitWidth));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000871 else if (LIBitWidth > NTy->getBitWidth())
872 FromVal =
Bob Wilson328e91b2011-01-13 20:59:44 +0000873 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000874 LIBitWidth));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000875
876 // If the result is an integer, this is a trunc or bitcast.
877 if (ToType->isIntegerTy()) {
878 // Should be done.
879 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
880 // Just do a bitcast, we know the sizes match up.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000881 FromVal = Builder.CreateBitCast(FromVal, ToType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000882 } else {
883 // Otherwise must be a pointer.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000884 FromVal = Builder.CreateIntToPtr(FromVal, ToType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000885 }
886 assert(FromVal->getType() == ToType && "Didn't convert right?");
887 return FromVal;
888}
889
890/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
891/// or vector value "Old" at the offset specified by Offset.
892///
893/// This happens when we are converting an "integer union" to a
894/// single integer scalar, or when we are converting a "vector union" to a
895/// vector with insert/extractelement instructions.
896///
897/// Offset is an offset from the original alloca, in bits that need to be
898/// shifted to the right.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000899///
900/// NonConstantIdx is an index value if there was a GEP with a non-constant
901/// index value. If this is 0 then all GEPs used to find this insert address
902/// are constant.
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000903Value *ConvertToScalarInfo::
904ConvertScalar_InsertValue(Value *SV, Value *Old,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000905 uint64_t Offset, Value* NonConstantIdx,
906 IRBuilder<> &Builder) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000907 // Convert the stored type to the actual type, shift it left to insert
908 // then 'or' into place.
Chris Lattner229907c2011-07-18 04:54:35 +0000909 Type *AllocaType = Old->getType();
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000910 LLVMContext &Context = Old->getContext();
911
Chris Lattner229907c2011-07-18 04:54:35 +0000912 if (VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000913 uint64_t VecSize = DL.getTypeAllocSizeInBits(VTy);
914 uint64_t ValSize = DL.getTypeAllocSizeInBits(SV->getType());
Bob Wilson328e91b2011-01-13 20:59:44 +0000915
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000916 // Changing the whole vector with memset or with an access of a different
917 // vector type?
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000918 if (ValSize == VecSize)
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000919 return Builder.CreateBitCast(SV, AllocaType);
Cameron Zwarich3b649f42011-03-09 05:43:05 +0000920
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000921 // Must be an element insertion.
Cameron Zwarich057fbb12011-10-23 07:02:10 +0000922 Type *EltTy = VTy->getElementType();
923 if (SV->getType() != EltTy)
924 SV = Builder.CreateBitCast(SV, EltTy);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000925 uint64_t EltSize = DL.getTypeAllocSizeInBits(EltTy);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000926 unsigned Elt = Offset/EltSize;
Pete Cooper33ee6c92012-06-17 03:58:26 +0000927 Value *Idx;
928 if (NonConstantIdx) {
929 if (Elt)
930 Idx = Builder.CreateAdd(NonConstantIdx,
931 Builder.getInt32(Elt),
932 "dyn.offset");
933 else
934 Idx = NonConstantIdx;
935 } else
936 Idx = Builder.getInt32(Elt);
937 return Builder.CreateInsertElement(Old, SV, Idx);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000938 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000939
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000940 // If SV is a first-class aggregate value, insert each value recursively.
Chris Lattner229907c2011-07-18 04:54:35 +0000941 if (StructType *ST = dyn_cast<StructType>(SV->getType())) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000942 assert(!NonConstantIdx &&
943 "Dynamic indexing into struct types not supported");
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000944 const StructLayout &Layout = *DL.getStructLayout(ST);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000945 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000946 Value *Elt = Builder.CreateExtractValue(SV, i);
Bob Wilson328e91b2011-01-13 20:59:44 +0000947 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000948 Offset+Layout.getElementOffsetInBits(i),
Craig Topperf40110f2014-04-25 05:29:35 +0000949 nullptr, Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000950 }
951 return Old;
952 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000953
Chris Lattner229907c2011-07-18 04:54:35 +0000954 if (ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000955 assert(!NonConstantIdx &&
956 "Dynamic indexing into array types not supported");
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000957 uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000958 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000959 Value *Elt = Builder.CreateExtractValue(SV, i);
Craig Topperf40110f2014-04-25 05:29:35 +0000960 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, nullptr,
961 Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000962 }
963 return Old;
964 }
965
966 // If SV is a float, convert it to the appropriate integer type.
967 // If it is a pointer, do the same.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000968 unsigned SrcWidth = DL.getTypeSizeInBits(SV->getType());
969 unsigned DestWidth = DL.getTypeSizeInBits(AllocaType);
970 unsigned SrcStoreWidth = DL.getTypeStoreSizeInBits(SV->getType());
971 unsigned DestStoreWidth = DL.getTypeStoreSizeInBits(AllocaType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000972 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000973 SV = Builder.CreateBitCast(SV, IntegerType::get(SV->getContext(),SrcWidth));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000974 else if (SV->getType()->isPointerTy())
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000975 SV = Builder.CreatePtrToInt(SV, DL.getIntPtrType(SV->getType()));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000976
977 // Zero extend or truncate the value if needed.
978 if (SV->getType() != AllocaType) {
979 if (SV->getType()->getPrimitiveSizeInBits() <
980 AllocaType->getPrimitiveSizeInBits())
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000981 SV = Builder.CreateZExt(SV, AllocaType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000982 else {
983 // Truncation may be needed if storing more than the alloca can hold
984 // (undefined behavior).
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000985 SV = Builder.CreateTrunc(SV, AllocaType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000986 SrcWidth = DestWidth;
987 SrcStoreWidth = DestStoreWidth;
988 }
989 }
990
991 // If this is a big-endian system and the store is narrower than the
992 // full alloca type, we need to do a shift to get the right bits.
993 int ShAmt = 0;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000994 if (DL.isBigEndian()) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000995 // On big-endian machines, the lowest bit is stored at the bit offset
996 // from the pointer given by getTypeStoreSizeInBits. This matters for
997 // integers with a bitwidth that is not a multiple of 8.
998 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
999 } else {
1000 ShAmt = Offset;
1001 }
1002
1003 // Note: we support negative bitwidths (with shr) which are not defined.
1004 // We do this to support (f.e.) stores off the end of a structure where
1005 // only some bits in the structure are set.
1006 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1007 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001008 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt));
Chris Lattner78d7dbb2010-04-16 00:24:57 +00001009 Mask <<= ShAmt;
1010 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001011 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt));
Chris Lattner78d7dbb2010-04-16 00:24:57 +00001012 Mask = Mask.lshr(-ShAmt);
1013 }
1014
1015 // Mask out the bits we are about to insert from the old value, and or
1016 // in the new bits.
1017 if (SrcWidth != DestWidth) {
1018 assert(DestWidth > SrcWidth);
1019 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1020 SV = Builder.CreateOr(Old, SV, "ins");
1021 }
1022 return SV;
1023}
1024
1025
1026//===----------------------------------------------------------------------===//
1027// SRoA Driver
1028//===----------------------------------------------------------------------===//
1029
1030
Chris Lattnerfb41a502003-05-27 15:45:27 +00001031bool SROA::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00001032 if (skipOptnoneFunction(F))
1033 return false;
1034
Chris Lattner9a95f2a2003-09-12 15:36:03 +00001035 bool Changed = performPromotion(F);
Dan Gohman915302c2009-08-19 18:22:18 +00001036
Chris Lattner9a95f2a2003-09-12 15:36:03 +00001037 while (1) {
1038 bool LocalChange = performScalarRepl(F);
1039 if (!LocalChange) break; // No need to repromote if no scalarrepl
1040 Changed = true;
1041 LocalChange = performPromotion(F);
1042 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
1043 }
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001044
1045 return Changed;
1046}
1047
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001048namespace {
1049class AllocaPromoter : public LoadAndStorePromoter {
1050 AllocaInst *AI;
Devang Patela3cbf522011-07-06 21:09:55 +00001051 DIBuilder *DIB;
Devang Patelc6ee9182011-07-06 22:06:11 +00001052 SmallVector<DbgDeclareInst *, 4> DDIs;
1053 SmallVector<DbgValueInst *, 4> DVIs;
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001054public:
Cameron Zwarich843bc7d2011-05-24 03:10:43 +00001055 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
Devang Patela3cbf522011-07-06 21:09:55 +00001056 DIBuilder *DB)
Craig Topperf40110f2014-04-25 05:29:35 +00001057 : LoadAndStorePromoter(Insts, S), AI(nullptr), DIB(DB) {}
Nadav Rotem465834c2012-07-24 10:51:42 +00001058
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001059 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001060 // Remember which alloca we're promoting (for isInstInList).
1061 this->AI = AI;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001062 if (auto *L = LocalAsMetadata::getIfExists(AI)) {
1063 if (auto *DebugNode = MetadataAsValue::getIfExists(AI->getContext(), L)) {
1064 for (User *U : DebugNode->users())
1065 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
1066 DDIs.push_back(DDI);
1067 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
1068 DVIs.push_back(DVI);
1069 }
Rafael Espindola2b14b802011-12-26 23:12:42 +00001070 }
Devang Patelc6ee9182011-07-06 22:06:11 +00001071
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001072 LoadAndStorePromoter::run(Insts);
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001073 AI->eraseFromParent();
Craig Topper31ee5862013-07-03 15:07:05 +00001074 for (SmallVectorImpl<DbgDeclareInst *>::iterator I = DDIs.begin(),
Devang Patelc6ee9182011-07-06 22:06:11 +00001075 E = DDIs.end(); I != E; ++I) {
1076 DbgDeclareInst *DDI = *I;
Devang Patela3cbf522011-07-06 21:09:55 +00001077 DDI->eraseFromParent();
Devang Patelc6ee9182011-07-06 22:06:11 +00001078 }
Craig Topper31ee5862013-07-03 15:07:05 +00001079 for (SmallVectorImpl<DbgValueInst *>::iterator I = DVIs.begin(),
Devang Patelc6ee9182011-07-06 22:06:11 +00001080 E = DVIs.end(); I != E; ++I) {
1081 DbgValueInst *DVI = *I;
1082 DVI->eraseFromParent();
1083 }
Chris Lattner543384e2011-01-14 07:50:47 +00001084 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001085
Craig Topper3e4c6972014-03-05 09:10:37 +00001086 bool isInstInList(Instruction *I,
1087 const SmallVectorImpl<Instruction*> &Insts) const override {
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001088 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1089 return LI->getOperand(0) == AI;
1090 return cast<StoreInst>(I)->getPointerOperand() == AI;
Chris Lattner543384e2011-01-14 07:50:47 +00001091 }
Devang Patela3cbf522011-07-06 21:09:55 +00001092
Craig Topper3e4c6972014-03-05 09:10:37 +00001093 void updateDebugInfo(Instruction *Inst) const override {
Craig Topper31ee5862013-07-03 15:07:05 +00001094 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
Devang Patelc6ee9182011-07-06 22:06:11 +00001095 E = DDIs.end(); I != E; ++I) {
1096 DbgDeclareInst *DDI = *I;
1097 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1098 ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
1099 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1100 ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
1101 }
Craig Topper31ee5862013-07-03 15:07:05 +00001102 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
Devang Patelc6ee9182011-07-06 22:06:11 +00001103 E = DVIs.end(); I != E; ++I) {
1104 DbgValueInst *DVI = *I;
Craig Topperf40110f2014-04-25 05:29:35 +00001105 Value *Arg = nullptr;
Devang Patelc6ee9182011-07-06 22:06:11 +00001106 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Devang Patelc6ee9182011-07-06 22:06:11 +00001107 // If an argument is zero extended then use argument directly. The ZExt
1108 // may be zapped by an optimization pass in future.
Devang Patelc6ee9182011-07-06 22:06:11 +00001109 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
Benjamin Kramer077e5522012-02-23 17:42:19 +00001110 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Devang Patelc6ee9182011-07-06 22:06:11 +00001111 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Benjamin Kramer077e5522012-02-23 17:42:19 +00001112 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1113 if (!Arg)
1114 Arg = SI->getOperand(0);
Devang Patelc6ee9182011-07-06 22:06:11 +00001115 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Benjamin Kramer077e5522012-02-23 17:42:19 +00001116 Arg = LI->getOperand(0);
1117 } else {
1118 continue;
Devang Patelc6ee9182011-07-06 22:06:11 +00001119 }
Duncan P. N. Exon Smith60635e32015-04-21 18:44:06 +00001120 DIB->insertDbgValueIntrinsic(Arg, 0, DVI->getVariable(),
1121 DVI->getExpression(), DVI->getDebugLoc(),
1122 Inst);
Devang Patelc6ee9182011-07-06 22:06:11 +00001123 }
Devang Patela3cbf522011-07-06 21:09:55 +00001124 }
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001125};
1126} // end anon namespace
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001127
Chris Lattnera9607252011-01-23 22:04:55 +00001128/// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1129/// subsequently loaded can be rewritten to load both input pointers and then
1130/// select between the result, allowing the load of the alloca to be promoted.
1131/// From this:
1132/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1133/// %V = load i32* %P2
1134/// to:
1135/// %V1 = load i32* %Alloca -> will be mem2reg'd
1136/// %V2 = load i32* %Other
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001137/// %V = select i1 %cond, i32 %V1, i32 %V2
Chris Lattnera9607252011-01-23 22:04:55 +00001138///
1139/// We can do this to a select if its only uses are loads and if the operand to
1140/// the select can be loaded unconditionally.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001141static bool isSafeSelectToSpeculate(SelectInst *SI) {
1142 const DataLayout &DL = SI->getModule()->getDataLayout();
Philip Reames5461d452015-04-23 17:36:48 +00001143 bool TDerefable = isDereferenceablePointer(SI->getTrueValue(), DL);
1144 bool FDerefable = isDereferenceablePointer(SI->getFalseValue(), DL);
Nadav Rotem465834c2012-07-24 10:51:42 +00001145
Chandler Carruthcdf47882014-03-09 03:16:01 +00001146 for (User *U : SI->users()) {
1147 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001148 if (!LI || !LI->isSimple()) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001149
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001150 // Both operands to the select need to be dereferencable, either absolutely
Chris Lattnera9607252011-01-23 22:04:55 +00001151 // (e.g. allocas) or at this point because we can see other accesses to it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001152 if (!TDerefable &&
1153 !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1154 LI->getAlignment()))
Chris Lattnera9607252011-01-23 22:04:55 +00001155 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001156 if (!FDerefable &&
1157 !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1158 LI->getAlignment()))
Chris Lattnera9607252011-01-23 22:04:55 +00001159 return false;
1160 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001161
Chris Lattnera9607252011-01-23 22:04:55 +00001162 return true;
1163}
1164
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001165/// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1166/// subsequently loaded can be rewritten to load both input pointers in the pred
1167/// blocks and then PHI the results, allowing the load of the alloca to be
1168/// promoted.
1169/// From this:
1170/// %P2 = phi [i32* %Alloca, i32* %Other]
1171/// %V = load i32* %P2
1172/// to:
1173/// %V1 = load i32* %Alloca -> will be mem2reg'd
1174/// ...
1175/// %V2 = load i32* %Other
1176/// ...
1177/// %V = phi [i32 %V1, i32 %V2]
1178///
1179/// We can do this to a select if its only uses are loads and if the operand to
1180/// the select can be loaded unconditionally.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001181static bool isSafePHIToSpeculate(PHINode *PN) {
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001182 // For now, we can only do this promotion if the load is in the same block as
1183 // the PHI, and if there are no stores between the phi and load.
1184 // TODO: Allow recursive phi users.
1185 // TODO: Allow stores.
1186 BasicBlock *BB = PN->getParent();
1187 unsigned MaxAlign = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001188 for (User *U : PN->users()) {
1189 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001190 if (!LI || !LI->isSimple()) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001191
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001192 // For now we only allow loads in the same block as the PHI. This is a
1193 // common case that happens when instcombine merges two loads through a PHI.
1194 if (LI->getParent() != BB) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001195
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001196 // Ensure that there are no instructions between the PHI and the load that
1197 // could store.
1198 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1199 if (BBI->mayWriteToMemory())
1200 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001201
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001202 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1203 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001204
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001205 const DataLayout &DL = PN->getModule()->getDataLayout();
1206
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001207 // Okay, we know that we have one or more loads in the same block as the PHI.
1208 // We can transform this if it is safe to push the loads into the predecessor
1209 // blocks. The only thing to watch out for is that we can't put a possibly
1210 // trapping load in the predecessor if it is a critical edge.
1211 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1212 BasicBlock *Pred = PN->getIncomingBlock(i);
Eli Friedmanf9b785f2011-09-22 18:56:30 +00001213 Value *InVal = PN->getIncomingValue(i);
1214
1215 // If the terminator of the predecessor has side-effects (an invoke),
1216 // there is no safe place to put a load in the predecessor.
1217 if (Pred->getTerminator()->mayHaveSideEffects())
1218 return false;
1219
1220 // If the value is produced by the terminator of the predecessor
1221 // (an invoke), there is no valid place to put a load in the predecessor.
1222 if (Pred->getTerminator() == InVal)
1223 return false;
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001224
1225 // If the predecessor has a single successor, then the edge isn't critical.
1226 if (Pred->getTerminator()->getNumSuccessors() == 1)
1227 continue;
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001228
1229 // If this pointer is always safe to load, or if we can prove that there is
1230 // already a load in the block, then we can move the load to the pred block.
Philip Reames5461d452015-04-23 17:36:48 +00001231 if (isDereferenceablePointer(InVal, DL) ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001232 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign))
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001233 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00001234
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001235 return false;
1236 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001237
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001238 return true;
1239}
1240
Chris Lattnera9607252011-01-23 22:04:55 +00001241
1242/// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1243/// direct (non-volatile) loads and stores to it. If the alloca is close but
1244/// not quite there, this will transform the code to allow promotion. As such,
1245/// it is a non-pure predicate.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001246static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const DataLayout &DL) {
Chris Lattnera9607252011-01-23 22:04:55 +00001247 SetVector<Instruction*, SmallVector<Instruction*, 4>,
1248 SmallPtrSet<Instruction*, 4> > InstsToRewrite;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001249 for (User *U : AI->users()) {
Chris Lattnera9607252011-01-23 22:04:55 +00001250 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Eli Friedman7c5dc122011-09-12 20:23:13 +00001251 if (!LI->isSimple())
Chris Lattnera9607252011-01-23 22:04:55 +00001252 return false;
1253 continue;
1254 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001255
Chris Lattnera9607252011-01-23 22:04:55 +00001256 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Eli Friedman7c5dc122011-09-12 20:23:13 +00001257 if (SI->getOperand(0) == AI || !SI->isSimple())
Chris Lattnera9607252011-01-23 22:04:55 +00001258 return false; // Don't allow a store OF the AI, only INTO the AI.
1259 continue;
1260 }
1261
1262 if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1263 // If the condition being selected on is a constant, fold the select, yes
1264 // this does (rarely) happen early on.
1265 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1266 Value *Result = SI->getOperand(1+CI->isZero());
1267 SI->replaceAllUsesWith(Result);
1268 SI->eraseFromParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001269
Chris Lattnera9607252011-01-23 22:04:55 +00001270 // This is very rare and we just scrambled the use list of AI, start
1271 // over completely.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001272 return tryToMakeAllocaBePromotable(AI, DL);
Chris Lattnera9607252011-01-23 22:04:55 +00001273 }
1274
1275 // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1276 // loads, then we can transform this by rewriting the select.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001277 if (!isSafeSelectToSpeculate(SI))
Chris Lattnera9607252011-01-23 22:04:55 +00001278 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001279
Chris Lattnera9607252011-01-23 22:04:55 +00001280 InstsToRewrite.insert(SI);
1281 continue;
1282 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001283
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001284 if (PHINode *PN = dyn_cast<PHINode>(U)) {
1285 if (PN->use_empty()) { // Dead PHIs can be stripped.
1286 InstsToRewrite.insert(PN);
1287 continue;
1288 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001289
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001290 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1291 // in the pred blocks, then we can transform this by rewriting the PHI.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001292 if (!isSafePHIToSpeculate(PN))
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001293 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001294
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001295 InstsToRewrite.insert(PN);
1296 continue;
1297 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001298
Nick Lewycky15e2d902011-07-25 23:14:22 +00001299 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1300 if (onlyUsedByLifetimeMarkers(BCI)) {
1301 InstsToRewrite.insert(BCI);
1302 continue;
1303 }
1304 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001305
Chris Lattnera9607252011-01-23 22:04:55 +00001306 return false;
1307 }
1308
1309 // If there are no instructions to rewrite, then all uses are load/stores and
1310 // we're done!
1311 if (InstsToRewrite.empty())
1312 return true;
Nadav Rotem465834c2012-07-24 10:51:42 +00001313
Chris Lattnera9607252011-01-23 22:04:55 +00001314 // If we have instructions that need to be rewritten for this to be promotable
1315 // take care of it now.
1316 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
Nick Lewycky15e2d902011-07-25 23:14:22 +00001317 if (BitCastInst *BCI = dyn_cast<BitCastInst>(InstsToRewrite[i])) {
1318 // This could only be a bitcast used by nothing but lifetime intrinsics.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001319 for (BitCastInst::user_iterator I = BCI->user_begin(), E = BCI->user_end();
1320 I != E;)
1321 cast<Instruction>(*I++)->eraseFromParent();
Nick Lewycky15e2d902011-07-25 23:14:22 +00001322 BCI->eraseFromParent();
1323 continue;
1324 }
1325
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001326 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1327 // Selects in InstsToRewrite only have load uses. Rewrite each as two
1328 // loads with a new select.
1329 while (!SI->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001330 LoadInst *LI = cast<LoadInst>(SI->user_back());
Nadav Rotem465834c2012-07-24 10:51:42 +00001331
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001332 IRBuilder<> Builder(LI);
Nadav Rotem465834c2012-07-24 10:51:42 +00001333 LoadInst *TrueLoad =
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001334 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
Nadav Rotem465834c2012-07-24 10:51:42 +00001335 LoadInst *FalseLoad =
Nick Lewyckyf64a3972011-07-01 06:27:03 +00001336 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".f");
Nadav Rotem465834c2012-07-24 10:51:42 +00001337
Hal Finkelcc39b672014-07-24 12:16:19 +00001338 // Transfer alignment and AA info if present.
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001339 TrueLoad->setAlignment(LI->getAlignment());
1340 FalseLoad->setAlignment(LI->getAlignment());
Hal Finkelcc39b672014-07-24 12:16:19 +00001341
1342 AAMDNodes Tags;
1343 LI->getAAMetadata(Tags);
1344 if (Tags) {
1345 TrueLoad->setAAMetadata(Tags);
1346 FalseLoad->setAAMetadata(Tags);
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001347 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001348
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001349 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1350 V->takeName(LI);
1351 LI->replaceAllUsesWith(V);
1352 LI->eraseFromParent();
Chris Lattnera9607252011-01-23 22:04:55 +00001353 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001354
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001355 // Now that all the loads are gone, the select is gone too.
1356 SI->eraseFromParent();
1357 continue;
1358 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001359
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001360 // Otherwise, we have a PHI node which allows us to push the loads into the
1361 // predecessors.
1362 PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1363 if (PN->use_empty()) {
1364 PN->eraseFromParent();
1365 continue;
1366 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001367
Chris Lattner229907c2011-07-18 04:54:35 +00001368 Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
Jay Foad52131342011-03-30 11:28:46 +00001369 PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1370 PN->getName()+".ld", PN);
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001371
Hal Finkelcc39b672014-07-24 12:16:19 +00001372 // Get the AA tags and alignment to use from one of the loads. It doesn't
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001373 // matter which one we get and if any differ, it doesn't matter.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001374 LoadInst *SomeLoad = cast<LoadInst>(PN->user_back());
Hal Finkelcc39b672014-07-24 12:16:19 +00001375
1376 AAMDNodes AATags;
1377 SomeLoad->getAAMetadata(AATags);
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001378 unsigned Align = SomeLoad->getAlignment();
Nadav Rotem465834c2012-07-24 10:51:42 +00001379
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001380 // Rewrite all loads of the PN to use the new PHI.
1381 while (!PN->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001382 LoadInst *LI = cast<LoadInst>(PN->user_back());
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001383 LI->replaceAllUsesWith(NewPN);
Chris Lattnera9607252011-01-23 22:04:55 +00001384 LI->eraseFromParent();
1385 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001386
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001387 // Inject loads into all of the pred blocks. Keep track of which blocks we
1388 // insert them into in case we have multiple edges from the same block.
1389 DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
Nadav Rotem465834c2012-07-24 10:51:42 +00001390
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001391 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1392 BasicBlock *Pred = PN->getIncomingBlock(i);
1393 LoadInst *&Load = InsertedLoads[Pred];
Craig Topperf40110f2014-04-25 05:29:35 +00001394 if (!Load) {
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001395 Load = new LoadInst(PN->getIncomingValue(i),
1396 PN->getName() + "." + Pred->getName(),
1397 Pred->getTerminator());
1398 Load->setAlignment(Align);
Hal Finkelcc39b672014-07-24 12:16:19 +00001399 if (AATags) Load->setAAMetadata(AATags);
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001400 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001401
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001402 NewPN->addIncoming(Load, Pred);
1403 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001404
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001405 PN->eraseFromParent();
Chris Lattnera9607252011-01-23 22:04:55 +00001406 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001407
Chris Lattnera9607252011-01-23 22:04:55 +00001408 ++NumAdjusted;
1409 return true;
1410}
1411
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001412bool SROA::performPromotion(Function &F) {
1413 std::vector<AllocaInst*> Allocas;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001414 const DataLayout &DL = F.getParent()->getDataLayout();
Craig Topperf40110f2014-04-25 05:29:35 +00001415 DominatorTree *DT = nullptr;
Cameron Zwarich4694e692011-01-18 03:53:26 +00001416 if (HasDomTree)
Chandler Carruth73523022014-01-13 13:07:17 +00001417 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth66b31302015-01-04 12:03:27 +00001418 AssumptionCache &AC =
1419 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001420
Chris Lattner5dac64f2003-09-20 14:39:18 +00001421 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001422 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
Chris Lattner9a95f2a2003-09-12 15:36:03 +00001423 bool Changed = false;
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001424 SmallVector<Instruction*, 64> Insts;
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001425 while (1) {
1426 Allocas.clear();
1427
1428 // Find allocas that are safe to promote, by looking at all instructions in
1429 // the entry node
1430 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1431 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001432 if (tryToMakeAllocaBePromotable(AI, DL))
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001433 Allocas.push_back(AI);
1434
1435 if (Allocas.empty()) break;
1436
Cameron Zwarich4694e692011-01-18 03:53:26 +00001437 if (HasDomTree)
Chandler Carruth66b31302015-01-04 12:03:27 +00001438 PromoteMemToReg(Allocas, *DT, nullptr, &AC);
Chris Lattner543384e2011-01-14 07:50:47 +00001439 else {
1440 SSAUpdater SSA;
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001441 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1442 AllocaInst *AI = Allocas[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00001443
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001444 // Build list of instructions to promote.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001445 for (User *U : AI->users())
1446 Insts.push_back(cast<Instruction>(U));
Devang Patela3cbf522011-07-06 21:09:55 +00001447 AllocaPromoter(Insts, SSA, &DIB).run(AI, Insts);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001448 Insts.clear();
1449 }
Chris Lattner543384e2011-01-14 07:50:47 +00001450 }
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001451 NumPromoted += Allocas.size();
1452 Changed = true;
1453 }
1454
1455 return Changed;
1456}
1457
Chris Lattner78d7dbb2010-04-16 00:24:57 +00001458
Bob Wilson04365c52010-02-03 17:23:56 +00001459/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1460/// SROA. It must be a struct or array type with a small number of elements.
Nadav Rotem4e9012c2012-06-21 13:44:31 +00001461bool SROA::ShouldAttemptScalarRepl(AllocaInst *AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00001462 Type *T = AI->getAllocatedType();
Nadav Rotem4e9012c2012-06-21 13:44:31 +00001463 // Do not promote any struct that has too many members.
Chris Lattner229907c2011-07-18 04:54:35 +00001464 if (StructType *ST = dyn_cast<StructType>(T))
Nadav Rotem4e9012c2012-06-21 13:44:31 +00001465 return ST->getNumElements() <= StructMemberThreshold;
1466 // Do not promote any array that has too many elements.
Chris Lattner229907c2011-07-18 04:54:35 +00001467 if (ArrayType *AT = dyn_cast<ArrayType>(T))
Nadav Rotem4e9012c2012-06-21 13:44:31 +00001468 return AT->getNumElements() <= ArrayElementThreshold;
Bob Wilson04365c52010-02-03 17:23:56 +00001469 return false;
Chris Lattner6ff85682008-06-22 17:46:21 +00001470}
1471
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001472// performScalarRepl - This algorithm is a simple worklist driven algorithm,
Chris Lattner8cf09412013-04-18 17:42:14 +00001473// which runs on all of the alloca instructions in the entry block, removing
1474// them if they are only used by getelementptr instructions.
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001475//
1476bool SROA::performScalarRepl(Function &F) {
Victor Hernandez8acf2952009-10-23 21:09:37 +00001477 std::vector<AllocaInst*> WorkList;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001478 const DataLayout &DL = F.getParent()->getDataLayout();
Chris Lattnerfb41a502003-05-27 15:45:27 +00001479
Chris Lattner9c1172d2010-04-15 21:59:20 +00001480 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner5dac64f2003-09-20 14:39:18 +00001481 BasicBlock &BB = F.getEntryBlock();
Chris Lattnerfb41a502003-05-27 15:45:27 +00001482 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez8acf2952009-10-23 21:09:37 +00001483 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnerfb41a502003-05-27 15:45:27 +00001484 WorkList.push_back(A);
1485
1486 // Process the worklist
1487 bool Changed = false;
1488 while (!WorkList.empty()) {
Victor Hernandez8acf2952009-10-23 21:09:37 +00001489 AllocaInst *AI = WorkList.back();
Chris Lattnerfb41a502003-05-27 15:45:27 +00001490 WorkList.pop_back();
Bob Wilson328e91b2011-01-13 20:59:44 +00001491
Chris Lattnerf171af92006-12-22 23:14:42 +00001492 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1493 // with unused elements.
1494 if (AI->use_empty()) {
1495 AI->eraseFromParent();
Chris Lattner9ef4eae2010-04-15 23:50:26 +00001496 Changed = true;
Chris Lattnerf171af92006-12-22 23:14:42 +00001497 continue;
1498 }
Chris Lattner09b65ab2009-02-03 01:30:09 +00001499
1500 // If this alloca is impossible for us to promote, reject it early.
1501 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1502 continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00001503
Chris Lattner09b65ab2009-02-03 01:30:09 +00001504 // Check to see if we can perform the core SROA transformation. We cannot
1505 // transform the allocation instruction if it is an array allocation
1506 // (allocations OF arrays are ok though), and an allocation of a scalar
1507 // value cannot be decomposed at all.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001508 uint64_t AllocaSize = DL.getTypeAllocSize(AI->getAllocatedType());
Bill Wendling3e44bf32009-03-03 12:12:58 +00001509
Nick Lewyckyaa464002009-08-17 05:37:31 +00001510 // Do not promote [0 x %struct].
1511 if (AllocaSize == 0) continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00001512
Chris Lattner9c1172d2010-04-15 21:59:20 +00001513 // Do not promote any struct whose size is too big.
1514 if (AllocaSize > SRThreshold) continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00001515
Bob Wilson04365c52010-02-03 17:23:56 +00001516 // If the alloca looks like a good candidate for scalar replacement, and if
1517 // all its users can be transformed, then split up the aggregate into its
1518 // separate elements.
1519 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1520 DoScalarReplacement(AI, WorkList);
1521 Changed = true;
1522 continue;
1523 }
1524
Chris Lattnerdf179872009-01-28 20:16:43 +00001525 // If we can turn this aggregate value (potentially with casts) into a
1526 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattnerec99c462009-01-31 02:28:54 +00001527 // IsNotTrivial tracks whether this is something that mem2reg could have
1528 // promoted itself. If so, we don't want to transform it needlessly. Note
1529 // that we can't just check based on the type: the alloca may be of an i32
1530 // but that has pointer arithmetic to set byte 3 of it or something.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001531 if (AllocaInst *NewAI =
1532 ConvertToScalarInfo((unsigned)AllocaSize, DL, ScalarLoadThreshold)
1533 .TryConvert(AI)) {
Chris Lattner09b65ab2009-02-03 01:30:09 +00001534 NewAI->takeName(AI);
1535 AI->eraseFromParent();
1536 ++NumConverted;
1537 Changed = true;
1538 continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00001539 }
1540
Chris Lattner09b65ab2009-02-03 01:30:09 +00001541 // Otherwise, couldn't process this alloca.
Chris Lattnerfb41a502003-05-27 15:45:27 +00001542 }
1543
1544 return Changed;
1545}
Chris Lattner6e5398d2003-05-30 04:15:41 +00001546
Chris Lattner31e5add2007-04-25 05:02:56 +00001547/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1548/// predicate, do SROA now.
Bob Wilson328e91b2011-01-13 20:59:44 +00001549void SROA::DoScalarReplacement(AllocaInst *AI,
Victor Hernandez8acf2952009-10-23 21:09:37 +00001550 std::vector<AllocaInst*> &WorkList) {
David Greene48c86be2010-01-05 01:27:09 +00001551 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattner31e5add2007-04-25 05:02:56 +00001552 SmallVector<AllocaInst*, 32> ElementAllocas;
Chris Lattner229907c2011-07-18 04:54:35 +00001553 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
Chris Lattner31e5add2007-04-25 05:02:56 +00001554 ElementAllocas.reserve(ST->getNumContainedTypes());
1555 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +00001556 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), nullptr,
Chris Lattner31e5add2007-04-25 05:02:56 +00001557 AI->getAlignment(),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001558 AI->getName() + "." + Twine(i), AI);
Chris Lattner31e5add2007-04-25 05:02:56 +00001559 ElementAllocas.push_back(NA);
1560 WorkList.push_back(NA); // Add to worklist for recursive processing
1561 }
1562 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00001563 ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
Chris Lattner31e5add2007-04-25 05:02:56 +00001564 ElementAllocas.reserve(AT->getNumElements());
Chris Lattner229907c2011-07-18 04:54:35 +00001565 Type *ElTy = AT->getElementType();
Chris Lattner31e5add2007-04-25 05:02:56 +00001566 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +00001567 AllocaInst *NA = new AllocaInst(ElTy, nullptr, AI->getAlignment(),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001568 AI->getName() + "." + Twine(i), AI);
Chris Lattner31e5add2007-04-25 05:02:56 +00001569 ElementAllocas.push_back(NA);
1570 WorkList.push_back(NA); // Add to worklist for recursive processing
1571 }
1572 }
1573
Bob Wilson532cd232009-12-18 20:14:40 +00001574 // Now that we have created the new alloca instructions, rewrite all the
1575 // uses of the old alloca.
1576 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattneraaa6ac12009-12-14 05:11:02 +00001577
Bob Wilson532cd232009-12-18 20:14:40 +00001578 // Now erase any instructions that were made dead while rewriting the alloca.
1579 DeleteDeadInstructions();
Bob Wilsonf3927b72009-12-17 18:34:24 +00001580 AI->eraseFromParent();
Bob Wilson532cd232009-12-18 20:14:40 +00001581
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001582 ++NumReplaced;
Chris Lattner31e5add2007-04-25 05:02:56 +00001583}
Chris Lattneraaa6ac12009-12-14 05:11:02 +00001584
Bob Wilson532cd232009-12-18 20:14:40 +00001585/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1586/// recursively including all their operands that become trivially dead.
1587void SROA::DeleteDeadInstructions() {
1588 while (!DeadInsts.empty()) {
1589 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattneraaa6ac12009-12-14 05:11:02 +00001590
Bob Wilson532cd232009-12-18 20:14:40 +00001591 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1592 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1593 // Zero out the operand and see if it becomes trivially dead.
1594 // (But, don't add allocas to the dead instruction list -- they are
1595 // already on the worklist and will be deleted separately.)
Craig Topperf40110f2014-04-25 05:29:35 +00001596 *OI = nullptr;
Bob Wilson532cd232009-12-18 20:14:40 +00001597 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1598 DeadInsts.push_back(U);
Chris Lattneraaa6ac12009-12-14 05:11:02 +00001599 }
Bob Wilson532cd232009-12-18 20:14:40 +00001600
1601 I->eraseFromParent();
Chris Lattneraaa6ac12009-12-14 05:11:02 +00001602 }
Chris Lattneraaa6ac12009-12-14 05:11:02 +00001603}
Bob Wilson328e91b2011-01-13 20:59:44 +00001604
Bob Wilson532cd232009-12-18 20:14:40 +00001605/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1606/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson88a05982009-12-21 18:39:47 +00001607/// the Info parameter. Offset indicates the position within AI that is
1608/// referenced by this instruction.
Chris Lattner8acbb792011-01-23 07:29:29 +00001609void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
Bob Wilson88a05982009-12-21 18:39:47 +00001610 AllocaInfo &Info) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001611 const DataLayout &DL = I->getModule()->getDataLayout();
Chandler Carruthcdf47882014-03-09 03:16:01 +00001612 for (Use &U : I->uses()) {
1613 Instruction *User = cast<Instruction>(U.getUser());
Chris Lattner52310702003-11-25 21:09:18 +00001614
Bob Wilson532cd232009-12-18 20:14:40 +00001615 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Chris Lattner8acbb792011-01-23 07:29:29 +00001616 isSafeForScalarRepl(BC, Offset, Info);
Bob Wilson532cd232009-12-18 20:14:40 +00001617 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001618 uint64_t GEPOffset = Offset;
Chris Lattner8acbb792011-01-23 07:29:29 +00001619 isSafeGEP(GEPI, GEPOffset, Info);
Bob Wilson532cd232009-12-18 20:14:40 +00001620 if (!Info.isUnsafe)
Chris Lattner8acbb792011-01-23 07:29:29 +00001621 isSafeForScalarRepl(GEPI, GEPOffset, Info);
Gabor Greif4300fc72010-06-28 11:20:42 +00001622 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001623 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +00001624 if (!Length || Length->isNegative())
Aaron Ballmana7332972012-03-15 00:05:31 +00001625 return MarkUnsafe(Info, User);
1626
Craig Topperf40110f2014-04-25 05:29:35 +00001627 isSafeMemAccess(Offset, Length->getZExtValue(), nullptr,
Chandler Carruthcdf47882014-03-09 03:16:01 +00001628 U.getOperandNo() == 0, Info, MI,
Chris Lattner9491dee2011-01-23 08:27:54 +00001629 true /*AllowWholeAccess*/);
Bob Wilson532cd232009-12-18 20:14:40 +00001630 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Eli Friedman7c5dc122011-09-12 20:23:13 +00001631 if (!LI->isSimple())
Chris Lattner3e56c292011-01-23 07:05:44 +00001632 return MarkUnsafe(Info, User);
Chris Lattner229907c2011-07-18 04:54:35 +00001633 Type *LIType = LI->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001634 isSafeMemAccess(Offset, DL.getTypeAllocSize(LIType), LIType, false, Info,
1635 LI, true /*AllowWholeAccess*/);
Chris Lattner3e56c292011-01-23 07:05:44 +00001636 Info.hasALoadOrStore = true;
Nadav Rotem465834c2012-07-24 10:51:42 +00001637
Bob Wilson532cd232009-12-18 20:14:40 +00001638 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1639 // Store is ok if storing INTO the pointer, not storing the pointer
Eli Friedman7c5dc122011-09-12 20:23:13 +00001640 if (!SI->isSimple() || SI->getOperand(0) == I)
Chris Lattner3e56c292011-01-23 07:05:44 +00001641 return MarkUnsafe(Info, User);
Nadav Rotem465834c2012-07-24 10:51:42 +00001642
Chris Lattner229907c2011-07-18 04:54:35 +00001643 Type *SIType = SI->getOperand(0)->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001644 isSafeMemAccess(Offset, DL.getTypeAllocSize(SIType), SIType, true, Info,
1645 SI, true /*AllowWholeAccess*/);
Chris Lattner3e56c292011-01-23 07:05:44 +00001646 Info.hasALoadOrStore = true;
Nick Lewycky15e2d902011-07-25 23:14:22 +00001647 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1648 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1649 II->getIntrinsicID() != Intrinsic::lifetime_end)
1650 return MarkUnsafe(Info, User);
Chris Lattner9491dee2011-01-23 08:27:54 +00001651 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1652 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1653 } else {
1654 return MarkUnsafe(Info, User);
1655 }
1656 if (Info.isUnsafe) return;
1657 }
1658}
Nadav Rotem465834c2012-07-24 10:51:42 +00001659
Chris Lattner9491dee2011-01-23 08:27:54 +00001660
1661/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1662/// derived from the alloca, we can often still split the alloca into elements.
1663/// This is useful if we have a large alloca where one element is phi'd
1664/// together somewhere: we can SRoA and promote all the other elements even if
1665/// we end up not being able to promote this one.
1666///
1667/// All we require is that the uses of the PHI do not index into other parts of
1668/// the alloca. The most important use case for this is single load and stores
1669/// that are PHI'd together, which can happen due to code sinking.
1670void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1671 AllocaInfo &Info) {
1672 // If we've already checked this PHI, don't do it again.
1673 if (PHINode *PN = dyn_cast<PHINode>(I))
David Blaikie70573dc2014-11-19 07:49:26 +00001674 if (!Info.CheckedPHIs.insert(PN).second)
Chris Lattner9491dee2011-01-23 08:27:54 +00001675 return;
Nadav Rotem465834c2012-07-24 10:51:42 +00001676
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001677 const DataLayout &DL = I->getModule()->getDataLayout();
Chandler Carruthcdf47882014-03-09 03:16:01 +00001678 for (User *U : I->users()) {
1679 Instruction *UI = cast<Instruction>(U);
Nadav Rotem465834c2012-07-24 10:51:42 +00001680
Chandler Carruthcdf47882014-03-09 03:16:01 +00001681 if (BitCastInst *BC = dyn_cast<BitCastInst>(UI)) {
Chris Lattner9491dee2011-01-23 08:27:54 +00001682 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
Chandler Carruthcdf47882014-03-09 03:16:01 +00001683 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(UI)) {
Chris Lattner9491dee2011-01-23 08:27:54 +00001684 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1685 // but would have to prove that we're staying inside of an element being
1686 // promoted.
1687 if (!GEPI->hasAllZeroIndices())
Chandler Carruthcdf47882014-03-09 03:16:01 +00001688 return MarkUnsafe(Info, UI);
Chris Lattner9491dee2011-01-23 08:27:54 +00001689 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
Chandler Carruthcdf47882014-03-09 03:16:01 +00001690 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
Eli Friedman7c5dc122011-09-12 20:23:13 +00001691 if (!LI->isSimple())
Chandler Carruthcdf47882014-03-09 03:16:01 +00001692 return MarkUnsafe(Info, UI);
Chris Lattner229907c2011-07-18 04:54:35 +00001693 Type *LIType = LI->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001694 isSafeMemAccess(Offset, DL.getTypeAllocSize(LIType), LIType, false, Info,
1695 LI, false /*AllowWholeAccess*/);
Chris Lattner9491dee2011-01-23 08:27:54 +00001696 Info.hasALoadOrStore = true;
Nadav Rotem465834c2012-07-24 10:51:42 +00001697
Chandler Carruthcdf47882014-03-09 03:16:01 +00001698 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner9491dee2011-01-23 08:27:54 +00001699 // Store is ok if storing INTO the pointer, not storing the pointer
Eli Friedman7c5dc122011-09-12 20:23:13 +00001700 if (!SI->isSimple() || SI->getOperand(0) == I)
Chandler Carruthcdf47882014-03-09 03:16:01 +00001701 return MarkUnsafe(Info, UI);
Nadav Rotem465834c2012-07-24 10:51:42 +00001702
Chris Lattner229907c2011-07-18 04:54:35 +00001703 Type *SIType = SI->getOperand(0)->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001704 isSafeMemAccess(Offset, DL.getTypeAllocSize(SIType), SIType, true, Info,
1705 SI, false /*AllowWholeAccess*/);
Chris Lattner9491dee2011-01-23 08:27:54 +00001706 Info.hasALoadOrStore = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001707 } else if (isa<PHINode>(UI) || isa<SelectInst>(UI)) {
1708 isSafePHISelectUseForScalarRepl(UI, Offset, Info);
Bob Wilson532cd232009-12-18 20:14:40 +00001709 } else {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001710 return MarkUnsafe(Info, UI);
Bob Wilson532cd232009-12-18 20:14:40 +00001711 }
1712 if (Info.isUnsafe) return;
Bob Wilsonf3927b72009-12-17 18:34:24 +00001713 }
Bob Wilson532cd232009-12-18 20:14:40 +00001714}
Bob Wilsonf3927b72009-12-17 18:34:24 +00001715
Bob Wilson532cd232009-12-18 20:14:40 +00001716/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1717/// replacement. It is safe when all the indices are constant, in-bounds
1718/// references, and when the resulting offset corresponds to an element within
1719/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson88a05982009-12-21 18:39:47 +00001720/// return, Offset is adjusted as specified by the GEP indices.
Chris Lattner8acbb792011-01-23 07:29:29 +00001721void SROA::isSafeGEP(GetElementPtrInst *GEPI,
Bob Wilson88a05982009-12-21 18:39:47 +00001722 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilson532cd232009-12-18 20:14:40 +00001723 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1724 if (GEPIt == E)
1725 return;
Pete Coopere24d6a12012-06-15 18:07:29 +00001726 bool NonConstant = false;
1727 unsigned NonConstantIdxSize = 0;
Bob Wilsonf3927b72009-12-17 18:34:24 +00001728
Chris Lattner3f972c92008-08-23 05:21:06 +00001729 // Walk through the GEP type indices, checking the types that this indexes
1730 // into.
Bob Wilson532cd232009-12-18 20:14:40 +00001731 for (; GEPIt != E; ++GEPIt) {
Chris Lattner3f972c92008-08-23 05:21:06 +00001732 // Ignore struct elements, no extra checking needed for these.
Duncan Sands19d0b472010-02-16 11:11:14 +00001733 if ((*GEPIt)->isStructTy())
Chris Lattner3f972c92008-08-23 05:21:06 +00001734 continue;
Matthijs Kooijmancbe5e162008-10-06 16:23:31 +00001735
Bob Wilson532cd232009-12-18 20:14:40 +00001736 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
Shuxin Yang95adf522013-04-05 21:07:08 +00001737 if (!IdxVal)
1738 return MarkUnsafe(Info, GEPI);
Chris Lattner3f972c92008-08-23 05:21:06 +00001739 }
Bob Wilson532cd232009-12-18 20:14:40 +00001740
Bob Wilson62a84ea2009-12-22 06:57:14 +00001741 // Compute the offset due to this GEP and check if the alloca has a
1742 // component element at that offset.
Bob Wilson88a05982009-12-21 18:39:47 +00001743 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
Alp Tokerf907b892013-12-05 05:44:44 +00001744 // If this GEP is non-constant then the last operand must have been a
Pete Coopere24d6a12012-06-15 18:07:29 +00001745 // dynamic index into a vector. Pop this now as it has no impact on the
1746 // constant part of the offset.
1747 if (NonConstant)
1748 Indices.pop_back();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001749
1750 const DataLayout &DL = GEPI->getModule()->getDataLayout();
1751 Offset += DL.getIndexedOffset(GEPI->getPointerOperandType(), Indices);
1752 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, NonConstantIdxSize,
1753 DL))
Chris Lattner3e56c292011-01-23 07:05:44 +00001754 MarkUnsafe(Info, GEPI);
Chris Lattner6e5398d2003-05-30 04:15:41 +00001755}
1756
Bob Wilson08713d32011-01-13 17:45:11 +00001757/// isHomogeneousAggregate - Check if type T is a struct or array containing
1758/// elements of the same type (which is always true for arrays). If so,
1759/// return true with NumElts and EltTy set to the number of elements and the
1760/// element type, respectively.
Chris Lattner229907c2011-07-18 04:54:35 +00001761static bool isHomogeneousAggregate(Type *T, unsigned &NumElts,
1762 Type *&EltTy) {
1763 if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
Bob Wilson08713d32011-01-13 17:45:11 +00001764 NumElts = AT->getNumElements();
Craig Topperf40110f2014-04-25 05:29:35 +00001765 EltTy = (NumElts == 0 ? nullptr : AT->getElementType());
Bob Wilson08713d32011-01-13 17:45:11 +00001766 return true;
1767 }
Chris Lattner229907c2011-07-18 04:54:35 +00001768 if (StructType *ST = dyn_cast<StructType>(T)) {
Bob Wilson08713d32011-01-13 17:45:11 +00001769 NumElts = ST->getNumContainedTypes();
Craig Topperf40110f2014-04-25 05:29:35 +00001770 EltTy = (NumElts == 0 ? nullptr : ST->getContainedType(0));
Bob Wilson08713d32011-01-13 17:45:11 +00001771 for (unsigned n = 1; n < NumElts; ++n) {
1772 if (ST->getContainedType(n) != EltTy)
1773 return false;
1774 }
1775 return true;
1776 }
1777 return false;
1778}
1779
1780/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1781/// "homogeneous" aggregates with the same element type and number of elements.
Chris Lattner229907c2011-07-18 04:54:35 +00001782static bool isCompatibleAggregate(Type *T1, Type *T2) {
Bob Wilson08713d32011-01-13 17:45:11 +00001783 if (T1 == T2)
1784 return true;
1785
1786 unsigned NumElts1, NumElts2;
Chris Lattner229907c2011-07-18 04:54:35 +00001787 Type *EltTy1, *EltTy2;
Bob Wilson08713d32011-01-13 17:45:11 +00001788 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1789 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1790 NumElts1 == NumElts2 &&
1791 EltTy1 == EltTy2)
1792 return true;
1793
1794 return false;
1795}
1796
Bob Wilson532cd232009-12-18 20:14:40 +00001797/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1798/// alloca or has an offset and size that corresponds to a component element
1799/// within it. The offset checked here may have been formed from a GEP with a
1800/// pointer bitcasted to a different type.
Chris Lattner9491dee2011-01-23 08:27:54 +00001801///
1802/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1803/// unit. If false, it only allows accesses known to be in a single element.
Chris Lattner8acbb792011-01-23 07:29:29 +00001804void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattner229907c2011-07-18 04:54:35 +00001805 Type *MemOpType, bool isStore,
Chris Lattner9491dee2011-01-23 08:27:54 +00001806 AllocaInfo &Info, Instruction *TheAccess,
1807 bool AllowWholeAccess) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001808 const DataLayout &DL = TheAccess->getModule()->getDataLayout();
Bob Wilson532cd232009-12-18 20:14:40 +00001809 // Check if this is a load/store of the entire alloca.
Chris Lattner9491dee2011-01-23 08:27:54 +00001810 if (Offset == 0 && AllowWholeAccess &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001811 MemSize == DL.getTypeAllocSize(Info.AI->getAllocatedType())) {
Bob Wilson08713d32011-01-13 17:45:11 +00001812 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1813 // loads/stores (which are essentially the same as the MemIntrinsics with
1814 // regard to copying padding between elements). But, if an alloca is
1815 // flagged as both a source and destination of such operations, we'll need
1816 // to check later for padding between elements.
1817 if (!MemOpType || MemOpType->isIntegerTy()) {
1818 if (isStore)
1819 Info.isMemCpyDst = true;
1820 else
1821 Info.isMemCpySrc = true;
Bob Wilson532cd232009-12-18 20:14:40 +00001822 return;
1823 }
Bob Wilson08713d32011-01-13 17:45:11 +00001824 // This is also safe for references using a type that is compatible with
1825 // the type of the alloca, so that loads/stores can be rewritten using
1826 // insertvalue/extractvalue.
Chris Lattner8acbb792011-01-23 07:29:29 +00001827 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
Chris Lattner6fab2e92011-01-16 06:18:28 +00001828 Info.hasSubelementAccess = true;
Bob Wilson08713d32011-01-13 17:45:11 +00001829 return;
Chris Lattner6fab2e92011-01-16 06:18:28 +00001830 }
Bob Wilson532cd232009-12-18 20:14:40 +00001831 }
1832 // Check if the offset/size correspond to a component within the alloca type.
Chris Lattner229907c2011-07-18 04:54:35 +00001833 Type *T = Info.AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001834 if (TypeHasComponent(T, Offset, MemSize, DL)) {
Chris Lattner6fab2e92011-01-16 06:18:28 +00001835 Info.hasSubelementAccess = true;
Bob Wilson532cd232009-12-18 20:14:40 +00001836 return;
Chris Lattner6fab2e92011-01-16 06:18:28 +00001837 }
Bob Wilson532cd232009-12-18 20:14:40 +00001838
Chris Lattner3e56c292011-01-23 07:05:44 +00001839 return MarkUnsafe(Info, TheAccess);
Bob Wilson532cd232009-12-18 20:14:40 +00001840}
1841
1842/// TypeHasComponent - Return true if T has a component type with the
1843/// specified offset and size. If Size is zero, do not check the size.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001844bool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size,
1845 const DataLayout &DL) {
Chris Lattner229907c2011-07-18 04:54:35 +00001846 Type *EltTy;
Bob Wilson532cd232009-12-18 20:14:40 +00001847 uint64_t EltSize;
Chris Lattner229907c2011-07-18 04:54:35 +00001848 if (StructType *ST = dyn_cast<StructType>(T)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001849 const StructLayout *Layout = DL.getStructLayout(ST);
Bob Wilson532cd232009-12-18 20:14:40 +00001850 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1851 EltTy = ST->getContainedType(EltIdx);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001852 EltSize = DL.getTypeAllocSize(EltTy);
Bob Wilson532cd232009-12-18 20:14:40 +00001853 Offset -= Layout->getElementOffset(EltIdx);
Chris Lattner229907c2011-07-18 04:54:35 +00001854 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001855 EltTy = AT->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001856 EltSize = DL.getTypeAllocSize(EltTy);
Bob Wilson62a84ea2009-12-22 06:57:14 +00001857 if (Offset >= AT->getNumElements() * EltSize)
1858 return false;
Bob Wilson532cd232009-12-18 20:14:40 +00001859 Offset %= EltSize;
Pete Cooper1d1fa722012-06-14 23:53:53 +00001860 } else if (VectorType *VT = dyn_cast<VectorType>(T)) {
1861 EltTy = VT->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001862 EltSize = DL.getTypeAllocSize(EltTy);
Pete Cooper1d1fa722012-06-14 23:53:53 +00001863 if (Offset >= VT->getNumElements() * EltSize)
1864 return false;
1865 Offset %= EltSize;
Bob Wilson532cd232009-12-18 20:14:40 +00001866 } else {
1867 return false;
1868 }
1869 if (Offset == 0 && (Size == 0 || EltSize == Size))
1870 return true;
1871 // Check if the component spans multiple elements.
1872 if (Offset + Size > EltSize)
1873 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001874 return TypeHasComponent(EltTy, Offset, Size, DL);
Bob Wilson532cd232009-12-18 20:14:40 +00001875}
1876
1877/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1878/// the instruction I, which references it, to use the separate elements.
1879/// Offset indicates the position within AI that is referenced by this
1880/// instruction.
1881void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00001882 SmallVectorImpl<AllocaInst *> &NewElts) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001883 const DataLayout &DL = I->getModule()->getDataLayout();
Chris Lattner9491dee2011-01-23 08:27:54 +00001884 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001885 Use &TheUse = *UI++;
1886 Instruction *User = cast<Instruction>(TheUse.getUser());
Bob Wilson532cd232009-12-18 20:14:40 +00001887
1888 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1889 RewriteBitCast(BC, AI, Offset, NewElts);
Chris Lattner9491dee2011-01-23 08:27:54 +00001890 continue;
1891 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001892
Chris Lattner9491dee2011-01-23 08:27:54 +00001893 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001894 RewriteGEP(GEPI, AI, Offset, NewElts);
Chris Lattner9491dee2011-01-23 08:27:54 +00001895 continue;
1896 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001897
Chris Lattner9491dee2011-01-23 08:27:54 +00001898 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001899 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1900 uint64_t MemSize = Length->getZExtValue();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001901 if (Offset == 0 && MemSize == DL.getTypeAllocSize(AI->getAllocatedType()))
Bob Wilson532cd232009-12-18 20:14:40 +00001902 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsonc16811b2009-12-19 06:53:17 +00001903 // Otherwise the intrinsic can only touch a single element and the
1904 // address operand will be updated, so nothing else needs to be done.
Chris Lattner9491dee2011-01-23 08:27:54 +00001905 continue;
1906 }
Nick Lewycky15e2d902011-07-25 23:14:22 +00001907
1908 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1909 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1910 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1911 RewriteLifetimeIntrinsic(II, AI, Offset, NewElts);
1912 }
1913 continue;
1914 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001915
Chris Lattner9491dee2011-01-23 08:27:54 +00001916 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner229907c2011-07-18 04:54:35 +00001917 Type *LIType = LI->getType();
Nadav Rotem465834c2012-07-24 10:51:42 +00001918
Bob Wilson08713d32011-01-13 17:45:11 +00001919 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
Bob Wilson532cd232009-12-18 20:14:40 +00001920 // Replace:
1921 // %res = load { i32, i32 }* %alloc
1922 // with:
1923 // %load.0 = load i32* %alloc.0
1924 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1925 // %load.1 = load i32* %alloc.1
1926 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1927 // (Also works for arrays instead of structs)
1928 Value *Insert = UndefValue::get(LIType);
Devang Patel84bb33a2011-06-03 19:46:19 +00001929 IRBuilder<> Builder(LI);
Bob Wilson532cd232009-12-18 20:14:40 +00001930 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patel84bb33a2011-06-03 19:46:19 +00001931 Value *Load = Builder.CreateLoad(NewElts[i], "load");
1932 Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
Bob Wilson532cd232009-12-18 20:14:40 +00001933 }
1934 LI->replaceAllUsesWith(Insert);
1935 DeadInsts.push_back(LI);
Duncan Sands19d0b472010-02-16 11:11:14 +00001936 } else if (LIType->isIntegerTy() &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001937 DL.getTypeAllocSize(LIType) ==
1938 DL.getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilson532cd232009-12-18 20:14:40 +00001939 // If this is a load of the entire alloca to an integer, rewrite it.
1940 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1941 }
Chris Lattner9491dee2011-01-23 08:27:54 +00001942 continue;
1943 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001944
Chris Lattner9491dee2011-01-23 08:27:54 +00001945 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001946 Value *Val = SI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00001947 Type *SIType = Val->getType();
Bob Wilson08713d32011-01-13 17:45:11 +00001948 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
Bob Wilson532cd232009-12-18 20:14:40 +00001949 // Replace:
1950 // store { i32, i32 } %val, { i32, i32 }* %alloc
1951 // with:
1952 // %val.0 = extractvalue { i32, i32 } %val, 0
1953 // store i32 %val.0, i32* %alloc.0
1954 // %val.1 = extractvalue { i32, i32 } %val, 1
1955 // store i32 %val.1, i32* %alloc.1
1956 // (Also works for arrays instead of structs)
Devang Patel84bb33a2011-06-03 19:46:19 +00001957 IRBuilder<> Builder(SI);
Bob Wilson532cd232009-12-18 20:14:40 +00001958 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patel84bb33a2011-06-03 19:46:19 +00001959 Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
1960 Builder.CreateStore(Extract, NewElts[i]);
Bob Wilson532cd232009-12-18 20:14:40 +00001961 }
1962 DeadInsts.push_back(SI);
Duncan Sands19d0b472010-02-16 11:11:14 +00001963 } else if (SIType->isIntegerTy() &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001964 DL.getTypeAllocSize(SIType) ==
1965 DL.getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilson532cd232009-12-18 20:14:40 +00001966 // If this is a store of the entire alloca from an integer, rewrite it.
1967 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1968 }
Chris Lattner9491dee2011-01-23 08:27:54 +00001969 continue;
1970 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001971
Chris Lattner9491dee2011-01-23 08:27:54 +00001972 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
Nadav Rotem465834c2012-07-24 10:51:42 +00001973 // If we have a PHI user of the alloca itself (as opposed to a GEP or
Chris Lattner9491dee2011-01-23 08:27:54 +00001974 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
1975 // the new pointer.
1976 if (!isa<AllocaInst>(I)) continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00001977
Chris Lattner9491dee2011-01-23 08:27:54 +00001978 assert(Offset == 0 && NewElts[0] &&
1979 "Direct alloca use should have a zero offset");
Nadav Rotem465834c2012-07-24 10:51:42 +00001980
Chris Lattner9491dee2011-01-23 08:27:54 +00001981 // If we have a use of the alloca, we know the derived uses will be
1982 // utilizing just the first element of the scalarized result. Insert a
1983 // bitcast of the first alloca before the user as required.
1984 AllocaInst *NewAI = NewElts[0];
1985 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1986 NewAI->moveBefore(BCI);
1987 TheUse = BCI;
1988 continue;
Bob Wilson532cd232009-12-18 20:14:40 +00001989 }
Bob Wilsonf3927b72009-12-17 18:34:24 +00001990 }
1991}
1992
Bob Wilson532cd232009-12-18 20:14:40 +00001993/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1994/// and recursively continue updating all of its uses.
1995void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00001996 SmallVectorImpl<AllocaInst *> &NewElts) {
Bob Wilson532cd232009-12-18 20:14:40 +00001997 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1998 if (BC->getOperand(0) != AI)
1999 return;
Bob Wilsonf3927b72009-12-17 18:34:24 +00002000
Bob Wilson532cd232009-12-18 20:14:40 +00002001 // The bitcast references the original alloca. Replace its uses with
Eli Friedmanecb45382011-11-12 02:07:50 +00002002 // references to the alloca containing offset zero (which is normally at
2003 // index zero, but might not be in cases involving structs with elements
2004 // of size zero).
2005 Type *T = AI->getAllocatedType();
2006 uint64_t EltOffset = 0;
2007 Type *IdxTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002008 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy,
2009 BC->getModule()->getDataLayout());
Eli Friedmanecb45382011-11-12 02:07:50 +00002010 Instruction *Val = NewElts[Idx];
Bob Wilson532cd232009-12-18 20:14:40 +00002011 if (Val->getType() != BC->getDestTy()) {
2012 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
2013 Val->takeName(BC);
Daniel Dunbar133efc32009-12-16 10:56:17 +00002014 }
Bob Wilson532cd232009-12-18 20:14:40 +00002015 BC->replaceAllUsesWith(Val);
2016 DeadInsts.push_back(BC);
Daniel Dunbar133efc32009-12-16 10:56:17 +00002017}
2018
Bob Wilson532cd232009-12-18 20:14:40 +00002019/// FindElementAndOffset - Return the index of the element containing Offset
2020/// within the specified type, which must be either a struct or an array.
2021/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsonc16811b2009-12-19 06:53:17 +00002022/// element. IdxTy is set to the type of the index result to be used in a
2023/// GEP instruction.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002024uint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset, Type *&IdxTy,
2025 const DataLayout &DL) {
Bob Wilsonc16811b2009-12-19 06:53:17 +00002026 uint64_t Idx = 0;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002027
Chris Lattner229907c2011-07-18 04:54:35 +00002028 if (StructType *ST = dyn_cast<StructType>(T)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002029 const StructLayout *Layout = DL.getStructLayout(ST);
Bob Wilson532cd232009-12-18 20:14:40 +00002030 Idx = Layout->getElementContainingOffset(Offset);
2031 T = ST->getContainedType(Idx);
2032 Offset -= Layout->getElementOffset(Idx);
Bob Wilsonc16811b2009-12-19 06:53:17 +00002033 IdxTy = Type::getInt32Ty(T->getContext());
2034 return Idx;
Pete Cooper1d1fa722012-06-14 23:53:53 +00002035 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
2036 T = AT->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002037 uint64_t EltSize = DL.getTypeAllocSize(T);
Pete Cooper1d1fa722012-06-14 23:53:53 +00002038 Idx = Offset / EltSize;
2039 Offset -= Idx * EltSize;
2040 IdxTy = Type::getInt64Ty(T->getContext());
2041 return Idx;
Chris Lattneraaa6ac12009-12-14 05:11:02 +00002042 }
Pete Cooper1d1fa722012-06-14 23:53:53 +00002043 VectorType *VT = cast<VectorType>(T);
2044 T = VT->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002045 uint64_t EltSize = DL.getTypeAllocSize(T);
Bob Wilsonc16811b2009-12-19 06:53:17 +00002046 Idx = Offset / EltSize;
2047 Offset -= Idx * EltSize;
2048 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilson532cd232009-12-18 20:14:40 +00002049 return Idx;
2050}
2051
2052/// RewriteGEP - Check if this GEP instruction moves the pointer across
2053/// elements of the alloca that are being split apart, and if so, rewrite
2054/// the GEP to be relative to the new element.
2055void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00002056 SmallVectorImpl<AllocaInst *> &NewElts) {
Bob Wilson532cd232009-12-18 20:14:40 +00002057 uint64_t OldOffset = Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002058 const DataLayout &DL = GEPI->getModule()->getDataLayout();
Bob Wilson532cd232009-12-18 20:14:40 +00002059 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
Pete Coopere24d6a12012-06-15 18:07:29 +00002060 // If the GEP was dynamic then it must have been a dynamic vector lookup.
2061 // In this case, it must be the last GEP operand which is dynamic so keep that
2062 // aside until we've found the constant GEP offset then add it back in at the
2063 // end.
Craig Topperf40110f2014-04-25 05:29:35 +00002064 Value* NonConstantIdx = nullptr;
Pete Coopere24d6a12012-06-15 18:07:29 +00002065 if (!GEPI->hasAllConstantIndices())
2066 NonConstantIdx = Indices.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002067 Offset += DL.getIndexedOffset(GEPI->getPointerOperandType(), Indices);
Bob Wilson532cd232009-12-18 20:14:40 +00002068
2069 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
2070
Chris Lattner229907c2011-07-18 04:54:35 +00002071 Type *T = AI->getAllocatedType();
2072 Type *IdxTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002073 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy, DL);
Bob Wilson532cd232009-12-18 20:14:40 +00002074 if (GEPI->getOperand(0) == AI)
Bob Wilsonc16811b2009-12-19 06:53:17 +00002075 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilson532cd232009-12-18 20:14:40 +00002076
2077 T = AI->getAllocatedType();
2078 uint64_t EltOffset = Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002079 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy, DL);
Bob Wilson532cd232009-12-18 20:14:40 +00002080
2081 // If this GEP does not move the pointer across elements of the alloca
2082 // being split, then it does not needs to be rewritten.
2083 if (Idx == OldIdx)
2084 return;
2085
Chris Lattner229907c2011-07-18 04:54:35 +00002086 Type *i32Ty = Type::getInt32Ty(AI->getContext());
Bob Wilson532cd232009-12-18 20:14:40 +00002087 SmallVector<Value*, 8> NewArgs;
2088 NewArgs.push_back(Constant::getNullValue(i32Ty));
2089 while (EltOffset != 0) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002090 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy, DL);
Bob Wilsonc16811b2009-12-19 06:53:17 +00002091 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilson532cd232009-12-18 20:14:40 +00002092 }
Pete Cooper818e9f42012-06-16 01:43:26 +00002093 if (NonConstantIdx) {
2094 Type* GepTy = T;
2095 // This GEP has a dynamic index. We need to add "i32 0" to index through
2096 // any structs or arrays in the original type until we get to the vector
2097 // to index.
2098 while (!isa<VectorType>(GepTy)) {
2099 NewArgs.push_back(Constant::getNullValue(i32Ty));
2100 GepTy = cast<CompositeType>(GepTy)->getTypeAtIndex(0U);
2101 }
Pete Coopere24d6a12012-06-15 18:07:29 +00002102 NewArgs.push_back(NonConstantIdx);
Pete Cooper818e9f42012-06-16 01:43:26 +00002103 }
Bob Wilson532cd232009-12-18 20:14:40 +00002104 Instruction *Val = NewElts[Idx];
2105 if (NewArgs.size() > 1) {
Jay Foadd1b78492011-07-25 09:48:08 +00002106 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs, "", GEPI);
Bob Wilson532cd232009-12-18 20:14:40 +00002107 Val->takeName(GEPI);
2108 }
2109 if (Val->getType() != GEPI->getType())
Benjamin Kramer40582a82010-01-27 19:46:52 +00002110 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilson532cd232009-12-18 20:14:40 +00002111 GEPI->replaceAllUsesWith(Val);
2112 DeadInsts.push_back(GEPI);
Chris Lattner9a2de652009-01-07 07:18:45 +00002113}
2114
Nick Lewycky15e2d902011-07-25 23:14:22 +00002115/// RewriteLifetimeIntrinsic - II is a lifetime.start/lifetime.end. Rewrite it
2116/// to mark the lifetime of the scalarized memory.
2117void SROA::RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
2118 uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00002119 SmallVectorImpl<AllocaInst *> &NewElts) {
Nick Lewycky15e2d902011-07-25 23:14:22 +00002120 ConstantInt *OldSize = cast<ConstantInt>(II->getArgOperand(0));
2121 // Put matching lifetime markers on everything from Offset up to
2122 // Offset+OldSize.
2123 Type *AIType = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002124 const DataLayout &DL = II->getModule()->getDataLayout();
Nick Lewycky15e2d902011-07-25 23:14:22 +00002125 uint64_t NewOffset = Offset;
2126 Type *IdxTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002127 uint64_t Idx = FindElementAndOffset(AIType, NewOffset, IdxTy, DL);
Nick Lewycky15e2d902011-07-25 23:14:22 +00002128
2129 IRBuilder<> Builder(II);
2130 uint64_t Size = OldSize->getLimitedValue();
2131
2132 if (NewOffset) {
2133 // Splice the first element and index 'NewOffset' bytes in. SROA will
2134 // split the alloca again later.
Matt Arsenaultbe558882014-04-23 20:58:57 +00002135 unsigned AS = AI->getType()->getAddressSpace();
2136 Value *V = Builder.CreateBitCast(NewElts[Idx], Builder.getInt8PtrTy(AS));
David Blaikie93c54442015-04-03 19:41:44 +00002137 V = Builder.CreateGEP(Builder.getInt8Ty(), V, Builder.getInt64(NewOffset));
Nick Lewycky15e2d902011-07-25 23:14:22 +00002138
2139 IdxTy = NewElts[Idx]->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002140 uint64_t EltSize = DL.getTypeAllocSize(IdxTy) - NewOffset;
Nick Lewycky15e2d902011-07-25 23:14:22 +00002141 if (EltSize > Size) {
2142 EltSize = Size;
2143 Size = 0;
2144 } else {
2145 Size -= EltSize;
2146 }
2147 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2148 Builder.CreateLifetimeStart(V, Builder.getInt64(EltSize));
2149 else
2150 Builder.CreateLifetimeEnd(V, Builder.getInt64(EltSize));
2151 ++Idx;
2152 }
2153
2154 for (; Idx != NewElts.size() && Size; ++Idx) {
2155 IdxTy = NewElts[Idx]->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002156 uint64_t EltSize = DL.getTypeAllocSize(IdxTy);
Nick Lewycky15e2d902011-07-25 23:14:22 +00002157 if (EltSize > Size) {
2158 EltSize = Size;
2159 Size = 0;
2160 } else {
2161 Size -= EltSize;
2162 }
2163 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2164 Builder.CreateLifetimeStart(NewElts[Idx],
2165 Builder.getInt64(EltSize));
2166 else
2167 Builder.CreateLifetimeEnd(NewElts[Idx],
2168 Builder.getInt64(EltSize));
2169 }
2170 DeadInsts.push_back(II);
2171}
2172
Chris Lattner9a2de652009-01-07 07:18:45 +00002173/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
2174/// Rewrite it to copy or set the elements of the scalarized memory.
Craig Topperb94011f2013-07-14 04:42:23 +00002175void
2176SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
2177 AllocaInst *AI,
2178 SmallVectorImpl<AllocaInst *> &NewElts) {
Chris Lattner9a2de652009-01-07 07:18:45 +00002179 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattnera41bb402009-03-04 19:23:25 +00002180 // appropriate type. The "Other" pointer is the pointer that goes to memory
2181 // that doesn't have anything to do with the alloca that we are promoting. For
2182 // memset, this Value* stays null.
Craig Topperf40110f2014-04-25 05:29:35 +00002183 Value *OtherPtr = nullptr;
Chris Lattnerdc35e5b2009-03-08 03:59:00 +00002184 unsigned MemAlignment = MI->getAlignment();
Chris Lattner334268a2009-03-08 03:37:16 +00002185 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilson532cd232009-12-18 20:14:40 +00002186 if (Inst == MTI->getRawDest())
Chris Lattner334268a2009-03-08 03:37:16 +00002187 OtherPtr = MTI->getRawSource();
Chris Lattner9a2de652009-01-07 07:18:45 +00002188 else {
Bob Wilson532cd232009-12-18 20:14:40 +00002189 assert(Inst == MTI->getRawSource());
Chris Lattner334268a2009-03-08 03:37:16 +00002190 OtherPtr = MTI->getRawDest();
Chris Lattner9a2de652009-01-07 07:18:45 +00002191 }
2192 }
Bob Wilson2029ea02009-12-08 18:22:03 +00002193
Chris Lattner9a2de652009-01-07 07:18:45 +00002194 // If there is an other pointer, we want to convert it to the same pointer
2195 // type as AI has, so we can GEP through it safely.
2196 if (OtherPtr) {
Chris Lattnerefa3c822010-07-08 00:27:05 +00002197 unsigned AddrSpace =
2198 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilson532cd232009-12-18 20:14:40 +00002199
2200 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
2201 // optimization, but it's also required to detect the corner case where
2202 // both pointer operands are referencing the same memory, and where
2203 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
2204 // function is only called for mem intrinsics that access the whole
2205 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattnerefa3c822010-07-08 00:27:05 +00002206 OtherPtr = OtherPtr->stripPointerCasts();
Bob Wilson328e91b2011-01-13 20:59:44 +00002207
Bob Wilson58d59fe2010-01-19 04:32:48 +00002208 // Copying the alloca to itself is a no-op: just delete it.
2209 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2210 // This code will run twice for a no-op memcpy -- once for each operand.
2211 // Put only one reference to MI on the DeadInsts list.
Craig Topper31ee5862013-07-03 15:07:05 +00002212 for (SmallVectorImpl<Value *>::const_iterator I = DeadInsts.begin(),
Bob Wilson58d59fe2010-01-19 04:32:48 +00002213 E = DeadInsts.end(); I != E; ++I)
2214 if (*I == MI) return;
2215 DeadInsts.push_back(MI);
Bob Wilson532cd232009-12-18 20:14:40 +00002216 return;
Bob Wilson58d59fe2010-01-19 04:32:48 +00002217 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002218
Chris Lattner9a2de652009-01-07 07:18:45 +00002219 // If the pointer is not the right type, insert a bitcast to the right
2220 // type.
Chris Lattner229907c2011-07-18 04:54:35 +00002221 Type *NewTy =
Chris Lattnerefa3c822010-07-08 00:27:05 +00002222 PointerType::get(AI->getType()->getElementType(), AddrSpace);
Bob Wilson328e91b2011-01-13 20:59:44 +00002223
Chris Lattnerefa3c822010-07-08 00:27:05 +00002224 if (OtherPtr->getType() != NewTy)
2225 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattner9a2de652009-01-07 07:18:45 +00002226 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002227
Chris Lattner9a2de652009-01-07 07:18:45 +00002228 // Process each element of the aggregate.
Bob Wilson532cd232009-12-18 20:14:40 +00002229 bool SROADest = MI->getRawDest() == Inst;
Bob Wilson328e91b2011-01-13 20:59:44 +00002230
Owen Anderson55f1c092009-08-13 21:58:54 +00002231 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002232 const DataLayout &DL = MI->getModule()->getDataLayout();
Chris Lattner9a2de652009-01-07 07:18:45 +00002233
2234 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2235 // If this is a memcpy/memmove, emit a GEP of the other element address.
Craig Topperf40110f2014-04-25 05:29:35 +00002236 Value *OtherElt = nullptr;
Chris Lattner5c204c92009-03-04 19:20:50 +00002237 unsigned OtherEltAlign = MemAlignment;
Bob Wilson328e91b2011-01-13 20:59:44 +00002238
Bob Wilson58d59fe2010-01-19 04:32:48 +00002239 if (OtherPtr) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002240 Value *Idx[2] = { Zero,
2241 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Jay Foadd1b78492011-07-25 09:48:08 +00002242 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx,
Benjamin Kramer40582a82010-01-27 19:46:52 +00002243 OtherPtr->getName()+"."+Twine(i),
Bob Wilson532cd232009-12-18 20:14:40 +00002244 MI);
Chris Lattner5c204c92009-03-04 19:20:50 +00002245 uint64_t EltOffset;
Chris Lattner229907c2011-07-18 04:54:35 +00002246 PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
2247 Type *OtherTy = OtherPtrTy->getElementType();
2248 if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002249 EltOffset = DL.getStructLayout(ST)->getElementOffset(i);
Chris Lattner5c204c92009-03-04 19:20:50 +00002250 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002251 Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002252 EltOffset = DL.getTypeAllocSize(EltTy) * i;
Chris Lattner5c204c92009-03-04 19:20:50 +00002253 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002254
Chris Lattner5c204c92009-03-04 19:20:50 +00002255 // The alignment of the other pointer is the guaranteed alignment of the
2256 // element, which is affected by both the known alignment of the whole
2257 // mem intrinsic and the alignment of the element. If the alignment of
2258 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2259 // known alignment is just 4 bytes.
2260 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattner9f022d52007-03-08 06:36:54 +00002261 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002262
Chris Lattner9a2de652009-01-07 07:18:45 +00002263 Value *EltPtr = NewElts[i];
Chris Lattner229907c2011-07-18 04:54:35 +00002264 Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Bob Wilson328e91b2011-01-13 20:59:44 +00002265
Chris Lattner9a2de652009-01-07 07:18:45 +00002266 // If we got down to a scalar, insert a load or store as appropriate.
2267 if (EltTy->isSingleValueType()) {
Chris Lattner334268a2009-03-08 03:37:16 +00002268 if (isa<MemTransferInst>(MI)) {
Chris Lattner5c204c92009-03-04 19:20:50 +00002269 if (SROADest) {
2270 // From Other to Alloca.
2271 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2272 new StoreInst(Elt, EltPtr, MI);
2273 } else {
2274 // From Alloca to Other.
2275 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2276 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2277 }
Chris Lattner9a2de652009-01-07 07:18:45 +00002278 continue;
2279 }
2280 assert(isa<MemSetInst>(MI));
Bob Wilson328e91b2011-01-13 20:59:44 +00002281
Chris Lattner9a2de652009-01-07 07:18:45 +00002282 // If the stored element is zero (common case), just store a null
2283 // constant.
2284 Constant *StoreVal;
Gabor Greiffe252e62010-06-30 09:16:16 +00002285 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattner9a2de652009-01-07 07:18:45 +00002286 if (CI->isZero()) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00002287 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattner9a2de652009-01-07 07:18:45 +00002288 } else {
2289 // If EltTy is a vector type, get the element type.
Chris Lattner229907c2011-07-18 04:54:35 +00002290 Type *ValTy = EltTy->getScalarType();
Dan Gohmanadfd42a2009-06-16 00:20:26 +00002291
Chris Lattner9a2de652009-01-07 07:18:45 +00002292 // Construct an integer with the right value.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002293 unsigned EltSize = DL.getTypeSizeInBits(ValTy);
Chris Lattner9a2de652009-01-07 07:18:45 +00002294 APInt OneVal(EltSize, CI->getZExtValue());
2295 APInt TotalVal(OneVal);
2296 // Set each byte.
2297 for (unsigned i = 0; 8*i < EltSize; ++i) {
2298 TotalVal = TotalVal.shl(8);
2299 TotalVal |= OneVal;
2300 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002301
Chris Lattner9a2de652009-01-07 07:18:45 +00002302 // Convert the integer value to the appropriate type.
Chris Lattner1146d322010-04-16 01:05:38 +00002303 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands19d0b472010-02-16 11:11:14 +00002304 if (ValTy->isPointerTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002305 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sands9dff9be2010-02-15 16:12:20 +00002306 else if (ValTy->isFloatingPointTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002307 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattner9a2de652009-01-07 07:18:45 +00002308 assert(StoreVal->getType() == ValTy && "Type mismatch!");
Bob Wilson328e91b2011-01-13 20:59:44 +00002309
Chris Lattner9a2de652009-01-07 07:18:45 +00002310 // If the requested value was a vector constant, create it.
Cameron Zwarich1a761dc2011-10-11 21:26:40 +00002311 if (EltTy->isVectorTy()) {
2312 unsigned NumElts = cast<VectorType>(EltTy)->getNumElements();
Chris Lattner47a86bd2012-01-25 06:02:56 +00002313 StoreVal = ConstantVector::getSplat(NumElts, StoreVal);
Chris Lattner9a2de652009-01-07 07:18:45 +00002314 }
2315 }
2316 new StoreInst(StoreVal, EltPtr, MI);
2317 continue;
2318 }
2319 // Otherwise, if we're storing a byte variable, use a memset call for
2320 // this element.
2321 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002322
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002323 unsigned EltSize = DL.getTypeAllocSize(EltTy);
Eli Friedmanecb45382011-11-12 02:07:50 +00002324 if (!EltSize)
2325 continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00002326
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00002327 IRBuilder<> Builder(MI);
Bob Wilson328e91b2011-01-13 20:59:44 +00002328
Chris Lattner9a2de652009-01-07 07:18:45 +00002329 // Finally, insert the meminst for this element.
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00002330 if (isa<MemSetInst>(MI)) {
2331 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2332 MI->isVolatile());
Chris Lattner9a2de652009-01-07 07:18:45 +00002333 } else {
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00002334 assert(isa<MemTransferInst>(MI));
2335 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
2336 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
Bob Wilson328e91b2011-01-13 20:59:44 +00002337
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00002338 if (isa<MemCpyInst>(MI))
2339 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2340 else
2341 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
Chris Lattner9a2de652009-01-07 07:18:45 +00002342 }
Chris Lattner66e6a822007-03-05 07:52:57 +00002343 }
Bob Wilson532cd232009-12-18 20:14:40 +00002344 DeadInsts.push_back(MI);
Chris Lattner66e6a822007-03-05 07:52:57 +00002345}
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002346
Bob Wilson050b8122009-12-04 21:57:37 +00002347/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002348/// overwrites the entire allocation. Extract out the pieces of the stored
2349/// integer and store them individually.
Craig Topperb94011f2013-07-14 04:42:23 +00002350void
2351SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
2352 SmallVectorImpl<AllocaInst *> &NewElts) {
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002353 // Extract each element out of the integer according to its structure offset
2354 // and store the element value to the individual alloca.
2355 Value *SrcVal = SI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002356 Type *AllocaEltTy = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002357 const DataLayout &DL = SI->getModule()->getDataLayout();
2358 uint64_t AllocaSizeBits = DL.getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002359
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002360 IRBuilder<> Builder(SI);
Nadav Rotem465834c2012-07-24 10:51:42 +00002361
Eli Friedmanee94e3c2009-06-01 09:14:32 +00002362 // Handle tail padding by extending the operand
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002363 if (DL.getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002364 SrcVal = Builder.CreateZExt(SrcVal,
2365 IntegerType::get(SI->getContext(), AllocaSizeBits));
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002366
David Greene48c86be2010-01-05 01:27:09 +00002367 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky7465cd72009-09-15 07:08:25 +00002368 << '\n');
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002369
2370 // There are two forms here: AI could be an array or struct. Both cases
2371 // have different ways to compute the element offset.
Chris Lattner229907c2011-07-18 04:54:35 +00002372 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002373 const StructLayout *Layout = DL.getStructLayout(EltSTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002374
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002375 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2376 // Get the number of bits to shift SrcVal to get the value.
Chris Lattner229907c2011-07-18 04:54:35 +00002377 Type *FieldTy = EltSTy->getElementType(i);
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002378 uint64_t Shift = Layout->getElementOffsetInBits(i);
Bob Wilson328e91b2011-01-13 20:59:44 +00002379
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002380 if (DL.isBigEndian())
2381 Shift = AllocaSizeBits - Shift - DL.getTypeAllocSizeInBits(FieldTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002382
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002383 Value *EltVal = SrcVal;
2384 if (Shift) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002385 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002386 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002387 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002388
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002389 // Truncate down to an integer of the right size.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002390 uint64_t FieldSizeBits = DL.getTypeSizeInBits(FieldTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002391
Chris Lattnerae0e8572009-01-09 18:18:43 +00002392 // Ignore zero sized fields like {}, they obviously contain no data.
2393 if (FieldSizeBits == 0) continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00002394
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002395 if (FieldSizeBits != AllocaSizeBits)
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002396 EltVal = Builder.CreateTrunc(EltVal,
2397 IntegerType::get(SI->getContext(), FieldSizeBits));
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002398 Value *DestField = NewElts[i];
2399 if (EltVal->getType() == FieldTy) {
2400 // Storing to an integer field of this size, just do it.
Duncan Sands19d0b472010-02-16 11:11:14 +00002401 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002402 // Bitcast to the right element type (for fp/vector values).
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002403 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002404 } else {
2405 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002406 DestField = Builder.CreateBitCast(DestField,
2407 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002408 }
2409 new StoreInst(EltVal, DestField, SI);
2410 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002411
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002412 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002413 ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2414 Type *ArrayEltTy = ATy->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002415 uint64_t ElementOffset = DL.getTypeAllocSizeInBits(ArrayEltTy);
2416 uint64_t ElementSizeBits = DL.getTypeSizeInBits(ArrayEltTy);
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002417
2418 uint64_t Shift;
Bob Wilson328e91b2011-01-13 20:59:44 +00002419
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002420 if (DL.isBigEndian())
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002421 Shift = AllocaSizeBits-ElementOffset;
Bob Wilson328e91b2011-01-13 20:59:44 +00002422 else
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002423 Shift = 0;
Bob Wilson328e91b2011-01-13 20:59:44 +00002424
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002425 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattnerae0e8572009-01-09 18:18:43 +00002426 // Ignore zero sized fields like {}, they obviously contain no data.
2427 if (ElementSizeBits == 0) continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00002428
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002429 Value *EltVal = SrcVal;
2430 if (Shift) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002431 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002432 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002433 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002434
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002435 // Truncate down to an integer of the right size.
2436 if (ElementSizeBits != AllocaSizeBits)
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002437 EltVal = Builder.CreateTrunc(EltVal,
2438 IntegerType::get(SI->getContext(),
2439 ElementSizeBits));
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002440 Value *DestField = NewElts[i];
2441 if (EltVal->getType() == ArrayEltTy) {
2442 // Storing to an integer field of this size, just do it.
Duncan Sands9dff9be2010-02-15 16:12:20 +00002443 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +00002444 ArrayEltTy->isVectorTy()) {
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002445 // Bitcast to the right element type (for fp/vector values).
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002446 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002447 } else {
2448 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002449 DestField = Builder.CreateBitCast(DestField,
2450 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002451 }
2452 new StoreInst(EltVal, DestField, SI);
Bob Wilson328e91b2011-01-13 20:59:44 +00002453
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002454 if (DL.isBigEndian())
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002455 Shift -= ElementOffset;
Bob Wilson328e91b2011-01-13 20:59:44 +00002456 else
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002457 Shift += ElementOffset;
2458 }
2459 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002460
Bob Wilson532cd232009-12-18 20:14:40 +00002461 DeadInsts.push_back(SI);
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002462}
2463
Bob Wilson050b8122009-12-04 21:57:37 +00002464/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002465/// an integer. Load the individual pieces to form the aggregate value.
Craig Topperb94011f2013-07-14 04:42:23 +00002466void
2467SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
2468 SmallVectorImpl<AllocaInst *> &NewElts) {
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002469 // Extract each element out of the NewElts according to its structure offset
2470 // and form the result value.
Chris Lattner229907c2011-07-18 04:54:35 +00002471 Type *AllocaEltTy = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002472 const DataLayout &DL = LI->getModule()->getDataLayout();
2473 uint64_t AllocaSizeBits = DL.getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002474
David Greene48c86be2010-01-05 01:27:09 +00002475 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky7465cd72009-09-15 07:08:25 +00002476 << '\n');
Bob Wilson328e91b2011-01-13 20:59:44 +00002477
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002478 // There are two forms here: AI could be an array or struct. Both cases
2479 // have different ways to compute the element offset.
Craig Topperf40110f2014-04-25 05:29:35 +00002480 const StructLayout *Layout = nullptr;
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002481 uint64_t ArrayEltBitOffset = 0;
Chris Lattner229907c2011-07-18 04:54:35 +00002482 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002483 Layout = DL.getStructLayout(EltSTy);
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002484 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002485 Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002486 ArrayEltBitOffset = DL.getTypeAllocSizeInBits(ArrayEltTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002487 }
2488
2489 Value *ResultVal =
Owen Anderson55f1c092009-08-13 21:58:54 +00002490 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Bob Wilson328e91b2011-01-13 20:59:44 +00002491
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002492 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2493 // Load the value from the alloca. If the NewElt is an aggregate, cast
2494 // the pointer to an integer of the same size before doing the load.
2495 Value *SrcField = NewElts[i];
Chris Lattner229907c2011-07-18 04:54:35 +00002496 Type *FieldTy =
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002497 cast<PointerType>(SrcField->getType())->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002498 uint64_t FieldSizeBits = DL.getTypeSizeInBits(FieldTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002499
Chris Lattnerae0e8572009-01-09 18:18:43 +00002500 // Ignore zero sized fields like {}, they obviously contain no data.
2501 if (FieldSizeBits == 0) continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00002502
Chris Lattner229907c2011-07-18 04:54:35 +00002503 IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00002504 FieldSizeBits);
Duncan Sands19d0b472010-02-16 11:11:14 +00002505 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2506 !FieldTy->isVectorTy())
Owen Anderson340288c2009-07-03 19:42:02 +00002507 SrcField = new BitCastInst(SrcField,
Owen Anderson4056ca92009-07-29 22:17:13 +00002508 PointerType::getUnqual(FieldIntTy),
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002509 "", LI);
2510 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2511
2512 // If SrcField is a fp or vector of the right size but that isn't an
2513 // integer type, bitcast to an integer so we can shift it.
2514 if (SrcField->getType() != FieldIntTy)
2515 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2516
2517 // Zero extend the field to be the same size as the final alloca so that
2518 // we can shift and insert it.
2519 if (SrcField->getType() != ResultVal->getType())
2520 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
Bob Wilson328e91b2011-01-13 20:59:44 +00002521
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002522 // Determine the number of bits to shift SrcField.
2523 uint64_t Shift;
2524 if (Layout) // Struct case.
2525 Shift = Layout->getElementOffsetInBits(i);
2526 else // Array case.
2527 Shift = i*ArrayEltBitOffset;
Bob Wilson328e91b2011-01-13 20:59:44 +00002528
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002529 if (DL.isBigEndian())
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002530 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
Bob Wilson328e91b2011-01-13 20:59:44 +00002531
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002532 if (Shift) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002533 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002534 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2535 }
2536
Chris Lattner25a843f2010-06-27 07:58:26 +00002537 // Don't create an 'or x, 0' on the first iteration.
2538 if (!isa<Constant>(ResultVal) ||
2539 !cast<Constant>(ResultVal)->isNullValue())
2540 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2541 else
2542 ResultVal = SrcField;
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002543 }
Eli Friedmanee94e3c2009-06-01 09:14:32 +00002544
2545 // Handle tail padding by truncating the result
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002546 if (DL.getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
Eli Friedmanee94e3c2009-06-01 09:14:32 +00002547 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2548
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002549 LI->replaceAllUsesWith(ResultVal);
Bob Wilson532cd232009-12-18 20:14:40 +00002550 DeadInsts.push_back(LI);
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002551}
2552
Duncan Sands399d9792007-11-04 14:43:57 +00002553/// HasPadding - Return true if the specified type has any structure or
Bob Wilson12eec402011-01-13 17:45:08 +00002554/// alignment padding in between the elements that would be split apart
2555/// by SROA; return false otherwise.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002556static bool HasPadding(Type *Ty, const DataLayout &DL) {
Chris Lattner229907c2011-07-18 04:54:35 +00002557 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Bob Wilson12eec402011-01-13 17:45:08 +00002558 Ty = ATy->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002559 return DL.getTypeSizeInBits(Ty) != DL.getTypeAllocSizeInBits(Ty);
Chris Lattner87679202007-05-30 06:11:23 +00002560 }
Bob Wilson12eec402011-01-13 17:45:08 +00002561
2562 // SROA currently handles only Arrays and Structs.
Chris Lattner229907c2011-07-18 04:54:35 +00002563 StructType *STy = cast<StructType>(Ty);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002564 const StructLayout *SL = DL.getStructLayout(STy);
Bob Wilson12eec402011-01-13 17:45:08 +00002565 unsigned PrevFieldBitOffset = 0;
2566 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2567 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2568
2569 // Check to see if there is any padding between this element and the
2570 // previous one.
2571 if (i) {
2572 unsigned PrevFieldEnd =
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002573 PrevFieldBitOffset+DL.getTypeSizeInBits(STy->getElementType(i-1));
Bob Wilson12eec402011-01-13 17:45:08 +00002574 if (PrevFieldEnd < FieldBitOffset)
2575 return true;
2576 }
2577 PrevFieldBitOffset = FieldBitOffset;
2578 }
2579 // Check for tail padding.
2580 if (unsigned EltCount = STy->getNumElements()) {
2581 unsigned PrevFieldEnd = PrevFieldBitOffset +
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002582 DL.getTypeSizeInBits(STy->getElementType(EltCount-1));
Bob Wilson12eec402011-01-13 17:45:08 +00002583 if (PrevFieldEnd < SL->getSizeInBits())
2584 return true;
2585 }
2586 return false;
Chris Lattner87679202007-05-30 06:11:23 +00002587}
Chris Lattner66e6a822007-03-05 07:52:57 +00002588
Chris Lattner88819122004-11-14 04:24:28 +00002589/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2590/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2591/// or 1 if safe after canonicalization has been performed.
Victor Hernandez1df65182010-01-21 23:05:53 +00002592bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner6e5398d2003-05-30 04:15:41 +00002593 // Loop over the use list of the alloca. We can only transform it if all of
2594 // the users are safe to transform.
Chris Lattner8acbb792011-01-23 07:29:29 +00002595 AllocaInfo Info(AI);
Bob Wilson328e91b2011-01-13 20:59:44 +00002596
Chris Lattner8acbb792011-01-23 07:29:29 +00002597 isSafeForScalarRepl(AI, 0, Info);
Bob Wilson532cd232009-12-18 20:14:40 +00002598 if (Info.isUnsafe) {
David Greene48c86be2010-01-05 01:27:09 +00002599 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez1df65182010-01-21 23:05:53 +00002600 return false;
Chris Lattner88819122004-11-14 04:24:28 +00002601 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002602
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002603 const DataLayout &DL = AI->getModule()->getDataLayout();
2604
Chris Lattner87679202007-05-30 06:11:23 +00002605 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2606 // source and destination, we have to be careful. In particular, the memcpy
2607 // could be moving around elements that live in structure padding of the LLVM
2608 // types, but may actually be used. In these cases, we refuse to promote the
2609 // struct.
2610 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002611 HasPadding(AI->getAllocatedType(), DL))
Victor Hernandez1df65182010-01-21 23:05:53 +00002612 return false;
Duncan Sands399d9792007-11-04 14:43:57 +00002613
Chris Lattner7c9f4c92011-01-16 17:46:19 +00002614 // If the alloca never has an access to just *part* of it, but is accessed
2615 // via loads and stores, then we should use ConvertToScalarInfo to promote
Chris Lattner6fab2e92011-01-16 06:18:28 +00002616 // the alloca instead of promoting each piece at a time and inserting fission
2617 // and fusion code.
2618 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2619 // If the struct/array just has one element, use basic SRoA.
Chris Lattner229907c2011-07-18 04:54:35 +00002620 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
Chris Lattner6fab2e92011-01-16 06:18:28 +00002621 if (ST->getNumElements() > 1) return false;
2622 } else {
2623 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2624 return false;
2625 }
2626 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002627
Victor Hernandez1df65182010-01-21 23:05:53 +00002628 return true;
Chris Lattner6e5398d2003-05-30 04:15:41 +00002629}