blob: 8f954d5c84803950c02d6e99cb59af57d2e16a28 [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
Chris Lattner79a42ac2006-12-19 21:40:18 +000022#define DEBUG_TYPE "scalarrepl"
Chris Lattnerfb41a502003-05-27 15:45:27 +000023#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/ADT/SetVector.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/Loads.h"
28#include "llvm/Analysis/ValueTracking.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000029#include "llvm/DIBuilder.h"
Bill Wendlinge38859d2012-06-28 00:05:13 +000030#include "llvm/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Constants.h"
32#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000034#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Function.h"
36#include "llvm/IR/GlobalVariable.h"
37#include "llvm/IR/IRBuilder.h"
38#include "llvm/IR/Instructions.h"
39#include "llvm/IR/IntrinsicInst.h"
40#include "llvm/IR/LLVMContext.h"
41#include "llvm/IR/Module.h"
42#include "llvm/IR/Operator.h"
Chris Lattner66e6a822007-03-05 07:52:57 +000043#include "llvm/Pass.h"
Chris Lattnerf183d5c2010-11-18 06:26:49 +000044#include "llvm/Support/CallSite.h"
Chris Lattner996795b2006-06-28 23:17:24 +000045#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000046#include "llvm/Support/ErrorHandling.h"
Chris Lattner3b0a62d2005-12-12 07:19:13 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
48#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
Chris Lattner79a42ac2006-12-19 21:40:18 +000055STATISTIC(NumReplaced, "Number of allocas broken up");
56STATISTIC(NumPromoted, "Number of allocas promoted");
Chris Lattnera9607252011-01-23 22:04:55 +000057STATISTIC(NumAdjusted, "Number of scalar allocas adjusted to allow promotion");
Chris Lattner79a42ac2006-12-19 21:40:18 +000058STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattnerfb41a502003-05-27 15:45:27 +000059
Chris Lattner79a42ac2006-12-19 21:40:18 +000060namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +000061 struct SROA : public FunctionPass {
Nadav Rotem4e9012c2012-06-21 13:44:31 +000062 SROA(int T, bool hasDT, char &ID, int ST, int AT, int SLT)
Cameron Zwarich4694e692011-01-18 03:53:26 +000063 : FunctionPass(ID), HasDomTree(hasDT) {
Devang Patele8ec7662007-07-09 21:19:23 +000064 if (T == -1)
Chris Lattner1f708162007-08-02 21:33:36 +000065 SRThreshold = 128;
Devang Patele8ec7662007-07-09 21:19:23 +000066 else
67 SRThreshold = T;
Nadav Rotem4e9012c2012-06-21 13:44:31 +000068 if (ST == -1)
69 StructMemberThreshold = 32;
70 else
71 StructMemberThreshold = ST;
72 if (AT == -1)
73 ArrayElementThreshold = 8;
74 else
75 ArrayElementThreshold = AT;
76 if (SLT == -1)
77 // Do not limit the scalar integer load size if no threshold is given.
78 ScalarLoadThreshold = -1;
79 else
80 ScalarLoadThreshold = SLT;
Devang Patele8ec7662007-07-09 21:19:23 +000081 }
Devang Patel09f162c2007-05-01 21:15:47 +000082
Chris Lattnerfb41a502003-05-27 15:45:27 +000083 bool runOnFunction(Function &F);
84
Chris Lattner5d8a12e2003-09-11 16:45:55 +000085 bool performScalarRepl(Function &F);
86 bool performPromotion(Function &F);
87
Chris Lattnerfb41a502003-05-27 15:45:27 +000088 private:
Cameron Zwarich4694e692011-01-18 03:53:26 +000089 bool HasDomTree;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +000090 const DataLayout *DL;
Bob Wilson328e91b2011-01-13 20:59:44 +000091
Bob Wilson532cd232009-12-18 20:14:40 +000092 /// DeadInsts - Keep track of instructions we have made dead, so that
93 /// we can remove them after we are done working.
94 SmallVector<Value*, 32> DeadInsts;
95
Chris Lattner87679202007-05-30 06:11:23 +000096 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
97 /// information about the uses. All these fields are initialized to false
98 /// and set to true when something is learned.
99 struct AllocaInfo {
Chris Lattner8acbb792011-01-23 07:29:29 +0000100 /// The alloca to promote.
101 AllocaInst *AI;
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000102
Chris Lattner9491dee2011-01-23 08:27:54 +0000103 /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
104 /// looping and avoid redundant work.
105 SmallPtrSet<PHINode*, 8> CheckedPHIs;
Nadav Rotem465834c2012-07-24 10:51:42 +0000106
Chris Lattner87679202007-05-30 06:11:23 +0000107 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
108 bool isUnsafe : 1;
Bob Wilson328e91b2011-01-13 20:59:44 +0000109
Chris Lattner87679202007-05-30 06:11:23 +0000110 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
111 bool isMemCpySrc : 1;
112
Zhou Sheng1ee941d2007-07-06 06:01:16 +0000113 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner87679202007-05-30 06:11:23 +0000114 bool isMemCpyDst : 1;
115
Chris Lattner6fab2e92011-01-16 06:18:28 +0000116 /// hasSubelementAccess - This is true if a subelement of the alloca is
117 /// ever accessed, or false if the alloca is only accessed with mem
118 /// intrinsics or load/store that only access the entire alloca at once.
119 bool hasSubelementAccess : 1;
Nadav Rotem465834c2012-07-24 10:51:42 +0000120
Chris Lattner6fab2e92011-01-16 06:18:28 +0000121 /// hasALoadOrStore - This is true if there are any loads or stores to it.
122 /// The alloca may just be accessed with memcpy, for example, which would
123 /// not set this.
124 bool hasALoadOrStore : 1;
Nadav Rotem465834c2012-07-24 10:51:42 +0000125
Chris Lattner8acbb792011-01-23 07:29:29 +0000126 explicit AllocaInfo(AllocaInst *ai)
127 : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
Chris Lattner6fab2e92011-01-16 06:18:28 +0000128 hasSubelementAccess(false), hasALoadOrStore(false) {}
Chris Lattner87679202007-05-30 06:11:23 +0000129 };
Bob Wilson328e91b2011-01-13 20:59:44 +0000130
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000131 /// SRThreshold - The maximum alloca size to considered for SROA.
Devang Patele8ec7662007-07-09 21:19:23 +0000132 unsigned SRThreshold;
133
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000134 /// StructMemberThreshold - The maximum number of members a struct can
135 /// contain to be considered for SROA.
136 unsigned StructMemberThreshold;
137
138 /// ArrayElementThreshold - The maximum number of elements an array can
139 /// have to be considered for SROA.
140 unsigned ArrayElementThreshold;
141
142 /// ScalarLoadThreshold - The maximum size in bits of scalars to load when
143 /// converting to scalar
144 unsigned ScalarLoadThreshold;
145
Chris Lattner3e56c292011-01-23 07:05:44 +0000146 void MarkUnsafe(AllocaInfo &I, Instruction *User) {
147 I.isUnsafe = true;
148 DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
149 }
Chris Lattner87679202007-05-30 06:11:23 +0000150
Victor Hernandez1df65182010-01-21 23:05:53 +0000151 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner87679202007-05-30 06:11:23 +0000152
Chris Lattner8acbb792011-01-23 07:29:29 +0000153 void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
Chris Lattner9491dee2011-01-23 08:27:54 +0000154 void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
155 AllocaInfo &Info);
Chris Lattner8acbb792011-01-23 07:29:29 +0000156 void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
157 void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattner229907c2011-07-18 04:54:35 +0000158 Type *MemOpType, bool isStore, AllocaInfo &Info,
Chris Lattner9491dee2011-01-23 08:27:54 +0000159 Instruction *TheAccess, bool AllowWholeAccess);
Chris Lattner229907c2011-07-18 04:54:35 +0000160 bool TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size);
161 uint64_t FindElementAndOffset(Type *&T, uint64_t &Offset,
162 Type *&IdxTy);
Bob Wilson328e91b2011-01-13 20:59:44 +0000163
164 void DoScalarReplacement(AllocaInst *AI,
Victor Hernandez8acf2952009-10-23 21:09:37 +0000165 std::vector<AllocaInst*> &WorkList);
Bob Wilson532cd232009-12-18 20:14:40 +0000166 void DeleteDeadInstructions();
Bob Wilson328e91b2011-01-13 20:59:44 +0000167
Bob Wilson532cd232009-12-18 20:14:40 +0000168 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +0000169 SmallVectorImpl<AllocaInst *> &NewElts);
Bob Wilson532cd232009-12-18 20:14:40 +0000170 void RewriteBitCast(BitCastInst *BC, 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 RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +0000173 SmallVectorImpl<AllocaInst *> &NewElts);
Nick Lewycky15e2d902011-07-25 23:14:22 +0000174 void RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
175 uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +0000176 SmallVectorImpl<AllocaInst *> &NewElts);
Bob Wilson532cd232009-12-18 20:14:40 +0000177 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez8acf2952009-10-23 21:09:37 +0000178 AllocaInst *AI,
Craig Topperb94011f2013-07-14 04:42:23 +0000179 SmallVectorImpl<AllocaInst *> &NewElts);
Victor Hernandez8acf2952009-10-23 21:09:37 +0000180 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Craig Topperb94011f2013-07-14 04:42:23 +0000181 SmallVectorImpl<AllocaInst *> &NewElts);
Victor Hernandez8acf2952009-10-23 21:09:37 +0000182 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Craig Topperb94011f2013-07-14 04:42:23 +0000183 SmallVectorImpl<AllocaInst *> &NewElts);
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000184 bool ShouldAttemptScalarRepl(AllocaInst *AI);
Chris Lattnerfb41a502003-05-27 15:45:27 +0000185 };
Nadav Rotem465834c2012-07-24 10:51:42 +0000186
Cameron Zwarich4694e692011-01-18 03:53:26 +0000187 // SROA_DT - SROA that uses DominatorTree.
188 struct SROA_DT : public SROA {
Chris Lattner9987a6f2011-01-14 08:13:00 +0000189 static char ID;
190 public:
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000191 SROA_DT(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
192 SROA(T, true, ID, ST, AT, SLT) {
Cameron Zwarich4694e692011-01-18 03:53:26 +0000193 initializeSROA_DTPass(*PassRegistry::getPassRegistry());
Chris Lattner9987a6f2011-01-14 08:13:00 +0000194 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000195
Chris Lattner9987a6f2011-01-14 08:13:00 +0000196 // getAnalysisUsage - This pass does not require any passes, but we know it
197 // will not alter the CFG, so say so.
198 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth73523022014-01-13 13:07:17 +0000199 AU.addRequired<DominatorTreeWrapperPass>();
Chris Lattner9987a6f2011-01-14 08:13:00 +0000200 AU.setPreservesCFG();
201 }
202 };
Nadav Rotem465834c2012-07-24 10:51:42 +0000203
Chris Lattner9987a6f2011-01-14 08:13:00 +0000204 // SROA_SSAUp - SROA that uses SSAUpdater.
205 struct SROA_SSAUp : public SROA {
206 static char ID;
207 public:
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000208 SROA_SSAUp(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
209 SROA(T, false, ID, ST, AT, SLT) {
Chris Lattner9987a6f2011-01-14 08:13:00 +0000210 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
211 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000212
Chris Lattner9987a6f2011-01-14 08:13:00 +0000213 // getAnalysisUsage - This pass does not require any passes, but we know it
214 // will not alter the CFG, so say so.
215 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
216 AU.setPreservesCFG();
217 }
218 };
Nadav Rotem465834c2012-07-24 10:51:42 +0000219
Chris Lattnerfb41a502003-05-27 15:45:27 +0000220}
221
Cameron Zwarich4694e692011-01-18 03:53:26 +0000222char SROA_DT::ID = 0;
Chris Lattner9987a6f2011-01-14 08:13:00 +0000223char SROA_SSAUp::ID = 0;
224
Cameron Zwarich4694e692011-01-18 03:53:26 +0000225INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
226 "Scalar Replacement of Aggregates (DT)", false, false)
Chandler Carruth73523022014-01-13 13:07:17 +0000227INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Cameron Zwarich4694e692011-01-18 03:53:26 +0000228INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
229 "Scalar Replacement of Aggregates (DT)", false, false)
Chris Lattner9987a6f2011-01-14 08:13:00 +0000230
231INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
232 "Scalar Replacement of Aggregates (SSAUp)", false, false)
233INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
234 "Scalar Replacement of Aggregates (SSAUp)", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000235
Brian Gaeke960707c2003-11-11 22:41:34 +0000236// Public interface to the ScalarReplAggregates pass
Chris Lattner9987a6f2011-01-14 08:13:00 +0000237FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000238 bool UseDomTree,
239 int StructMemberThreshold,
240 int ArrayElementThreshold,
241 int ScalarLoadThreshold) {
Cameron Zwarich4694e692011-01-18 03:53:26 +0000242 if (UseDomTree)
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000243 return new SROA_DT(Threshold, StructMemberThreshold, ArrayElementThreshold,
244 ScalarLoadThreshold);
245 return new SROA_SSAUp(Threshold, StructMemberThreshold,
246 ArrayElementThreshold, ScalarLoadThreshold);
Devang Patele8ec7662007-07-09 21:19:23 +0000247}
Chris Lattnerfb41a502003-05-27 15:45:27 +0000248
249
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000250//===----------------------------------------------------------------------===//
251// Convert To Scalar Optimization.
252//===----------------------------------------------------------------------===//
253
254namespace {
Chris Lattnerb7355292010-04-16 00:38:19 +0000255/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
256/// optimization, which scans the uses of an alloca and determines if it can
257/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000258class ConvertToScalarInfo {
Cameron Zwarich63062cc2011-03-16 00:13:35 +0000259 /// AllocaSize - The size of the alloca being considered in bytes.
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000260 unsigned AllocaSize;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000261 const DataLayout &DL;
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000262 unsigned ScalarLoadThreshold;
Bob Wilson328e91b2011-01-13 20:59:44 +0000263
Chris Lattnerbd2d9432010-04-16 02:32:17 +0000264 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnerb7355292010-04-16 00:38:19 +0000265 /// which means that mem2reg can't promote it.
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000266 bool IsNotTrivial;
Bob Wilson328e91b2011-01-13 20:59:44 +0000267
Cameron Zwarich5e9a0be2011-06-13 21:44:35 +0000268 /// ScalarKind - Tracks the kind of alloca being considered for promotion,
269 /// computed based on the uses of the alloca rather than the LLVM type system.
270 enum {
271 Unknown,
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000272
Cameron Zwarich922e4942011-06-13 23:39:23 +0000273 // Accesses via GEPs that are consistent with element access of a vector
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000274 // type. This will not be converted into a vector unless there is a later
275 // access using an actual vector type.
276 ImplicitVector,
277
Cameron Zwarich922e4942011-06-13 23:39:23 +0000278 // Accesses via vector operations and GEPs that are consistent with the
279 // layout of a vector type.
Cameron Zwarich5e9a0be2011-06-13 21:44:35 +0000280 Vector,
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000281
282 // An integer bag-of-bits with bitwise operations for insertion and
283 // extraction. Any combination of types can be converted into this kind
284 // of scalar.
Cameron Zwarich5e9a0be2011-06-13 21:44:35 +0000285 Integer
286 } ScalarKind;
287
Chris Lattnerb7355292010-04-16 00:38:19 +0000288 /// VectorTy - This tracks the type that we should promote the vector to if
289 /// it is possible to turn it into a vector. This starts out null, and if it
290 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Chris Lattner229907c2011-07-18 04:54:35 +0000291 VectorType *VectorTy;
Bob Wilson328e91b2011-01-13 20:59:44 +0000292
Nadav Rotem465834c2012-07-24 10:51:42 +0000293 /// HadNonMemTransferAccess - True if there is at least one access to the
Cameron Zwarich7599b102011-03-16 08:13:42 +0000294 /// alloca that is not a MemTransferInst. We don't want to turn structs into
295 /// large integers unless there is some potential for optimization.
Cameron Zwarich04542532011-03-16 00:13:44 +0000296 bool HadNonMemTransferAccess;
297
Pete Cooper33ee6c92012-06-17 03:58:26 +0000298 /// HadDynamicAccess - True if some element of this alloca was dynamic.
299 /// We don't yet have support for turning a dynamic access into a large
300 /// integer.
301 bool HadDynamicAccess;
302
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000303public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000304 explicit ConvertToScalarInfo(unsigned Size, const DataLayout &DL,
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000305 unsigned SLT)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000306 : AllocaSize(Size), DL(DL), ScalarLoadThreshold(SLT), IsNotTrivial(false),
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000307 ScalarKind(Unknown), VectorTy(0), HadNonMemTransferAccess(false),
308 HadDynamicAccess(false) { }
Bob Wilson328e91b2011-01-13 20:59:44 +0000309
Chris Lattnerb7355292010-04-16 00:38:19 +0000310 AllocaInst *TryConvert(AllocaInst *AI);
Bob Wilson328e91b2011-01-13 20:59:44 +0000311
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000312private:
Pete Cooper33ee6c92012-06-17 03:58:26 +0000313 bool CanConvertToScalar(Value *V, uint64_t Offset, Value* NonConstantIdx);
Chris Lattner229907c2011-07-18 04:54:35 +0000314 void MergeInTypeForLoadOrStore(Type *In, uint64_t Offset);
315 bool MergeInVectorType(VectorType *VInTy, uint64_t Offset);
Pete Cooper33ee6c92012-06-17 03:58:26 +0000316 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset,
317 Value *NonConstantIdx);
Bob Wilson328e91b2011-01-13 20:59:44 +0000318
Chris Lattner229907c2011-07-18 04:54:35 +0000319 Value *ConvertScalar_ExtractValue(Value *NV, Type *ToType,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000320 uint64_t Offset, Value* NonConstantIdx,
321 IRBuilder<> &Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000322 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000323 uint64_t Offset, Value* NonConstantIdx,
324 IRBuilder<> &Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000325};
326} // end anonymous namespace.
327
Chris Lattner34e53612010-09-01 05:14:33 +0000328
Chris Lattnerb7355292010-04-16 00:38:19 +0000329/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
330/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
331/// alloca if possible or null if not.
332AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
333 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
334 // out.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000335 if (!CanConvertToScalar(AI, 0, 0) || !IsNotTrivial)
Chris Lattnerb7355292010-04-16 00:38:19 +0000336 return 0;
Bob Wilson328e91b2011-01-13 20:59:44 +0000337
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000338 // If an alloca has only memset / memcpy uses, it may still have an Unknown
339 // ScalarKind. Treat it as an Integer below.
340 if (ScalarKind == Unknown)
341 ScalarKind = Integer;
342
Cameron Zwarich9601ddb2011-06-18 06:17:51 +0000343 if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
344 ScalarKind = Integer;
345
Chris Lattnerb7355292010-04-16 00:38:19 +0000346 // If we were able to find a vector type that can handle this with
347 // insert/extract elements, and if there was at least one use that had
348 // a vector type, promote this to a vector. We don't want to promote
349 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
350 // we just get a lot of insert/extracts. If at least one vector is
351 // involved, then we probably really do have a union of vector/array.
Chris Lattner229907c2011-07-18 04:54:35 +0000352 Type *NewTy;
Cameron Zwarichb5f19d92011-06-14 06:33:51 +0000353 if (ScalarKind == Vector) {
354 assert(VectorTy && "Missing type for vector scalar.");
Chris Lattnerb7355292010-04-16 00:38:19 +0000355 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
356 << *VectorTy << '\n');
357 NewTy = VectorTy; // Use the vector type.
358 } else {
Cameron Zwarich04542532011-03-16 00:13:44 +0000359 unsigned BitWidth = AllocaSize * 8;
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000360
361 // Do not convert to scalar integer if the alloca size exceeds the
362 // scalar load threshold.
363 if (BitWidth > ScalarLoadThreshold)
364 return 0;
365
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000366 if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000367 !HadNonMemTransferAccess && !DL.fitsInLegalInteger(BitWidth))
Cameron Zwarich04542532011-03-16 00:13:44 +0000368 return 0;
Pete Cooper33ee6c92012-06-17 03:58:26 +0000369 // Dynamic accesses on integers aren't yet supported. They need us to shift
370 // by a dynamic amount which could be difficult to work out as we might not
371 // know whether to use a left or right shift.
372 if (ScalarKind == Integer && HadDynamicAccess)
373 return 0;
Cameron Zwarich04542532011-03-16 00:13:44 +0000374
Chris Lattnerb7355292010-04-16 00:38:19 +0000375 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
376 // Create and insert the integer alloca.
Cameron Zwarich04542532011-03-16 00:13:44 +0000377 NewTy = IntegerType::get(AI->getContext(), BitWidth);
Chris Lattnerb7355292010-04-16 00:38:19 +0000378 }
379 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
Pete Cooper33ee6c92012-06-17 03:58:26 +0000380 ConvertUsesToScalar(AI, NewAI, 0, 0);
Chris Lattnerb7355292010-04-16 00:38:19 +0000381 return NewAI;
382}
383
Cameron Zwarich3ecbd592011-06-13 21:44:43 +0000384/// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
385/// (VectorTy) so far at the offset specified by Offset (which is specified in
386/// bytes).
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000387///
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000388/// There are two cases we handle here:
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000389/// 1) A union of vector types of the same size and potentially its elements.
390/// Here we turn element accesses into insert/extract element operations.
391/// This promotes a <4 x float> with a store of float to the third element
392/// into a <4 x float> that uses insert element.
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000393/// 2) A fully general blob of memory, which we turn into some (potentially
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000394/// large) integer type with extract and insert operations where the loads
Chris Lattnerb7355292010-04-16 00:38:19 +0000395/// and stores would mutate the memory. We mark this by setting VectorTy
396/// to VoidTy.
Chris Lattner229907c2011-07-18 04:54:35 +0000397void ConvertToScalarInfo::MergeInTypeForLoadOrStore(Type *In,
Cameron Zwarich3ecbd592011-06-13 21:44:43 +0000398 uint64_t Offset) {
Chris Lattnerb7355292010-04-16 00:38:19 +0000399 // If we already decided to turn this into a blob of integer memory, there is
400 // nothing to be done.
Cameron Zwarich5e9a0be2011-06-13 21:44:35 +0000401 if (ScalarKind == Integer)
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000402 return;
Bob Wilson328e91b2011-01-13 20:59:44 +0000403
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000404 // If this could be contributing to a vector, analyze it.
405
406 // If the In type is a vector that is the same size as the alloca, see if it
407 // matches the existing VecTy.
Chris Lattner229907c2011-07-18 04:54:35 +0000408 if (VectorType *VInTy = dyn_cast<VectorType>(In)) {
Cameron Zwarich43a241f2011-03-09 05:43:01 +0000409 if (MergeInVectorType(VInTy, Offset))
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000410 return;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000411 } else if (In->isFloatTy() || In->isDoubleTy() ||
412 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
413 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
Cameron Zwarichff811cc2011-03-29 05:19:52 +0000414 // Full width accesses can be ignored, because they can always be turned
415 // into bitcasts.
416 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
Cameron Zwarich8deb6152011-06-13 21:44:31 +0000417 if (EltSize == AllocaSize)
Cameron Zwarichff811cc2011-03-29 05:19:52 +0000418 return;
Cameron Zwarich4cd9a4a2011-04-20 21:48:16 +0000419
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000420 // If we're accessing something that could be an element of a vector, see
421 // if the implied vector agrees with what we already have and if Offset is
422 // compatible with it.
Cameron Zwarich77a699a2011-06-09 01:45:33 +0000423 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000424 (!VectorTy || EltSize == VectorTy->getElementType()
425 ->getPrimitiveSizeInBits()/8)) {
Cameron Zwarich4cd9a4a2011-04-20 21:48:16 +0000426 if (!VectorTy) {
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000427 ScalarKind = ImplicitVector;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000428 VectorTy = VectorType::get(In, AllocaSize/EltSize);
Cameron Zwarich4cd9a4a2011-04-20 21:48:16 +0000429 }
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000430 return;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000431 }
432 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000433
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000434 // Otherwise, we have a case that we can't handle with an optimized vector
435 // form. We can still turn this into a large integer.
Cameron Zwarich5e9a0be2011-06-13 21:44:35 +0000436 ScalarKind = Integer;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000437}
438
Cameron Zwarich3ecbd592011-06-13 21:44:43 +0000439/// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
440/// returning true if the type was successfully merged and false otherwise.
Chris Lattner229907c2011-07-18 04:54:35 +0000441bool ConvertToScalarInfo::MergeInVectorType(VectorType *VInTy,
Cameron Zwarich43a241f2011-03-09 05:43:01 +0000442 uint64_t Offset) {
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000443 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
444 // If we're storing/loading a vector of the right size, allow it as a
445 // vector. If this the first vector we see, remember the type so that
446 // we know the element size. If this is a subsequent access, ignore it
447 // even if it is a differing type but the same size. Worst case we can
448 // bitcast the resultant vectors.
449 if (!VectorTy)
450 VectorTy = VInTy;
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000451 ScalarKind = Vector;
Cameron Zwarich3b649f42011-03-09 05:43:05 +0000452 return true;
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000453 }
Cameron Zwarich3b649f42011-03-09 05:43:05 +0000454
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000455 return false;
Cameron Zwarich43a241f2011-03-09 05:43:01 +0000456}
457
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000458/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
459/// its accesses to a single vector type, return true and set VecTy to
460/// the new type. If we could convert the alloca into a single promotable
461/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
462/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
463/// is the current offset from the base of the alloca being analyzed.
464///
465/// If we see at least one access to the value that is as a vector type, set the
466/// SawVec flag.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000467bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset,
468 Value* NonConstantIdx) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000469 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
470 Instruction *User = cast<Instruction>(*UI);
Bob Wilson328e91b2011-01-13 20:59:44 +0000471
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000472 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
473 // Don't break volatile loads.
Eli Friedman7c5dc122011-09-12 20:23:13 +0000474 if (!LI->isSimple())
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000475 return false;
Dale Johannesendd224d22010-09-30 23:57:10 +0000476 // Don't touch MMX operations.
477 if (LI->getType()->isX86_MMXTy())
478 return false;
Cameron Zwarich04542532011-03-16 00:13:44 +0000479 HadNonMemTransferAccess = true;
Cameron Zwarich3ecbd592011-06-13 21:44:43 +0000480 MergeInTypeForLoadOrStore(LI->getType(), Offset);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000481 continue;
482 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000483
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000484 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
485 // Storing the pointer, not into the value?
Eli Friedman7c5dc122011-09-12 20:23:13 +0000486 if (SI->getOperand(0) == V || !SI->isSimple()) return false;
Dale Johannesendd224d22010-09-30 23:57:10 +0000487 // Don't touch MMX operations.
488 if (SI->getOperand(0)->getType()->isX86_MMXTy())
489 return false;
Cameron Zwarich04542532011-03-16 00:13:44 +0000490 HadNonMemTransferAccess = true;
Cameron Zwarich3ecbd592011-06-13 21:44:43 +0000491 MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000492 continue;
493 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000494
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000495 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Nick Lewycky15e2d902011-07-25 23:14:22 +0000496 if (!onlyUsedByLifetimeMarkers(BCI))
497 IsNotTrivial = true; // Can't be mem2reg'd.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000498 if (!CanConvertToScalar(BCI, Offset, NonConstantIdx))
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000499 return false;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000500 continue;
501 }
502
503 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
504 // If this is a GEP with a variable indices, we can't handle it.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000505 PointerType* PtrTy = dyn_cast<PointerType>(GEP->getPointerOperandType());
506 if (!PtrTy)
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000507 return false;
Bob Wilson328e91b2011-01-13 20:59:44 +0000508
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000509 // Compute the offset that this GEP adds to the pointer.
510 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Pete Cooper33ee6c92012-06-17 03:58:26 +0000511 Value *GEPNonConstantIdx = 0;
512 if (!GEP->hasAllConstantIndices()) {
513 if (!isa<VectorType>(PtrTy->getElementType()))
514 return false;
515 if (NonConstantIdx)
516 return false;
517 GEPNonConstantIdx = Indices.pop_back_val();
518 if (!GEPNonConstantIdx->getType()->isIntegerTy(32))
519 return false;
520 HadDynamicAccess = true;
521 } else
522 GEPNonConstantIdx = NonConstantIdx;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000523 uint64_t GEPOffset = DL.getIndexedOffset(PtrTy,
Jay Foadbf904772011-07-19 14:01:37 +0000524 Indices);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000525 // See if all uses can be converted.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000526 if (!CanConvertToScalar(GEP, Offset+GEPOffset, GEPNonConstantIdx))
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000527 return false;
Chris Lattnerb7355292010-04-16 00:38:19 +0000528 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich04542532011-03-16 00:13:44 +0000529 HadNonMemTransferAccess = true;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000530 continue;
531 }
532
533 // If this is a constant sized memset of a constant value (e.g. 0) we can
534 // handle it.
535 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000536 // Store to dynamic index.
537 if (NonConstantIdx)
538 return false;
Cameron Zwarich2a261002011-06-18 05:47:49 +0000539 // Store of constant value.
540 if (!isa<ConstantInt>(MSI->getValue()))
Chris Lattnerb7355292010-04-16 00:38:19 +0000541 return false;
Cameron Zwarich2a261002011-06-18 05:47:49 +0000542
543 // Store of constant size.
544 ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
545 if (!Len)
546 return false;
547
548 // If the size differs from the alloca, we can only convert the alloca to
549 // an integer bag-of-bits.
550 // FIXME: This should handle all of the cases that are currently accepted
551 // as vector element insertions.
552 if (Len->getZExtValue() != AllocaSize || Offset != 0)
553 ScalarKind = Integer;
554
Chris Lattnerb7355292010-04-16 00:38:19 +0000555 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich04542532011-03-16 00:13:44 +0000556 HadNonMemTransferAccess = true;
Chris Lattnerb7355292010-04-16 00:38:19 +0000557 continue;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000558 }
559
560 // If this is a memcpy or memmove into or out of the whole allocation, we
561 // can handle it like a load or store of the scalar type.
562 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000563 // Store to dynamic index.
564 if (NonConstantIdx)
565 return false;
Chris Lattnerb7355292010-04-16 00:38:19 +0000566 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
567 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
568 return false;
Bob Wilson328e91b2011-01-13 20:59:44 +0000569
Chris Lattnerb7355292010-04-16 00:38:19 +0000570 IsNotTrivial = true; // Can't be mem2reg'd.
571 continue;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000572 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000573
Nick Lewycky15e2d902011-07-25 23:14:22 +0000574 // If this is a lifetime intrinsic, we can handle it.
575 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
576 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
577 II->getIntrinsicID() == Intrinsic::lifetime_end) {
578 continue;
579 }
580 }
581
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000582 // Otherwise, we cannot handle this!
583 return false;
584 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000585
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000586 return true;
587}
588
589/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
590/// directly. This happens when we are converting an "integer union" to a
591/// single integer scalar, or when we are converting a "vector union" to a
592/// vector with insert/extractelement instructions.
593///
594/// Offset is an offset from the original alloca, in bits that need to be
595/// shifted to the right. By the end of this, there should be no uses of Ptr.
596void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000597 uint64_t Offset,
598 Value* NonConstantIdx) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000599 while (!Ptr->use_empty()) {
600 Instruction *User = cast<Instruction>(Ptr->use_back());
601
602 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000603 ConvertUsesToScalar(CI, NewAI, Offset, NonConstantIdx);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000604 CI->eraseFromParent();
605 continue;
606 }
607
608 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
609 // Compute the offset that this GEP adds to the pointer.
610 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Pete Cooper0deca6b2012-08-10 03:26:36 +0000611 Value* GEPNonConstantIdx = 0;
612 if (!GEP->hasAllConstantIndices()) {
613 assert(!NonConstantIdx &&
614 "Dynamic GEP reading from dynamic GEP unsupported");
615 GEPNonConstantIdx = Indices.pop_back_val();
616 } else
617 GEPNonConstantIdx = NonConstantIdx;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000618 uint64_t GEPOffset = DL.getIndexedOffset(GEP->getPointerOperandType(),
Jay Foadbf904772011-07-19 14:01:37 +0000619 Indices);
Pete Cooper0deca6b2012-08-10 03:26:36 +0000620 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8, GEPNonConstantIdx);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000621 GEP->eraseFromParent();
622 continue;
623 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000624
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000625 IRBuilder<> Builder(User);
Bob Wilson328e91b2011-01-13 20:59:44 +0000626
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000627 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
628 // The load is a bit extract from NewAI shifted right by Offset bits.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000629 Value *LoadedVal = Builder.CreateLoad(NewAI);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000630 Value *NewLoadVal
Pete Cooper33ee6c92012-06-17 03:58:26 +0000631 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset,
632 NonConstantIdx, Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000633 LI->replaceAllUsesWith(NewLoadVal);
634 LI->eraseFromParent();
635 continue;
636 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000637
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000638 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
639 assert(SI->getOperand(0) != Ptr && "Consistency error!");
640 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
641 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000642 NonConstantIdx, Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000643 Builder.CreateStore(New, NewAI);
644 SI->eraseFromParent();
Bob Wilson328e91b2011-01-13 20:59:44 +0000645
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000646 // If the load we just inserted is now dead, then the inserted store
647 // overwrote the entire thing.
648 if (Old->use_empty())
649 Old->eraseFromParent();
650 continue;
651 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000652
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000653 // If this is a constant sized memset of a constant value (e.g. 0) we can
654 // transform it into a store of the expanded constant value.
655 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
656 assert(MSI->getRawDest() == Ptr && "Consistency error!");
Pete Cooper33ee6c92012-06-17 03:58:26 +0000657 assert(!NonConstantIdx && "Cannot replace dynamic memset with insert");
Duncan Sands8f897dc2012-03-23 08:29:04 +0000658 int64_t SNumBytes = cast<ConstantInt>(MSI->getLength())->getSExtValue();
Chris Lattner7d7dba32012-03-22 03:46:58 +0000659 if (SNumBytes > 0 && (SNumBytes >> 32) == 0) {
Aaron Ballmana7332972012-03-15 00:05:31 +0000660 unsigned NumBytes = static_cast<unsigned>(SNumBytes);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000661 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
Bob Wilson328e91b2011-01-13 20:59:44 +0000662
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000663 // Compute the value replicated the right number of times.
664 APInt APVal(NumBytes*8, Val);
665
666 // Splat the value if non-zero.
667 if (Val)
668 for (unsigned i = 1; i != NumBytes; ++i)
669 APVal |= APVal << 8;
Bob Wilson328e91b2011-01-13 20:59:44 +0000670
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000671 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
672 Value *New = ConvertScalar_InsertValue(
673 ConstantInt::get(User->getContext(), APVal),
Pete Cooper33ee6c92012-06-17 03:58:26 +0000674 Old, Offset, 0, Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000675 Builder.CreateStore(New, NewAI);
Bob Wilson328e91b2011-01-13 20:59:44 +0000676
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000677 // If the load we just inserted is now dead, then the memset overwrote
678 // the entire thing.
679 if (Old->use_empty())
Bob Wilson328e91b2011-01-13 20:59:44 +0000680 Old->eraseFromParent();
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000681 }
682 MSI->eraseFromParent();
683 continue;
684 }
685
686 // If this is a memcpy or memmove into or out of the whole allocation, we
687 // can handle it like a load or store of the scalar type.
688 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
689 assert(Offset == 0 && "must be store to start of alloca");
Pete Cooper33ee6c92012-06-17 03:58:26 +0000690 assert(!NonConstantIdx && "Cannot replace dynamic transfer with insert");
Bob Wilson328e91b2011-01-13 20:59:44 +0000691
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000692 // If the source and destination are both to the same alloca, then this is
693 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
694 // as appropriate.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000695 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &DL, 0));
Bob Wilson328e91b2011-01-13 20:59:44 +0000696
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000697 if (GetUnderlyingObject(MTI->getSource(), &DL, 0) != OrigAI) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000698 // Dest must be OrigAI, change this to be a load from the original
699 // pointer (bitcasted), then a store to our new alloca.
700 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
701 Value *SrcPtr = MTI->getSource();
Chris Lattner229907c2011-07-18 04:54:35 +0000702 PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
703 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
Mon P Wang18b762a2010-12-23 01:41:32 +0000704 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
705 AIPTy = PointerType::get(AIPTy->getElementType(),
706 SPTy->getAddressSpace());
707 }
708 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
709
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000710 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
711 SrcVal->setAlignment(MTI->getAlignment());
712 Builder.CreateStore(SrcVal, NewAI);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000713 } else if (GetUnderlyingObject(MTI->getDest(), &DL, 0) != OrigAI) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000714 // Src must be OrigAI, change this to be a load from NewAI then a store
715 // through the original dest pointer (bitcasted).
716 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
717 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
718
Chris Lattner229907c2011-07-18 04:54:35 +0000719 PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
720 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
Mon P Wang18b762a2010-12-23 01:41:32 +0000721 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
722 AIPTy = PointerType::get(AIPTy->getElementType(),
723 DPTy->getAddressSpace());
724 }
725 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
726
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000727 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
728 NewStore->setAlignment(MTI->getAlignment());
729 } else {
730 // Noop transfer. Src == Dst
731 }
732
733 MTI->eraseFromParent();
734 continue;
735 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000736
Nick Lewycky15e2d902011-07-25 23:14:22 +0000737 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
738 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
739 II->getIntrinsicID() == Intrinsic::lifetime_end) {
740 // There's no need to preserve these, as the resulting alloca will be
741 // converted to a register anyways.
742 II->eraseFromParent();
743 continue;
744 }
745 }
746
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000747 llvm_unreachable("Unsupported operation!");
748 }
749}
750
751/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
752/// or vector value FromVal, extracting the bits from the offset specified by
753/// Offset. This returns the value, which is of type ToType.
754///
755/// This happens when we are converting an "integer union" to a single
756/// integer scalar, or when we are converting a "vector union" to a vector with
757/// insert/extractelement instructions.
758///
759/// Offset is an offset from the original alloca, in bits that need to be
760/// shifted to the right.
761Value *ConvertToScalarInfo::
Chris Lattner229907c2011-07-18 04:54:35 +0000762ConvertScalar_ExtractValue(Value *FromVal, Type *ToType,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000763 uint64_t Offset, Value* NonConstantIdx,
764 IRBuilder<> &Builder) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000765 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattner229907c2011-07-18 04:54:35 +0000766 Type *FromType = FromVal->getType();
Mon P Wang2e5528f2011-04-13 21:40:02 +0000767 if (FromType == ToType && Offset == 0)
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000768 return FromVal;
769
770 // If the result alloca is a vector type, this is either an element
771 // access or a bitcast to another vector type of the same size.
Chris Lattner229907c2011-07-18 04:54:35 +0000772 if (VectorType *VTy = dyn_cast<VectorType>(FromType)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000773 unsigned FromTypeSize = DL.getTypeAllocSize(FromType);
774 unsigned ToTypeSize = DL.getTypeAllocSize(ToType);
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000775 if (FromTypeSize == ToTypeSize)
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000776 return Builder.CreateBitCast(FromVal, ToType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000777
778 // Otherwise it must be an element access.
779 unsigned Elt = 0;
780 if (Offset) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000781 unsigned EltSize = DL.getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000782 Elt = Offset/EltSize;
783 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
784 }
785 // Return the element extracted out of it.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000786 Value *Idx;
787 if (NonConstantIdx) {
788 if (Elt)
789 Idx = Builder.CreateAdd(NonConstantIdx,
790 Builder.getInt32(Elt),
791 "dyn.offset");
792 else
793 Idx = NonConstantIdx;
794 } else
795 Idx = Builder.getInt32(Elt);
796 Value *V = Builder.CreateExtractElement(FromVal, Idx);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000797 if (V->getType() != ToType)
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000798 V = Builder.CreateBitCast(V, ToType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000799 return V;
800 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000801
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000802 // If ToType is a first class aggregate, extract out each of the pieces and
803 // use insertvalue's to form the FCA.
Chris Lattner229907c2011-07-18 04:54:35 +0000804 if (StructType *ST = dyn_cast<StructType>(ToType)) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000805 assert(!NonConstantIdx &&
806 "Dynamic indexing into struct types not supported");
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000807 const StructLayout &Layout = *DL.getStructLayout(ST);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000808 Value *Res = UndefValue::get(ST);
809 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
810 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
811 Offset+Layout.getElementOffsetInBits(i),
Pete Cooper33ee6c92012-06-17 03:58:26 +0000812 0, Builder);
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000813 Res = Builder.CreateInsertValue(Res, Elt, i);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000814 }
815 return Res;
816 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000817
Chris Lattner229907c2011-07-18 04:54:35 +0000818 if (ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000819 assert(!NonConstantIdx &&
820 "Dynamic indexing into array types not supported");
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000821 uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000822 Value *Res = UndefValue::get(AT);
823 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
824 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
Pete Cooper33ee6c92012-06-17 03:58:26 +0000825 Offset+i*EltSize, 0, Builder);
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000826 Res = Builder.CreateInsertValue(Res, Elt, i);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000827 }
828 return Res;
829 }
830
831 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattner229907c2011-07-18 04:54:35 +0000832 IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000833
834 // If this is a big-endian system and the load is narrower than the
835 // full alloca type, we need to do a shift to get the right bits.
836 int ShAmt = 0;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000837 if (DL.isBigEndian()) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000838 // On big-endian machines, the lowest bit is stored at the bit offset
839 // from the pointer given by getTypeStoreSizeInBits. This matters for
840 // integers with a bitwidth that is not a multiple of 8.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000841 ShAmt = DL.getTypeStoreSizeInBits(NTy) -
842 DL.getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000843 } else {
844 ShAmt = Offset;
845 }
846
847 // Note: we support negative bitwidths (with shl) which are not defined.
848 // We do this to support (f.e.) loads off the end of a structure where
849 // only some bits are used.
850 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
851 FromVal = Builder.CreateLShr(FromVal,
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000852 ConstantInt::get(FromVal->getType(), ShAmt));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000853 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Bob Wilson328e91b2011-01-13 20:59:44 +0000854 FromVal = Builder.CreateShl(FromVal,
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000855 ConstantInt::get(FromVal->getType(), -ShAmt));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000856
857 // Finally, unconditionally truncate the integer to the right width.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000858 unsigned LIBitWidth = DL.getTypeSizeInBits(ToType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000859 if (LIBitWidth < NTy->getBitWidth())
860 FromVal =
Bob Wilson328e91b2011-01-13 20:59:44 +0000861 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000862 LIBitWidth));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000863 else if (LIBitWidth > NTy->getBitWidth())
864 FromVal =
Bob Wilson328e91b2011-01-13 20:59:44 +0000865 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000866 LIBitWidth));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000867
868 // If the result is an integer, this is a trunc or bitcast.
869 if (ToType->isIntegerTy()) {
870 // Should be done.
871 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
872 // Just do a bitcast, we know the sizes match up.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000873 FromVal = Builder.CreateBitCast(FromVal, ToType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000874 } else {
875 // Otherwise must be a pointer.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000876 FromVal = Builder.CreateIntToPtr(FromVal, ToType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000877 }
878 assert(FromVal->getType() == ToType && "Didn't convert right?");
879 return FromVal;
880}
881
882/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
883/// or vector value "Old" at the offset specified by Offset.
884///
885/// This happens when we are converting an "integer union" to a
886/// single integer scalar, or when we are converting a "vector union" to a
887/// vector with insert/extractelement instructions.
888///
889/// Offset is an offset from the original alloca, in bits that need to be
890/// shifted to the right.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000891///
892/// NonConstantIdx is an index value if there was a GEP with a non-constant
893/// index value. If this is 0 then all GEPs used to find this insert address
894/// are constant.
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000895Value *ConvertToScalarInfo::
896ConvertScalar_InsertValue(Value *SV, Value *Old,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000897 uint64_t Offset, Value* NonConstantIdx,
898 IRBuilder<> &Builder) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000899 // Convert the stored type to the actual type, shift it left to insert
900 // then 'or' into place.
Chris Lattner229907c2011-07-18 04:54:35 +0000901 Type *AllocaType = Old->getType();
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000902 LLVMContext &Context = Old->getContext();
903
Chris Lattner229907c2011-07-18 04:54:35 +0000904 if (VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000905 uint64_t VecSize = DL.getTypeAllocSizeInBits(VTy);
906 uint64_t ValSize = DL.getTypeAllocSizeInBits(SV->getType());
Bob Wilson328e91b2011-01-13 20:59:44 +0000907
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000908 // Changing the whole vector with memset or with an access of a different
909 // vector type?
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000910 if (ValSize == VecSize)
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000911 return Builder.CreateBitCast(SV, AllocaType);
Cameron Zwarich3b649f42011-03-09 05:43:05 +0000912
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000913 // Must be an element insertion.
Cameron Zwarich057fbb12011-10-23 07:02:10 +0000914 Type *EltTy = VTy->getElementType();
915 if (SV->getType() != EltTy)
916 SV = Builder.CreateBitCast(SV, EltTy);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000917 uint64_t EltSize = DL.getTypeAllocSizeInBits(EltTy);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000918 unsigned Elt = Offset/EltSize;
Pete Cooper33ee6c92012-06-17 03:58:26 +0000919 Value *Idx;
920 if (NonConstantIdx) {
921 if (Elt)
922 Idx = Builder.CreateAdd(NonConstantIdx,
923 Builder.getInt32(Elt),
924 "dyn.offset");
925 else
926 Idx = NonConstantIdx;
927 } else
928 Idx = Builder.getInt32(Elt);
929 return Builder.CreateInsertElement(Old, SV, Idx);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000930 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000931
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000932 // If SV is a first-class aggregate value, insert each value recursively.
Chris Lattner229907c2011-07-18 04:54:35 +0000933 if (StructType *ST = dyn_cast<StructType>(SV->getType())) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000934 assert(!NonConstantIdx &&
935 "Dynamic indexing into struct types not supported");
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000936 const StructLayout &Layout = *DL.getStructLayout(ST);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000937 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000938 Value *Elt = Builder.CreateExtractValue(SV, i);
Bob Wilson328e91b2011-01-13 20:59:44 +0000939 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000940 Offset+Layout.getElementOffsetInBits(i),
Pete Cooper33ee6c92012-06-17 03:58:26 +0000941 0, Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000942 }
943 return Old;
944 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000945
Chris Lattner229907c2011-07-18 04:54:35 +0000946 if (ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000947 assert(!NonConstantIdx &&
948 "Dynamic indexing into array types not supported");
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000949 uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000950 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000951 Value *Elt = Builder.CreateExtractValue(SV, i);
Pete Cooper33ee6c92012-06-17 03:58:26 +0000952 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, 0, Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000953 }
954 return Old;
955 }
956
957 // If SV is a float, convert it to the appropriate integer type.
958 // If it is a pointer, do the same.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000959 unsigned SrcWidth = DL.getTypeSizeInBits(SV->getType());
960 unsigned DestWidth = DL.getTypeSizeInBits(AllocaType);
961 unsigned SrcStoreWidth = DL.getTypeStoreSizeInBits(SV->getType());
962 unsigned DestStoreWidth = DL.getTypeStoreSizeInBits(AllocaType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000963 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000964 SV = Builder.CreateBitCast(SV, IntegerType::get(SV->getContext(),SrcWidth));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000965 else if (SV->getType()->isPointerTy())
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000966 SV = Builder.CreatePtrToInt(SV, DL.getIntPtrType(SV->getType()));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000967
968 // Zero extend or truncate the value if needed.
969 if (SV->getType() != AllocaType) {
970 if (SV->getType()->getPrimitiveSizeInBits() <
971 AllocaType->getPrimitiveSizeInBits())
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000972 SV = Builder.CreateZExt(SV, AllocaType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000973 else {
974 // Truncation may be needed if storing more than the alloca can hold
975 // (undefined behavior).
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000976 SV = Builder.CreateTrunc(SV, AllocaType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000977 SrcWidth = DestWidth;
978 SrcStoreWidth = DestStoreWidth;
979 }
980 }
981
982 // If this is a big-endian system and the store is narrower than the
983 // full alloca type, we need to do a shift to get the right bits.
984 int ShAmt = 0;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000985 if (DL.isBigEndian()) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000986 // On big-endian machines, the lowest bit is stored at the bit offset
987 // from the pointer given by getTypeStoreSizeInBits. This matters for
988 // integers with a bitwidth that is not a multiple of 8.
989 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
990 } else {
991 ShAmt = Offset;
992 }
993
994 // Note: we support negative bitwidths (with shr) which are not defined.
995 // We do this to support (f.e.) stores off the end of a structure where
996 // only some bits in the structure are set.
997 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
998 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000999 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt));
Chris Lattner78d7dbb2010-04-16 00:24:57 +00001000 Mask <<= ShAmt;
1001 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001002 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt));
Chris Lattner78d7dbb2010-04-16 00:24:57 +00001003 Mask = Mask.lshr(-ShAmt);
1004 }
1005
1006 // Mask out the bits we are about to insert from the old value, and or
1007 // in the new bits.
1008 if (SrcWidth != DestWidth) {
1009 assert(DestWidth > SrcWidth);
1010 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1011 SV = Builder.CreateOr(Old, SV, "ins");
1012 }
1013 return SV;
1014}
1015
1016
1017//===----------------------------------------------------------------------===//
1018// SRoA Driver
1019//===----------------------------------------------------------------------===//
1020
1021
Chris Lattnerfb41a502003-05-27 15:45:27 +00001022bool SROA::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00001023 if (skipOptnoneFunction(F))
1024 return false;
1025
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001026 DL = getAnalysisIfAvailable<DataLayout>();
Dan Gohman915302c2009-08-19 18:22:18 +00001027
Chris Lattner9a95f2a2003-09-12 15:36:03 +00001028 bool Changed = performPromotion(F);
Dan Gohman915302c2009-08-19 18:22:18 +00001029
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001030 // FIXME: ScalarRepl currently depends on DataLayout more than it
Dan Gohman915302c2009-08-19 18:22:18 +00001031 // theoretically needs to. It should be refactored in order to support
1032 // target-independent IR. Until this is done, just skip the actual
1033 // scalar-replacement portion of this pass.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001034 if (!DL) return Changed;
Dan Gohman915302c2009-08-19 18:22:18 +00001035
Chris Lattner9a95f2a2003-09-12 15:36:03 +00001036 while (1) {
1037 bool LocalChange = performScalarRepl(F);
1038 if (!LocalChange) break; // No need to repromote if no scalarrepl
1039 Changed = true;
1040 LocalChange = performPromotion(F);
1041 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
1042 }
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001043
1044 return Changed;
1045}
1046
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001047namespace {
1048class AllocaPromoter : public LoadAndStorePromoter {
1049 AllocaInst *AI;
Devang Patela3cbf522011-07-06 21:09:55 +00001050 DIBuilder *DIB;
Devang Patelc6ee9182011-07-06 22:06:11 +00001051 SmallVector<DbgDeclareInst *, 4> DDIs;
1052 SmallVector<DbgValueInst *, 4> DVIs;
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001053public:
Cameron Zwarich843bc7d2011-05-24 03:10:43 +00001054 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
Devang Patela3cbf522011-07-06 21:09:55 +00001055 DIBuilder *DB)
Devang Patelc6ee9182011-07-06 22:06:11 +00001056 : LoadAndStorePromoter(Insts, S), AI(0), DIB(DB) {}
Nadav Rotem465834c2012-07-24 10:51:42 +00001057
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001058 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001059 // Remember which alloca we're promoting (for isInstInList).
1060 this->AI = AI;
Rafael Espindola2b14b802011-12-26 23:12:42 +00001061 if (MDNode *DebugNode = MDNode::getIfExists(AI->getContext(), AI)) {
Devang Patelc6ee9182011-07-06 22:06:11 +00001062 for (Value::use_iterator UI = DebugNode->use_begin(),
1063 E = DebugNode->use_end(); UI != E; ++UI)
1064 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1065 DDIs.push_back(DDI);
1066 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1067 DVIs.push_back(DVI);
Rafael Espindola2b14b802011-12-26 23:12:42 +00001068 }
Devang Patelc6ee9182011-07-06 22:06:11 +00001069
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001070 LoadAndStorePromoter::run(Insts);
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001071 AI->eraseFromParent();
Craig Topper31ee5862013-07-03 15:07:05 +00001072 for (SmallVectorImpl<DbgDeclareInst *>::iterator I = DDIs.begin(),
Devang Patelc6ee9182011-07-06 22:06:11 +00001073 E = DDIs.end(); I != E; ++I) {
1074 DbgDeclareInst *DDI = *I;
Devang Patela3cbf522011-07-06 21:09:55 +00001075 DDI->eraseFromParent();
Devang Patelc6ee9182011-07-06 22:06:11 +00001076 }
Craig Topper31ee5862013-07-03 15:07:05 +00001077 for (SmallVectorImpl<DbgValueInst *>::iterator I = DVIs.begin(),
Devang Patelc6ee9182011-07-06 22:06:11 +00001078 E = DVIs.end(); I != E; ++I) {
1079 DbgValueInst *DVI = *I;
1080 DVI->eraseFromParent();
1081 }
Chris Lattner543384e2011-01-14 07:50:47 +00001082 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001083
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001084 virtual bool isInstInList(Instruction *I,
1085 const SmallVectorImpl<Instruction*> &Insts) const {
1086 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1087 return LI->getOperand(0) == AI;
1088 return cast<StoreInst>(I)->getPointerOperand() == AI;
Chris Lattner543384e2011-01-14 07:50:47 +00001089 }
Devang Patela3cbf522011-07-06 21:09:55 +00001090
Devang Patelc6ee9182011-07-06 22:06:11 +00001091 virtual void updateDebugInfo(Instruction *Inst) const {
Craig Topper31ee5862013-07-03 15:07:05 +00001092 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
Devang Patelc6ee9182011-07-06 22:06:11 +00001093 E = DDIs.end(); I != E; ++I) {
1094 DbgDeclareInst *DDI = *I;
1095 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1096 ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
1097 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1098 ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
1099 }
Craig Topper31ee5862013-07-03 15:07:05 +00001100 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
Devang Patelc6ee9182011-07-06 22:06:11 +00001101 E = DVIs.end(); I != E; ++I) {
1102 DbgValueInst *DVI = *I;
Benjamin Kramer077e5522012-02-23 17:42:19 +00001103 Value *Arg = NULL;
Devang Patelc6ee9182011-07-06 22:06:11 +00001104 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Devang Patelc6ee9182011-07-06 22:06:11 +00001105 // If an argument is zero extended then use argument directly. The ZExt
1106 // may be zapped by an optimization pass in future.
Devang Patelc6ee9182011-07-06 22:06:11 +00001107 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
Benjamin Kramer077e5522012-02-23 17:42:19 +00001108 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Devang Patelc6ee9182011-07-06 22:06:11 +00001109 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Benjamin Kramer077e5522012-02-23 17:42:19 +00001110 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1111 if (!Arg)
1112 Arg = SI->getOperand(0);
Devang Patelc6ee9182011-07-06 22:06:11 +00001113 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Benjamin Kramer077e5522012-02-23 17:42:19 +00001114 Arg = LI->getOperand(0);
1115 } else {
1116 continue;
Devang Patelc6ee9182011-07-06 22:06:11 +00001117 }
Benjamin Kramer077e5522012-02-23 17:42:19 +00001118 Instruction *DbgVal =
1119 DIB->insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1120 Inst);
1121 DbgVal->setDebugLoc(DVI->getDebugLoc());
Devang Patelc6ee9182011-07-06 22:06:11 +00001122 }
Devang Patela3cbf522011-07-06 21:09:55 +00001123 }
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001124};
1125} // end anon namespace
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001126
Chris Lattnera9607252011-01-23 22:04:55 +00001127/// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1128/// subsequently loaded can be rewritten to load both input pointers and then
1129/// select between the result, allowing the load of the alloca to be promoted.
1130/// From this:
1131/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1132/// %V = load i32* %P2
1133/// to:
1134/// %V1 = load i32* %Alloca -> will be mem2reg'd
1135/// %V2 = load i32* %Other
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001136/// %V = select i1 %cond, i32 %V1, i32 %V2
Chris Lattnera9607252011-01-23 22:04:55 +00001137///
1138/// We can do this to a select if its only uses are loads and if the operand to
1139/// the select can be loaded unconditionally.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001140static bool isSafeSelectToSpeculate(SelectInst *SI, const DataLayout *DL) {
Chris Lattnera9607252011-01-23 22:04:55 +00001141 bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
1142 bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
Nadav Rotem465834c2012-07-24 10:51:42 +00001143
Chris Lattnera9607252011-01-23 22:04:55 +00001144 for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
1145 UI != UE; ++UI) {
1146 LoadInst *LI = dyn_cast<LoadInst>(*UI);
Eli Friedman7c5dc122011-09-12 20:23:13 +00001147 if (LI == 0 || !LI->isSimple()) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001148
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001149 // Both operands to the select need to be dereferencable, either absolutely
Chris Lattnera9607252011-01-23 22:04:55 +00001150 // (e.g. allocas) or at this point because we can see other accesses to it.
1151 if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001152 LI->getAlignment(), DL))
Chris Lattnera9607252011-01-23 22:04:55 +00001153 return false;
1154 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001155 LI->getAlignment(), DL))
Chris Lattnera9607252011-01-23 22:04:55 +00001156 return false;
1157 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001158
Chris Lattnera9607252011-01-23 22:04:55 +00001159 return true;
1160}
1161
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001162/// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1163/// subsequently loaded can be rewritten to load both input pointers in the pred
1164/// blocks and then PHI the results, allowing the load of the alloca to be
1165/// promoted.
1166/// From this:
1167/// %P2 = phi [i32* %Alloca, i32* %Other]
1168/// %V = load i32* %P2
1169/// to:
1170/// %V1 = load i32* %Alloca -> will be mem2reg'd
1171/// ...
1172/// %V2 = load i32* %Other
1173/// ...
1174/// %V = phi [i32 %V1, i32 %V2]
1175///
1176/// We can do this to a select if its only uses are loads and if the operand to
1177/// the select can be loaded unconditionally.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001178static bool isSafePHIToSpeculate(PHINode *PN, const DataLayout *DL) {
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001179 // For now, we can only do this promotion if the load is in the same block as
1180 // the PHI, and if there are no stores between the phi and load.
1181 // TODO: Allow recursive phi users.
1182 // TODO: Allow stores.
1183 BasicBlock *BB = PN->getParent();
1184 unsigned MaxAlign = 0;
1185 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1186 UI != UE; ++UI) {
1187 LoadInst *LI = dyn_cast<LoadInst>(*UI);
Eli Friedman7c5dc122011-09-12 20:23:13 +00001188 if (LI == 0 || !LI->isSimple()) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001189
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001190 // For now we only allow loads in the same block as the PHI. This is a
1191 // common case that happens when instcombine merges two loads through a PHI.
1192 if (LI->getParent() != BB) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001193
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001194 // Ensure that there are no instructions between the PHI and the load that
1195 // could store.
1196 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1197 if (BBI->mayWriteToMemory())
1198 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001199
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001200 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1201 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001202
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001203 // Okay, we know that we have one or more loads in the same block as the PHI.
1204 // We can transform this if it is safe to push the loads into the predecessor
1205 // blocks. The only thing to watch out for is that we can't put a possibly
1206 // trapping load in the predecessor if it is a critical edge.
1207 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1208 BasicBlock *Pred = PN->getIncomingBlock(i);
Eli Friedmanf9b785f2011-09-22 18:56:30 +00001209 Value *InVal = PN->getIncomingValue(i);
1210
1211 // If the terminator of the predecessor has side-effects (an invoke),
1212 // there is no safe place to put a load in the predecessor.
1213 if (Pred->getTerminator()->mayHaveSideEffects())
1214 return false;
1215
1216 // If the value is produced by the terminator of the predecessor
1217 // (an invoke), there is no valid place to put a load in the predecessor.
1218 if (Pred->getTerminator() == InVal)
1219 return false;
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001220
1221 // If the predecessor has a single successor, then the edge isn't critical.
1222 if (Pred->getTerminator()->getNumSuccessors() == 1)
1223 continue;
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001224
1225 // If this pointer is always safe to load, or if we can prove that there is
1226 // already a load in the block, then we can move the load to the pred block.
1227 if (InVal->isDereferenceablePointer() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001228 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, DL))
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001229 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00001230
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001231 return false;
1232 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001233
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001234 return true;
1235}
1236
Chris Lattnera9607252011-01-23 22:04:55 +00001237
1238/// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1239/// direct (non-volatile) loads and stores to it. If the alloca is close but
1240/// not quite there, this will transform the code to allow promotion. As such,
1241/// it is a non-pure predicate.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001242static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const DataLayout *DL) {
Chris Lattnera9607252011-01-23 22:04:55 +00001243 SetVector<Instruction*, SmallVector<Instruction*, 4>,
1244 SmallPtrSet<Instruction*, 4> > InstsToRewrite;
Nadav Rotem465834c2012-07-24 10:51:42 +00001245
Chris Lattnera9607252011-01-23 22:04:55 +00001246 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
1247 UI != UE; ++UI) {
1248 User *U = *UI;
1249 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Eli Friedman7c5dc122011-09-12 20:23:13 +00001250 if (!LI->isSimple())
Chris Lattnera9607252011-01-23 22:04:55 +00001251 return false;
1252 continue;
1253 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001254
Chris Lattnera9607252011-01-23 22:04:55 +00001255 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Eli Friedman7c5dc122011-09-12 20:23:13 +00001256 if (SI->getOperand(0) == AI || !SI->isSimple())
Chris Lattnera9607252011-01-23 22:04:55 +00001257 return false; // Don't allow a store OF the AI, only INTO the AI.
1258 continue;
1259 }
1260
1261 if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1262 // If the condition being selected on is a constant, fold the select, yes
1263 // this does (rarely) happen early on.
1264 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1265 Value *Result = SI->getOperand(1+CI->isZero());
1266 SI->replaceAllUsesWith(Result);
1267 SI->eraseFromParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001268
Chris Lattnera9607252011-01-23 22:04:55 +00001269 // This is very rare and we just scrambled the use list of AI, start
1270 // over completely.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001271 return tryToMakeAllocaBePromotable(AI, DL);
Chris Lattnera9607252011-01-23 22:04:55 +00001272 }
1273
1274 // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1275 // loads, then we can transform this by rewriting the select.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001276 if (!isSafeSelectToSpeculate(SI, DL))
Chris Lattnera9607252011-01-23 22:04:55 +00001277 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001278
Chris Lattnera9607252011-01-23 22:04:55 +00001279 InstsToRewrite.insert(SI);
1280 continue;
1281 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001282
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001283 if (PHINode *PN = dyn_cast<PHINode>(U)) {
1284 if (PN->use_empty()) { // Dead PHIs can be stripped.
1285 InstsToRewrite.insert(PN);
1286 continue;
1287 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001288
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001289 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1290 // in the pred blocks, then we can transform this by rewriting the PHI.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001291 if (!isSafePHIToSpeculate(PN, DL))
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001292 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001293
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001294 InstsToRewrite.insert(PN);
1295 continue;
1296 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001297
Nick Lewycky15e2d902011-07-25 23:14:22 +00001298 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1299 if (onlyUsedByLifetimeMarkers(BCI)) {
1300 InstsToRewrite.insert(BCI);
1301 continue;
1302 }
1303 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001304
Chris Lattnera9607252011-01-23 22:04:55 +00001305 return false;
1306 }
1307
1308 // If there are no instructions to rewrite, then all uses are load/stores and
1309 // we're done!
1310 if (InstsToRewrite.empty())
1311 return true;
Nadav Rotem465834c2012-07-24 10:51:42 +00001312
Chris Lattnera9607252011-01-23 22:04:55 +00001313 // If we have instructions that need to be rewritten for this to be promotable
1314 // take care of it now.
1315 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
Nick Lewycky15e2d902011-07-25 23:14:22 +00001316 if (BitCastInst *BCI = dyn_cast<BitCastInst>(InstsToRewrite[i])) {
1317 // This could only be a bitcast used by nothing but lifetime intrinsics.
1318 for (BitCastInst::use_iterator I = BCI->use_begin(), E = BCI->use_end();
1319 I != E;) {
1320 Use &U = I.getUse();
1321 ++I;
1322 cast<Instruction>(U.getUser())->eraseFromParent();
1323 }
1324 BCI->eraseFromParent();
1325 continue;
1326 }
1327
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001328 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1329 // Selects in InstsToRewrite only have load uses. Rewrite each as two
1330 // loads with a new select.
1331 while (!SI->use_empty()) {
1332 LoadInst *LI = cast<LoadInst>(SI->use_back());
Nadav Rotem465834c2012-07-24 10:51:42 +00001333
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001334 IRBuilder<> Builder(LI);
Nadav Rotem465834c2012-07-24 10:51:42 +00001335 LoadInst *TrueLoad =
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001336 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
Nadav Rotem465834c2012-07-24 10:51:42 +00001337 LoadInst *FalseLoad =
Nick Lewyckyf64a3972011-07-01 06:27:03 +00001338 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".f");
Nadav Rotem465834c2012-07-24 10:51:42 +00001339
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001340 // Transfer alignment and TBAA info if present.
1341 TrueLoad->setAlignment(LI->getAlignment());
1342 FalseLoad->setAlignment(LI->getAlignment());
1343 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1344 TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1345 FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1346 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001347
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001348 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1349 V->takeName(LI);
1350 LI->replaceAllUsesWith(V);
1351 LI->eraseFromParent();
Chris Lattnera9607252011-01-23 22:04:55 +00001352 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001353
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001354 // Now that all the loads are gone, the select is gone too.
1355 SI->eraseFromParent();
1356 continue;
1357 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001358
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001359 // Otherwise, we have a PHI node which allows us to push the loads into the
1360 // predecessors.
1361 PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1362 if (PN->use_empty()) {
1363 PN->eraseFromParent();
1364 continue;
1365 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001366
Chris Lattner229907c2011-07-18 04:54:35 +00001367 Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
Jay Foad52131342011-03-30 11:28:46 +00001368 PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1369 PN->getName()+".ld", PN);
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001370
1371 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1372 // matter which one we get and if any differ, it doesn't matter.
1373 LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
1374 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1375 unsigned Align = SomeLoad->getAlignment();
Nadav Rotem465834c2012-07-24 10:51:42 +00001376
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001377 // Rewrite all loads of the PN to use the new PHI.
1378 while (!PN->use_empty()) {
1379 LoadInst *LI = cast<LoadInst>(PN->use_back());
1380 LI->replaceAllUsesWith(NewPN);
Chris Lattnera9607252011-01-23 22:04:55 +00001381 LI->eraseFromParent();
1382 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001383
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001384 // Inject loads into all of the pred blocks. Keep track of which blocks we
1385 // insert them into in case we have multiple edges from the same block.
1386 DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
Nadav Rotem465834c2012-07-24 10:51:42 +00001387
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001388 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1389 BasicBlock *Pred = PN->getIncomingBlock(i);
1390 LoadInst *&Load = InsertedLoads[Pred];
1391 if (Load == 0) {
1392 Load = new LoadInst(PN->getIncomingValue(i),
1393 PN->getName() + "." + Pred->getName(),
1394 Pred->getTerminator());
1395 Load->setAlignment(Align);
1396 if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1397 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001398
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001399 NewPN->addIncoming(Load, Pred);
1400 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001401
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001402 PN->eraseFromParent();
Chris Lattnera9607252011-01-23 22:04:55 +00001403 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001404
Chris Lattnera9607252011-01-23 22:04:55 +00001405 ++NumAdjusted;
1406 return true;
1407}
1408
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001409bool SROA::performPromotion(Function &F) {
1410 std::vector<AllocaInst*> Allocas;
Chris Lattner543384e2011-01-14 07:50:47 +00001411 DominatorTree *DT = 0;
Cameron Zwarich4694e692011-01-18 03:53:26 +00001412 if (HasDomTree)
Chandler Carruth73523022014-01-13 13:07:17 +00001413 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001414
Chris Lattner5dac64f2003-09-20 14:39:18 +00001415 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Devang Patela3cbf522011-07-06 21:09:55 +00001416 DIBuilder DIB(*F.getParent());
Chris Lattner9a95f2a2003-09-12 15:36:03 +00001417 bool Changed = false;
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001418 SmallVector<Instruction*, 64> Insts;
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001419 while (1) {
1420 Allocas.clear();
1421
1422 // Find allocas that are safe to promote, by looking at all instructions in
1423 // the entry node
1424 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1425 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001426 if (tryToMakeAllocaBePromotable(AI, DL))
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001427 Allocas.push_back(AI);
1428
1429 if (Allocas.empty()) break;
1430
Cameron Zwarich4694e692011-01-18 03:53:26 +00001431 if (HasDomTree)
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001432 PromoteMemToReg(Allocas, *DT);
Chris Lattner543384e2011-01-14 07:50:47 +00001433 else {
1434 SSAUpdater SSA;
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001435 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1436 AllocaInst *AI = Allocas[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00001437
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001438 // Build list of instructions to promote.
1439 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1440 UI != E; ++UI)
1441 Insts.push_back(cast<Instruction>(*UI));
Devang Patela3cbf522011-07-06 21:09:55 +00001442 AllocaPromoter(Insts, SSA, &DIB).run(AI, Insts);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001443 Insts.clear();
1444 }
Chris Lattner543384e2011-01-14 07:50:47 +00001445 }
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001446 NumPromoted += Allocas.size();
1447 Changed = true;
1448 }
1449
1450 return Changed;
1451}
1452
Chris Lattner78d7dbb2010-04-16 00:24:57 +00001453
Bob Wilson04365c52010-02-03 17:23:56 +00001454/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1455/// SROA. It must be a struct or array type with a small number of elements.
Nadav Rotem4e9012c2012-06-21 13:44:31 +00001456bool SROA::ShouldAttemptScalarRepl(AllocaInst *AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00001457 Type *T = AI->getAllocatedType();
Nadav Rotem4e9012c2012-06-21 13:44:31 +00001458 // Do not promote any struct that has too many members.
Chris Lattner229907c2011-07-18 04:54:35 +00001459 if (StructType *ST = dyn_cast<StructType>(T))
Nadav Rotem4e9012c2012-06-21 13:44:31 +00001460 return ST->getNumElements() <= StructMemberThreshold;
1461 // Do not promote any array that has too many elements.
Chris Lattner229907c2011-07-18 04:54:35 +00001462 if (ArrayType *AT = dyn_cast<ArrayType>(T))
Nadav Rotem4e9012c2012-06-21 13:44:31 +00001463 return AT->getNumElements() <= ArrayElementThreshold;
Bob Wilson04365c52010-02-03 17:23:56 +00001464 return false;
Chris Lattner6ff85682008-06-22 17:46:21 +00001465}
1466
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001467// performScalarRepl - This algorithm is a simple worklist driven algorithm,
Chris Lattner8cf09412013-04-18 17:42:14 +00001468// which runs on all of the alloca instructions in the entry block, removing
1469// them if they are only used by getelementptr instructions.
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001470//
1471bool SROA::performScalarRepl(Function &F) {
Victor Hernandez8acf2952009-10-23 21:09:37 +00001472 std::vector<AllocaInst*> WorkList;
Chris Lattnerfb41a502003-05-27 15:45:27 +00001473
Chris Lattner9c1172d2010-04-15 21:59:20 +00001474 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner5dac64f2003-09-20 14:39:18 +00001475 BasicBlock &BB = F.getEntryBlock();
Chris Lattnerfb41a502003-05-27 15:45:27 +00001476 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez8acf2952009-10-23 21:09:37 +00001477 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnerfb41a502003-05-27 15:45:27 +00001478 WorkList.push_back(A);
1479
1480 // Process the worklist
1481 bool Changed = false;
1482 while (!WorkList.empty()) {
Victor Hernandez8acf2952009-10-23 21:09:37 +00001483 AllocaInst *AI = WorkList.back();
Chris Lattnerfb41a502003-05-27 15:45:27 +00001484 WorkList.pop_back();
Bob Wilson328e91b2011-01-13 20:59:44 +00001485
Chris Lattnerf171af92006-12-22 23:14:42 +00001486 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1487 // with unused elements.
1488 if (AI->use_empty()) {
1489 AI->eraseFromParent();
Chris Lattner9ef4eae2010-04-15 23:50:26 +00001490 Changed = true;
Chris Lattnerf171af92006-12-22 23:14:42 +00001491 continue;
1492 }
Chris Lattner09b65ab2009-02-03 01:30:09 +00001493
1494 // If this alloca is impossible for us to promote, reject it early.
1495 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1496 continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00001497
Chris Lattner09b65ab2009-02-03 01:30:09 +00001498 // Check to see if we can perform the core SROA transformation. We cannot
1499 // transform the allocation instruction if it is an array allocation
1500 // (allocations OF arrays are ok though), and an allocation of a scalar
1501 // value cannot be decomposed at all.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001502 uint64_t AllocaSize = DL->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling3e44bf32009-03-03 12:12:58 +00001503
Nick Lewyckyaa464002009-08-17 05:37:31 +00001504 // Do not promote [0 x %struct].
1505 if (AllocaSize == 0) continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00001506
Chris Lattner9c1172d2010-04-15 21:59:20 +00001507 // Do not promote any struct whose size is too big.
1508 if (AllocaSize > SRThreshold) continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00001509
Bob Wilson04365c52010-02-03 17:23:56 +00001510 // If the alloca looks like a good candidate for scalar replacement, and if
1511 // all its users can be transformed, then split up the aggregate into its
1512 // separate elements.
1513 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1514 DoScalarReplacement(AI, WorkList);
1515 Changed = true;
1516 continue;
1517 }
1518
Chris Lattnerdf179872009-01-28 20:16:43 +00001519 // If we can turn this aggregate value (potentially with casts) into a
1520 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattnerec99c462009-01-31 02:28:54 +00001521 // IsNotTrivial tracks whether this is something that mem2reg could have
1522 // promoted itself. If so, we don't want to transform it needlessly. Note
1523 // that we can't just check based on the type: the alloca may be of an i32
1524 // but that has pointer arithmetic to set byte 3 of it or something.
Nadav Rotem4e9012c2012-06-21 13:44:31 +00001525 if (AllocaInst *NewAI = ConvertToScalarInfo(
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001526 (unsigned)AllocaSize, *DL, ScalarLoadThreshold).TryConvert(AI)) {
Chris Lattner09b65ab2009-02-03 01:30:09 +00001527 NewAI->takeName(AI);
1528 AI->eraseFromParent();
1529 ++NumConverted;
1530 Changed = true;
1531 continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00001532 }
1533
Chris Lattner09b65ab2009-02-03 01:30:09 +00001534 // Otherwise, couldn't process this alloca.
Chris Lattnerfb41a502003-05-27 15:45:27 +00001535 }
1536
1537 return Changed;
1538}
Chris Lattner6e5398d2003-05-30 04:15:41 +00001539
Chris Lattner31e5add2007-04-25 05:02:56 +00001540/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1541/// predicate, do SROA now.
Bob Wilson328e91b2011-01-13 20:59:44 +00001542void SROA::DoScalarReplacement(AllocaInst *AI,
Victor Hernandez8acf2952009-10-23 21:09:37 +00001543 std::vector<AllocaInst*> &WorkList) {
David Greene48c86be2010-01-05 01:27:09 +00001544 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattner31e5add2007-04-25 05:02:56 +00001545 SmallVector<AllocaInst*, 32> ElementAllocas;
Chris Lattner229907c2011-07-18 04:54:35 +00001546 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
Chris Lattner31e5add2007-04-25 05:02:56 +00001547 ElementAllocas.reserve(ST->getNumContainedTypes());
1548 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Bob Wilson328e91b2011-01-13 20:59:44 +00001549 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattner31e5add2007-04-25 05:02:56 +00001550 AI->getAlignment(),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001551 AI->getName() + "." + Twine(i), AI);
Chris Lattner31e5add2007-04-25 05:02:56 +00001552 ElementAllocas.push_back(NA);
1553 WorkList.push_back(NA); // Add to worklist for recursive processing
1554 }
1555 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00001556 ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
Chris Lattner31e5add2007-04-25 05:02:56 +00001557 ElementAllocas.reserve(AT->getNumElements());
Chris Lattner229907c2011-07-18 04:54:35 +00001558 Type *ElTy = AT->getElementType();
Chris Lattner31e5add2007-04-25 05:02:56 +00001559 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson4fdeba92009-07-15 23:53:25 +00001560 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001561 AI->getName() + "." + Twine(i), AI);
Chris Lattner31e5add2007-04-25 05:02:56 +00001562 ElementAllocas.push_back(NA);
1563 WorkList.push_back(NA); // Add to worklist for recursive processing
1564 }
1565 }
1566
Bob Wilson532cd232009-12-18 20:14:40 +00001567 // Now that we have created the new alloca instructions, rewrite all the
1568 // uses of the old alloca.
1569 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattneraaa6ac12009-12-14 05:11:02 +00001570
Bob Wilson532cd232009-12-18 20:14:40 +00001571 // Now erase any instructions that were made dead while rewriting the alloca.
1572 DeleteDeadInstructions();
Bob Wilsonf3927b72009-12-17 18:34:24 +00001573 AI->eraseFromParent();
Bob Wilson532cd232009-12-18 20:14:40 +00001574
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001575 ++NumReplaced;
Chris Lattner31e5add2007-04-25 05:02:56 +00001576}
Chris Lattneraaa6ac12009-12-14 05:11:02 +00001577
Bob Wilson532cd232009-12-18 20:14:40 +00001578/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1579/// recursively including all their operands that become trivially dead.
1580void SROA::DeleteDeadInstructions() {
1581 while (!DeadInsts.empty()) {
1582 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattneraaa6ac12009-12-14 05:11:02 +00001583
Bob Wilson532cd232009-12-18 20:14:40 +00001584 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1585 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1586 // Zero out the operand and see if it becomes trivially dead.
1587 // (But, don't add allocas to the dead instruction list -- they are
1588 // already on the worklist and will be deleted separately.)
1589 *OI = 0;
1590 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1591 DeadInsts.push_back(U);
Chris Lattneraaa6ac12009-12-14 05:11:02 +00001592 }
Bob Wilson532cd232009-12-18 20:14:40 +00001593
1594 I->eraseFromParent();
Chris Lattneraaa6ac12009-12-14 05:11:02 +00001595 }
Chris Lattneraaa6ac12009-12-14 05:11:02 +00001596}
Bob Wilson328e91b2011-01-13 20:59:44 +00001597
Bob Wilson532cd232009-12-18 20:14:40 +00001598/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1599/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson88a05982009-12-21 18:39:47 +00001600/// the Info parameter. Offset indicates the position within AI that is
1601/// referenced by this instruction.
Chris Lattner8acbb792011-01-23 07:29:29 +00001602void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
Bob Wilson88a05982009-12-21 18:39:47 +00001603 AllocaInfo &Info) {
Bob Wilson532cd232009-12-18 20:14:40 +00001604 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1605 Instruction *User = cast<Instruction>(*UI);
Chris Lattner52310702003-11-25 21:09:18 +00001606
Bob Wilson532cd232009-12-18 20:14:40 +00001607 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Chris Lattner8acbb792011-01-23 07:29:29 +00001608 isSafeForScalarRepl(BC, Offset, Info);
Bob Wilson532cd232009-12-18 20:14:40 +00001609 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001610 uint64_t GEPOffset = Offset;
Chris Lattner8acbb792011-01-23 07:29:29 +00001611 isSafeGEP(GEPI, GEPOffset, Info);
Bob Wilson532cd232009-12-18 20:14:40 +00001612 if (!Info.isUnsafe)
Chris Lattner8acbb792011-01-23 07:29:29 +00001613 isSafeForScalarRepl(GEPI, GEPOffset, Info);
Gabor Greif4300fc72010-06-28 11:20:42 +00001614 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001615 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattner3e56c292011-01-23 07:05:44 +00001616 if (Length == 0)
1617 return MarkUnsafe(Info, User);
Aaron Ballmana7332972012-03-15 00:05:31 +00001618 if (Length->isNegative())
1619 return MarkUnsafe(Info, User);
1620
Chris Lattner8acbb792011-01-23 07:29:29 +00001621 isSafeMemAccess(Offset, Length->getZExtValue(), 0,
Chris Lattner9491dee2011-01-23 08:27:54 +00001622 UI.getOperandNo() == 0, Info, MI,
1623 true /*AllowWholeAccess*/);
Bob Wilson532cd232009-12-18 20:14:40 +00001624 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Eli Friedman7c5dc122011-09-12 20:23:13 +00001625 if (!LI->isSimple())
Chris Lattner3e56c292011-01-23 07:05:44 +00001626 return MarkUnsafe(Info, User);
Chris Lattner229907c2011-07-18 04:54:35 +00001627 Type *LIType = LI->getType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001628 isSafeMemAccess(Offset, DL->getTypeAllocSize(LIType),
Chris Lattner9491dee2011-01-23 08:27:54 +00001629 LIType, false, Info, LI, true /*AllowWholeAccess*/);
Chris Lattner3e56c292011-01-23 07:05:44 +00001630 Info.hasALoadOrStore = true;
Nadav Rotem465834c2012-07-24 10:51:42 +00001631
Bob Wilson532cd232009-12-18 20:14:40 +00001632 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1633 // Store is ok if storing INTO the pointer, not storing the pointer
Eli Friedman7c5dc122011-09-12 20:23:13 +00001634 if (!SI->isSimple() || SI->getOperand(0) == I)
Chris Lattner3e56c292011-01-23 07:05:44 +00001635 return MarkUnsafe(Info, User);
Nadav Rotem465834c2012-07-24 10:51:42 +00001636
Chris Lattner229907c2011-07-18 04:54:35 +00001637 Type *SIType = SI->getOperand(0)->getType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001638 isSafeMemAccess(Offset, DL->getTypeAllocSize(SIType),
Chris Lattner9491dee2011-01-23 08:27:54 +00001639 SIType, true, Info, SI, true /*AllowWholeAccess*/);
Chris Lattner3e56c292011-01-23 07:05:44 +00001640 Info.hasALoadOrStore = true;
Nick Lewycky15e2d902011-07-25 23:14:22 +00001641 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1642 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1643 II->getIntrinsicID() != Intrinsic::lifetime_end)
1644 return MarkUnsafe(Info, User);
Chris Lattner9491dee2011-01-23 08:27:54 +00001645 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1646 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1647 } else {
1648 return MarkUnsafe(Info, User);
1649 }
1650 if (Info.isUnsafe) return;
1651 }
1652}
Nadav Rotem465834c2012-07-24 10:51:42 +00001653
Chris Lattner9491dee2011-01-23 08:27:54 +00001654
1655/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1656/// derived from the alloca, we can often still split the alloca into elements.
1657/// This is useful if we have a large alloca where one element is phi'd
1658/// together somewhere: we can SRoA and promote all the other elements even if
1659/// we end up not being able to promote this one.
1660///
1661/// All we require is that the uses of the PHI do not index into other parts of
1662/// the alloca. The most important use case for this is single load and stores
1663/// that are PHI'd together, which can happen due to code sinking.
1664void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1665 AllocaInfo &Info) {
1666 // If we've already checked this PHI, don't do it again.
1667 if (PHINode *PN = dyn_cast<PHINode>(I))
1668 if (!Info.CheckedPHIs.insert(PN))
1669 return;
Nadav Rotem465834c2012-07-24 10:51:42 +00001670
Chris Lattner9491dee2011-01-23 08:27:54 +00001671 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1672 Instruction *User = cast<Instruction>(*UI);
Nadav Rotem465834c2012-07-24 10:51:42 +00001673
Chris Lattner9491dee2011-01-23 08:27:54 +00001674 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1675 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1676 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1677 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1678 // but would have to prove that we're staying inside of an element being
1679 // promoted.
1680 if (!GEPI->hasAllZeroIndices())
1681 return MarkUnsafe(Info, User);
1682 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1683 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Eli Friedman7c5dc122011-09-12 20:23:13 +00001684 if (!LI->isSimple())
Chris Lattner9491dee2011-01-23 08:27:54 +00001685 return MarkUnsafe(Info, User);
Chris Lattner229907c2011-07-18 04:54:35 +00001686 Type *LIType = LI->getType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001687 isSafeMemAccess(Offset, DL->getTypeAllocSize(LIType),
Chris Lattner9491dee2011-01-23 08:27:54 +00001688 LIType, false, Info, LI, false /*AllowWholeAccess*/);
1689 Info.hasALoadOrStore = true;
Nadav Rotem465834c2012-07-24 10:51:42 +00001690
Chris Lattner9491dee2011-01-23 08:27:54 +00001691 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1692 // Store is ok if storing INTO the pointer, not storing the pointer
Eli Friedman7c5dc122011-09-12 20:23:13 +00001693 if (!SI->isSimple() || SI->getOperand(0) == I)
Chris Lattner9491dee2011-01-23 08:27:54 +00001694 return MarkUnsafe(Info, User);
Nadav Rotem465834c2012-07-24 10:51:42 +00001695
Chris Lattner229907c2011-07-18 04:54:35 +00001696 Type *SIType = SI->getOperand(0)->getType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001697 isSafeMemAccess(Offset, DL->getTypeAllocSize(SIType),
Chris Lattner9491dee2011-01-23 08:27:54 +00001698 SIType, true, Info, SI, false /*AllowWholeAccess*/);
1699 Info.hasALoadOrStore = true;
1700 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1701 isSafePHISelectUseForScalarRepl(User, Offset, Info);
Bob Wilson532cd232009-12-18 20:14:40 +00001702 } else {
Chris Lattner3e56c292011-01-23 07:05:44 +00001703 return MarkUnsafe(Info, User);
Bob Wilson532cd232009-12-18 20:14:40 +00001704 }
1705 if (Info.isUnsafe) return;
Bob Wilsonf3927b72009-12-17 18:34:24 +00001706 }
Bob Wilson532cd232009-12-18 20:14:40 +00001707}
Bob Wilsonf3927b72009-12-17 18:34:24 +00001708
Bob Wilson532cd232009-12-18 20:14:40 +00001709/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1710/// replacement. It is safe when all the indices are constant, in-bounds
1711/// references, and when the resulting offset corresponds to an element within
1712/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson88a05982009-12-21 18:39:47 +00001713/// return, Offset is adjusted as specified by the GEP indices.
Chris Lattner8acbb792011-01-23 07:29:29 +00001714void SROA::isSafeGEP(GetElementPtrInst *GEPI,
Bob Wilson88a05982009-12-21 18:39:47 +00001715 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilson532cd232009-12-18 20:14:40 +00001716 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1717 if (GEPIt == E)
1718 return;
Pete Coopere24d6a12012-06-15 18:07:29 +00001719 bool NonConstant = false;
1720 unsigned NonConstantIdxSize = 0;
Bob Wilsonf3927b72009-12-17 18:34:24 +00001721
Chris Lattner3f972c92008-08-23 05:21:06 +00001722 // Walk through the GEP type indices, checking the types that this indexes
1723 // into.
Bob Wilson532cd232009-12-18 20:14:40 +00001724 for (; GEPIt != E; ++GEPIt) {
Chris Lattner3f972c92008-08-23 05:21:06 +00001725 // Ignore struct elements, no extra checking needed for these.
Duncan Sands19d0b472010-02-16 11:11:14 +00001726 if ((*GEPIt)->isStructTy())
Chris Lattner3f972c92008-08-23 05:21:06 +00001727 continue;
Matthijs Kooijmancbe5e162008-10-06 16:23:31 +00001728
Bob Wilson532cd232009-12-18 20:14:40 +00001729 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
Shuxin Yang95adf522013-04-05 21:07:08 +00001730 if (!IdxVal)
1731 return MarkUnsafe(Info, GEPI);
Chris Lattner3f972c92008-08-23 05:21:06 +00001732 }
Bob Wilson532cd232009-12-18 20:14:40 +00001733
Bob Wilson62a84ea2009-12-22 06:57:14 +00001734 // Compute the offset due to this GEP and check if the alloca has a
1735 // component element at that offset.
Bob Wilson88a05982009-12-21 18:39:47 +00001736 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
Alp Tokerf907b892013-12-05 05:44:44 +00001737 // If this GEP is non-constant then the last operand must have been a
Pete Coopere24d6a12012-06-15 18:07:29 +00001738 // dynamic index into a vector. Pop this now as it has no impact on the
1739 // constant part of the offset.
1740 if (NonConstant)
1741 Indices.pop_back();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001742 Offset += DL->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
Pete Coopere24d6a12012-06-15 18:07:29 +00001743 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset,
1744 NonConstantIdxSize))
Chris Lattner3e56c292011-01-23 07:05:44 +00001745 MarkUnsafe(Info, GEPI);
Chris Lattner6e5398d2003-05-30 04:15:41 +00001746}
1747
Bob Wilson08713d32011-01-13 17:45:11 +00001748/// isHomogeneousAggregate - Check if type T is a struct or array containing
1749/// elements of the same type (which is always true for arrays). If so,
1750/// return true with NumElts and EltTy set to the number of elements and the
1751/// element type, respectively.
Chris Lattner229907c2011-07-18 04:54:35 +00001752static bool isHomogeneousAggregate(Type *T, unsigned &NumElts,
1753 Type *&EltTy) {
1754 if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
Bob Wilson08713d32011-01-13 17:45:11 +00001755 NumElts = AT->getNumElements();
Bob Wilsonc8056a92011-01-13 18:26:59 +00001756 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
Bob Wilson08713d32011-01-13 17:45:11 +00001757 return true;
1758 }
Chris Lattner229907c2011-07-18 04:54:35 +00001759 if (StructType *ST = dyn_cast<StructType>(T)) {
Bob Wilson08713d32011-01-13 17:45:11 +00001760 NumElts = ST->getNumContainedTypes();
Bob Wilsonc8056a92011-01-13 18:26:59 +00001761 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
Bob Wilson08713d32011-01-13 17:45:11 +00001762 for (unsigned n = 1; n < NumElts; ++n) {
1763 if (ST->getContainedType(n) != EltTy)
1764 return false;
1765 }
1766 return true;
1767 }
1768 return false;
1769}
1770
1771/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1772/// "homogeneous" aggregates with the same element type and number of elements.
Chris Lattner229907c2011-07-18 04:54:35 +00001773static bool isCompatibleAggregate(Type *T1, Type *T2) {
Bob Wilson08713d32011-01-13 17:45:11 +00001774 if (T1 == T2)
1775 return true;
1776
1777 unsigned NumElts1, NumElts2;
Chris Lattner229907c2011-07-18 04:54:35 +00001778 Type *EltTy1, *EltTy2;
Bob Wilson08713d32011-01-13 17:45:11 +00001779 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1780 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1781 NumElts1 == NumElts2 &&
1782 EltTy1 == EltTy2)
1783 return true;
1784
1785 return false;
1786}
1787
Bob Wilson532cd232009-12-18 20:14:40 +00001788/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1789/// alloca or has an offset and size that corresponds to a component element
1790/// within it. The offset checked here may have been formed from a GEP with a
1791/// pointer bitcasted to a different type.
Chris Lattner9491dee2011-01-23 08:27:54 +00001792///
1793/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1794/// unit. If false, it only allows accesses known to be in a single element.
Chris Lattner8acbb792011-01-23 07:29:29 +00001795void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattner229907c2011-07-18 04:54:35 +00001796 Type *MemOpType, bool isStore,
Chris Lattner9491dee2011-01-23 08:27:54 +00001797 AllocaInfo &Info, Instruction *TheAccess,
1798 bool AllowWholeAccess) {
Bob Wilson532cd232009-12-18 20:14:40 +00001799 // Check if this is a load/store of the entire alloca.
Chris Lattner9491dee2011-01-23 08:27:54 +00001800 if (Offset == 0 && AllowWholeAccess &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001801 MemSize == DL->getTypeAllocSize(Info.AI->getAllocatedType())) {
Bob Wilson08713d32011-01-13 17:45:11 +00001802 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1803 // loads/stores (which are essentially the same as the MemIntrinsics with
1804 // regard to copying padding between elements). But, if an alloca is
1805 // flagged as both a source and destination of such operations, we'll need
1806 // to check later for padding between elements.
1807 if (!MemOpType || MemOpType->isIntegerTy()) {
1808 if (isStore)
1809 Info.isMemCpyDst = true;
1810 else
1811 Info.isMemCpySrc = true;
Bob Wilson532cd232009-12-18 20:14:40 +00001812 return;
1813 }
Bob Wilson08713d32011-01-13 17:45:11 +00001814 // This is also safe for references using a type that is compatible with
1815 // the type of the alloca, so that loads/stores can be rewritten using
1816 // insertvalue/extractvalue.
Chris Lattner8acbb792011-01-23 07:29:29 +00001817 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
Chris Lattner6fab2e92011-01-16 06:18:28 +00001818 Info.hasSubelementAccess = true;
Bob Wilson08713d32011-01-13 17:45:11 +00001819 return;
Chris Lattner6fab2e92011-01-16 06:18:28 +00001820 }
Bob Wilson532cd232009-12-18 20:14:40 +00001821 }
1822 // Check if the offset/size correspond to a component within the alloca type.
Chris Lattner229907c2011-07-18 04:54:35 +00001823 Type *T = Info.AI->getAllocatedType();
Chris Lattner6fab2e92011-01-16 06:18:28 +00001824 if (TypeHasComponent(T, Offset, MemSize)) {
1825 Info.hasSubelementAccess = true;
Bob Wilson532cd232009-12-18 20:14:40 +00001826 return;
Chris Lattner6fab2e92011-01-16 06:18:28 +00001827 }
Bob Wilson532cd232009-12-18 20:14:40 +00001828
Chris Lattner3e56c292011-01-23 07:05:44 +00001829 return MarkUnsafe(Info, TheAccess);
Bob Wilson532cd232009-12-18 20:14:40 +00001830}
1831
1832/// TypeHasComponent - Return true if T has a component type with the
1833/// specified offset and size. If Size is zero, do not check the size.
Chris Lattner229907c2011-07-18 04:54:35 +00001834bool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size) {
1835 Type *EltTy;
Bob Wilson532cd232009-12-18 20:14:40 +00001836 uint64_t EltSize;
Chris Lattner229907c2011-07-18 04:54:35 +00001837 if (StructType *ST = dyn_cast<StructType>(T)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001838 const StructLayout *Layout = DL->getStructLayout(ST);
Bob Wilson532cd232009-12-18 20:14:40 +00001839 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1840 EltTy = ST->getContainedType(EltIdx);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001841 EltSize = DL->getTypeAllocSize(EltTy);
Bob Wilson532cd232009-12-18 20:14:40 +00001842 Offset -= Layout->getElementOffset(EltIdx);
Chris Lattner229907c2011-07-18 04:54:35 +00001843 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001844 EltTy = AT->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001845 EltSize = DL->getTypeAllocSize(EltTy);
Bob Wilson62a84ea2009-12-22 06:57:14 +00001846 if (Offset >= AT->getNumElements() * EltSize)
1847 return false;
Bob Wilson532cd232009-12-18 20:14:40 +00001848 Offset %= EltSize;
Pete Cooper1d1fa722012-06-14 23:53:53 +00001849 } else if (VectorType *VT = dyn_cast<VectorType>(T)) {
1850 EltTy = VT->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001851 EltSize = DL->getTypeAllocSize(EltTy);
Pete Cooper1d1fa722012-06-14 23:53:53 +00001852 if (Offset >= VT->getNumElements() * EltSize)
1853 return false;
1854 Offset %= EltSize;
Bob Wilson532cd232009-12-18 20:14:40 +00001855 } else {
1856 return false;
1857 }
1858 if (Offset == 0 && (Size == 0 || EltSize == Size))
1859 return true;
1860 // Check if the component spans multiple elements.
1861 if (Offset + Size > EltSize)
1862 return false;
1863 return TypeHasComponent(EltTy, Offset, Size);
1864}
1865
1866/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1867/// the instruction I, which references it, to use the separate elements.
1868/// Offset indicates the position within AI that is referenced by this
1869/// instruction.
1870void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00001871 SmallVectorImpl<AllocaInst *> &NewElts) {
Chris Lattner9491dee2011-01-23 08:27:54 +00001872 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1873 Use &TheUse = UI.getUse();
1874 Instruction *User = cast<Instruction>(*UI++);
Bob Wilson532cd232009-12-18 20:14:40 +00001875
1876 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1877 RewriteBitCast(BC, AI, Offset, NewElts);
Chris Lattner9491dee2011-01-23 08:27:54 +00001878 continue;
1879 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001880
Chris Lattner9491dee2011-01-23 08:27:54 +00001881 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001882 RewriteGEP(GEPI, AI, Offset, NewElts);
Chris Lattner9491dee2011-01-23 08:27:54 +00001883 continue;
1884 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001885
Chris Lattner9491dee2011-01-23 08:27:54 +00001886 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001887 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1888 uint64_t MemSize = Length->getZExtValue();
1889 if (Offset == 0 &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001890 MemSize == DL->getTypeAllocSize(AI->getAllocatedType()))
Bob Wilson532cd232009-12-18 20:14:40 +00001891 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsonc16811b2009-12-19 06:53:17 +00001892 // Otherwise the intrinsic can only touch a single element and the
1893 // address operand will be updated, so nothing else needs to be done.
Chris Lattner9491dee2011-01-23 08:27:54 +00001894 continue;
1895 }
Nick Lewycky15e2d902011-07-25 23:14:22 +00001896
1897 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1898 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1899 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1900 RewriteLifetimeIntrinsic(II, AI, Offset, NewElts);
1901 }
1902 continue;
1903 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001904
Chris Lattner9491dee2011-01-23 08:27:54 +00001905 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner229907c2011-07-18 04:54:35 +00001906 Type *LIType = LI->getType();
Nadav Rotem465834c2012-07-24 10:51:42 +00001907
Bob Wilson08713d32011-01-13 17:45:11 +00001908 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
Bob Wilson532cd232009-12-18 20:14:40 +00001909 // Replace:
1910 // %res = load { i32, i32 }* %alloc
1911 // with:
1912 // %load.0 = load i32* %alloc.0
1913 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1914 // %load.1 = load i32* %alloc.1
1915 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1916 // (Also works for arrays instead of structs)
1917 Value *Insert = UndefValue::get(LIType);
Devang Patel84bb33a2011-06-03 19:46:19 +00001918 IRBuilder<> Builder(LI);
Bob Wilson532cd232009-12-18 20:14:40 +00001919 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patel84bb33a2011-06-03 19:46:19 +00001920 Value *Load = Builder.CreateLoad(NewElts[i], "load");
1921 Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
Bob Wilson532cd232009-12-18 20:14:40 +00001922 }
1923 LI->replaceAllUsesWith(Insert);
1924 DeadInsts.push_back(LI);
Duncan Sands19d0b472010-02-16 11:11:14 +00001925 } else if (LIType->isIntegerTy() &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001926 DL->getTypeAllocSize(LIType) ==
1927 DL->getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilson532cd232009-12-18 20:14:40 +00001928 // If this is a load of the entire alloca to an integer, rewrite it.
1929 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1930 }
Chris Lattner9491dee2011-01-23 08:27:54 +00001931 continue;
1932 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001933
Chris Lattner9491dee2011-01-23 08:27:54 +00001934 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001935 Value *Val = SI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00001936 Type *SIType = Val->getType();
Bob Wilson08713d32011-01-13 17:45:11 +00001937 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
Bob Wilson532cd232009-12-18 20:14:40 +00001938 // Replace:
1939 // store { i32, i32 } %val, { i32, i32 }* %alloc
1940 // with:
1941 // %val.0 = extractvalue { i32, i32 } %val, 0
1942 // store i32 %val.0, i32* %alloc.0
1943 // %val.1 = extractvalue { i32, i32 } %val, 1
1944 // store i32 %val.1, i32* %alloc.1
1945 // (Also works for arrays instead of structs)
Devang Patel84bb33a2011-06-03 19:46:19 +00001946 IRBuilder<> Builder(SI);
Bob Wilson532cd232009-12-18 20:14:40 +00001947 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patel84bb33a2011-06-03 19:46:19 +00001948 Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
1949 Builder.CreateStore(Extract, NewElts[i]);
Bob Wilson532cd232009-12-18 20:14:40 +00001950 }
1951 DeadInsts.push_back(SI);
Duncan Sands19d0b472010-02-16 11:11:14 +00001952 } else if (SIType->isIntegerTy() &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001953 DL->getTypeAllocSize(SIType) ==
1954 DL->getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilson532cd232009-12-18 20:14:40 +00001955 // If this is a store of the entire alloca from an integer, rewrite it.
1956 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1957 }
Chris Lattner9491dee2011-01-23 08:27:54 +00001958 continue;
1959 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001960
Chris Lattner9491dee2011-01-23 08:27:54 +00001961 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
Nadav Rotem465834c2012-07-24 10:51:42 +00001962 // If we have a PHI user of the alloca itself (as opposed to a GEP or
Chris Lattner9491dee2011-01-23 08:27:54 +00001963 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
1964 // the new pointer.
1965 if (!isa<AllocaInst>(I)) continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00001966
Chris Lattner9491dee2011-01-23 08:27:54 +00001967 assert(Offset == 0 && NewElts[0] &&
1968 "Direct alloca use should have a zero offset");
Nadav Rotem465834c2012-07-24 10:51:42 +00001969
Chris Lattner9491dee2011-01-23 08:27:54 +00001970 // If we have a use of the alloca, we know the derived uses will be
1971 // utilizing just the first element of the scalarized result. Insert a
1972 // bitcast of the first alloca before the user as required.
1973 AllocaInst *NewAI = NewElts[0];
1974 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1975 NewAI->moveBefore(BCI);
1976 TheUse = BCI;
1977 continue;
Bob Wilson532cd232009-12-18 20:14:40 +00001978 }
Bob Wilsonf3927b72009-12-17 18:34:24 +00001979 }
1980}
1981
Bob Wilson532cd232009-12-18 20:14:40 +00001982/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1983/// and recursively continue updating all of its uses.
1984void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00001985 SmallVectorImpl<AllocaInst *> &NewElts) {
Bob Wilson532cd232009-12-18 20:14:40 +00001986 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1987 if (BC->getOperand(0) != AI)
1988 return;
Bob Wilsonf3927b72009-12-17 18:34:24 +00001989
Bob Wilson532cd232009-12-18 20:14:40 +00001990 // The bitcast references the original alloca. Replace its uses with
Eli Friedmanecb45382011-11-12 02:07:50 +00001991 // references to the alloca containing offset zero (which is normally at
1992 // index zero, but might not be in cases involving structs with elements
1993 // of size zero).
1994 Type *T = AI->getAllocatedType();
1995 uint64_t EltOffset = 0;
1996 Type *IdxTy;
1997 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
1998 Instruction *Val = NewElts[Idx];
Bob Wilson532cd232009-12-18 20:14:40 +00001999 if (Val->getType() != BC->getDestTy()) {
2000 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
2001 Val->takeName(BC);
Daniel Dunbar133efc32009-12-16 10:56:17 +00002002 }
Bob Wilson532cd232009-12-18 20:14:40 +00002003 BC->replaceAllUsesWith(Val);
2004 DeadInsts.push_back(BC);
Daniel Dunbar133efc32009-12-16 10:56:17 +00002005}
2006
Bob Wilson532cd232009-12-18 20:14:40 +00002007/// FindElementAndOffset - Return the index of the element containing Offset
2008/// within the specified type, which must be either a struct or an array.
2009/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsonc16811b2009-12-19 06:53:17 +00002010/// element. IdxTy is set to the type of the index result to be used in a
2011/// GEP instruction.
Chris Lattner229907c2011-07-18 04:54:35 +00002012uint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset,
2013 Type *&IdxTy) {
Bob Wilsonc16811b2009-12-19 06:53:17 +00002014 uint64_t Idx = 0;
Chris Lattner229907c2011-07-18 04:54:35 +00002015 if (StructType *ST = dyn_cast<StructType>(T)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002016 const StructLayout *Layout = DL->getStructLayout(ST);
Bob Wilson532cd232009-12-18 20:14:40 +00002017 Idx = Layout->getElementContainingOffset(Offset);
2018 T = ST->getContainedType(Idx);
2019 Offset -= Layout->getElementOffset(Idx);
Bob Wilsonc16811b2009-12-19 06:53:17 +00002020 IdxTy = Type::getInt32Ty(T->getContext());
2021 return Idx;
Pete Cooper1d1fa722012-06-14 23:53:53 +00002022 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
2023 T = AT->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002024 uint64_t EltSize = DL->getTypeAllocSize(T);
Pete Cooper1d1fa722012-06-14 23:53:53 +00002025 Idx = Offset / EltSize;
2026 Offset -= Idx * EltSize;
2027 IdxTy = Type::getInt64Ty(T->getContext());
2028 return Idx;
Chris Lattneraaa6ac12009-12-14 05:11:02 +00002029 }
Pete Cooper1d1fa722012-06-14 23:53:53 +00002030 VectorType *VT = cast<VectorType>(T);
2031 T = VT->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002032 uint64_t EltSize = DL->getTypeAllocSize(T);
Bob Wilsonc16811b2009-12-19 06:53:17 +00002033 Idx = Offset / EltSize;
2034 Offset -= Idx * EltSize;
2035 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilson532cd232009-12-18 20:14:40 +00002036 return Idx;
2037}
2038
2039/// RewriteGEP - Check if this GEP instruction moves the pointer across
2040/// elements of the alloca that are being split apart, and if so, rewrite
2041/// the GEP to be relative to the new element.
2042void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00002043 SmallVectorImpl<AllocaInst *> &NewElts) {
Bob Wilson532cd232009-12-18 20:14:40 +00002044 uint64_t OldOffset = Offset;
2045 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
Pete Coopere24d6a12012-06-15 18:07:29 +00002046 // If the GEP was dynamic then it must have been a dynamic vector lookup.
2047 // In this case, it must be the last GEP operand which is dynamic so keep that
2048 // aside until we've found the constant GEP offset then add it back in at the
2049 // end.
2050 Value* NonConstantIdx = 0;
2051 if (!GEPI->hasAllConstantIndices())
2052 NonConstantIdx = Indices.pop_back_val();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002053 Offset += DL->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
Bob Wilson532cd232009-12-18 20:14:40 +00002054
2055 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
2056
Chris Lattner229907c2011-07-18 04:54:35 +00002057 Type *T = AI->getAllocatedType();
2058 Type *IdxTy;
Bob Wilsonc16811b2009-12-19 06:53:17 +00002059 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilson532cd232009-12-18 20:14:40 +00002060 if (GEPI->getOperand(0) == AI)
Bob Wilsonc16811b2009-12-19 06:53:17 +00002061 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilson532cd232009-12-18 20:14:40 +00002062
2063 T = AI->getAllocatedType();
2064 uint64_t EltOffset = Offset;
Bob Wilsonc16811b2009-12-19 06:53:17 +00002065 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilson532cd232009-12-18 20:14:40 +00002066
2067 // If this GEP does not move the pointer across elements of the alloca
2068 // being split, then it does not needs to be rewritten.
2069 if (Idx == OldIdx)
2070 return;
2071
Chris Lattner229907c2011-07-18 04:54:35 +00002072 Type *i32Ty = Type::getInt32Ty(AI->getContext());
Bob Wilson532cd232009-12-18 20:14:40 +00002073 SmallVector<Value*, 8> NewArgs;
2074 NewArgs.push_back(Constant::getNullValue(i32Ty));
2075 while (EltOffset != 0) {
Bob Wilsonc16811b2009-12-19 06:53:17 +00002076 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
2077 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilson532cd232009-12-18 20:14:40 +00002078 }
Pete Cooper818e9f42012-06-16 01:43:26 +00002079 if (NonConstantIdx) {
2080 Type* GepTy = T;
2081 // This GEP has a dynamic index. We need to add "i32 0" to index through
2082 // any structs or arrays in the original type until we get to the vector
2083 // to index.
2084 while (!isa<VectorType>(GepTy)) {
2085 NewArgs.push_back(Constant::getNullValue(i32Ty));
2086 GepTy = cast<CompositeType>(GepTy)->getTypeAtIndex(0U);
2087 }
Pete Coopere24d6a12012-06-15 18:07:29 +00002088 NewArgs.push_back(NonConstantIdx);
Pete Cooper818e9f42012-06-16 01:43:26 +00002089 }
Bob Wilson532cd232009-12-18 20:14:40 +00002090 Instruction *Val = NewElts[Idx];
2091 if (NewArgs.size() > 1) {
Jay Foadd1b78492011-07-25 09:48:08 +00002092 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs, "", GEPI);
Bob Wilson532cd232009-12-18 20:14:40 +00002093 Val->takeName(GEPI);
2094 }
2095 if (Val->getType() != GEPI->getType())
Benjamin Kramer40582a82010-01-27 19:46:52 +00002096 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilson532cd232009-12-18 20:14:40 +00002097 GEPI->replaceAllUsesWith(Val);
2098 DeadInsts.push_back(GEPI);
Chris Lattner9a2de652009-01-07 07:18:45 +00002099}
2100
Nick Lewycky15e2d902011-07-25 23:14:22 +00002101/// RewriteLifetimeIntrinsic - II is a lifetime.start/lifetime.end. Rewrite it
2102/// to mark the lifetime of the scalarized memory.
2103void SROA::RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
2104 uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00002105 SmallVectorImpl<AllocaInst *> &NewElts) {
Nick Lewycky15e2d902011-07-25 23:14:22 +00002106 ConstantInt *OldSize = cast<ConstantInt>(II->getArgOperand(0));
2107 // Put matching lifetime markers on everything from Offset up to
2108 // Offset+OldSize.
2109 Type *AIType = AI->getAllocatedType();
2110 uint64_t NewOffset = Offset;
2111 Type *IdxTy;
2112 uint64_t Idx = FindElementAndOffset(AIType, NewOffset, IdxTy);
2113
2114 IRBuilder<> Builder(II);
2115 uint64_t Size = OldSize->getLimitedValue();
2116
2117 if (NewOffset) {
2118 // Splice the first element and index 'NewOffset' bytes in. SROA will
2119 // split the alloca again later.
2120 Value *V = Builder.CreateBitCast(NewElts[Idx], Builder.getInt8PtrTy());
2121 V = Builder.CreateGEP(V, Builder.getInt64(NewOffset));
2122
2123 IdxTy = NewElts[Idx]->getAllocatedType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002124 uint64_t EltSize = DL->getTypeAllocSize(IdxTy) - NewOffset;
Nick Lewycky15e2d902011-07-25 23:14:22 +00002125 if (EltSize > Size) {
2126 EltSize = Size;
2127 Size = 0;
2128 } else {
2129 Size -= EltSize;
2130 }
2131 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2132 Builder.CreateLifetimeStart(V, Builder.getInt64(EltSize));
2133 else
2134 Builder.CreateLifetimeEnd(V, Builder.getInt64(EltSize));
2135 ++Idx;
2136 }
2137
2138 for (; Idx != NewElts.size() && Size; ++Idx) {
2139 IdxTy = NewElts[Idx]->getAllocatedType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002140 uint64_t EltSize = DL->getTypeAllocSize(IdxTy);
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(NewElts[Idx],
2149 Builder.getInt64(EltSize));
2150 else
2151 Builder.CreateLifetimeEnd(NewElts[Idx],
2152 Builder.getInt64(EltSize));
2153 }
2154 DeadInsts.push_back(II);
2155}
2156
Chris Lattner9a2de652009-01-07 07:18:45 +00002157/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
2158/// Rewrite it to copy or set the elements of the scalarized memory.
Craig Topperb94011f2013-07-14 04:42:23 +00002159void
2160SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
2161 AllocaInst *AI,
2162 SmallVectorImpl<AllocaInst *> &NewElts) {
Chris Lattner9a2de652009-01-07 07:18:45 +00002163 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattnera41bb402009-03-04 19:23:25 +00002164 // appropriate type. The "Other" pointer is the pointer that goes to memory
2165 // that doesn't have anything to do with the alloca that we are promoting. For
2166 // memset, this Value* stays null.
Chris Lattner9a2de652009-01-07 07:18:45 +00002167 Value *OtherPtr = 0;
Chris Lattnerdc35e5b2009-03-08 03:59:00 +00002168 unsigned MemAlignment = MI->getAlignment();
Chris Lattner334268a2009-03-08 03:37:16 +00002169 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilson532cd232009-12-18 20:14:40 +00002170 if (Inst == MTI->getRawDest())
Chris Lattner334268a2009-03-08 03:37:16 +00002171 OtherPtr = MTI->getRawSource();
Chris Lattner9a2de652009-01-07 07:18:45 +00002172 else {
Bob Wilson532cd232009-12-18 20:14:40 +00002173 assert(Inst == MTI->getRawSource());
Chris Lattner334268a2009-03-08 03:37:16 +00002174 OtherPtr = MTI->getRawDest();
Chris Lattner9a2de652009-01-07 07:18:45 +00002175 }
2176 }
Bob Wilson2029ea02009-12-08 18:22:03 +00002177
Chris Lattner9a2de652009-01-07 07:18:45 +00002178 // If there is an other pointer, we want to convert it to the same pointer
2179 // type as AI has, so we can GEP through it safely.
2180 if (OtherPtr) {
Chris Lattnerefa3c822010-07-08 00:27:05 +00002181 unsigned AddrSpace =
2182 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilson532cd232009-12-18 20:14:40 +00002183
2184 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
2185 // optimization, but it's also required to detect the corner case where
2186 // both pointer operands are referencing the same memory, and where
2187 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
2188 // function is only called for mem intrinsics that access the whole
2189 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattnerefa3c822010-07-08 00:27:05 +00002190 OtherPtr = OtherPtr->stripPointerCasts();
Bob Wilson328e91b2011-01-13 20:59:44 +00002191
Bob Wilson58d59fe2010-01-19 04:32:48 +00002192 // Copying the alloca to itself is a no-op: just delete it.
2193 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2194 // This code will run twice for a no-op memcpy -- once for each operand.
2195 // Put only one reference to MI on the DeadInsts list.
Craig Topper31ee5862013-07-03 15:07:05 +00002196 for (SmallVectorImpl<Value *>::const_iterator I = DeadInsts.begin(),
Bob Wilson58d59fe2010-01-19 04:32:48 +00002197 E = DeadInsts.end(); I != E; ++I)
2198 if (*I == MI) return;
2199 DeadInsts.push_back(MI);
Bob Wilson532cd232009-12-18 20:14:40 +00002200 return;
Bob Wilson58d59fe2010-01-19 04:32:48 +00002201 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002202
Chris Lattner9a2de652009-01-07 07:18:45 +00002203 // If the pointer is not the right type, insert a bitcast to the right
2204 // type.
Chris Lattner229907c2011-07-18 04:54:35 +00002205 Type *NewTy =
Chris Lattnerefa3c822010-07-08 00:27:05 +00002206 PointerType::get(AI->getType()->getElementType(), AddrSpace);
Bob Wilson328e91b2011-01-13 20:59:44 +00002207
Chris Lattnerefa3c822010-07-08 00:27:05 +00002208 if (OtherPtr->getType() != NewTy)
2209 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattner9a2de652009-01-07 07:18:45 +00002210 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002211
Chris Lattner9a2de652009-01-07 07:18:45 +00002212 // Process each element of the aggregate.
Bob Wilson532cd232009-12-18 20:14:40 +00002213 bool SROADest = MI->getRawDest() == Inst;
Bob Wilson328e91b2011-01-13 20:59:44 +00002214
Owen Anderson55f1c092009-08-13 21:58:54 +00002215 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattner9a2de652009-01-07 07:18:45 +00002216
2217 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2218 // If this is a memcpy/memmove, emit a GEP of the other element address.
2219 Value *OtherElt = 0;
Chris Lattner5c204c92009-03-04 19:20:50 +00002220 unsigned OtherEltAlign = MemAlignment;
Bob Wilson328e91b2011-01-13 20:59:44 +00002221
Bob Wilson58d59fe2010-01-19 04:32:48 +00002222 if (OtherPtr) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002223 Value *Idx[2] = { Zero,
2224 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Jay Foadd1b78492011-07-25 09:48:08 +00002225 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx,
Benjamin Kramer40582a82010-01-27 19:46:52 +00002226 OtherPtr->getName()+"."+Twine(i),
Bob Wilson532cd232009-12-18 20:14:40 +00002227 MI);
Chris Lattner5c204c92009-03-04 19:20:50 +00002228 uint64_t EltOffset;
Chris Lattner229907c2011-07-18 04:54:35 +00002229 PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
2230 Type *OtherTy = OtherPtrTy->getElementType();
2231 if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002232 EltOffset = DL->getStructLayout(ST)->getElementOffset(i);
Chris Lattner5c204c92009-03-04 19:20:50 +00002233 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002234 Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002235 EltOffset = DL->getTypeAllocSize(EltTy)*i;
Chris Lattner5c204c92009-03-04 19:20:50 +00002236 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002237
Chris Lattner5c204c92009-03-04 19:20:50 +00002238 // The alignment of the other pointer is the guaranteed alignment of the
2239 // element, which is affected by both the known alignment of the whole
2240 // mem intrinsic and the alignment of the element. If the alignment of
2241 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2242 // known alignment is just 4 bytes.
2243 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattner9f022d52007-03-08 06:36:54 +00002244 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002245
Chris Lattner9a2de652009-01-07 07:18:45 +00002246 Value *EltPtr = NewElts[i];
Chris Lattner229907c2011-07-18 04:54:35 +00002247 Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Bob Wilson328e91b2011-01-13 20:59:44 +00002248
Chris Lattner9a2de652009-01-07 07:18:45 +00002249 // If we got down to a scalar, insert a load or store as appropriate.
2250 if (EltTy->isSingleValueType()) {
Chris Lattner334268a2009-03-08 03:37:16 +00002251 if (isa<MemTransferInst>(MI)) {
Chris Lattner5c204c92009-03-04 19:20:50 +00002252 if (SROADest) {
2253 // From Other to Alloca.
2254 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2255 new StoreInst(Elt, EltPtr, MI);
2256 } else {
2257 // From Alloca to Other.
2258 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2259 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2260 }
Chris Lattner9a2de652009-01-07 07:18:45 +00002261 continue;
2262 }
2263 assert(isa<MemSetInst>(MI));
Bob Wilson328e91b2011-01-13 20:59:44 +00002264
Chris Lattner9a2de652009-01-07 07:18:45 +00002265 // If the stored element is zero (common case), just store a null
2266 // constant.
2267 Constant *StoreVal;
Gabor Greiffe252e62010-06-30 09:16:16 +00002268 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattner9a2de652009-01-07 07:18:45 +00002269 if (CI->isZero()) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00002270 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattner9a2de652009-01-07 07:18:45 +00002271 } else {
2272 // If EltTy is a vector type, get the element type.
Chris Lattner229907c2011-07-18 04:54:35 +00002273 Type *ValTy = EltTy->getScalarType();
Dan Gohmanadfd42a2009-06-16 00:20:26 +00002274
Chris Lattner9a2de652009-01-07 07:18:45 +00002275 // Construct an integer with the right value.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002276 unsigned EltSize = DL->getTypeSizeInBits(ValTy);
Chris Lattner9a2de652009-01-07 07:18:45 +00002277 APInt OneVal(EltSize, CI->getZExtValue());
2278 APInt TotalVal(OneVal);
2279 // Set each byte.
2280 for (unsigned i = 0; 8*i < EltSize; ++i) {
2281 TotalVal = TotalVal.shl(8);
2282 TotalVal |= OneVal;
2283 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002284
Chris Lattner9a2de652009-01-07 07:18:45 +00002285 // Convert the integer value to the appropriate type.
Chris Lattner1146d322010-04-16 01:05:38 +00002286 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands19d0b472010-02-16 11:11:14 +00002287 if (ValTy->isPointerTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002288 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sands9dff9be2010-02-15 16:12:20 +00002289 else if (ValTy->isFloatingPointTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002290 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattner9a2de652009-01-07 07:18:45 +00002291 assert(StoreVal->getType() == ValTy && "Type mismatch!");
Bob Wilson328e91b2011-01-13 20:59:44 +00002292
Chris Lattner9a2de652009-01-07 07:18:45 +00002293 // If the requested value was a vector constant, create it.
Cameron Zwarich1a761dc2011-10-11 21:26:40 +00002294 if (EltTy->isVectorTy()) {
2295 unsigned NumElts = cast<VectorType>(EltTy)->getNumElements();
Chris Lattner47a86bd2012-01-25 06:02:56 +00002296 StoreVal = ConstantVector::getSplat(NumElts, StoreVal);
Chris Lattner9a2de652009-01-07 07:18:45 +00002297 }
2298 }
2299 new StoreInst(StoreVal, EltPtr, MI);
2300 continue;
2301 }
2302 // Otherwise, if we're storing a byte variable, use a memset call for
2303 // this element.
2304 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002305
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002306 unsigned EltSize = DL->getTypeAllocSize(EltTy);
Eli Friedmanecb45382011-11-12 02:07:50 +00002307 if (!EltSize)
2308 continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00002309
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00002310 IRBuilder<> Builder(MI);
Bob Wilson328e91b2011-01-13 20:59:44 +00002311
Chris Lattner9a2de652009-01-07 07:18:45 +00002312 // Finally, insert the meminst for this element.
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00002313 if (isa<MemSetInst>(MI)) {
2314 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2315 MI->isVolatile());
Chris Lattner9a2de652009-01-07 07:18:45 +00002316 } else {
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00002317 assert(isa<MemTransferInst>(MI));
2318 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
2319 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
Bob Wilson328e91b2011-01-13 20:59:44 +00002320
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00002321 if (isa<MemCpyInst>(MI))
2322 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2323 else
2324 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
Chris Lattner9a2de652009-01-07 07:18:45 +00002325 }
Chris Lattner66e6a822007-03-05 07:52:57 +00002326 }
Bob Wilson532cd232009-12-18 20:14:40 +00002327 DeadInsts.push_back(MI);
Chris Lattner66e6a822007-03-05 07:52:57 +00002328}
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002329
Bob Wilson050b8122009-12-04 21:57:37 +00002330/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002331/// overwrites the entire allocation. Extract out the pieces of the stored
2332/// integer and store them individually.
Craig Topperb94011f2013-07-14 04:42:23 +00002333void
2334SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
2335 SmallVectorImpl<AllocaInst *> &NewElts) {
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002336 // Extract each element out of the integer according to its structure offset
2337 // and store the element value to the individual alloca.
2338 Value *SrcVal = SI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002339 Type *AllocaEltTy = AI->getAllocatedType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002340 uint64_t AllocaSizeBits = DL->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002341
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002342 IRBuilder<> Builder(SI);
Nadav Rotem465834c2012-07-24 10:51:42 +00002343
Eli Friedmanee94e3c2009-06-01 09:14:32 +00002344 // Handle tail padding by extending the operand
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002345 if (DL->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002346 SrcVal = Builder.CreateZExt(SrcVal,
2347 IntegerType::get(SI->getContext(), AllocaSizeBits));
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002348
David Greene48c86be2010-01-05 01:27:09 +00002349 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky7465cd72009-09-15 07:08:25 +00002350 << '\n');
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002351
2352 // There are two forms here: AI could be an array or struct. Both cases
2353 // have different ways to compute the element offset.
Chris Lattner229907c2011-07-18 04:54:35 +00002354 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002355 const StructLayout *Layout = DL->getStructLayout(EltSTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002356
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002357 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2358 // Get the number of bits to shift SrcVal to get the value.
Chris Lattner229907c2011-07-18 04:54:35 +00002359 Type *FieldTy = EltSTy->getElementType(i);
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002360 uint64_t Shift = Layout->getElementOffsetInBits(i);
Bob Wilson328e91b2011-01-13 20:59:44 +00002361
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002362 if (DL->isBigEndian())
2363 Shift = AllocaSizeBits-Shift-DL->getTypeAllocSizeInBits(FieldTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002364
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002365 Value *EltVal = SrcVal;
2366 if (Shift) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002367 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002368 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002369 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002370
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002371 // Truncate down to an integer of the right size.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002372 uint64_t FieldSizeBits = DL->getTypeSizeInBits(FieldTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002373
Chris Lattnerae0e8572009-01-09 18:18:43 +00002374 // Ignore zero sized fields like {}, they obviously contain no data.
2375 if (FieldSizeBits == 0) continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00002376
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002377 if (FieldSizeBits != AllocaSizeBits)
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002378 EltVal = Builder.CreateTrunc(EltVal,
2379 IntegerType::get(SI->getContext(), FieldSizeBits));
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002380 Value *DestField = NewElts[i];
2381 if (EltVal->getType() == FieldTy) {
2382 // Storing to an integer field of this size, just do it.
Duncan Sands19d0b472010-02-16 11:11:14 +00002383 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002384 // Bitcast to the right element type (for fp/vector values).
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002385 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002386 } else {
2387 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002388 DestField = Builder.CreateBitCast(DestField,
2389 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002390 }
2391 new StoreInst(EltVal, DestField, SI);
2392 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002393
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002394 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002395 ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2396 Type *ArrayEltTy = ATy->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002397 uint64_t ElementOffset = DL->getTypeAllocSizeInBits(ArrayEltTy);
2398 uint64_t ElementSizeBits = DL->getTypeSizeInBits(ArrayEltTy);
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002399
2400 uint64_t Shift;
Bob Wilson328e91b2011-01-13 20:59:44 +00002401
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002402 if (DL->isBigEndian())
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002403 Shift = AllocaSizeBits-ElementOffset;
Bob Wilson328e91b2011-01-13 20:59:44 +00002404 else
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002405 Shift = 0;
Bob Wilson328e91b2011-01-13 20:59:44 +00002406
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002407 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattnerae0e8572009-01-09 18:18:43 +00002408 // Ignore zero sized fields like {}, they obviously contain no data.
2409 if (ElementSizeBits == 0) continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00002410
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002411 Value *EltVal = SrcVal;
2412 if (Shift) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002413 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002414 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002415 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002416
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002417 // Truncate down to an integer of the right size.
2418 if (ElementSizeBits != AllocaSizeBits)
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002419 EltVal = Builder.CreateTrunc(EltVal,
2420 IntegerType::get(SI->getContext(),
2421 ElementSizeBits));
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002422 Value *DestField = NewElts[i];
2423 if (EltVal->getType() == ArrayEltTy) {
2424 // Storing to an integer field of this size, just do it.
Duncan Sands9dff9be2010-02-15 16:12:20 +00002425 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +00002426 ArrayEltTy->isVectorTy()) {
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002427 // Bitcast to the right element type (for fp/vector values).
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002428 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002429 } else {
2430 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002431 DestField = Builder.CreateBitCast(DestField,
2432 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002433 }
2434 new StoreInst(EltVal, DestField, SI);
Bob Wilson328e91b2011-01-13 20:59:44 +00002435
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002436 if (DL->isBigEndian())
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002437 Shift -= ElementOffset;
Bob Wilson328e91b2011-01-13 20:59:44 +00002438 else
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002439 Shift += ElementOffset;
2440 }
2441 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002442
Bob Wilson532cd232009-12-18 20:14:40 +00002443 DeadInsts.push_back(SI);
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002444}
2445
Bob Wilson050b8122009-12-04 21:57:37 +00002446/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002447/// an integer. Load the individual pieces to form the aggregate value.
Craig Topperb94011f2013-07-14 04:42:23 +00002448void
2449SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
2450 SmallVectorImpl<AllocaInst *> &NewElts) {
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002451 // Extract each element out of the NewElts according to its structure offset
2452 // and form the result value.
Chris Lattner229907c2011-07-18 04:54:35 +00002453 Type *AllocaEltTy = AI->getAllocatedType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002454 uint64_t AllocaSizeBits = DL->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002455
David Greene48c86be2010-01-05 01:27:09 +00002456 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky7465cd72009-09-15 07:08:25 +00002457 << '\n');
Bob Wilson328e91b2011-01-13 20:59:44 +00002458
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002459 // There are two forms here: AI could be an array or struct. Both cases
2460 // have different ways to compute the element offset.
2461 const StructLayout *Layout = 0;
2462 uint64_t ArrayEltBitOffset = 0;
Chris Lattner229907c2011-07-18 04:54:35 +00002463 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002464 Layout = DL->getStructLayout(EltSTy);
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002465 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002466 Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002467 ArrayEltBitOffset = DL->getTypeAllocSizeInBits(ArrayEltTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002468 }
2469
2470 Value *ResultVal =
Owen Anderson55f1c092009-08-13 21:58:54 +00002471 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Bob Wilson328e91b2011-01-13 20:59:44 +00002472
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002473 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2474 // Load the value from the alloca. If the NewElt is an aggregate, cast
2475 // the pointer to an integer of the same size before doing the load.
2476 Value *SrcField = NewElts[i];
Chris Lattner229907c2011-07-18 04:54:35 +00002477 Type *FieldTy =
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002478 cast<PointerType>(SrcField->getType())->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002479 uint64_t FieldSizeBits = DL->getTypeSizeInBits(FieldTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002480
Chris Lattnerae0e8572009-01-09 18:18:43 +00002481 // Ignore zero sized fields like {}, they obviously contain no data.
2482 if (FieldSizeBits == 0) continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00002483
Chris Lattner229907c2011-07-18 04:54:35 +00002484 IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00002485 FieldSizeBits);
Duncan Sands19d0b472010-02-16 11:11:14 +00002486 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2487 !FieldTy->isVectorTy())
Owen Anderson340288c2009-07-03 19:42:02 +00002488 SrcField = new BitCastInst(SrcField,
Owen Anderson4056ca92009-07-29 22:17:13 +00002489 PointerType::getUnqual(FieldIntTy),
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002490 "", LI);
2491 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2492
2493 // If SrcField is a fp or vector of the right size but that isn't an
2494 // integer type, bitcast to an integer so we can shift it.
2495 if (SrcField->getType() != FieldIntTy)
2496 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2497
2498 // Zero extend the field to be the same size as the final alloca so that
2499 // we can shift and insert it.
2500 if (SrcField->getType() != ResultVal->getType())
2501 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
Bob Wilson328e91b2011-01-13 20:59:44 +00002502
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002503 // Determine the number of bits to shift SrcField.
2504 uint64_t Shift;
2505 if (Layout) // Struct case.
2506 Shift = Layout->getElementOffsetInBits(i);
2507 else // Array case.
2508 Shift = i*ArrayEltBitOffset;
Bob Wilson328e91b2011-01-13 20:59:44 +00002509
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002510 if (DL->isBigEndian())
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002511 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
Bob Wilson328e91b2011-01-13 20:59:44 +00002512
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002513 if (Shift) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002514 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002515 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2516 }
2517
Chris Lattner25a843f2010-06-27 07:58:26 +00002518 // Don't create an 'or x, 0' on the first iteration.
2519 if (!isa<Constant>(ResultVal) ||
2520 !cast<Constant>(ResultVal)->isNullValue())
2521 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2522 else
2523 ResultVal = SrcField;
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002524 }
Eli Friedmanee94e3c2009-06-01 09:14:32 +00002525
2526 // Handle tail padding by truncating the result
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002527 if (DL->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
Eli Friedmanee94e3c2009-06-01 09:14:32 +00002528 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2529
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002530 LI->replaceAllUsesWith(ResultVal);
Bob Wilson532cd232009-12-18 20:14:40 +00002531 DeadInsts.push_back(LI);
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002532}
2533
Duncan Sands399d9792007-11-04 14:43:57 +00002534/// HasPadding - Return true if the specified type has any structure or
Bob Wilson12eec402011-01-13 17:45:08 +00002535/// alignment padding in between the elements that would be split apart
2536/// by SROA; return false otherwise.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002537static bool HasPadding(Type *Ty, const DataLayout &DL) {
Chris Lattner229907c2011-07-18 04:54:35 +00002538 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Bob Wilson12eec402011-01-13 17:45:08 +00002539 Ty = ATy->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002540 return DL.getTypeSizeInBits(Ty) != DL.getTypeAllocSizeInBits(Ty);
Chris Lattner87679202007-05-30 06:11:23 +00002541 }
Bob Wilson12eec402011-01-13 17:45:08 +00002542
2543 // SROA currently handles only Arrays and Structs.
Chris Lattner229907c2011-07-18 04:54:35 +00002544 StructType *STy = cast<StructType>(Ty);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002545 const StructLayout *SL = DL.getStructLayout(STy);
Bob Wilson12eec402011-01-13 17:45:08 +00002546 unsigned PrevFieldBitOffset = 0;
2547 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2548 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2549
2550 // Check to see if there is any padding between this element and the
2551 // previous one.
2552 if (i) {
2553 unsigned PrevFieldEnd =
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002554 PrevFieldBitOffset+DL.getTypeSizeInBits(STy->getElementType(i-1));
Bob Wilson12eec402011-01-13 17:45:08 +00002555 if (PrevFieldEnd < FieldBitOffset)
2556 return true;
2557 }
2558 PrevFieldBitOffset = FieldBitOffset;
2559 }
2560 // Check for tail padding.
2561 if (unsigned EltCount = STy->getNumElements()) {
2562 unsigned PrevFieldEnd = PrevFieldBitOffset +
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002563 DL.getTypeSizeInBits(STy->getElementType(EltCount-1));
Bob Wilson12eec402011-01-13 17:45:08 +00002564 if (PrevFieldEnd < SL->getSizeInBits())
2565 return true;
2566 }
2567 return false;
Chris Lattner87679202007-05-30 06:11:23 +00002568}
Chris Lattner66e6a822007-03-05 07:52:57 +00002569
Chris Lattner88819122004-11-14 04:24:28 +00002570/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2571/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2572/// or 1 if safe after canonicalization has been performed.
Victor Hernandez1df65182010-01-21 23:05:53 +00002573bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner6e5398d2003-05-30 04:15:41 +00002574 // Loop over the use list of the alloca. We can only transform it if all of
2575 // the users are safe to transform.
Chris Lattner8acbb792011-01-23 07:29:29 +00002576 AllocaInfo Info(AI);
Bob Wilson328e91b2011-01-13 20:59:44 +00002577
Chris Lattner8acbb792011-01-23 07:29:29 +00002578 isSafeForScalarRepl(AI, 0, Info);
Bob Wilson532cd232009-12-18 20:14:40 +00002579 if (Info.isUnsafe) {
David Greene48c86be2010-01-05 01:27:09 +00002580 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez1df65182010-01-21 23:05:53 +00002581 return false;
Chris Lattner88819122004-11-14 04:24:28 +00002582 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002583
Chris Lattner87679202007-05-30 06:11:23 +00002584 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2585 // source and destination, we have to be careful. In particular, the memcpy
2586 // could be moving around elements that live in structure padding of the LLVM
2587 // types, but may actually be used. In these cases, we refuse to promote the
2588 // struct.
2589 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002590 HasPadding(AI->getAllocatedType(), *DL))
Victor Hernandez1df65182010-01-21 23:05:53 +00002591 return false;
Duncan Sands399d9792007-11-04 14:43:57 +00002592
Chris Lattner7c9f4c92011-01-16 17:46:19 +00002593 // If the alloca never has an access to just *part* of it, but is accessed
2594 // via loads and stores, then we should use ConvertToScalarInfo to promote
Chris Lattner6fab2e92011-01-16 06:18:28 +00002595 // the alloca instead of promoting each piece at a time and inserting fission
2596 // and fusion code.
2597 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2598 // If the struct/array just has one element, use basic SRoA.
Chris Lattner229907c2011-07-18 04:54:35 +00002599 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
Chris Lattner6fab2e92011-01-16 06:18:28 +00002600 if (ST->getNumElements() > 1) return false;
2601 } else {
2602 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2603 return false;
2604 }
2605 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002606
Victor Hernandez1df65182010-01-21 23:05:53 +00002607 return true;
Chris Lattner6e5398d2003-05-30 04:15:41 +00002608}