blob: 579ce13e0b975941a1fcd8bcd5461bcd11396701 [file] [log] [blame]
Chris Lattnerfb41a502003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerfb41a502003-05-27 15:45:27 +00009//
10// This transformation implements the well known scalar replacement of
11// aggregates transformation. This xform breaks up alloca instructions of
12// aggregate type (structure or array) into individual alloca instructions for
Chris Lattner5d8a12e2003-09-11 16:45:55 +000013// each member (if possible). Then, if possible, it transforms the individual
14// alloca instructions into nice clean scalar SSA form.
15//
Chad Rosiercc899f32012-04-11 19:21:58 +000016// This combines a simple SRoA algorithm with the Mem2Reg algorithm because they
Chris Lattner5d8a12e2003-09-11 16:45:55 +000017// often interact, especially for C++ programs. As such, iterating between
18// SRoA, then Mem2Reg until we run out of things to promote works well.
Chris Lattnerfb41a502003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
22#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/ADT/SetVector.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Analysis/Loads.h"
27#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000028#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000030#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000032#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#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"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000036#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/GlobalVariable.h"
38#include "llvm/IR/IRBuilder.h"
39#include "llvm/IR/Instructions.h"
40#include "llvm/IR/IntrinsicInst.h"
41#include "llvm/IR/LLVMContext.h"
42#include "llvm/IR/Module.h"
43#include "llvm/IR/Operator.h"
Chris Lattner66e6a822007-03-05 07:52:57 +000044#include "llvm/Pass.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/MathExtras.h"
Chris Lattnerb25de3f2009-08-23 04:37:46 +000048#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000049#include "llvm/Transforms/Utils/Local.h"
50#include "llvm/Transforms/Utils/PromoteMemToReg.h"
51#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner40d2aeb2003-12-02 17:43:55 +000052using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000053
Chandler Carruth964daaa2014-04-22 02:55:47 +000054#define DEBUG_TYPE "scalarrepl"
55
Chris Lattner79a42ac2006-12-19 21:40:18 +000056STATISTIC(NumReplaced, "Number of allocas broken up");
57STATISTIC(NumPromoted, "Number of allocas promoted");
Chris Lattnera9607252011-01-23 22:04:55 +000058STATISTIC(NumAdjusted, "Number of scalar allocas adjusted to allow promotion");
Chris Lattner79a42ac2006-12-19 21:40:18 +000059STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattnerfb41a502003-05-27 15:45:27 +000060
Chris Lattner79a42ac2006-12-19 21:40:18 +000061namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +000062 struct SROA : public FunctionPass {
Nadav Rotem4e9012c2012-06-21 13:44:31 +000063 SROA(int T, bool hasDT, char &ID, int ST, int AT, int SLT)
Cameron Zwarich4694e692011-01-18 03:53:26 +000064 : FunctionPass(ID), HasDomTree(hasDT) {
Devang Patele8ec7662007-07-09 21:19:23 +000065 if (T == -1)
Chris Lattner1f708162007-08-02 21:33:36 +000066 SRThreshold = 128;
Devang Patele8ec7662007-07-09 21:19:23 +000067 else
68 SRThreshold = T;
Nadav Rotem4e9012c2012-06-21 13:44:31 +000069 if (ST == -1)
70 StructMemberThreshold = 32;
71 else
72 StructMemberThreshold = ST;
73 if (AT == -1)
74 ArrayElementThreshold = 8;
75 else
76 ArrayElementThreshold = AT;
77 if (SLT == -1)
78 // Do not limit the scalar integer load size if no threshold is given.
79 ScalarLoadThreshold = -1;
80 else
81 ScalarLoadThreshold = SLT;
Devang Patele8ec7662007-07-09 21:19:23 +000082 }
Devang Patel09f162c2007-05-01 21:15:47 +000083
Craig Topper3e4c6972014-03-05 09:10:37 +000084 bool runOnFunction(Function &F) override;
Chris Lattnerfb41a502003-05-27 15:45:27 +000085
Chris Lattner5d8a12e2003-09-11 16:45:55 +000086 bool performScalarRepl(Function &F);
87 bool performPromotion(Function &F);
88
Chris Lattnerfb41a502003-05-27 15:45:27 +000089 private:
Cameron Zwarich4694e692011-01-18 03:53:26 +000090 bool HasDomTree;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +000091 const DataLayout *DL;
Bob Wilson328e91b2011-01-13 20:59:44 +000092
Bob Wilson532cd232009-12-18 20:14:40 +000093 /// DeadInsts - Keep track of instructions we have made dead, so that
94 /// we can remove them after we are done working.
95 SmallVector<Value*, 32> DeadInsts;
96
Chris Lattner87679202007-05-30 06:11:23 +000097 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
98 /// information about the uses. All these fields are initialized to false
99 /// and set to true when something is learned.
100 struct AllocaInfo {
Chris Lattner8acbb792011-01-23 07:29:29 +0000101 /// The alloca to promote.
102 AllocaInst *AI;
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000103
Chris Lattner9491dee2011-01-23 08:27:54 +0000104 /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
105 /// looping and avoid redundant work.
106 SmallPtrSet<PHINode*, 8> CheckedPHIs;
Nadav Rotem465834c2012-07-24 10:51:42 +0000107
Chris Lattner87679202007-05-30 06:11:23 +0000108 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
109 bool isUnsafe : 1;
Bob Wilson328e91b2011-01-13 20:59:44 +0000110
Chris Lattner87679202007-05-30 06:11:23 +0000111 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
112 bool isMemCpySrc : 1;
113
Zhou Sheng1ee941d2007-07-06 06:01:16 +0000114 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner87679202007-05-30 06:11:23 +0000115 bool isMemCpyDst : 1;
116
Chris Lattner6fab2e92011-01-16 06:18:28 +0000117 /// hasSubelementAccess - This is true if a subelement of the alloca is
118 /// ever accessed, or false if the alloca is only accessed with mem
119 /// intrinsics or load/store that only access the entire alloca at once.
120 bool hasSubelementAccess : 1;
Nadav Rotem465834c2012-07-24 10:51:42 +0000121
Chris Lattner6fab2e92011-01-16 06:18:28 +0000122 /// hasALoadOrStore - This is true if there are any loads or stores to it.
123 /// The alloca may just be accessed with memcpy, for example, which would
124 /// not set this.
125 bool hasALoadOrStore : 1;
Nadav Rotem465834c2012-07-24 10:51:42 +0000126
Chris Lattner8acbb792011-01-23 07:29:29 +0000127 explicit AllocaInfo(AllocaInst *ai)
128 : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
Chris Lattner6fab2e92011-01-16 06:18:28 +0000129 hasSubelementAccess(false), hasALoadOrStore(false) {}
Chris Lattner87679202007-05-30 06:11:23 +0000130 };
Bob Wilson328e91b2011-01-13 20:59:44 +0000131
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000132 /// SRThreshold - The maximum alloca size to considered for SROA.
Devang Patele8ec7662007-07-09 21:19:23 +0000133 unsigned SRThreshold;
134
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000135 /// StructMemberThreshold - The maximum number of members a struct can
136 /// contain to be considered for SROA.
137 unsigned StructMemberThreshold;
138
139 /// ArrayElementThreshold - The maximum number of elements an array can
140 /// have to be considered for SROA.
141 unsigned ArrayElementThreshold;
142
143 /// ScalarLoadThreshold - The maximum size in bits of scalars to load when
144 /// converting to scalar
145 unsigned ScalarLoadThreshold;
146
Chris Lattner3e56c292011-01-23 07:05:44 +0000147 void MarkUnsafe(AllocaInfo &I, Instruction *User) {
148 I.isUnsafe = true;
149 DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
150 }
Chris Lattner87679202007-05-30 06:11:23 +0000151
Victor Hernandez1df65182010-01-21 23:05:53 +0000152 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner87679202007-05-30 06:11:23 +0000153
Chris Lattner8acbb792011-01-23 07:29:29 +0000154 void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
Chris Lattner9491dee2011-01-23 08:27:54 +0000155 void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
156 AllocaInfo &Info);
Chris Lattner8acbb792011-01-23 07:29:29 +0000157 void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
158 void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattner229907c2011-07-18 04:54:35 +0000159 Type *MemOpType, bool isStore, AllocaInfo &Info,
Chris Lattner9491dee2011-01-23 08:27:54 +0000160 Instruction *TheAccess, bool AllowWholeAccess);
Chris Lattner229907c2011-07-18 04:54:35 +0000161 bool TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size);
162 uint64_t FindElementAndOffset(Type *&T, uint64_t &Offset,
163 Type *&IdxTy);
Bob Wilson328e91b2011-01-13 20:59:44 +0000164
165 void DoScalarReplacement(AllocaInst *AI,
Victor Hernandez8acf2952009-10-23 21:09:37 +0000166 std::vector<AllocaInst*> &WorkList);
Bob Wilson532cd232009-12-18 20:14:40 +0000167 void DeleteDeadInstructions();
Bob Wilson328e91b2011-01-13 20:59:44 +0000168
Bob Wilson532cd232009-12-18 20:14:40 +0000169 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +0000170 SmallVectorImpl<AllocaInst *> &NewElts);
Bob Wilson532cd232009-12-18 20:14:40 +0000171 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +0000172 SmallVectorImpl<AllocaInst *> &NewElts);
Bob Wilson532cd232009-12-18 20:14:40 +0000173 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +0000174 SmallVectorImpl<AllocaInst *> &NewElts);
Nick Lewycky15e2d902011-07-25 23:14:22 +0000175 void RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
176 uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +0000177 SmallVectorImpl<AllocaInst *> &NewElts);
Bob Wilson532cd232009-12-18 20:14:40 +0000178 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez8acf2952009-10-23 21:09:37 +0000179 AllocaInst *AI,
Craig Topperb94011f2013-07-14 04:42:23 +0000180 SmallVectorImpl<AllocaInst *> &NewElts);
Victor Hernandez8acf2952009-10-23 21:09:37 +0000181 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Craig Topperb94011f2013-07-14 04:42:23 +0000182 SmallVectorImpl<AllocaInst *> &NewElts);
Victor Hernandez8acf2952009-10-23 21:09:37 +0000183 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Craig Topperb94011f2013-07-14 04:42:23 +0000184 SmallVectorImpl<AllocaInst *> &NewElts);
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000185 bool ShouldAttemptScalarRepl(AllocaInst *AI);
Chris Lattnerfb41a502003-05-27 15:45:27 +0000186 };
Nadav Rotem465834c2012-07-24 10:51:42 +0000187
Cameron Zwarich4694e692011-01-18 03:53:26 +0000188 // SROA_DT - SROA that uses DominatorTree.
189 struct SROA_DT : public SROA {
Chris Lattner9987a6f2011-01-14 08:13:00 +0000190 static char ID;
191 public:
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000192 SROA_DT(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
193 SROA(T, true, ID, ST, AT, SLT) {
Cameron Zwarich4694e692011-01-18 03:53:26 +0000194 initializeSROA_DTPass(*PassRegistry::getPassRegistry());
Chris Lattner9987a6f2011-01-14 08:13:00 +0000195 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000196
Chris Lattner9987a6f2011-01-14 08:13:00 +0000197 // getAnalysisUsage - This pass does not require any passes, but we know it
198 // will not alter the CFG, so say so.
Craig Topper3e4c6972014-03-05 09:10:37 +0000199 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000200 AU.addRequired<DominatorTreeWrapperPass>();
Chris Lattner9987a6f2011-01-14 08:13:00 +0000201 AU.setPreservesCFG();
202 }
203 };
Nadav Rotem465834c2012-07-24 10:51:42 +0000204
Chris Lattner9987a6f2011-01-14 08:13:00 +0000205 // SROA_SSAUp - SROA that uses SSAUpdater.
206 struct SROA_SSAUp : public SROA {
207 static char ID;
208 public:
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000209 SROA_SSAUp(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
210 SROA(T, false, ID, ST, AT, SLT) {
Chris Lattner9987a6f2011-01-14 08:13:00 +0000211 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
212 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000213
Chris Lattner9987a6f2011-01-14 08:13:00 +0000214 // getAnalysisUsage - This pass does not require any passes, but we know it
215 // will not alter the CFG, so say so.
Craig Topper3e4c6972014-03-05 09:10:37 +0000216 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chris Lattner9987a6f2011-01-14 08:13:00 +0000217 AU.setPreservesCFG();
218 }
219 };
Nadav Rotem465834c2012-07-24 10:51:42 +0000220
Chris Lattnerfb41a502003-05-27 15:45:27 +0000221}
222
Cameron Zwarich4694e692011-01-18 03:53:26 +0000223char SROA_DT::ID = 0;
Chris Lattner9987a6f2011-01-14 08:13:00 +0000224char SROA_SSAUp::ID = 0;
225
Cameron Zwarich4694e692011-01-18 03:53:26 +0000226INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
227 "Scalar Replacement of Aggregates (DT)", false, false)
Chandler Carruth73523022014-01-13 13:07:17 +0000228INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Cameron Zwarich4694e692011-01-18 03:53:26 +0000229INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
230 "Scalar Replacement of Aggregates (DT)", false, false)
Chris Lattner9987a6f2011-01-14 08:13:00 +0000231
232INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
233 "Scalar Replacement of Aggregates (SSAUp)", false, false)
234INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
235 "Scalar Replacement of Aggregates (SSAUp)", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000236
Brian Gaeke960707c2003-11-11 22:41:34 +0000237// Public interface to the ScalarReplAggregates pass
Chris Lattner9987a6f2011-01-14 08:13:00 +0000238FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000239 bool UseDomTree,
240 int StructMemberThreshold,
241 int ArrayElementThreshold,
242 int ScalarLoadThreshold) {
Cameron Zwarich4694e692011-01-18 03:53:26 +0000243 if (UseDomTree)
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000244 return new SROA_DT(Threshold, StructMemberThreshold, ArrayElementThreshold,
245 ScalarLoadThreshold);
246 return new SROA_SSAUp(Threshold, StructMemberThreshold,
247 ArrayElementThreshold, ScalarLoadThreshold);
Devang Patele8ec7662007-07-09 21:19:23 +0000248}
Chris Lattnerfb41a502003-05-27 15:45:27 +0000249
250
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000251//===----------------------------------------------------------------------===//
252// Convert To Scalar Optimization.
253//===----------------------------------------------------------------------===//
254
255namespace {
Chris Lattnerb7355292010-04-16 00:38:19 +0000256/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
257/// optimization, which scans the uses of an alloca and determines if it can
258/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000259class ConvertToScalarInfo {
Cameron Zwarich63062cc2011-03-16 00:13:35 +0000260 /// AllocaSize - The size of the alloca being considered in bytes.
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000261 unsigned AllocaSize;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000262 const DataLayout &DL;
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000263 unsigned ScalarLoadThreshold;
Bob Wilson328e91b2011-01-13 20:59:44 +0000264
Chris Lattnerbd2d9432010-04-16 02:32:17 +0000265 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnerb7355292010-04-16 00:38:19 +0000266 /// which means that mem2reg can't promote it.
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000267 bool IsNotTrivial;
Bob Wilson328e91b2011-01-13 20:59:44 +0000268
Cameron Zwarich5e9a0be2011-06-13 21:44:35 +0000269 /// ScalarKind - Tracks the kind of alloca being considered for promotion,
270 /// computed based on the uses of the alloca rather than the LLVM type system.
271 enum {
272 Unknown,
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000273
Cameron Zwarich922e4942011-06-13 23:39:23 +0000274 // Accesses via GEPs that are consistent with element access of a vector
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000275 // type. This will not be converted into a vector unless there is a later
276 // access using an actual vector type.
277 ImplicitVector,
278
Cameron Zwarich922e4942011-06-13 23:39:23 +0000279 // Accesses via vector operations and GEPs that are consistent with the
280 // layout of a vector type.
Cameron Zwarich5e9a0be2011-06-13 21:44:35 +0000281 Vector,
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000282
283 // An integer bag-of-bits with bitwise operations for insertion and
284 // extraction. Any combination of types can be converted into this kind
285 // of scalar.
Cameron Zwarich5e9a0be2011-06-13 21:44:35 +0000286 Integer
287 } ScalarKind;
288
Chris Lattnerb7355292010-04-16 00:38:19 +0000289 /// VectorTy - This tracks the type that we should promote the vector to if
290 /// it is possible to turn it into a vector. This starts out null, and if it
291 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Chris Lattner229907c2011-07-18 04:54:35 +0000292 VectorType *VectorTy;
Bob Wilson328e91b2011-01-13 20:59:44 +0000293
Nadav Rotem465834c2012-07-24 10:51:42 +0000294 /// HadNonMemTransferAccess - True if there is at least one access to the
Cameron Zwarich7599b102011-03-16 08:13:42 +0000295 /// alloca that is not a MemTransferInst. We don't want to turn structs into
296 /// large integers unless there is some potential for optimization.
Cameron Zwarich04542532011-03-16 00:13:44 +0000297 bool HadNonMemTransferAccess;
298
Pete Cooper33ee6c92012-06-17 03:58:26 +0000299 /// HadDynamicAccess - True if some element of this alloca was dynamic.
300 /// We don't yet have support for turning a dynamic access into a large
301 /// integer.
302 bool HadDynamicAccess;
303
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000304public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000305 explicit ConvertToScalarInfo(unsigned Size, const DataLayout &DL,
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000306 unsigned SLT)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000307 : AllocaSize(Size), DL(DL), ScalarLoadThreshold(SLT), IsNotTrivial(false),
Craig Topperf40110f2014-04-25 05:29:35 +0000308 ScalarKind(Unknown), VectorTy(nullptr), HadNonMemTransferAccess(false),
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000309 HadDynamicAccess(false) { }
Bob Wilson328e91b2011-01-13 20:59:44 +0000310
Chris Lattnerb7355292010-04-16 00:38:19 +0000311 AllocaInst *TryConvert(AllocaInst *AI);
Bob Wilson328e91b2011-01-13 20:59:44 +0000312
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000313private:
Pete Cooper33ee6c92012-06-17 03:58:26 +0000314 bool CanConvertToScalar(Value *V, uint64_t Offset, Value* NonConstantIdx);
Chris Lattner229907c2011-07-18 04:54:35 +0000315 void MergeInTypeForLoadOrStore(Type *In, uint64_t Offset);
316 bool MergeInVectorType(VectorType *VInTy, uint64_t Offset);
Pete Cooper33ee6c92012-06-17 03:58:26 +0000317 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset,
318 Value *NonConstantIdx);
Bob Wilson328e91b2011-01-13 20:59:44 +0000319
Chris Lattner229907c2011-07-18 04:54:35 +0000320 Value *ConvertScalar_ExtractValue(Value *NV, Type *ToType,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000321 uint64_t Offset, Value* NonConstantIdx,
322 IRBuilder<> &Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000323 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000324 uint64_t Offset, Value* NonConstantIdx,
325 IRBuilder<> &Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000326};
327} // end anonymous namespace.
328
Chris Lattner34e53612010-09-01 05:14:33 +0000329
Chris Lattnerb7355292010-04-16 00:38:19 +0000330/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
331/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
332/// alloca if possible or null if not.
333AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
334 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
335 // out.
Craig Topperf40110f2014-04-25 05:29:35 +0000336 if (!CanConvertToScalar(AI, 0, nullptr) || !IsNotTrivial)
337 return nullptr;
Bob Wilson328e91b2011-01-13 20:59:44 +0000338
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000339 // If an alloca has only memset / memcpy uses, it may still have an Unknown
340 // ScalarKind. Treat it as an Integer below.
341 if (ScalarKind == Unknown)
342 ScalarKind = Integer;
343
Cameron Zwarich9601ddb2011-06-18 06:17:51 +0000344 if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
345 ScalarKind = Integer;
346
Chris Lattnerb7355292010-04-16 00:38:19 +0000347 // If we were able to find a vector type that can handle this with
348 // insert/extract elements, and if there was at least one use that had
349 // a vector type, promote this to a vector. We don't want to promote
350 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
351 // we just get a lot of insert/extracts. If at least one vector is
352 // involved, then we probably really do have a union of vector/array.
Chris Lattner229907c2011-07-18 04:54:35 +0000353 Type *NewTy;
Cameron Zwarichb5f19d92011-06-14 06:33:51 +0000354 if (ScalarKind == Vector) {
355 assert(VectorTy && "Missing type for vector scalar.");
Chris Lattnerb7355292010-04-16 00:38:19 +0000356 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
357 << *VectorTy << '\n');
358 NewTy = VectorTy; // Use the vector type.
359 } else {
Cameron Zwarich04542532011-03-16 00:13:44 +0000360 unsigned BitWidth = AllocaSize * 8;
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000361
362 // Do not convert to scalar integer if the alloca size exceeds the
363 // scalar load threshold.
364 if (BitWidth > ScalarLoadThreshold)
Craig Topperf40110f2014-04-25 05:29:35 +0000365 return nullptr;
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000366
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000367 if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000368 !HadNonMemTransferAccess && !DL.fitsInLegalInteger(BitWidth))
Craig Topperf40110f2014-04-25 05:29:35 +0000369 return nullptr;
Pete Cooper33ee6c92012-06-17 03:58:26 +0000370 // Dynamic accesses on integers aren't yet supported. They need us to shift
371 // by a dynamic amount which could be difficult to work out as we might not
372 // know whether to use a left or right shift.
373 if (ScalarKind == Integer && HadDynamicAccess)
Craig Topperf40110f2014-04-25 05:29:35 +0000374 return nullptr;
Cameron Zwarich04542532011-03-16 00:13:44 +0000375
Chris Lattnerb7355292010-04-16 00:38:19 +0000376 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
377 // Create and insert the integer alloca.
Cameron Zwarich04542532011-03-16 00:13:44 +0000378 NewTy = IntegerType::get(AI->getContext(), BitWidth);
Chris Lattnerb7355292010-04-16 00:38:19 +0000379 }
Craig Topperf40110f2014-04-25 05:29:35 +0000380 AllocaInst *NewAI = new AllocaInst(NewTy, nullptr, "",
381 AI->getParent()->begin());
382 ConvertUsesToScalar(AI, NewAI, 0, nullptr);
Chris Lattnerb7355292010-04-16 00:38:19 +0000383 return NewAI;
384}
385
Cameron Zwarich3ecbd592011-06-13 21:44:43 +0000386/// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
387/// (VectorTy) so far at the offset specified by Offset (which is specified in
388/// bytes).
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000389///
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000390/// There are two cases we handle here:
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000391/// 1) A union of vector types of the same size and potentially its elements.
392/// Here we turn element accesses into insert/extract element operations.
393/// This promotes a <4 x float> with a store of float to the third element
394/// into a <4 x float> that uses insert element.
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000395/// 2) A fully general blob of memory, which we turn into some (potentially
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000396/// large) integer type with extract and insert operations where the loads
Chris Lattnerb7355292010-04-16 00:38:19 +0000397/// and stores would mutate the memory. We mark this by setting VectorTy
398/// to VoidTy.
Chris Lattner229907c2011-07-18 04:54:35 +0000399void ConvertToScalarInfo::MergeInTypeForLoadOrStore(Type *In,
Cameron Zwarich3ecbd592011-06-13 21:44:43 +0000400 uint64_t Offset) {
Chris Lattnerb7355292010-04-16 00:38:19 +0000401 // If we already decided to turn this into a blob of integer memory, there is
402 // nothing to be done.
Cameron Zwarich5e9a0be2011-06-13 21:44:35 +0000403 if (ScalarKind == Integer)
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000404 return;
Bob Wilson328e91b2011-01-13 20:59:44 +0000405
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000406 // If this could be contributing to a vector, analyze it.
407
408 // If the In type is a vector that is the same size as the alloca, see if it
409 // matches the existing VecTy.
Chris Lattner229907c2011-07-18 04:54:35 +0000410 if (VectorType *VInTy = dyn_cast<VectorType>(In)) {
Cameron Zwarich43a241f2011-03-09 05:43:01 +0000411 if (MergeInVectorType(VInTy, Offset))
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000412 return;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000413 } else if (In->isFloatTy() || In->isDoubleTy() ||
414 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
415 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
Cameron Zwarichff811cc2011-03-29 05:19:52 +0000416 // Full width accesses can be ignored, because they can always be turned
417 // into bitcasts.
418 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
Cameron Zwarich8deb6152011-06-13 21:44:31 +0000419 if (EltSize == AllocaSize)
Cameron Zwarichff811cc2011-03-29 05:19:52 +0000420 return;
Cameron Zwarich4cd9a4a2011-04-20 21:48:16 +0000421
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000422 // If we're accessing something that could be an element of a vector, see
423 // if the implied vector agrees with what we already have and if Offset is
424 // compatible with it.
Cameron Zwarich77a699a2011-06-09 01:45:33 +0000425 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000426 (!VectorTy || EltSize == VectorTy->getElementType()
427 ->getPrimitiveSizeInBits()/8)) {
Cameron Zwarich4cd9a4a2011-04-20 21:48:16 +0000428 if (!VectorTy) {
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000429 ScalarKind = ImplicitVector;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000430 VectorTy = VectorType::get(In, AllocaSize/EltSize);
Cameron Zwarich4cd9a4a2011-04-20 21:48:16 +0000431 }
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000432 return;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000433 }
434 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000435
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000436 // Otherwise, we have a case that we can't handle with an optimized vector
437 // form. We can still turn this into a large integer.
Cameron Zwarich5e9a0be2011-06-13 21:44:35 +0000438 ScalarKind = Integer;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000439}
440
Cameron Zwarich3ecbd592011-06-13 21:44:43 +0000441/// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
442/// returning true if the type was successfully merged and false otherwise.
Chris Lattner229907c2011-07-18 04:54:35 +0000443bool ConvertToScalarInfo::MergeInVectorType(VectorType *VInTy,
Cameron Zwarich43a241f2011-03-09 05:43:01 +0000444 uint64_t Offset) {
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000445 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
446 // If we're storing/loading a vector of the right size, allow it as a
447 // vector. If this the first vector we see, remember the type so that
448 // we know the element size. If this is a subsequent access, ignore it
449 // even if it is a differing type but the same size. Worst case we can
450 // bitcast the resultant vectors.
451 if (!VectorTy)
452 VectorTy = VInTy;
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000453 ScalarKind = Vector;
Cameron Zwarich3b649f42011-03-09 05:43:05 +0000454 return true;
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000455 }
Cameron Zwarich3b649f42011-03-09 05:43:05 +0000456
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000457 return false;
Cameron Zwarich43a241f2011-03-09 05:43:01 +0000458}
459
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000460/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
461/// its accesses to a single vector type, return true and set VecTy to
462/// the new type. If we could convert the alloca into a single promotable
463/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
464/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
465/// is the current offset from the base of the alloca being analyzed.
466///
467/// If we see at least one access to the value that is as a vector type, set the
468/// SawVec flag.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000469bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset,
470 Value* NonConstantIdx) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000471 for (User *U : V->users()) {
472 Instruction *UI = cast<Instruction>(U);
Bob Wilson328e91b2011-01-13 20:59:44 +0000473
Chandler Carruthcdf47882014-03-09 03:16:01 +0000474 if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000475 // Don't break volatile loads.
Eli Friedman7c5dc122011-09-12 20:23:13 +0000476 if (!LI->isSimple())
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000477 return false;
Dale Johannesendd224d22010-09-30 23:57:10 +0000478 // Don't touch MMX operations.
479 if (LI->getType()->isX86_MMXTy())
480 return false;
Cameron Zwarich04542532011-03-16 00:13:44 +0000481 HadNonMemTransferAccess = true;
Cameron Zwarich3ecbd592011-06-13 21:44:43 +0000482 MergeInTypeForLoadOrStore(LI->getType(), Offset);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000483 continue;
484 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000485
Chandler Carruthcdf47882014-03-09 03:16:01 +0000486 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000487 // Storing the pointer, not into the value?
Eli Friedman7c5dc122011-09-12 20:23:13 +0000488 if (SI->getOperand(0) == V || !SI->isSimple()) return false;
Dale Johannesendd224d22010-09-30 23:57:10 +0000489 // Don't touch MMX operations.
490 if (SI->getOperand(0)->getType()->isX86_MMXTy())
491 return false;
Cameron Zwarich04542532011-03-16 00:13:44 +0000492 HadNonMemTransferAccess = true;
Cameron Zwarich3ecbd592011-06-13 21:44:43 +0000493 MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000494 continue;
495 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000496
Chandler Carruthcdf47882014-03-09 03:16:01 +0000497 if (BitCastInst *BCI = dyn_cast<BitCastInst>(UI)) {
Nick Lewycky15e2d902011-07-25 23:14:22 +0000498 if (!onlyUsedByLifetimeMarkers(BCI))
499 IsNotTrivial = true; // Can't be mem2reg'd.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000500 if (!CanConvertToScalar(BCI, Offset, NonConstantIdx))
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000501 return false;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000502 continue;
503 }
504
Chandler Carruthcdf47882014-03-09 03:16:01 +0000505 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UI)) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000506 // If this is a GEP with a variable indices, we can't handle it.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000507 PointerType* PtrTy = dyn_cast<PointerType>(GEP->getPointerOperandType());
508 if (!PtrTy)
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000509 return false;
Bob Wilson328e91b2011-01-13 20:59:44 +0000510
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000511 // Compute the offset that this GEP adds to the pointer.
512 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Craig Topperf40110f2014-04-25 05:29:35 +0000513 Value *GEPNonConstantIdx = nullptr;
Pete Cooper33ee6c92012-06-17 03:58:26 +0000514 if (!GEP->hasAllConstantIndices()) {
515 if (!isa<VectorType>(PtrTy->getElementType()))
516 return false;
517 if (NonConstantIdx)
518 return false;
519 GEPNonConstantIdx = Indices.pop_back_val();
520 if (!GEPNonConstantIdx->getType()->isIntegerTy(32))
521 return false;
522 HadDynamicAccess = true;
523 } else
524 GEPNonConstantIdx = NonConstantIdx;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000525 uint64_t GEPOffset = DL.getIndexedOffset(PtrTy,
Jay Foadbf904772011-07-19 14:01:37 +0000526 Indices);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000527 // See if all uses can be converted.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000528 if (!CanConvertToScalar(GEP, Offset+GEPOffset, GEPNonConstantIdx))
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000529 return false;
Chris Lattnerb7355292010-04-16 00:38:19 +0000530 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich04542532011-03-16 00:13:44 +0000531 HadNonMemTransferAccess = true;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000532 continue;
533 }
534
535 // If this is a constant sized memset of a constant value (e.g. 0) we can
536 // handle it.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000537 if (MemSetInst *MSI = dyn_cast<MemSetInst>(UI)) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000538 // Store to dynamic index.
539 if (NonConstantIdx)
540 return false;
Cameron Zwarich2a261002011-06-18 05:47:49 +0000541 // Store of constant value.
542 if (!isa<ConstantInt>(MSI->getValue()))
Chris Lattnerb7355292010-04-16 00:38:19 +0000543 return false;
Cameron Zwarich2a261002011-06-18 05:47:49 +0000544
545 // Store of constant size.
546 ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
547 if (!Len)
548 return false;
549
550 // If the size differs from the alloca, we can only convert the alloca to
551 // an integer bag-of-bits.
552 // FIXME: This should handle all of the cases that are currently accepted
553 // as vector element insertions.
554 if (Len->getZExtValue() != AllocaSize || Offset != 0)
555 ScalarKind = Integer;
556
Chris Lattnerb7355292010-04-16 00:38:19 +0000557 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich04542532011-03-16 00:13:44 +0000558 HadNonMemTransferAccess = true;
Chris Lattnerb7355292010-04-16 00:38:19 +0000559 continue;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000560 }
561
562 // If this is a memcpy or memmove into or out of the whole allocation, we
563 // can handle it like a load or store of the scalar type.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000564 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(UI)) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000565 // Store to dynamic index.
566 if (NonConstantIdx)
567 return false;
Chris Lattnerb7355292010-04-16 00:38:19 +0000568 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +0000569 if (!Len || Len->getZExtValue() != AllocaSize || Offset != 0)
Chris Lattnerb7355292010-04-16 00:38:19 +0000570 return false;
Bob Wilson328e91b2011-01-13 20:59:44 +0000571
Chris Lattnerb7355292010-04-16 00:38:19 +0000572 IsNotTrivial = true; // Can't be mem2reg'd.
573 continue;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000574 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000575
Nick Lewycky15e2d902011-07-25 23:14:22 +0000576 // If this is a lifetime intrinsic, we can handle it.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000577 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(UI)) {
Nick Lewycky15e2d902011-07-25 23:14:22 +0000578 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
579 II->getIntrinsicID() == Intrinsic::lifetime_end) {
580 continue;
581 }
582 }
583
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000584 // Otherwise, we cannot handle this!
585 return false;
586 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000587
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000588 return true;
589}
590
591/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
592/// directly. This happens when we are converting an "integer union" to a
593/// single integer scalar, or when we are converting a "vector union" to a
594/// vector with insert/extractelement instructions.
595///
596/// Offset is an offset from the original alloca, in bits that need to be
597/// shifted to the right. By the end of this, there should be no uses of Ptr.
598void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000599 uint64_t Offset,
600 Value* NonConstantIdx) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000601 while (!Ptr->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000602 Instruction *User = cast<Instruction>(Ptr->user_back());
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000603
604 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000605 ConvertUsesToScalar(CI, NewAI, Offset, NonConstantIdx);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000606 CI->eraseFromParent();
607 continue;
608 }
609
610 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
611 // Compute the offset that this GEP adds to the pointer.
612 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Craig Topperf40110f2014-04-25 05:29:35 +0000613 Value* GEPNonConstantIdx = nullptr;
Pete Cooper0deca6b2012-08-10 03:26:36 +0000614 if (!GEP->hasAllConstantIndices()) {
615 assert(!NonConstantIdx &&
616 "Dynamic GEP reading from dynamic GEP unsupported");
617 GEPNonConstantIdx = Indices.pop_back_val();
618 } else
619 GEPNonConstantIdx = NonConstantIdx;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000620 uint64_t GEPOffset = DL.getIndexedOffset(GEP->getPointerOperandType(),
Jay Foadbf904772011-07-19 14:01:37 +0000621 Indices);
Pete Cooper0deca6b2012-08-10 03:26:36 +0000622 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8, GEPNonConstantIdx);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000623 GEP->eraseFromParent();
624 continue;
625 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000626
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000627 IRBuilder<> Builder(User);
Bob Wilson328e91b2011-01-13 20:59:44 +0000628
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000629 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
630 // The load is a bit extract from NewAI shifted right by Offset bits.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000631 Value *LoadedVal = Builder.CreateLoad(NewAI);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000632 Value *NewLoadVal
Pete Cooper33ee6c92012-06-17 03:58:26 +0000633 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset,
634 NonConstantIdx, Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000635 LI->replaceAllUsesWith(NewLoadVal);
636 LI->eraseFromParent();
637 continue;
638 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000639
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000640 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
641 assert(SI->getOperand(0) != Ptr && "Consistency error!");
642 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
643 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000644 NonConstantIdx, Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000645 Builder.CreateStore(New, NewAI);
646 SI->eraseFromParent();
Bob Wilson328e91b2011-01-13 20:59:44 +0000647
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000648 // If the load we just inserted is now dead, then the inserted store
649 // overwrote the entire thing.
650 if (Old->use_empty())
651 Old->eraseFromParent();
652 continue;
653 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000654
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000655 // If this is a constant sized memset of a constant value (e.g. 0) we can
656 // transform it into a store of the expanded constant value.
657 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
658 assert(MSI->getRawDest() == Ptr && "Consistency error!");
Pete Cooper33ee6c92012-06-17 03:58:26 +0000659 assert(!NonConstantIdx && "Cannot replace dynamic memset with insert");
Duncan Sands8f897dc2012-03-23 08:29:04 +0000660 int64_t SNumBytes = cast<ConstantInt>(MSI->getLength())->getSExtValue();
Chris Lattner7d7dba32012-03-22 03:46:58 +0000661 if (SNumBytes > 0 && (SNumBytes >> 32) == 0) {
Aaron Ballmana7332972012-03-15 00:05:31 +0000662 unsigned NumBytes = static_cast<unsigned>(SNumBytes);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000663 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
Bob Wilson328e91b2011-01-13 20:59:44 +0000664
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000665 // Compute the value replicated the right number of times.
666 APInt APVal(NumBytes*8, Val);
667
668 // Splat the value if non-zero.
669 if (Val)
670 for (unsigned i = 1; i != NumBytes; ++i)
671 APVal |= APVal << 8;
Bob Wilson328e91b2011-01-13 20:59:44 +0000672
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000673 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
674 Value *New = ConvertScalar_InsertValue(
675 ConstantInt::get(User->getContext(), APVal),
Craig Topperf40110f2014-04-25 05:29:35 +0000676 Old, Offset, nullptr, Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000677 Builder.CreateStore(New, NewAI);
Bob Wilson328e91b2011-01-13 20:59:44 +0000678
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000679 // If the load we just inserted is now dead, then the memset overwrote
680 // the entire thing.
681 if (Old->use_empty())
Bob Wilson328e91b2011-01-13 20:59:44 +0000682 Old->eraseFromParent();
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000683 }
684 MSI->eraseFromParent();
685 continue;
686 }
687
688 // If this is a memcpy or memmove into or out of the whole allocation, we
689 // can handle it like a load or store of the scalar type.
690 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
691 assert(Offset == 0 && "must be store to start of alloca");
Pete Cooper33ee6c92012-06-17 03:58:26 +0000692 assert(!NonConstantIdx && "Cannot replace dynamic transfer with insert");
Bob Wilson328e91b2011-01-13 20:59:44 +0000693
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000694 // If the source and destination are both to the same alloca, then this is
695 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
696 // as appropriate.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000697 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &DL, 0));
Bob Wilson328e91b2011-01-13 20:59:44 +0000698
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000699 if (GetUnderlyingObject(MTI->getSource(), &DL, 0) != OrigAI) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000700 // Dest must be OrigAI, change this to be a load from the original
701 // pointer (bitcasted), then a store to our new alloca.
702 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
703 Value *SrcPtr = MTI->getSource();
Chris Lattner229907c2011-07-18 04:54:35 +0000704 PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
705 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
Mon P Wang18b762a2010-12-23 01:41:32 +0000706 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
707 AIPTy = PointerType::get(AIPTy->getElementType(),
708 SPTy->getAddressSpace());
709 }
710 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
711
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000712 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
713 SrcVal->setAlignment(MTI->getAlignment());
714 Builder.CreateStore(SrcVal, NewAI);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000715 } else if (GetUnderlyingObject(MTI->getDest(), &DL, 0) != OrigAI) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000716 // Src must be OrigAI, change this to be a load from NewAI then a store
717 // through the original dest pointer (bitcasted).
718 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
719 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
720
Chris Lattner229907c2011-07-18 04:54:35 +0000721 PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
722 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
Mon P Wang18b762a2010-12-23 01:41:32 +0000723 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
724 AIPTy = PointerType::get(AIPTy->getElementType(),
725 DPTy->getAddressSpace());
726 }
727 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
728
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000729 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
730 NewStore->setAlignment(MTI->getAlignment());
731 } else {
732 // Noop transfer. Src == Dst
733 }
734
735 MTI->eraseFromParent();
736 continue;
737 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000738
Nick Lewycky15e2d902011-07-25 23:14:22 +0000739 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
740 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
741 II->getIntrinsicID() == Intrinsic::lifetime_end) {
742 // There's no need to preserve these, as the resulting alloca will be
743 // converted to a register anyways.
744 II->eraseFromParent();
745 continue;
746 }
747 }
748
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000749 llvm_unreachable("Unsupported operation!");
750 }
751}
752
753/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
754/// or vector value FromVal, extracting the bits from the offset specified by
755/// Offset. This returns the value, which is of type ToType.
756///
757/// This happens when we are converting an "integer union" to a single
758/// integer scalar, or when we are converting a "vector union" to a vector with
759/// insert/extractelement instructions.
760///
761/// Offset is an offset from the original alloca, in bits that need to be
762/// shifted to the right.
763Value *ConvertToScalarInfo::
Chris Lattner229907c2011-07-18 04:54:35 +0000764ConvertScalar_ExtractValue(Value *FromVal, Type *ToType,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000765 uint64_t Offset, Value* NonConstantIdx,
766 IRBuilder<> &Builder) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000767 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattner229907c2011-07-18 04:54:35 +0000768 Type *FromType = FromVal->getType();
Mon P Wang2e5528f2011-04-13 21:40:02 +0000769 if (FromType == ToType && Offset == 0)
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000770 return FromVal;
771
772 // If the result alloca is a vector type, this is either an element
773 // access or a bitcast to another vector type of the same size.
Chris Lattner229907c2011-07-18 04:54:35 +0000774 if (VectorType *VTy = dyn_cast<VectorType>(FromType)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000775 unsigned FromTypeSize = DL.getTypeAllocSize(FromType);
776 unsigned ToTypeSize = DL.getTypeAllocSize(ToType);
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000777 if (FromTypeSize == ToTypeSize)
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000778 return Builder.CreateBitCast(FromVal, ToType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000779
780 // Otherwise it must be an element access.
781 unsigned Elt = 0;
782 if (Offset) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000783 unsigned EltSize = DL.getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000784 Elt = Offset/EltSize;
785 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
786 }
787 // Return the element extracted out of it.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000788 Value *Idx;
789 if (NonConstantIdx) {
790 if (Elt)
791 Idx = Builder.CreateAdd(NonConstantIdx,
792 Builder.getInt32(Elt),
793 "dyn.offset");
794 else
795 Idx = NonConstantIdx;
796 } else
797 Idx = Builder.getInt32(Elt);
798 Value *V = Builder.CreateExtractElement(FromVal, Idx);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000799 if (V->getType() != ToType)
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000800 V = Builder.CreateBitCast(V, ToType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000801 return V;
802 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000803
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000804 // If ToType is a first class aggregate, extract out each of the pieces and
805 // use insertvalue's to form the FCA.
Chris Lattner229907c2011-07-18 04:54:35 +0000806 if (StructType *ST = dyn_cast<StructType>(ToType)) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000807 assert(!NonConstantIdx &&
808 "Dynamic indexing into struct types not supported");
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000809 const StructLayout &Layout = *DL.getStructLayout(ST);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000810 Value *Res = UndefValue::get(ST);
811 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
812 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
813 Offset+Layout.getElementOffsetInBits(i),
Craig Topperf40110f2014-04-25 05:29:35 +0000814 nullptr, Builder);
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000815 Res = Builder.CreateInsertValue(Res, Elt, i);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000816 }
817 return Res;
818 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000819
Chris Lattner229907c2011-07-18 04:54:35 +0000820 if (ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000821 assert(!NonConstantIdx &&
822 "Dynamic indexing into array types not supported");
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000823 uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000824 Value *Res = UndefValue::get(AT);
825 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
826 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
Craig Topperf40110f2014-04-25 05:29:35 +0000827 Offset+i*EltSize, nullptr,
828 Builder);
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000829 Res = Builder.CreateInsertValue(Res, Elt, i);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000830 }
831 return Res;
832 }
833
834 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattner229907c2011-07-18 04:54:35 +0000835 IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000836
837 // If this is a big-endian system and the load is narrower than the
838 // full alloca type, we need to do a shift to get the right bits.
839 int ShAmt = 0;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000840 if (DL.isBigEndian()) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000841 // On big-endian machines, the lowest bit is stored at the bit offset
842 // from the pointer given by getTypeStoreSizeInBits. This matters for
843 // integers with a bitwidth that is not a multiple of 8.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000844 ShAmt = DL.getTypeStoreSizeInBits(NTy) -
845 DL.getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000846 } else {
847 ShAmt = Offset;
848 }
849
850 // Note: we support negative bitwidths (with shl) which are not defined.
851 // We do this to support (f.e.) loads off the end of a structure where
852 // only some bits are used.
853 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
854 FromVal = Builder.CreateLShr(FromVal,
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000855 ConstantInt::get(FromVal->getType(), ShAmt));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000856 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Bob Wilson328e91b2011-01-13 20:59:44 +0000857 FromVal = Builder.CreateShl(FromVal,
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000858 ConstantInt::get(FromVal->getType(), -ShAmt));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000859
860 // Finally, unconditionally truncate the integer to the right width.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000861 unsigned LIBitWidth = DL.getTypeSizeInBits(ToType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000862 if (LIBitWidth < NTy->getBitWidth())
863 FromVal =
Bob Wilson328e91b2011-01-13 20:59:44 +0000864 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000865 LIBitWidth));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000866 else if (LIBitWidth > NTy->getBitWidth())
867 FromVal =
Bob Wilson328e91b2011-01-13 20:59:44 +0000868 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000869 LIBitWidth));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000870
871 // If the result is an integer, this is a trunc or bitcast.
872 if (ToType->isIntegerTy()) {
873 // Should be done.
874 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
875 // Just do a bitcast, we know the sizes match up.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000876 FromVal = Builder.CreateBitCast(FromVal, ToType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000877 } else {
878 // Otherwise must be a pointer.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000879 FromVal = Builder.CreateIntToPtr(FromVal, ToType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000880 }
881 assert(FromVal->getType() == ToType && "Didn't convert right?");
882 return FromVal;
883}
884
885/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
886/// or vector value "Old" at the offset specified by Offset.
887///
888/// This happens when we are converting an "integer union" to a
889/// single integer scalar, or when we are converting a "vector union" to a
890/// vector with insert/extractelement instructions.
891///
892/// Offset is an offset from the original alloca, in bits that need to be
893/// shifted to the right.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000894///
895/// NonConstantIdx is an index value if there was a GEP with a non-constant
896/// index value. If this is 0 then all GEPs used to find this insert address
897/// are constant.
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000898Value *ConvertToScalarInfo::
899ConvertScalar_InsertValue(Value *SV, Value *Old,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000900 uint64_t Offset, Value* NonConstantIdx,
901 IRBuilder<> &Builder) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000902 // Convert the stored type to the actual type, shift it left to insert
903 // then 'or' into place.
Chris Lattner229907c2011-07-18 04:54:35 +0000904 Type *AllocaType = Old->getType();
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000905 LLVMContext &Context = Old->getContext();
906
Chris Lattner229907c2011-07-18 04:54:35 +0000907 if (VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000908 uint64_t VecSize = DL.getTypeAllocSizeInBits(VTy);
909 uint64_t ValSize = DL.getTypeAllocSizeInBits(SV->getType());
Bob Wilson328e91b2011-01-13 20:59:44 +0000910
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000911 // Changing the whole vector with memset or with an access of a different
912 // vector type?
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000913 if (ValSize == VecSize)
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000914 return Builder.CreateBitCast(SV, AllocaType);
Cameron Zwarich3b649f42011-03-09 05:43:05 +0000915
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000916 // Must be an element insertion.
Cameron Zwarich057fbb12011-10-23 07:02:10 +0000917 Type *EltTy = VTy->getElementType();
918 if (SV->getType() != EltTy)
919 SV = Builder.CreateBitCast(SV, EltTy);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000920 uint64_t EltSize = DL.getTypeAllocSizeInBits(EltTy);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000921 unsigned Elt = Offset/EltSize;
Pete Cooper33ee6c92012-06-17 03:58:26 +0000922 Value *Idx;
923 if (NonConstantIdx) {
924 if (Elt)
925 Idx = Builder.CreateAdd(NonConstantIdx,
926 Builder.getInt32(Elt),
927 "dyn.offset");
928 else
929 Idx = NonConstantIdx;
930 } else
931 Idx = Builder.getInt32(Elt);
932 return Builder.CreateInsertElement(Old, SV, Idx);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000933 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000934
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000935 // If SV is a first-class aggregate value, insert each value recursively.
Chris Lattner229907c2011-07-18 04:54:35 +0000936 if (StructType *ST = dyn_cast<StructType>(SV->getType())) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000937 assert(!NonConstantIdx &&
938 "Dynamic indexing into struct types not supported");
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000939 const StructLayout &Layout = *DL.getStructLayout(ST);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000940 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000941 Value *Elt = Builder.CreateExtractValue(SV, i);
Bob Wilson328e91b2011-01-13 20:59:44 +0000942 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000943 Offset+Layout.getElementOffsetInBits(i),
Craig Topperf40110f2014-04-25 05:29:35 +0000944 nullptr, Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000945 }
946 return Old;
947 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000948
Chris Lattner229907c2011-07-18 04:54:35 +0000949 if (ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000950 assert(!NonConstantIdx &&
951 "Dynamic indexing into array types not supported");
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000952 uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000953 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000954 Value *Elt = Builder.CreateExtractValue(SV, i);
Craig Topperf40110f2014-04-25 05:29:35 +0000955 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, nullptr,
956 Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000957 }
958 return Old;
959 }
960
961 // If SV is a float, convert it to the appropriate integer type.
962 // If it is a pointer, do the same.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000963 unsigned SrcWidth = DL.getTypeSizeInBits(SV->getType());
964 unsigned DestWidth = DL.getTypeSizeInBits(AllocaType);
965 unsigned SrcStoreWidth = DL.getTypeStoreSizeInBits(SV->getType());
966 unsigned DestStoreWidth = DL.getTypeStoreSizeInBits(AllocaType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000967 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000968 SV = Builder.CreateBitCast(SV, IntegerType::get(SV->getContext(),SrcWidth));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000969 else if (SV->getType()->isPointerTy())
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000970 SV = Builder.CreatePtrToInt(SV, DL.getIntPtrType(SV->getType()));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000971
972 // Zero extend or truncate the value if needed.
973 if (SV->getType() != AllocaType) {
974 if (SV->getType()->getPrimitiveSizeInBits() <
975 AllocaType->getPrimitiveSizeInBits())
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000976 SV = Builder.CreateZExt(SV, AllocaType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000977 else {
978 // Truncation may be needed if storing more than the alloca can hold
979 // (undefined behavior).
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000980 SV = Builder.CreateTrunc(SV, AllocaType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000981 SrcWidth = DestWidth;
982 SrcStoreWidth = DestStoreWidth;
983 }
984 }
985
986 // If this is a big-endian system and the store is narrower than the
987 // full alloca type, we need to do a shift to get the right bits.
988 int ShAmt = 0;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000989 if (DL.isBigEndian()) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000990 // On big-endian machines, the lowest bit is stored at the bit offset
991 // from the pointer given by getTypeStoreSizeInBits. This matters for
992 // integers with a bitwidth that is not a multiple of 8.
993 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
994 } else {
995 ShAmt = Offset;
996 }
997
998 // Note: we support negative bitwidths (with shr) which are not defined.
999 // We do this to support (f.e.) stores off the end of a structure where
1000 // only some bits in the structure are set.
1001 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1002 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001003 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt));
Chris Lattner78d7dbb2010-04-16 00:24:57 +00001004 Mask <<= ShAmt;
1005 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001006 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt));
Chris Lattner78d7dbb2010-04-16 00:24:57 +00001007 Mask = Mask.lshr(-ShAmt);
1008 }
1009
1010 // Mask out the bits we are about to insert from the old value, and or
1011 // in the new bits.
1012 if (SrcWidth != DestWidth) {
1013 assert(DestWidth > SrcWidth);
1014 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1015 SV = Builder.CreateOr(Old, SV, "ins");
1016 }
1017 return SV;
1018}
1019
1020
1021//===----------------------------------------------------------------------===//
1022// SRoA Driver
1023//===----------------------------------------------------------------------===//
1024
1025
Chris Lattnerfb41a502003-05-27 15:45:27 +00001026bool SROA::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00001027 if (skipOptnoneFunction(F))
1028 return false;
1029
Rafael Espindola93512512014-02-25 17:30:31 +00001030 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Craig Topperf40110f2014-04-25 05:29:35 +00001031 DL = DLP ? &DLP->getDataLayout() : nullptr;
Dan Gohman915302c2009-08-19 18:22:18 +00001032
Chris Lattner9a95f2a2003-09-12 15:36:03 +00001033 bool Changed = performPromotion(F);
Dan Gohman915302c2009-08-19 18:22:18 +00001034
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001035 // FIXME: ScalarRepl currently depends on DataLayout more than it
Dan Gohman915302c2009-08-19 18:22:18 +00001036 // theoretically needs to. It should be refactored in order to support
1037 // target-independent IR. Until this is done, just skip the actual
1038 // scalar-replacement portion of this pass.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001039 if (!DL) return Changed;
Dan Gohman915302c2009-08-19 18:22:18 +00001040
Chris Lattner9a95f2a2003-09-12 15:36:03 +00001041 while (1) {
1042 bool LocalChange = performScalarRepl(F);
1043 if (!LocalChange) break; // No need to repromote if no scalarrepl
1044 Changed = true;
1045 LocalChange = performPromotion(F);
1046 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
1047 }
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001048
1049 return Changed;
1050}
1051
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001052namespace {
1053class AllocaPromoter : public LoadAndStorePromoter {
1054 AllocaInst *AI;
Devang Patela3cbf522011-07-06 21:09:55 +00001055 DIBuilder *DIB;
Devang Patelc6ee9182011-07-06 22:06:11 +00001056 SmallVector<DbgDeclareInst *, 4> DDIs;
1057 SmallVector<DbgValueInst *, 4> DVIs;
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001058public:
Cameron Zwarich843bc7d2011-05-24 03:10:43 +00001059 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
Devang Patela3cbf522011-07-06 21:09:55 +00001060 DIBuilder *DB)
Craig Topperf40110f2014-04-25 05:29:35 +00001061 : LoadAndStorePromoter(Insts, S), AI(nullptr), DIB(DB) {}
Nadav Rotem465834c2012-07-24 10:51:42 +00001062
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001063 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001064 // Remember which alloca we're promoting (for isInstInList).
1065 this->AI = AI;
Rafael Espindola2b14b802011-12-26 23:12:42 +00001066 if (MDNode *DebugNode = MDNode::getIfExists(AI->getContext(), AI)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001067 for (User *U : DebugNode->users())
1068 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
Devang Patelc6ee9182011-07-06 22:06:11 +00001069 DDIs.push_back(DDI);
Chandler Carruthcdf47882014-03-09 03:16:01 +00001070 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
Devang Patelc6ee9182011-07-06 22:06:11 +00001071 DVIs.push_back(DVI);
Rafael Espindola2b14b802011-12-26 23:12:42 +00001072 }
Devang Patelc6ee9182011-07-06 22:06:11 +00001073
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001074 LoadAndStorePromoter::run(Insts);
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001075 AI->eraseFromParent();
Craig Topper31ee5862013-07-03 15:07:05 +00001076 for (SmallVectorImpl<DbgDeclareInst *>::iterator I = DDIs.begin(),
Devang Patelc6ee9182011-07-06 22:06:11 +00001077 E = DDIs.end(); I != E; ++I) {
1078 DbgDeclareInst *DDI = *I;
Devang Patela3cbf522011-07-06 21:09:55 +00001079 DDI->eraseFromParent();
Devang Patelc6ee9182011-07-06 22:06:11 +00001080 }
Craig Topper31ee5862013-07-03 15:07:05 +00001081 for (SmallVectorImpl<DbgValueInst *>::iterator I = DVIs.begin(),
Devang Patelc6ee9182011-07-06 22:06:11 +00001082 E = DVIs.end(); I != E; ++I) {
1083 DbgValueInst *DVI = *I;
1084 DVI->eraseFromParent();
1085 }
Chris Lattner543384e2011-01-14 07:50:47 +00001086 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001087
Craig Topper3e4c6972014-03-05 09:10:37 +00001088 bool isInstInList(Instruction *I,
1089 const SmallVectorImpl<Instruction*> &Insts) const override {
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001090 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1091 return LI->getOperand(0) == AI;
1092 return cast<StoreInst>(I)->getPointerOperand() == AI;
Chris Lattner543384e2011-01-14 07:50:47 +00001093 }
Devang Patela3cbf522011-07-06 21:09:55 +00001094
Craig Topper3e4c6972014-03-05 09:10:37 +00001095 void updateDebugInfo(Instruction *Inst) const override {
Craig Topper31ee5862013-07-03 15:07:05 +00001096 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
Devang Patelc6ee9182011-07-06 22:06:11 +00001097 E = DDIs.end(); I != E; ++I) {
1098 DbgDeclareInst *DDI = *I;
1099 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1100 ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
1101 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1102 ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
1103 }
Craig Topper31ee5862013-07-03 15:07:05 +00001104 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
Devang Patelc6ee9182011-07-06 22:06:11 +00001105 E = DVIs.end(); I != E; ++I) {
1106 DbgValueInst *DVI = *I;
Craig Topperf40110f2014-04-25 05:29:35 +00001107 Value *Arg = nullptr;
Devang Patelc6ee9182011-07-06 22:06:11 +00001108 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Devang Patelc6ee9182011-07-06 22:06:11 +00001109 // If an argument is zero extended then use argument directly. The ZExt
1110 // may be zapped by an optimization pass in future.
Devang Patelc6ee9182011-07-06 22:06:11 +00001111 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
Benjamin Kramer077e5522012-02-23 17:42:19 +00001112 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Devang Patelc6ee9182011-07-06 22:06:11 +00001113 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Benjamin Kramer077e5522012-02-23 17:42:19 +00001114 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1115 if (!Arg)
1116 Arg = SI->getOperand(0);
Devang Patelc6ee9182011-07-06 22:06:11 +00001117 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Benjamin Kramer077e5522012-02-23 17:42:19 +00001118 Arg = LI->getOperand(0);
1119 } else {
1120 continue;
Devang Patelc6ee9182011-07-06 22:06:11 +00001121 }
Benjamin Kramer077e5522012-02-23 17:42:19 +00001122 Instruction *DbgVal =
1123 DIB->insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1124 Inst);
1125 DbgVal->setDebugLoc(DVI->getDebugLoc());
Devang Patelc6ee9182011-07-06 22:06:11 +00001126 }
Devang Patela3cbf522011-07-06 21:09:55 +00001127 }
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001128};
1129} // end anon namespace
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001130
Chris Lattnera9607252011-01-23 22:04:55 +00001131/// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1132/// subsequently loaded can be rewritten to load both input pointers and then
1133/// select between the result, allowing the load of the alloca to be promoted.
1134/// From this:
1135/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1136/// %V = load i32* %P2
1137/// to:
1138/// %V1 = load i32* %Alloca -> will be mem2reg'd
1139/// %V2 = load i32* %Other
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001140/// %V = select i1 %cond, i32 %V1, i32 %V2
Chris Lattnera9607252011-01-23 22:04:55 +00001141///
1142/// We can do this to a select if its only uses are loads and if the operand to
1143/// the select can be loaded unconditionally.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001144static bool isSafeSelectToSpeculate(SelectInst *SI, const DataLayout *DL) {
Hal Finkel2e42c342014-07-10 05:27:53 +00001145 bool TDerefable = SI->getTrueValue()->isDereferenceablePointer(DL);
1146 bool FDerefable = SI->getFalseValue()->isDereferenceablePointer(DL);
Nadav Rotem465834c2012-07-24 10:51:42 +00001147
Chandler Carruthcdf47882014-03-09 03:16:01 +00001148 for (User *U : SI->users()) {
1149 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001150 if (!LI || !LI->isSimple()) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001151
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001152 // Both operands to the select need to be dereferencable, either absolutely
Chris Lattnera9607252011-01-23 22:04:55 +00001153 // (e.g. allocas) or at this point because we can see other accesses to it.
1154 if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001155 LI->getAlignment(), DL))
Chris Lattnera9607252011-01-23 22:04:55 +00001156 return false;
1157 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001158 LI->getAlignment(), DL))
Chris Lattnera9607252011-01-23 22:04:55 +00001159 return false;
1160 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001161
Chris Lattnera9607252011-01-23 22:04:55 +00001162 return true;
1163}
1164
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001165/// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1166/// subsequently loaded can be rewritten to load both input pointers in the pred
1167/// blocks and then PHI the results, allowing the load of the alloca to be
1168/// promoted.
1169/// From this:
1170/// %P2 = phi [i32* %Alloca, i32* %Other]
1171/// %V = load i32* %P2
1172/// to:
1173/// %V1 = load i32* %Alloca -> will be mem2reg'd
1174/// ...
1175/// %V2 = load i32* %Other
1176/// ...
1177/// %V = phi [i32 %V1, i32 %V2]
1178///
1179/// We can do this to a select if its only uses are loads and if the operand to
1180/// the select can be loaded unconditionally.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001181static bool isSafePHIToSpeculate(PHINode *PN, const DataLayout *DL) {
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001182 // For now, we can only do this promotion if the load is in the same block as
1183 // the PHI, and if there are no stores between the phi and load.
1184 // TODO: Allow recursive phi users.
1185 // TODO: Allow stores.
1186 BasicBlock *BB = PN->getParent();
1187 unsigned MaxAlign = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001188 for (User *U : PN->users()) {
1189 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001190 if (!LI || !LI->isSimple()) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001191
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001192 // For now we only allow loads in the same block as the PHI. This is a
1193 // common case that happens when instcombine merges two loads through a PHI.
1194 if (LI->getParent() != BB) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001195
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001196 // Ensure that there are no instructions between the PHI and the load that
1197 // could store.
1198 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1199 if (BBI->mayWriteToMemory())
1200 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001201
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001202 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1203 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001204
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001205 // Okay, we know that we have one or more loads in the same block as the PHI.
1206 // We can transform this if it is safe to push the loads into the predecessor
1207 // blocks. The only thing to watch out for is that we can't put a possibly
1208 // trapping load in the predecessor if it is a critical edge.
1209 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1210 BasicBlock *Pred = PN->getIncomingBlock(i);
Eli Friedmanf9b785f2011-09-22 18:56:30 +00001211 Value *InVal = PN->getIncomingValue(i);
1212
1213 // If the terminator of the predecessor has side-effects (an invoke),
1214 // there is no safe place to put a load in the predecessor.
1215 if (Pred->getTerminator()->mayHaveSideEffects())
1216 return false;
1217
1218 // If the value is produced by the terminator of the predecessor
1219 // (an invoke), there is no valid place to put a load in the predecessor.
1220 if (Pred->getTerminator() == InVal)
1221 return false;
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001222
1223 // If the predecessor has a single successor, then the edge isn't critical.
1224 if (Pred->getTerminator()->getNumSuccessors() == 1)
1225 continue;
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001226
1227 // If this pointer is always safe to load, or if we can prove that there is
1228 // already a load in the block, then we can move the load to the pred block.
Hal Finkel2e42c342014-07-10 05:27:53 +00001229 if (InVal->isDereferenceablePointer(DL) ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001230 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, DL))
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001231 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00001232
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001233 return false;
1234 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001235
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001236 return true;
1237}
1238
Chris Lattnera9607252011-01-23 22:04:55 +00001239
1240/// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1241/// direct (non-volatile) loads and stores to it. If the alloca is close but
1242/// not quite there, this will transform the code to allow promotion. As such,
1243/// it is a non-pure predicate.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001244static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const DataLayout *DL) {
Chris Lattnera9607252011-01-23 22:04:55 +00001245 SetVector<Instruction*, SmallVector<Instruction*, 4>,
1246 SmallPtrSet<Instruction*, 4> > InstsToRewrite;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001247 for (User *U : AI->users()) {
Chris Lattnera9607252011-01-23 22:04:55 +00001248 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Eli Friedman7c5dc122011-09-12 20:23:13 +00001249 if (!LI->isSimple())
Chris Lattnera9607252011-01-23 22:04:55 +00001250 return false;
1251 continue;
1252 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001253
Chris Lattnera9607252011-01-23 22:04:55 +00001254 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Eli Friedman7c5dc122011-09-12 20:23:13 +00001255 if (SI->getOperand(0) == AI || !SI->isSimple())
Chris Lattnera9607252011-01-23 22:04:55 +00001256 return false; // Don't allow a store OF the AI, only INTO the AI.
1257 continue;
1258 }
1259
1260 if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1261 // If the condition being selected on is a constant, fold the select, yes
1262 // this does (rarely) happen early on.
1263 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1264 Value *Result = SI->getOperand(1+CI->isZero());
1265 SI->replaceAllUsesWith(Result);
1266 SI->eraseFromParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001267
Chris Lattnera9607252011-01-23 22:04:55 +00001268 // This is very rare and we just scrambled the use list of AI, start
1269 // over completely.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001270 return tryToMakeAllocaBePromotable(AI, DL);
Chris Lattnera9607252011-01-23 22:04:55 +00001271 }
1272
1273 // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1274 // loads, then we can transform this by rewriting the select.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001275 if (!isSafeSelectToSpeculate(SI, DL))
Chris Lattnera9607252011-01-23 22:04:55 +00001276 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001277
Chris Lattnera9607252011-01-23 22:04:55 +00001278 InstsToRewrite.insert(SI);
1279 continue;
1280 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001281
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001282 if (PHINode *PN = dyn_cast<PHINode>(U)) {
1283 if (PN->use_empty()) { // Dead PHIs can be stripped.
1284 InstsToRewrite.insert(PN);
1285 continue;
1286 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001287
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001288 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1289 // in the pred blocks, then we can transform this by rewriting the PHI.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001290 if (!isSafePHIToSpeculate(PN, DL))
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001291 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001292
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001293 InstsToRewrite.insert(PN);
1294 continue;
1295 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001296
Nick Lewycky15e2d902011-07-25 23:14:22 +00001297 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1298 if (onlyUsedByLifetimeMarkers(BCI)) {
1299 InstsToRewrite.insert(BCI);
1300 continue;
1301 }
1302 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001303
Chris Lattnera9607252011-01-23 22:04:55 +00001304 return false;
1305 }
1306
1307 // If there are no instructions to rewrite, then all uses are load/stores and
1308 // we're done!
1309 if (InstsToRewrite.empty())
1310 return true;
Nadav Rotem465834c2012-07-24 10:51:42 +00001311
Chris Lattnera9607252011-01-23 22:04:55 +00001312 // If we have instructions that need to be rewritten for this to be promotable
1313 // take care of it now.
1314 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
Nick Lewycky15e2d902011-07-25 23:14:22 +00001315 if (BitCastInst *BCI = dyn_cast<BitCastInst>(InstsToRewrite[i])) {
1316 // This could only be a bitcast used by nothing but lifetime intrinsics.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001317 for (BitCastInst::user_iterator I = BCI->user_begin(), E = BCI->user_end();
1318 I != E;)
1319 cast<Instruction>(*I++)->eraseFromParent();
Nick Lewycky15e2d902011-07-25 23:14:22 +00001320 BCI->eraseFromParent();
1321 continue;
1322 }
1323
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001324 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1325 // Selects in InstsToRewrite only have load uses. Rewrite each as two
1326 // loads with a new select.
1327 while (!SI->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001328 LoadInst *LI = cast<LoadInst>(SI->user_back());
Nadav Rotem465834c2012-07-24 10:51:42 +00001329
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001330 IRBuilder<> Builder(LI);
Nadav Rotem465834c2012-07-24 10:51:42 +00001331 LoadInst *TrueLoad =
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001332 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
Nadav Rotem465834c2012-07-24 10:51:42 +00001333 LoadInst *FalseLoad =
Nick Lewyckyf64a3972011-07-01 06:27:03 +00001334 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".f");
Nadav Rotem465834c2012-07-24 10:51:42 +00001335
Hal Finkelcc39b672014-07-24 12:16:19 +00001336 // Transfer alignment and AA info if present.
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001337 TrueLoad->setAlignment(LI->getAlignment());
1338 FalseLoad->setAlignment(LI->getAlignment());
Hal Finkelcc39b672014-07-24 12:16:19 +00001339
1340 AAMDNodes Tags;
1341 LI->getAAMetadata(Tags);
1342 if (Tags) {
1343 TrueLoad->setAAMetadata(Tags);
1344 FalseLoad->setAAMetadata(Tags);
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001345 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001346
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001347 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1348 V->takeName(LI);
1349 LI->replaceAllUsesWith(V);
1350 LI->eraseFromParent();
Chris Lattnera9607252011-01-23 22:04:55 +00001351 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001352
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001353 // Now that all the loads are gone, the select is gone too.
1354 SI->eraseFromParent();
1355 continue;
1356 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001357
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001358 // Otherwise, we have a PHI node which allows us to push the loads into the
1359 // predecessors.
1360 PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1361 if (PN->use_empty()) {
1362 PN->eraseFromParent();
1363 continue;
1364 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001365
Chris Lattner229907c2011-07-18 04:54:35 +00001366 Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
Jay Foad52131342011-03-30 11:28:46 +00001367 PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1368 PN->getName()+".ld", PN);
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001369
Hal Finkelcc39b672014-07-24 12:16:19 +00001370 // Get the AA tags and alignment to use from one of the loads. It doesn't
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001371 // matter which one we get and if any differ, it doesn't matter.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001372 LoadInst *SomeLoad = cast<LoadInst>(PN->user_back());
Hal Finkelcc39b672014-07-24 12:16:19 +00001373
1374 AAMDNodes AATags;
1375 SomeLoad->getAAMetadata(AATags);
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001376 unsigned Align = SomeLoad->getAlignment();
Nadav Rotem465834c2012-07-24 10:51:42 +00001377
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001378 // Rewrite all loads of the PN to use the new PHI.
1379 while (!PN->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001380 LoadInst *LI = cast<LoadInst>(PN->user_back());
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001381 LI->replaceAllUsesWith(NewPN);
Chris Lattnera9607252011-01-23 22:04:55 +00001382 LI->eraseFromParent();
1383 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001384
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001385 // Inject loads into all of the pred blocks. Keep track of which blocks we
1386 // insert them into in case we have multiple edges from the same block.
1387 DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
Nadav Rotem465834c2012-07-24 10:51:42 +00001388
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001389 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1390 BasicBlock *Pred = PN->getIncomingBlock(i);
1391 LoadInst *&Load = InsertedLoads[Pred];
Craig Topperf40110f2014-04-25 05:29:35 +00001392 if (!Load) {
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001393 Load = new LoadInst(PN->getIncomingValue(i),
1394 PN->getName() + "." + Pred->getName(),
1395 Pred->getTerminator());
1396 Load->setAlignment(Align);
Hal Finkelcc39b672014-07-24 12:16:19 +00001397 if (AATags) Load->setAAMetadata(AATags);
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001398 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001399
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001400 NewPN->addIncoming(Load, Pred);
1401 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001402
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001403 PN->eraseFromParent();
Chris Lattnera9607252011-01-23 22:04:55 +00001404 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001405
Chris Lattnera9607252011-01-23 22:04:55 +00001406 ++NumAdjusted;
1407 return true;
1408}
1409
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001410bool SROA::performPromotion(Function &F) {
1411 std::vector<AllocaInst*> Allocas;
Craig Topperf40110f2014-04-25 05:29:35 +00001412 DominatorTree *DT = nullptr;
Cameron Zwarich4694e692011-01-18 03:53:26 +00001413 if (HasDomTree)
Chandler Carruth73523022014-01-13 13:07:17 +00001414 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001415
Chris Lattner5dac64f2003-09-20 14:39:18 +00001416 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Devang Patela3cbf522011-07-06 21:09:55 +00001417 DIBuilder DIB(*F.getParent());
Chris Lattner9a95f2a2003-09-12 15:36:03 +00001418 bool Changed = false;
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001419 SmallVector<Instruction*, 64> Insts;
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001420 while (1) {
1421 Allocas.clear();
1422
1423 // Find allocas that are safe to promote, by looking at all instructions in
1424 // the entry node
1425 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1426 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001427 if (tryToMakeAllocaBePromotable(AI, DL))
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001428 Allocas.push_back(AI);
1429
1430 if (Allocas.empty()) break;
1431
Cameron Zwarich4694e692011-01-18 03:53:26 +00001432 if (HasDomTree)
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001433 PromoteMemToReg(Allocas, *DT);
Chris Lattner543384e2011-01-14 07:50:47 +00001434 else {
1435 SSAUpdater SSA;
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001436 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1437 AllocaInst *AI = Allocas[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00001438
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001439 // Build list of instructions to promote.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001440 for (User *U : AI->users())
1441 Insts.push_back(cast<Instruction>(U));
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) {
Craig Topperf40110f2014-04-25 05:29:35 +00001549 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), nullptr,
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) {
Craig Topperf40110f2014-04-25 05:29:35 +00001560 AllocaInst *NA = new AllocaInst(ElTy, nullptr, 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.)
Craig Topperf40110f2014-04-25 05:29:35 +00001589 *OI = nullptr;
Bob Wilson532cd232009-12-18 20:14:40 +00001590 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) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001604 for (Use &U : I->uses()) {
1605 Instruction *User = cast<Instruction>(U.getUser());
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());
Craig Topperf40110f2014-04-25 05:29:35 +00001616 if (!Length || Length->isNegative())
Aaron Ballmana7332972012-03-15 00:05:31 +00001617 return MarkUnsafe(Info, User);
1618
Craig Topperf40110f2014-04-25 05:29:35 +00001619 isSafeMemAccess(Offset, Length->getZExtValue(), nullptr,
Chandler Carruthcdf47882014-03-09 03:16:01 +00001620 U.getOperandNo() == 0, Info, MI,
Chris Lattner9491dee2011-01-23 08:27:54 +00001621 true /*AllowWholeAccess*/);
Bob Wilson532cd232009-12-18 20:14:40 +00001622 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Eli Friedman7c5dc122011-09-12 20:23:13 +00001623 if (!LI->isSimple())
Chris Lattner3e56c292011-01-23 07:05:44 +00001624 return MarkUnsafe(Info, User);
Chris Lattner229907c2011-07-18 04:54:35 +00001625 Type *LIType = LI->getType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001626 isSafeMemAccess(Offset, DL->getTypeAllocSize(LIType),
Chris Lattner9491dee2011-01-23 08:27:54 +00001627 LIType, false, Info, LI, true /*AllowWholeAccess*/);
Chris Lattner3e56c292011-01-23 07:05:44 +00001628 Info.hasALoadOrStore = true;
Nadav Rotem465834c2012-07-24 10:51:42 +00001629
Bob Wilson532cd232009-12-18 20:14:40 +00001630 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1631 // Store is ok if storing INTO the pointer, not storing the pointer
Eli Friedman7c5dc122011-09-12 20:23:13 +00001632 if (!SI->isSimple() || SI->getOperand(0) == I)
Chris Lattner3e56c292011-01-23 07:05:44 +00001633 return MarkUnsafe(Info, User);
Nadav Rotem465834c2012-07-24 10:51:42 +00001634
Chris Lattner229907c2011-07-18 04:54:35 +00001635 Type *SIType = SI->getOperand(0)->getType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001636 isSafeMemAccess(Offset, DL->getTypeAllocSize(SIType),
Chris Lattner9491dee2011-01-23 08:27:54 +00001637 SIType, true, Info, SI, true /*AllowWholeAccess*/);
Chris Lattner3e56c292011-01-23 07:05:44 +00001638 Info.hasALoadOrStore = true;
Nick Lewycky15e2d902011-07-25 23:14:22 +00001639 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1640 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1641 II->getIntrinsicID() != Intrinsic::lifetime_end)
1642 return MarkUnsafe(Info, User);
Chris Lattner9491dee2011-01-23 08:27:54 +00001643 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1644 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1645 } else {
1646 return MarkUnsafe(Info, User);
1647 }
1648 if (Info.isUnsafe) return;
1649 }
1650}
Nadav Rotem465834c2012-07-24 10:51:42 +00001651
Chris Lattner9491dee2011-01-23 08:27:54 +00001652
1653/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1654/// derived from the alloca, we can often still split the alloca into elements.
1655/// This is useful if we have a large alloca where one element is phi'd
1656/// together somewhere: we can SRoA and promote all the other elements even if
1657/// we end up not being able to promote this one.
1658///
1659/// All we require is that the uses of the PHI do not index into other parts of
1660/// the alloca. The most important use case for this is single load and stores
1661/// that are PHI'd together, which can happen due to code sinking.
1662void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1663 AllocaInfo &Info) {
1664 // If we've already checked this PHI, don't do it again.
1665 if (PHINode *PN = dyn_cast<PHINode>(I))
1666 if (!Info.CheckedPHIs.insert(PN))
1667 return;
Nadav Rotem465834c2012-07-24 10:51:42 +00001668
Chandler Carruthcdf47882014-03-09 03:16:01 +00001669 for (User *U : I->users()) {
1670 Instruction *UI = cast<Instruction>(U);
Nadav Rotem465834c2012-07-24 10:51:42 +00001671
Chandler Carruthcdf47882014-03-09 03:16:01 +00001672 if (BitCastInst *BC = dyn_cast<BitCastInst>(UI)) {
Chris Lattner9491dee2011-01-23 08:27:54 +00001673 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
Chandler Carruthcdf47882014-03-09 03:16:01 +00001674 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(UI)) {
Chris Lattner9491dee2011-01-23 08:27:54 +00001675 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1676 // but would have to prove that we're staying inside of an element being
1677 // promoted.
1678 if (!GEPI->hasAllZeroIndices())
Chandler Carruthcdf47882014-03-09 03:16:01 +00001679 return MarkUnsafe(Info, UI);
Chris Lattner9491dee2011-01-23 08:27:54 +00001680 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
Chandler Carruthcdf47882014-03-09 03:16:01 +00001681 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
Eli Friedman7c5dc122011-09-12 20:23:13 +00001682 if (!LI->isSimple())
Chandler Carruthcdf47882014-03-09 03:16:01 +00001683 return MarkUnsafe(Info, UI);
Chris Lattner229907c2011-07-18 04:54:35 +00001684 Type *LIType = LI->getType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001685 isSafeMemAccess(Offset, DL->getTypeAllocSize(LIType),
Chris Lattner9491dee2011-01-23 08:27:54 +00001686 LIType, false, Info, LI, false /*AllowWholeAccess*/);
1687 Info.hasALoadOrStore = true;
Nadav Rotem465834c2012-07-24 10:51:42 +00001688
Chandler Carruthcdf47882014-03-09 03:16:01 +00001689 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner9491dee2011-01-23 08:27:54 +00001690 // Store is ok if storing INTO the pointer, not storing the pointer
Eli Friedman7c5dc122011-09-12 20:23:13 +00001691 if (!SI->isSimple() || SI->getOperand(0) == I)
Chandler Carruthcdf47882014-03-09 03:16:01 +00001692 return MarkUnsafe(Info, UI);
Nadav Rotem465834c2012-07-24 10:51:42 +00001693
Chris Lattner229907c2011-07-18 04:54:35 +00001694 Type *SIType = SI->getOperand(0)->getType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001695 isSafeMemAccess(Offset, DL->getTypeAllocSize(SIType),
Chris Lattner9491dee2011-01-23 08:27:54 +00001696 SIType, true, Info, SI, false /*AllowWholeAccess*/);
1697 Info.hasALoadOrStore = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001698 } else if (isa<PHINode>(UI) || isa<SelectInst>(UI)) {
1699 isSafePHISelectUseForScalarRepl(UI, Offset, Info);
Bob Wilson532cd232009-12-18 20:14:40 +00001700 } else {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001701 return MarkUnsafe(Info, UI);
Bob Wilson532cd232009-12-18 20:14:40 +00001702 }
1703 if (Info.isUnsafe) return;
Bob Wilsonf3927b72009-12-17 18:34:24 +00001704 }
Bob Wilson532cd232009-12-18 20:14:40 +00001705}
Bob Wilsonf3927b72009-12-17 18:34:24 +00001706
Bob Wilson532cd232009-12-18 20:14:40 +00001707/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1708/// replacement. It is safe when all the indices are constant, in-bounds
1709/// references, and when the resulting offset corresponds to an element within
1710/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson88a05982009-12-21 18:39:47 +00001711/// return, Offset is adjusted as specified by the GEP indices.
Chris Lattner8acbb792011-01-23 07:29:29 +00001712void SROA::isSafeGEP(GetElementPtrInst *GEPI,
Bob Wilson88a05982009-12-21 18:39:47 +00001713 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilson532cd232009-12-18 20:14:40 +00001714 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1715 if (GEPIt == E)
1716 return;
Pete Coopere24d6a12012-06-15 18:07:29 +00001717 bool NonConstant = false;
1718 unsigned NonConstantIdxSize = 0;
Bob Wilsonf3927b72009-12-17 18:34:24 +00001719
Chris Lattner3f972c92008-08-23 05:21:06 +00001720 // Walk through the GEP type indices, checking the types that this indexes
1721 // into.
Bob Wilson532cd232009-12-18 20:14:40 +00001722 for (; GEPIt != E; ++GEPIt) {
Chris Lattner3f972c92008-08-23 05:21:06 +00001723 // Ignore struct elements, no extra checking needed for these.
Duncan Sands19d0b472010-02-16 11:11:14 +00001724 if ((*GEPIt)->isStructTy())
Chris Lattner3f972c92008-08-23 05:21:06 +00001725 continue;
Matthijs Kooijmancbe5e162008-10-06 16:23:31 +00001726
Bob Wilson532cd232009-12-18 20:14:40 +00001727 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
Shuxin Yang95adf522013-04-05 21:07:08 +00001728 if (!IdxVal)
1729 return MarkUnsafe(Info, GEPI);
Chris Lattner3f972c92008-08-23 05:21:06 +00001730 }
Bob Wilson532cd232009-12-18 20:14:40 +00001731
Bob Wilson62a84ea2009-12-22 06:57:14 +00001732 // Compute the offset due to this GEP and check if the alloca has a
1733 // component element at that offset.
Bob Wilson88a05982009-12-21 18:39:47 +00001734 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
Alp Tokerf907b892013-12-05 05:44:44 +00001735 // If this GEP is non-constant then the last operand must have been a
Pete Coopere24d6a12012-06-15 18:07:29 +00001736 // dynamic index into a vector. Pop this now as it has no impact on the
1737 // constant part of the offset.
1738 if (NonConstant)
1739 Indices.pop_back();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001740 Offset += DL->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
Pete Coopere24d6a12012-06-15 18:07:29 +00001741 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset,
1742 NonConstantIdxSize))
Chris Lattner3e56c292011-01-23 07:05:44 +00001743 MarkUnsafe(Info, GEPI);
Chris Lattner6e5398d2003-05-30 04:15:41 +00001744}
1745
Bob Wilson08713d32011-01-13 17:45:11 +00001746/// isHomogeneousAggregate - Check if type T is a struct or array containing
1747/// elements of the same type (which is always true for arrays). If so,
1748/// return true with NumElts and EltTy set to the number of elements and the
1749/// element type, respectively.
Chris Lattner229907c2011-07-18 04:54:35 +00001750static bool isHomogeneousAggregate(Type *T, unsigned &NumElts,
1751 Type *&EltTy) {
1752 if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
Bob Wilson08713d32011-01-13 17:45:11 +00001753 NumElts = AT->getNumElements();
Craig Topperf40110f2014-04-25 05:29:35 +00001754 EltTy = (NumElts == 0 ? nullptr : AT->getElementType());
Bob Wilson08713d32011-01-13 17:45:11 +00001755 return true;
1756 }
Chris Lattner229907c2011-07-18 04:54:35 +00001757 if (StructType *ST = dyn_cast<StructType>(T)) {
Bob Wilson08713d32011-01-13 17:45:11 +00001758 NumElts = ST->getNumContainedTypes();
Craig Topperf40110f2014-04-25 05:29:35 +00001759 EltTy = (NumElts == 0 ? nullptr : ST->getContainedType(0));
Bob Wilson08713d32011-01-13 17:45:11 +00001760 for (unsigned n = 1; n < NumElts; ++n) {
1761 if (ST->getContainedType(n) != EltTy)
1762 return false;
1763 }
1764 return true;
1765 }
1766 return false;
1767}
1768
1769/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1770/// "homogeneous" aggregates with the same element type and number of elements.
Chris Lattner229907c2011-07-18 04:54:35 +00001771static bool isCompatibleAggregate(Type *T1, Type *T2) {
Bob Wilson08713d32011-01-13 17:45:11 +00001772 if (T1 == T2)
1773 return true;
1774
1775 unsigned NumElts1, NumElts2;
Chris Lattner229907c2011-07-18 04:54:35 +00001776 Type *EltTy1, *EltTy2;
Bob Wilson08713d32011-01-13 17:45:11 +00001777 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1778 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1779 NumElts1 == NumElts2 &&
1780 EltTy1 == EltTy2)
1781 return true;
1782
1783 return false;
1784}
1785
Bob Wilson532cd232009-12-18 20:14:40 +00001786/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1787/// alloca or has an offset and size that corresponds to a component element
1788/// within it. The offset checked here may have been formed from a GEP with a
1789/// pointer bitcasted to a different type.
Chris Lattner9491dee2011-01-23 08:27:54 +00001790///
1791/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1792/// unit. If false, it only allows accesses known to be in a single element.
Chris Lattner8acbb792011-01-23 07:29:29 +00001793void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattner229907c2011-07-18 04:54:35 +00001794 Type *MemOpType, bool isStore,
Chris Lattner9491dee2011-01-23 08:27:54 +00001795 AllocaInfo &Info, Instruction *TheAccess,
1796 bool AllowWholeAccess) {
Bob Wilson532cd232009-12-18 20:14:40 +00001797 // Check if this is a load/store of the entire alloca.
Chris Lattner9491dee2011-01-23 08:27:54 +00001798 if (Offset == 0 && AllowWholeAccess &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001799 MemSize == DL->getTypeAllocSize(Info.AI->getAllocatedType())) {
Bob Wilson08713d32011-01-13 17:45:11 +00001800 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1801 // loads/stores (which are essentially the same as the MemIntrinsics with
1802 // regard to copying padding between elements). But, if an alloca is
1803 // flagged as both a source and destination of such operations, we'll need
1804 // to check later for padding between elements.
1805 if (!MemOpType || MemOpType->isIntegerTy()) {
1806 if (isStore)
1807 Info.isMemCpyDst = true;
1808 else
1809 Info.isMemCpySrc = true;
Bob Wilson532cd232009-12-18 20:14:40 +00001810 return;
1811 }
Bob Wilson08713d32011-01-13 17:45:11 +00001812 // This is also safe for references using a type that is compatible with
1813 // the type of the alloca, so that loads/stores can be rewritten using
1814 // insertvalue/extractvalue.
Chris Lattner8acbb792011-01-23 07:29:29 +00001815 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
Chris Lattner6fab2e92011-01-16 06:18:28 +00001816 Info.hasSubelementAccess = true;
Bob Wilson08713d32011-01-13 17:45:11 +00001817 return;
Chris Lattner6fab2e92011-01-16 06:18:28 +00001818 }
Bob Wilson532cd232009-12-18 20:14:40 +00001819 }
1820 // Check if the offset/size correspond to a component within the alloca type.
Chris Lattner229907c2011-07-18 04:54:35 +00001821 Type *T = Info.AI->getAllocatedType();
Chris Lattner6fab2e92011-01-16 06:18:28 +00001822 if (TypeHasComponent(T, Offset, MemSize)) {
1823 Info.hasSubelementAccess = true;
Bob Wilson532cd232009-12-18 20:14:40 +00001824 return;
Chris Lattner6fab2e92011-01-16 06:18:28 +00001825 }
Bob Wilson532cd232009-12-18 20:14:40 +00001826
Chris Lattner3e56c292011-01-23 07:05:44 +00001827 return MarkUnsafe(Info, TheAccess);
Bob Wilson532cd232009-12-18 20:14:40 +00001828}
1829
1830/// TypeHasComponent - Return true if T has a component type with the
1831/// specified offset and size. If Size is zero, do not check the size.
Chris Lattner229907c2011-07-18 04:54:35 +00001832bool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size) {
1833 Type *EltTy;
Bob Wilson532cd232009-12-18 20:14:40 +00001834 uint64_t EltSize;
Chris Lattner229907c2011-07-18 04:54:35 +00001835 if (StructType *ST = dyn_cast<StructType>(T)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001836 const StructLayout *Layout = DL->getStructLayout(ST);
Bob Wilson532cd232009-12-18 20:14:40 +00001837 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1838 EltTy = ST->getContainedType(EltIdx);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001839 EltSize = DL->getTypeAllocSize(EltTy);
Bob Wilson532cd232009-12-18 20:14:40 +00001840 Offset -= Layout->getElementOffset(EltIdx);
Chris Lattner229907c2011-07-18 04:54:35 +00001841 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001842 EltTy = AT->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001843 EltSize = DL->getTypeAllocSize(EltTy);
Bob Wilson62a84ea2009-12-22 06:57:14 +00001844 if (Offset >= AT->getNumElements() * EltSize)
1845 return false;
Bob Wilson532cd232009-12-18 20:14:40 +00001846 Offset %= EltSize;
Pete Cooper1d1fa722012-06-14 23:53:53 +00001847 } else if (VectorType *VT = dyn_cast<VectorType>(T)) {
1848 EltTy = VT->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001849 EltSize = DL->getTypeAllocSize(EltTy);
Pete Cooper1d1fa722012-06-14 23:53:53 +00001850 if (Offset >= VT->getNumElements() * EltSize)
1851 return false;
1852 Offset %= EltSize;
Bob Wilson532cd232009-12-18 20:14:40 +00001853 } else {
1854 return false;
1855 }
1856 if (Offset == 0 && (Size == 0 || EltSize == Size))
1857 return true;
1858 // Check if the component spans multiple elements.
1859 if (Offset + Size > EltSize)
1860 return false;
1861 return TypeHasComponent(EltTy, Offset, Size);
1862}
1863
1864/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1865/// the instruction I, which references it, to use the separate elements.
1866/// Offset indicates the position within AI that is referenced by this
1867/// instruction.
1868void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00001869 SmallVectorImpl<AllocaInst *> &NewElts) {
Chris Lattner9491dee2011-01-23 08:27:54 +00001870 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001871 Use &TheUse = *UI++;
1872 Instruction *User = cast<Instruction>(TheUse.getUser());
Bob Wilson532cd232009-12-18 20:14:40 +00001873
1874 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1875 RewriteBitCast(BC, AI, Offset, NewElts);
Chris Lattner9491dee2011-01-23 08:27:54 +00001876 continue;
1877 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001878
Chris Lattner9491dee2011-01-23 08:27:54 +00001879 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001880 RewriteGEP(GEPI, AI, Offset, NewElts);
Chris Lattner9491dee2011-01-23 08:27:54 +00001881 continue;
1882 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001883
Chris Lattner9491dee2011-01-23 08:27:54 +00001884 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001885 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1886 uint64_t MemSize = Length->getZExtValue();
1887 if (Offset == 0 &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001888 MemSize == DL->getTypeAllocSize(AI->getAllocatedType()))
Bob Wilson532cd232009-12-18 20:14:40 +00001889 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsonc16811b2009-12-19 06:53:17 +00001890 // Otherwise the intrinsic can only touch a single element and the
1891 // address operand will be updated, so nothing else needs to be done.
Chris Lattner9491dee2011-01-23 08:27:54 +00001892 continue;
1893 }
Nick Lewycky15e2d902011-07-25 23:14:22 +00001894
1895 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1896 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1897 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1898 RewriteLifetimeIntrinsic(II, AI, Offset, NewElts);
1899 }
1900 continue;
1901 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001902
Chris Lattner9491dee2011-01-23 08:27:54 +00001903 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner229907c2011-07-18 04:54:35 +00001904 Type *LIType = LI->getType();
Nadav Rotem465834c2012-07-24 10:51:42 +00001905
Bob Wilson08713d32011-01-13 17:45:11 +00001906 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
Bob Wilson532cd232009-12-18 20:14:40 +00001907 // Replace:
1908 // %res = load { i32, i32 }* %alloc
1909 // with:
1910 // %load.0 = load i32* %alloc.0
1911 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1912 // %load.1 = load i32* %alloc.1
1913 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1914 // (Also works for arrays instead of structs)
1915 Value *Insert = UndefValue::get(LIType);
Devang Patel84bb33a2011-06-03 19:46:19 +00001916 IRBuilder<> Builder(LI);
Bob Wilson532cd232009-12-18 20:14:40 +00001917 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patel84bb33a2011-06-03 19:46:19 +00001918 Value *Load = Builder.CreateLoad(NewElts[i], "load");
1919 Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
Bob Wilson532cd232009-12-18 20:14:40 +00001920 }
1921 LI->replaceAllUsesWith(Insert);
1922 DeadInsts.push_back(LI);
Duncan Sands19d0b472010-02-16 11:11:14 +00001923 } else if (LIType->isIntegerTy() &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001924 DL->getTypeAllocSize(LIType) ==
1925 DL->getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilson532cd232009-12-18 20:14:40 +00001926 // If this is a load of the entire alloca to an integer, rewrite it.
1927 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1928 }
Chris Lattner9491dee2011-01-23 08:27:54 +00001929 continue;
1930 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001931
Chris Lattner9491dee2011-01-23 08:27:54 +00001932 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001933 Value *Val = SI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00001934 Type *SIType = Val->getType();
Bob Wilson08713d32011-01-13 17:45:11 +00001935 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
Bob Wilson532cd232009-12-18 20:14:40 +00001936 // Replace:
1937 // store { i32, i32 } %val, { i32, i32 }* %alloc
1938 // with:
1939 // %val.0 = extractvalue { i32, i32 } %val, 0
1940 // store i32 %val.0, i32* %alloc.0
1941 // %val.1 = extractvalue { i32, i32 } %val, 1
1942 // store i32 %val.1, i32* %alloc.1
1943 // (Also works for arrays instead of structs)
Devang Patel84bb33a2011-06-03 19:46:19 +00001944 IRBuilder<> Builder(SI);
Bob Wilson532cd232009-12-18 20:14:40 +00001945 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patel84bb33a2011-06-03 19:46:19 +00001946 Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
1947 Builder.CreateStore(Extract, NewElts[i]);
Bob Wilson532cd232009-12-18 20:14:40 +00001948 }
1949 DeadInsts.push_back(SI);
Duncan Sands19d0b472010-02-16 11:11:14 +00001950 } else if (SIType->isIntegerTy() &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001951 DL->getTypeAllocSize(SIType) ==
1952 DL->getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilson532cd232009-12-18 20:14:40 +00001953 // If this is a store of the entire alloca from an integer, rewrite it.
1954 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1955 }
Chris Lattner9491dee2011-01-23 08:27:54 +00001956 continue;
1957 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001958
Chris Lattner9491dee2011-01-23 08:27:54 +00001959 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
Nadav Rotem465834c2012-07-24 10:51:42 +00001960 // If we have a PHI user of the alloca itself (as opposed to a GEP or
Chris Lattner9491dee2011-01-23 08:27:54 +00001961 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
1962 // the new pointer.
1963 if (!isa<AllocaInst>(I)) continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00001964
Chris Lattner9491dee2011-01-23 08:27:54 +00001965 assert(Offset == 0 && NewElts[0] &&
1966 "Direct alloca use should have a zero offset");
Nadav Rotem465834c2012-07-24 10:51:42 +00001967
Chris Lattner9491dee2011-01-23 08:27:54 +00001968 // If we have a use of the alloca, we know the derived uses will be
1969 // utilizing just the first element of the scalarized result. Insert a
1970 // bitcast of the first alloca before the user as required.
1971 AllocaInst *NewAI = NewElts[0];
1972 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1973 NewAI->moveBefore(BCI);
1974 TheUse = BCI;
1975 continue;
Bob Wilson532cd232009-12-18 20:14:40 +00001976 }
Bob Wilsonf3927b72009-12-17 18:34:24 +00001977 }
1978}
1979
Bob Wilson532cd232009-12-18 20:14:40 +00001980/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1981/// and recursively continue updating all of its uses.
1982void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00001983 SmallVectorImpl<AllocaInst *> &NewElts) {
Bob Wilson532cd232009-12-18 20:14:40 +00001984 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1985 if (BC->getOperand(0) != AI)
1986 return;
Bob Wilsonf3927b72009-12-17 18:34:24 +00001987
Bob Wilson532cd232009-12-18 20:14:40 +00001988 // The bitcast references the original alloca. Replace its uses with
Eli Friedmanecb45382011-11-12 02:07:50 +00001989 // references to the alloca containing offset zero (which is normally at
1990 // index zero, but might not be in cases involving structs with elements
1991 // of size zero).
1992 Type *T = AI->getAllocatedType();
1993 uint64_t EltOffset = 0;
1994 Type *IdxTy;
1995 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
1996 Instruction *Val = NewElts[Idx];
Bob Wilson532cd232009-12-18 20:14:40 +00001997 if (Val->getType() != BC->getDestTy()) {
1998 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1999 Val->takeName(BC);
Daniel Dunbar133efc32009-12-16 10:56:17 +00002000 }
Bob Wilson532cd232009-12-18 20:14:40 +00002001 BC->replaceAllUsesWith(Val);
2002 DeadInsts.push_back(BC);
Daniel Dunbar133efc32009-12-16 10:56:17 +00002003}
2004
Bob Wilson532cd232009-12-18 20:14:40 +00002005/// FindElementAndOffset - Return the index of the element containing Offset
2006/// within the specified type, which must be either a struct or an array.
2007/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsonc16811b2009-12-19 06:53:17 +00002008/// element. IdxTy is set to the type of the index result to be used in a
2009/// GEP instruction.
Chris Lattner229907c2011-07-18 04:54:35 +00002010uint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset,
2011 Type *&IdxTy) {
Bob Wilsonc16811b2009-12-19 06:53:17 +00002012 uint64_t Idx = 0;
Chris Lattner229907c2011-07-18 04:54:35 +00002013 if (StructType *ST = dyn_cast<StructType>(T)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002014 const StructLayout *Layout = DL->getStructLayout(ST);
Bob Wilson532cd232009-12-18 20:14:40 +00002015 Idx = Layout->getElementContainingOffset(Offset);
2016 T = ST->getContainedType(Idx);
2017 Offset -= Layout->getElementOffset(Idx);
Bob Wilsonc16811b2009-12-19 06:53:17 +00002018 IdxTy = Type::getInt32Ty(T->getContext());
2019 return Idx;
Pete Cooper1d1fa722012-06-14 23:53:53 +00002020 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
2021 T = AT->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002022 uint64_t EltSize = DL->getTypeAllocSize(T);
Pete Cooper1d1fa722012-06-14 23:53:53 +00002023 Idx = Offset / EltSize;
2024 Offset -= Idx * EltSize;
2025 IdxTy = Type::getInt64Ty(T->getContext());
2026 return Idx;
Chris Lattneraaa6ac12009-12-14 05:11:02 +00002027 }
Pete Cooper1d1fa722012-06-14 23:53:53 +00002028 VectorType *VT = cast<VectorType>(T);
2029 T = VT->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002030 uint64_t EltSize = DL->getTypeAllocSize(T);
Bob Wilsonc16811b2009-12-19 06:53:17 +00002031 Idx = Offset / EltSize;
2032 Offset -= Idx * EltSize;
2033 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilson532cd232009-12-18 20:14:40 +00002034 return Idx;
2035}
2036
2037/// RewriteGEP - Check if this GEP instruction moves the pointer across
2038/// elements of the alloca that are being split apart, and if so, rewrite
2039/// the GEP to be relative to the new element.
2040void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00002041 SmallVectorImpl<AllocaInst *> &NewElts) {
Bob Wilson532cd232009-12-18 20:14:40 +00002042 uint64_t OldOffset = Offset;
2043 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
Pete Coopere24d6a12012-06-15 18:07:29 +00002044 // If the GEP was dynamic then it must have been a dynamic vector lookup.
2045 // In this case, it must be the last GEP operand which is dynamic so keep that
2046 // aside until we've found the constant GEP offset then add it back in at the
2047 // end.
Craig Topperf40110f2014-04-25 05:29:35 +00002048 Value* NonConstantIdx = nullptr;
Pete Coopere24d6a12012-06-15 18:07:29 +00002049 if (!GEPI->hasAllConstantIndices())
2050 NonConstantIdx = Indices.pop_back_val();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002051 Offset += DL->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
Bob Wilson532cd232009-12-18 20:14:40 +00002052
2053 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
2054
Chris Lattner229907c2011-07-18 04:54:35 +00002055 Type *T = AI->getAllocatedType();
2056 Type *IdxTy;
Bob Wilsonc16811b2009-12-19 06:53:17 +00002057 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilson532cd232009-12-18 20:14:40 +00002058 if (GEPI->getOperand(0) == AI)
Bob Wilsonc16811b2009-12-19 06:53:17 +00002059 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilson532cd232009-12-18 20:14:40 +00002060
2061 T = AI->getAllocatedType();
2062 uint64_t EltOffset = Offset;
Bob Wilsonc16811b2009-12-19 06:53:17 +00002063 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilson532cd232009-12-18 20:14:40 +00002064
2065 // If this GEP does not move the pointer across elements of the alloca
2066 // being split, then it does not needs to be rewritten.
2067 if (Idx == OldIdx)
2068 return;
2069
Chris Lattner229907c2011-07-18 04:54:35 +00002070 Type *i32Ty = Type::getInt32Ty(AI->getContext());
Bob Wilson532cd232009-12-18 20:14:40 +00002071 SmallVector<Value*, 8> NewArgs;
2072 NewArgs.push_back(Constant::getNullValue(i32Ty));
2073 while (EltOffset != 0) {
Bob Wilsonc16811b2009-12-19 06:53:17 +00002074 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
2075 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilson532cd232009-12-18 20:14:40 +00002076 }
Pete Cooper818e9f42012-06-16 01:43:26 +00002077 if (NonConstantIdx) {
2078 Type* GepTy = T;
2079 // This GEP has a dynamic index. We need to add "i32 0" to index through
2080 // any structs or arrays in the original type until we get to the vector
2081 // to index.
2082 while (!isa<VectorType>(GepTy)) {
2083 NewArgs.push_back(Constant::getNullValue(i32Ty));
2084 GepTy = cast<CompositeType>(GepTy)->getTypeAtIndex(0U);
2085 }
Pete Coopere24d6a12012-06-15 18:07:29 +00002086 NewArgs.push_back(NonConstantIdx);
Pete Cooper818e9f42012-06-16 01:43:26 +00002087 }
Bob Wilson532cd232009-12-18 20:14:40 +00002088 Instruction *Val = NewElts[Idx];
2089 if (NewArgs.size() > 1) {
Jay Foadd1b78492011-07-25 09:48:08 +00002090 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs, "", GEPI);
Bob Wilson532cd232009-12-18 20:14:40 +00002091 Val->takeName(GEPI);
2092 }
2093 if (Val->getType() != GEPI->getType())
Benjamin Kramer40582a82010-01-27 19:46:52 +00002094 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilson532cd232009-12-18 20:14:40 +00002095 GEPI->replaceAllUsesWith(Val);
2096 DeadInsts.push_back(GEPI);
Chris Lattner9a2de652009-01-07 07:18:45 +00002097}
2098
Nick Lewycky15e2d902011-07-25 23:14:22 +00002099/// RewriteLifetimeIntrinsic - II is a lifetime.start/lifetime.end. Rewrite it
2100/// to mark the lifetime of the scalarized memory.
2101void SROA::RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
2102 uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00002103 SmallVectorImpl<AllocaInst *> &NewElts) {
Nick Lewycky15e2d902011-07-25 23:14:22 +00002104 ConstantInt *OldSize = cast<ConstantInt>(II->getArgOperand(0));
2105 // Put matching lifetime markers on everything from Offset up to
2106 // Offset+OldSize.
2107 Type *AIType = AI->getAllocatedType();
2108 uint64_t NewOffset = Offset;
2109 Type *IdxTy;
2110 uint64_t Idx = FindElementAndOffset(AIType, NewOffset, IdxTy);
2111
2112 IRBuilder<> Builder(II);
2113 uint64_t Size = OldSize->getLimitedValue();
2114
2115 if (NewOffset) {
2116 // Splice the first element and index 'NewOffset' bytes in. SROA will
2117 // split the alloca again later.
Matt Arsenaultbe558882014-04-23 20:58:57 +00002118 unsigned AS = AI->getType()->getAddressSpace();
2119 Value *V = Builder.CreateBitCast(NewElts[Idx], Builder.getInt8PtrTy(AS));
Nick Lewycky15e2d902011-07-25 23:14:22 +00002120 V = Builder.CreateGEP(V, Builder.getInt64(NewOffset));
2121
2122 IdxTy = NewElts[Idx]->getAllocatedType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002123 uint64_t EltSize = DL->getTypeAllocSize(IdxTy) - NewOffset;
Nick Lewycky15e2d902011-07-25 23:14:22 +00002124 if (EltSize > Size) {
2125 EltSize = Size;
2126 Size = 0;
2127 } else {
2128 Size -= EltSize;
2129 }
2130 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2131 Builder.CreateLifetimeStart(V, Builder.getInt64(EltSize));
2132 else
2133 Builder.CreateLifetimeEnd(V, Builder.getInt64(EltSize));
2134 ++Idx;
2135 }
2136
2137 for (; Idx != NewElts.size() && Size; ++Idx) {
2138 IdxTy = NewElts[Idx]->getAllocatedType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002139 uint64_t EltSize = DL->getTypeAllocSize(IdxTy);
Nick Lewycky15e2d902011-07-25 23:14:22 +00002140 if (EltSize > Size) {
2141 EltSize = Size;
2142 Size = 0;
2143 } else {
2144 Size -= EltSize;
2145 }
2146 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2147 Builder.CreateLifetimeStart(NewElts[Idx],
2148 Builder.getInt64(EltSize));
2149 else
2150 Builder.CreateLifetimeEnd(NewElts[Idx],
2151 Builder.getInt64(EltSize));
2152 }
2153 DeadInsts.push_back(II);
2154}
2155
Chris Lattner9a2de652009-01-07 07:18:45 +00002156/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
2157/// Rewrite it to copy or set the elements of the scalarized memory.
Craig Topperb94011f2013-07-14 04:42:23 +00002158void
2159SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
2160 AllocaInst *AI,
2161 SmallVectorImpl<AllocaInst *> &NewElts) {
Chris Lattner9a2de652009-01-07 07:18:45 +00002162 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattnera41bb402009-03-04 19:23:25 +00002163 // appropriate type. The "Other" pointer is the pointer that goes to memory
2164 // that doesn't have anything to do with the alloca that we are promoting. For
2165 // memset, this Value* stays null.
Craig Topperf40110f2014-04-25 05:29:35 +00002166 Value *OtherPtr = nullptr;
Chris Lattnerdc35e5b2009-03-08 03:59:00 +00002167 unsigned MemAlignment = MI->getAlignment();
Chris Lattner334268a2009-03-08 03:37:16 +00002168 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilson532cd232009-12-18 20:14:40 +00002169 if (Inst == MTI->getRawDest())
Chris Lattner334268a2009-03-08 03:37:16 +00002170 OtherPtr = MTI->getRawSource();
Chris Lattner9a2de652009-01-07 07:18:45 +00002171 else {
Bob Wilson532cd232009-12-18 20:14:40 +00002172 assert(Inst == MTI->getRawSource());
Chris Lattner334268a2009-03-08 03:37:16 +00002173 OtherPtr = MTI->getRawDest();
Chris Lattner9a2de652009-01-07 07:18:45 +00002174 }
2175 }
Bob Wilson2029ea02009-12-08 18:22:03 +00002176
Chris Lattner9a2de652009-01-07 07:18:45 +00002177 // If there is an other pointer, we want to convert it to the same pointer
2178 // type as AI has, so we can GEP through it safely.
2179 if (OtherPtr) {
Chris Lattnerefa3c822010-07-08 00:27:05 +00002180 unsigned AddrSpace =
2181 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilson532cd232009-12-18 20:14:40 +00002182
2183 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
2184 // optimization, but it's also required to detect the corner case where
2185 // both pointer operands are referencing the same memory, and where
2186 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
2187 // function is only called for mem intrinsics that access the whole
2188 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattnerefa3c822010-07-08 00:27:05 +00002189 OtherPtr = OtherPtr->stripPointerCasts();
Bob Wilson328e91b2011-01-13 20:59:44 +00002190
Bob Wilson58d59fe2010-01-19 04:32:48 +00002191 // Copying the alloca to itself is a no-op: just delete it.
2192 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2193 // This code will run twice for a no-op memcpy -- once for each operand.
2194 // Put only one reference to MI on the DeadInsts list.
Craig Topper31ee5862013-07-03 15:07:05 +00002195 for (SmallVectorImpl<Value *>::const_iterator I = DeadInsts.begin(),
Bob Wilson58d59fe2010-01-19 04:32:48 +00002196 E = DeadInsts.end(); I != E; ++I)
2197 if (*I == MI) return;
2198 DeadInsts.push_back(MI);
Bob Wilson532cd232009-12-18 20:14:40 +00002199 return;
Bob Wilson58d59fe2010-01-19 04:32:48 +00002200 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002201
Chris Lattner9a2de652009-01-07 07:18:45 +00002202 // If the pointer is not the right type, insert a bitcast to the right
2203 // type.
Chris Lattner229907c2011-07-18 04:54:35 +00002204 Type *NewTy =
Chris Lattnerefa3c822010-07-08 00:27:05 +00002205 PointerType::get(AI->getType()->getElementType(), AddrSpace);
Bob Wilson328e91b2011-01-13 20:59:44 +00002206
Chris Lattnerefa3c822010-07-08 00:27:05 +00002207 if (OtherPtr->getType() != NewTy)
2208 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattner9a2de652009-01-07 07:18:45 +00002209 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002210
Chris Lattner9a2de652009-01-07 07:18:45 +00002211 // Process each element of the aggregate.
Bob Wilson532cd232009-12-18 20:14:40 +00002212 bool SROADest = MI->getRawDest() == Inst;
Bob Wilson328e91b2011-01-13 20:59:44 +00002213
Owen Anderson55f1c092009-08-13 21:58:54 +00002214 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattner9a2de652009-01-07 07:18:45 +00002215
2216 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2217 // If this is a memcpy/memmove, emit a GEP of the other element address.
Craig Topperf40110f2014-04-25 05:29:35 +00002218 Value *OtherElt = nullptr;
Chris Lattner5c204c92009-03-04 19:20:50 +00002219 unsigned OtherEltAlign = MemAlignment;
Bob Wilson328e91b2011-01-13 20:59:44 +00002220
Bob Wilson58d59fe2010-01-19 04:32:48 +00002221 if (OtherPtr) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002222 Value *Idx[2] = { Zero,
2223 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Jay Foadd1b78492011-07-25 09:48:08 +00002224 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx,
Benjamin Kramer40582a82010-01-27 19:46:52 +00002225 OtherPtr->getName()+"."+Twine(i),
Bob Wilson532cd232009-12-18 20:14:40 +00002226 MI);
Chris Lattner5c204c92009-03-04 19:20:50 +00002227 uint64_t EltOffset;
Chris Lattner229907c2011-07-18 04:54:35 +00002228 PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
2229 Type *OtherTy = OtherPtrTy->getElementType();
2230 if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002231 EltOffset = DL->getStructLayout(ST)->getElementOffset(i);
Chris Lattner5c204c92009-03-04 19:20:50 +00002232 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002233 Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002234 EltOffset = DL->getTypeAllocSize(EltTy)*i;
Chris Lattner5c204c92009-03-04 19:20:50 +00002235 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002236
Chris Lattner5c204c92009-03-04 19:20:50 +00002237 // The alignment of the other pointer is the guaranteed alignment of the
2238 // element, which is affected by both the known alignment of the whole
2239 // mem intrinsic and the alignment of the element. If the alignment of
2240 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2241 // known alignment is just 4 bytes.
2242 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattner9f022d52007-03-08 06:36:54 +00002243 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002244
Chris Lattner9a2de652009-01-07 07:18:45 +00002245 Value *EltPtr = NewElts[i];
Chris Lattner229907c2011-07-18 04:54:35 +00002246 Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Bob Wilson328e91b2011-01-13 20:59:44 +00002247
Chris Lattner9a2de652009-01-07 07:18:45 +00002248 // If we got down to a scalar, insert a load or store as appropriate.
2249 if (EltTy->isSingleValueType()) {
Chris Lattner334268a2009-03-08 03:37:16 +00002250 if (isa<MemTransferInst>(MI)) {
Chris Lattner5c204c92009-03-04 19:20:50 +00002251 if (SROADest) {
2252 // From Other to Alloca.
2253 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2254 new StoreInst(Elt, EltPtr, MI);
2255 } else {
2256 // From Alloca to Other.
2257 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2258 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2259 }
Chris Lattner9a2de652009-01-07 07:18:45 +00002260 continue;
2261 }
2262 assert(isa<MemSetInst>(MI));
Bob Wilson328e91b2011-01-13 20:59:44 +00002263
Chris Lattner9a2de652009-01-07 07:18:45 +00002264 // If the stored element is zero (common case), just store a null
2265 // constant.
2266 Constant *StoreVal;
Gabor Greiffe252e62010-06-30 09:16:16 +00002267 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattner9a2de652009-01-07 07:18:45 +00002268 if (CI->isZero()) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00002269 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattner9a2de652009-01-07 07:18:45 +00002270 } else {
2271 // If EltTy is a vector type, get the element type.
Chris Lattner229907c2011-07-18 04:54:35 +00002272 Type *ValTy = EltTy->getScalarType();
Dan Gohmanadfd42a2009-06-16 00:20:26 +00002273
Chris Lattner9a2de652009-01-07 07:18:45 +00002274 // Construct an integer with the right value.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002275 unsigned EltSize = DL->getTypeSizeInBits(ValTy);
Chris Lattner9a2de652009-01-07 07:18:45 +00002276 APInt OneVal(EltSize, CI->getZExtValue());
2277 APInt TotalVal(OneVal);
2278 // Set each byte.
2279 for (unsigned i = 0; 8*i < EltSize; ++i) {
2280 TotalVal = TotalVal.shl(8);
2281 TotalVal |= OneVal;
2282 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002283
Chris Lattner9a2de652009-01-07 07:18:45 +00002284 // Convert the integer value to the appropriate type.
Chris Lattner1146d322010-04-16 01:05:38 +00002285 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands19d0b472010-02-16 11:11:14 +00002286 if (ValTy->isPointerTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002287 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sands9dff9be2010-02-15 16:12:20 +00002288 else if (ValTy->isFloatingPointTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002289 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattner9a2de652009-01-07 07:18:45 +00002290 assert(StoreVal->getType() == ValTy && "Type mismatch!");
Bob Wilson328e91b2011-01-13 20:59:44 +00002291
Chris Lattner9a2de652009-01-07 07:18:45 +00002292 // If the requested value was a vector constant, create it.
Cameron Zwarich1a761dc2011-10-11 21:26:40 +00002293 if (EltTy->isVectorTy()) {
2294 unsigned NumElts = cast<VectorType>(EltTy)->getNumElements();
Chris Lattner47a86bd2012-01-25 06:02:56 +00002295 StoreVal = ConstantVector::getSplat(NumElts, StoreVal);
Chris Lattner9a2de652009-01-07 07:18:45 +00002296 }
2297 }
2298 new StoreInst(StoreVal, EltPtr, MI);
2299 continue;
2300 }
2301 // Otherwise, if we're storing a byte variable, use a memset call for
2302 // this element.
2303 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002304
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002305 unsigned EltSize = DL->getTypeAllocSize(EltTy);
Eli Friedmanecb45382011-11-12 02:07:50 +00002306 if (!EltSize)
2307 continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00002308
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00002309 IRBuilder<> Builder(MI);
Bob Wilson328e91b2011-01-13 20:59:44 +00002310
Chris Lattner9a2de652009-01-07 07:18:45 +00002311 // Finally, insert the meminst for this element.
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00002312 if (isa<MemSetInst>(MI)) {
2313 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2314 MI->isVolatile());
Chris Lattner9a2de652009-01-07 07:18:45 +00002315 } else {
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00002316 assert(isa<MemTransferInst>(MI));
2317 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
2318 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
Bob Wilson328e91b2011-01-13 20:59:44 +00002319
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00002320 if (isa<MemCpyInst>(MI))
2321 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2322 else
2323 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
Chris Lattner9a2de652009-01-07 07:18:45 +00002324 }
Chris Lattner66e6a822007-03-05 07:52:57 +00002325 }
Bob Wilson532cd232009-12-18 20:14:40 +00002326 DeadInsts.push_back(MI);
Chris Lattner66e6a822007-03-05 07:52:57 +00002327}
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002328
Bob Wilson050b8122009-12-04 21:57:37 +00002329/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002330/// overwrites the entire allocation. Extract out the pieces of the stored
2331/// integer and store them individually.
Craig Topperb94011f2013-07-14 04:42:23 +00002332void
2333SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
2334 SmallVectorImpl<AllocaInst *> &NewElts) {
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002335 // Extract each element out of the integer according to its structure offset
2336 // and store the element value to the individual alloca.
2337 Value *SrcVal = SI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002338 Type *AllocaEltTy = AI->getAllocatedType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002339 uint64_t AllocaSizeBits = DL->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002340
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002341 IRBuilder<> Builder(SI);
Nadav Rotem465834c2012-07-24 10:51:42 +00002342
Eli Friedmanee94e3c2009-06-01 09:14:32 +00002343 // Handle tail padding by extending the operand
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002344 if (DL->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002345 SrcVal = Builder.CreateZExt(SrcVal,
2346 IntegerType::get(SI->getContext(), AllocaSizeBits));
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002347
David Greene48c86be2010-01-05 01:27:09 +00002348 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky7465cd72009-09-15 07:08:25 +00002349 << '\n');
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002350
2351 // There are two forms here: AI could be an array or struct. Both cases
2352 // have different ways to compute the element offset.
Chris Lattner229907c2011-07-18 04:54:35 +00002353 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002354 const StructLayout *Layout = DL->getStructLayout(EltSTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002355
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002356 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2357 // Get the number of bits to shift SrcVal to get the value.
Chris Lattner229907c2011-07-18 04:54:35 +00002358 Type *FieldTy = EltSTy->getElementType(i);
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002359 uint64_t Shift = Layout->getElementOffsetInBits(i);
Bob Wilson328e91b2011-01-13 20:59:44 +00002360
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002361 if (DL->isBigEndian())
2362 Shift = AllocaSizeBits-Shift-DL->getTypeAllocSizeInBits(FieldTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002363
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002364 Value *EltVal = SrcVal;
2365 if (Shift) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002366 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002367 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002368 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002369
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002370 // Truncate down to an integer of the right size.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002371 uint64_t FieldSizeBits = DL->getTypeSizeInBits(FieldTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002372
Chris Lattnerae0e8572009-01-09 18:18:43 +00002373 // Ignore zero sized fields like {}, they obviously contain no data.
2374 if (FieldSizeBits == 0) continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00002375
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002376 if (FieldSizeBits != AllocaSizeBits)
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002377 EltVal = Builder.CreateTrunc(EltVal,
2378 IntegerType::get(SI->getContext(), FieldSizeBits));
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002379 Value *DestField = NewElts[i];
2380 if (EltVal->getType() == FieldTy) {
2381 // Storing to an integer field of this size, just do it.
Duncan Sands19d0b472010-02-16 11:11:14 +00002382 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002383 // Bitcast to the right element type (for fp/vector values).
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002384 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002385 } else {
2386 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002387 DestField = Builder.CreateBitCast(DestField,
2388 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002389 }
2390 new StoreInst(EltVal, DestField, SI);
2391 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002392
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002393 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002394 ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2395 Type *ArrayEltTy = ATy->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002396 uint64_t ElementOffset = DL->getTypeAllocSizeInBits(ArrayEltTy);
2397 uint64_t ElementSizeBits = DL->getTypeSizeInBits(ArrayEltTy);
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002398
2399 uint64_t Shift;
Bob Wilson328e91b2011-01-13 20:59:44 +00002400
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002401 if (DL->isBigEndian())
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002402 Shift = AllocaSizeBits-ElementOffset;
Bob Wilson328e91b2011-01-13 20:59:44 +00002403 else
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002404 Shift = 0;
Bob Wilson328e91b2011-01-13 20:59:44 +00002405
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002406 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattnerae0e8572009-01-09 18:18:43 +00002407 // Ignore zero sized fields like {}, they obviously contain no data.
2408 if (ElementSizeBits == 0) continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00002409
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002410 Value *EltVal = SrcVal;
2411 if (Shift) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002412 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002413 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002414 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002415
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002416 // Truncate down to an integer of the right size.
2417 if (ElementSizeBits != AllocaSizeBits)
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002418 EltVal = Builder.CreateTrunc(EltVal,
2419 IntegerType::get(SI->getContext(),
2420 ElementSizeBits));
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002421 Value *DestField = NewElts[i];
2422 if (EltVal->getType() == ArrayEltTy) {
2423 // Storing to an integer field of this size, just do it.
Duncan Sands9dff9be2010-02-15 16:12:20 +00002424 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +00002425 ArrayEltTy->isVectorTy()) {
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002426 // Bitcast to the right element type (for fp/vector values).
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002427 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002428 } else {
2429 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002430 DestField = Builder.CreateBitCast(DestField,
2431 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002432 }
2433 new StoreInst(EltVal, DestField, SI);
Bob Wilson328e91b2011-01-13 20:59:44 +00002434
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002435 if (DL->isBigEndian())
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002436 Shift -= ElementOffset;
Bob Wilson328e91b2011-01-13 20:59:44 +00002437 else
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002438 Shift += ElementOffset;
2439 }
2440 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002441
Bob Wilson532cd232009-12-18 20:14:40 +00002442 DeadInsts.push_back(SI);
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002443}
2444
Bob Wilson050b8122009-12-04 21:57:37 +00002445/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002446/// an integer. Load the individual pieces to form the aggregate value.
Craig Topperb94011f2013-07-14 04:42:23 +00002447void
2448SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
2449 SmallVectorImpl<AllocaInst *> &NewElts) {
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002450 // Extract each element out of the NewElts according to its structure offset
2451 // and form the result value.
Chris Lattner229907c2011-07-18 04:54:35 +00002452 Type *AllocaEltTy = AI->getAllocatedType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002453 uint64_t AllocaSizeBits = DL->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002454
David Greene48c86be2010-01-05 01:27:09 +00002455 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky7465cd72009-09-15 07:08:25 +00002456 << '\n');
Bob Wilson328e91b2011-01-13 20:59:44 +00002457
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002458 // There are two forms here: AI could be an array or struct. Both cases
2459 // have different ways to compute the element offset.
Craig Topperf40110f2014-04-25 05:29:35 +00002460 const StructLayout *Layout = nullptr;
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002461 uint64_t ArrayEltBitOffset = 0;
Chris Lattner229907c2011-07-18 04:54:35 +00002462 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002463 Layout = DL->getStructLayout(EltSTy);
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002464 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002465 Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002466 ArrayEltBitOffset = DL->getTypeAllocSizeInBits(ArrayEltTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002467 }
2468
2469 Value *ResultVal =
Owen Anderson55f1c092009-08-13 21:58:54 +00002470 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Bob Wilson328e91b2011-01-13 20:59:44 +00002471
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002472 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2473 // Load the value from the alloca. If the NewElt is an aggregate, cast
2474 // the pointer to an integer of the same size before doing the load.
2475 Value *SrcField = NewElts[i];
Chris Lattner229907c2011-07-18 04:54:35 +00002476 Type *FieldTy =
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002477 cast<PointerType>(SrcField->getType())->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002478 uint64_t FieldSizeBits = DL->getTypeSizeInBits(FieldTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002479
Chris Lattnerae0e8572009-01-09 18:18:43 +00002480 // Ignore zero sized fields like {}, they obviously contain no data.
2481 if (FieldSizeBits == 0) continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00002482
Chris Lattner229907c2011-07-18 04:54:35 +00002483 IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00002484 FieldSizeBits);
Duncan Sands19d0b472010-02-16 11:11:14 +00002485 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2486 !FieldTy->isVectorTy())
Owen Anderson340288c2009-07-03 19:42:02 +00002487 SrcField = new BitCastInst(SrcField,
Owen Anderson4056ca92009-07-29 22:17:13 +00002488 PointerType::getUnqual(FieldIntTy),
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002489 "", LI);
2490 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2491
2492 // If SrcField is a fp or vector of the right size but that isn't an
2493 // integer type, bitcast to an integer so we can shift it.
2494 if (SrcField->getType() != FieldIntTy)
2495 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2496
2497 // Zero extend the field to be the same size as the final alloca so that
2498 // we can shift and insert it.
2499 if (SrcField->getType() != ResultVal->getType())
2500 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
Bob Wilson328e91b2011-01-13 20:59:44 +00002501
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002502 // Determine the number of bits to shift SrcField.
2503 uint64_t Shift;
2504 if (Layout) // Struct case.
2505 Shift = Layout->getElementOffsetInBits(i);
2506 else // Array case.
2507 Shift = i*ArrayEltBitOffset;
Bob Wilson328e91b2011-01-13 20:59:44 +00002508
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002509 if (DL->isBigEndian())
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002510 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
Bob Wilson328e91b2011-01-13 20:59:44 +00002511
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002512 if (Shift) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002513 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002514 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2515 }
2516
Chris Lattner25a843f2010-06-27 07:58:26 +00002517 // Don't create an 'or x, 0' on the first iteration.
2518 if (!isa<Constant>(ResultVal) ||
2519 !cast<Constant>(ResultVal)->isNullValue())
2520 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2521 else
2522 ResultVal = SrcField;
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002523 }
Eli Friedmanee94e3c2009-06-01 09:14:32 +00002524
2525 // Handle tail padding by truncating the result
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002526 if (DL->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
Eli Friedmanee94e3c2009-06-01 09:14:32 +00002527 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2528
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002529 LI->replaceAllUsesWith(ResultVal);
Bob Wilson532cd232009-12-18 20:14:40 +00002530 DeadInsts.push_back(LI);
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002531}
2532
Duncan Sands399d9792007-11-04 14:43:57 +00002533/// HasPadding - Return true if the specified type has any structure or
Bob Wilson12eec402011-01-13 17:45:08 +00002534/// alignment padding in between the elements that would be split apart
2535/// by SROA; return false otherwise.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002536static bool HasPadding(Type *Ty, const DataLayout &DL) {
Chris Lattner229907c2011-07-18 04:54:35 +00002537 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Bob Wilson12eec402011-01-13 17:45:08 +00002538 Ty = ATy->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002539 return DL.getTypeSizeInBits(Ty) != DL.getTypeAllocSizeInBits(Ty);
Chris Lattner87679202007-05-30 06:11:23 +00002540 }
Bob Wilson12eec402011-01-13 17:45:08 +00002541
2542 // SROA currently handles only Arrays and Structs.
Chris Lattner229907c2011-07-18 04:54:35 +00002543 StructType *STy = cast<StructType>(Ty);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002544 const StructLayout *SL = DL.getStructLayout(STy);
Bob Wilson12eec402011-01-13 17:45:08 +00002545 unsigned PrevFieldBitOffset = 0;
2546 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2547 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2548
2549 // Check to see if there is any padding between this element and the
2550 // previous one.
2551 if (i) {
2552 unsigned PrevFieldEnd =
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002553 PrevFieldBitOffset+DL.getTypeSizeInBits(STy->getElementType(i-1));
Bob Wilson12eec402011-01-13 17:45:08 +00002554 if (PrevFieldEnd < FieldBitOffset)
2555 return true;
2556 }
2557 PrevFieldBitOffset = FieldBitOffset;
2558 }
2559 // Check for tail padding.
2560 if (unsigned EltCount = STy->getNumElements()) {
2561 unsigned PrevFieldEnd = PrevFieldBitOffset +
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002562 DL.getTypeSizeInBits(STy->getElementType(EltCount-1));
Bob Wilson12eec402011-01-13 17:45:08 +00002563 if (PrevFieldEnd < SL->getSizeInBits())
2564 return true;
2565 }
2566 return false;
Chris Lattner87679202007-05-30 06:11:23 +00002567}
Chris Lattner66e6a822007-03-05 07:52:57 +00002568
Chris Lattner88819122004-11-14 04:24:28 +00002569/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2570/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2571/// or 1 if safe after canonicalization has been performed.
Victor Hernandez1df65182010-01-21 23:05:53 +00002572bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner6e5398d2003-05-30 04:15:41 +00002573 // Loop over the use list of the alloca. We can only transform it if all of
2574 // the users are safe to transform.
Chris Lattner8acbb792011-01-23 07:29:29 +00002575 AllocaInfo Info(AI);
Bob Wilson328e91b2011-01-13 20:59:44 +00002576
Chris Lattner8acbb792011-01-23 07:29:29 +00002577 isSafeForScalarRepl(AI, 0, Info);
Bob Wilson532cd232009-12-18 20:14:40 +00002578 if (Info.isUnsafe) {
David Greene48c86be2010-01-05 01:27:09 +00002579 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez1df65182010-01-21 23:05:53 +00002580 return false;
Chris Lattner88819122004-11-14 04:24:28 +00002581 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002582
Chris Lattner87679202007-05-30 06:11:23 +00002583 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2584 // source and destination, we have to be careful. In particular, the memcpy
2585 // could be moving around elements that live in structure padding of the LLVM
2586 // types, but may actually be used. In these cases, we refuse to promote the
2587 // struct.
2588 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002589 HasPadding(AI->getAllocatedType(), *DL))
Victor Hernandez1df65182010-01-21 23:05:53 +00002590 return false;
Duncan Sands399d9792007-11-04 14:43:57 +00002591
Chris Lattner7c9f4c92011-01-16 17:46:19 +00002592 // If the alloca never has an access to just *part* of it, but is accessed
2593 // via loads and stores, then we should use ConvertToScalarInfo to promote
Chris Lattner6fab2e92011-01-16 06:18:28 +00002594 // the alloca instead of promoting each piece at a time and inserting fission
2595 // and fusion code.
2596 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2597 // If the struct/array just has one element, use basic SRoA.
Chris Lattner229907c2011-07-18 04:54:35 +00002598 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
Chris Lattner6fab2e92011-01-16 06:18:28 +00002599 if (ST->getNumElements() > 1) return false;
2600 } else {
2601 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2602 return false;
2603 }
2604 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002605
Victor Hernandez1df65182010-01-21 23:05:53 +00002606 return true;
Chris Lattner6e5398d2003-05-30 04:15:41 +00002607}