blob: 336da509b48e33c6eaea1f062c81b40ec40276a7 [file] [log] [blame]
Chris Lattnered7b41e2003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnered7b41e2003-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 Lattner38aec322003-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//
16// This combines a simple SRoA algorithm with the Mem2Reg algorithm because
17// 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 Lattnered7b41e2003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
Chris Lattner0e5f4992006-12-19 21:40:18 +000022#define DEBUG_TYPE "scalarrepl"
Chris Lattnered7b41e2003-05-27 15:45:27 +000023#include "llvm/Transforms/Scalar.h"
Chris Lattner38aec322003-09-11 16:45:55 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnered7b41e2003-05-27 15:45:27 +000026#include "llvm/Function.h"
Chris Lattner79b3bd32007-04-25 06:40:51 +000027#include "llvm/GlobalVariable.h"
Misha Brukmand8e1eea2004-07-29 17:05:13 +000028#include "llvm/Instructions.h"
Chris Lattner372dda82007-03-05 07:52:57 +000029#include "llvm/IntrinsicInst.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000030#include "llvm/LLVMContext.h"
Chris Lattner372dda82007-03-05 07:52:57 +000031#include "llvm/Pass.h"
Chris Lattner38aec322003-09-11 16:45:55 +000032#include "llvm/Analysis/Dominators.h"
33#include "llvm/Target/TargetData.h"
34#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000035#include "llvm/Transforms/Utils/Local.h"
Chris Lattner95255282006-06-28 23:17:24 +000036#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000037#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000038#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000039#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000040#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000041#include "llvm/Support/raw_ostream.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000042#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000043#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000044using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000045
Chris Lattner0e5f4992006-12-19 21:40:18 +000046STATISTIC(NumReplaced, "Number of allocas broken up");
47STATISTIC(NumPromoted, "Number of allocas promoted");
48STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000049STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000050
Chris Lattner0e5f4992006-12-19 21:40:18 +000051namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000052 struct SROA : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000053 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000054 explicit SROA(signed T = -1) : FunctionPass(&ID) {
Devang Patelff366852007-07-09 21:19:23 +000055 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000056 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000057 else
58 SRThreshold = T;
59 }
Devang Patel794fd752007-05-01 21:15:47 +000060
Chris Lattnered7b41e2003-05-27 15:45:27 +000061 bool runOnFunction(Function &F);
62
Chris Lattner38aec322003-09-11 16:45:55 +000063 bool performScalarRepl(Function &F);
64 bool performPromotion(Function &F);
65
Chris Lattnera15854c2003-08-31 00:45:13 +000066 // getAnalysisUsage - This pass does not require any passes, but we know it
67 // will not alter the CFG, so say so.
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patel326821e2007-06-07 21:57:03 +000069 AU.addRequired<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +000070 AU.addRequired<DominanceFrontier>();
Chris Lattnera15854c2003-08-31 00:45:13 +000071 AU.setPreservesCFG();
72 }
73
Chris Lattnered7b41e2003-05-27 15:45:27 +000074 private:
Chris Lattner56c38522009-01-07 06:34:28 +000075 TargetData *TD;
76
Bob Wilsonb742def2009-12-18 20:14:40 +000077 /// DeadInsts - Keep track of instructions we have made dead, so that
78 /// we can remove them after we are done working.
79 SmallVector<Value*, 32> DeadInsts;
80
Chris Lattner39a1c042007-05-30 06:11:23 +000081 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
82 /// information about the uses. All these fields are initialized to false
83 /// and set to true when something is learned.
84 struct AllocaInfo {
85 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
86 bool isUnsafe : 1;
87
Devang Patel4afc90d2009-02-10 07:00:59 +000088 /// needsCleanup - This is set to true if there is some use of the alloca
89 /// that requires cleanup.
90 bool needsCleanup : 1;
Chris Lattner39a1c042007-05-30 06:11:23 +000091
92 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
93 bool isMemCpySrc : 1;
94
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000095 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000096 bool isMemCpyDst : 1;
97
98 AllocaInfo()
Devang Patel4afc90d2009-02-10 07:00:59 +000099 : isUnsafe(false), needsCleanup(false),
Chris Lattner39a1c042007-05-30 06:11:23 +0000100 isMemCpySrc(false), isMemCpyDst(false) {}
101 };
102
Devang Patelff366852007-07-09 21:19:23 +0000103 unsigned SRThreshold;
104
Chris Lattner39a1c042007-05-30 06:11:23 +0000105 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
106
Victor Hernandez7b929da2009-10-23 21:09:37 +0000107 int isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000108
Bob Wilsonb742def2009-12-18 20:14:40 +0000109 void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000110 AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000111 void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000112 AllocaInfo &Info);
113 void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
114 const Type *MemOpType, bool isStore, AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000115 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
Bob Wilsone88728d2009-12-19 06:53:17 +0000116 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
117 const Type *&IdxTy);
Chris Lattner39a1c042007-05-30 06:11:23 +0000118
Victor Hernandez7b929da2009-10-23 21:09:37 +0000119 void DoScalarReplacement(AllocaInst *AI,
120 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000121 void DeleteDeadInstructions();
Bob Wilsonb742def2009-12-18 20:14:40 +0000122 void CleanupAllocaUsers(Value *V);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000123 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocaInst *Base);
Chris Lattnera1888942005-12-12 07:19:13 +0000124
Bob Wilsonb742def2009-12-18 20:14:40 +0000125 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
126 SmallVector<AllocaInst*, 32> &NewElts);
127 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
128 SmallVector<AllocaInst*, 32> &NewElts);
129 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
130 SmallVector<AllocaInst*, 32> &NewElts);
131 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000132 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000133 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000134 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000135 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000136 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000137 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000138
Chris Lattner7809ecd2009-02-03 01:30:09 +0000139 bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
Chris Lattner1a3257b2009-02-03 18:15:05 +0000140 bool &SawVec, uint64_t Offset, unsigned AllocaSize);
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000141 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Chris Lattner6e011152009-02-03 21:01:03 +0000142 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
Chris Lattner9bc67da2009-02-03 19:45:44 +0000143 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +0000144 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
Chris Lattner65a65022009-02-03 19:41:50 +0000145 uint64_t Offset, IRBuilder<> &Builder);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000146 static Instruction *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000147 };
Chris Lattnered7b41e2003-05-27 15:45:27 +0000148}
149
Dan Gohman844731a2008-05-13 00:00:25 +0000150char SROA::ID = 0;
151static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
152
Brian Gaeked0fde302003-11-11 22:41:34 +0000153// Public interface to the ScalarReplAggregates pass
Devang Patelff366852007-07-09 21:19:23 +0000154FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
155 return new SROA(Threshold);
156}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000157
158
Chris Lattnered7b41e2003-05-27 15:45:27 +0000159bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000160 TD = getAnalysisIfAvailable<TargetData>();
161
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000162 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000163
164 // FIXME: ScalarRepl currently depends on TargetData more than it
165 // theoretically needs to. It should be refactored in order to support
166 // target-independent IR. Until this is done, just skip the actual
167 // scalar-replacement portion of this pass.
168 if (!TD) return Changed;
169
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000170 while (1) {
171 bool LocalChange = performScalarRepl(F);
172 if (!LocalChange) break; // No need to repromote if no scalarrepl
173 Changed = true;
174 LocalChange = performPromotion(F);
175 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
176 }
Chris Lattner38aec322003-09-11 16:45:55 +0000177
178 return Changed;
179}
180
181
182bool SROA::performPromotion(Function &F) {
183 std::vector<AllocaInst*> Allocas;
Devang Patel326821e2007-06-07 21:57:03 +0000184 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000185 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner38aec322003-09-11 16:45:55 +0000186
Chris Lattner02a3be02003-09-20 14:39:18 +0000187 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000188
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000189 bool Changed = false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000190
Chris Lattner38aec322003-09-11 16:45:55 +0000191 while (1) {
192 Allocas.clear();
193
194 // Find allocas that are safe to promote, by looking at all instructions in
195 // the entry node
196 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
197 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000198 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000199 Allocas.push_back(AI);
200
201 if (Allocas.empty()) break;
202
Nick Lewyckyce2c51b2009-11-23 03:50:44 +0000203 PromoteMemToReg(Allocas, DT, DF);
Chris Lattner38aec322003-09-11 16:45:55 +0000204 NumPromoted += Allocas.size();
205 Changed = true;
206 }
207
208 return Changed;
209}
210
Chris Lattner963a97f2008-06-22 17:46:21 +0000211/// getNumSAElements - Return the number of elements in the specific struct or
212/// array.
213static uint64_t getNumSAElements(const Type *T) {
214 if (const StructType *ST = dyn_cast<StructType>(T))
215 return ST->getNumElements();
216 return cast<ArrayType>(T)->getNumElements();
217}
218
Chris Lattner38aec322003-09-11 16:45:55 +0000219// performScalarRepl - This algorithm is a simple worklist driven algorithm,
220// which runs on all of the malloc/alloca instructions in the function, removing
221// them if they are only used by getelementptr instructions.
222//
223bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000224 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000225
226 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
Chris Lattner02a3be02003-09-20 14:39:18 +0000227 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000228 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +0000229 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +0000230 WorkList.push_back(A);
231
232 // Process the worklist
233 bool Changed = false;
234 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000235 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000236 WorkList.pop_back();
Chris Lattnera1888942005-12-12 07:19:13 +0000237
Chris Lattneradd2bd72006-12-22 23:14:42 +0000238 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
239 // with unused elements.
240 if (AI->use_empty()) {
241 AI->eraseFromParent();
242 continue;
243 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000244
245 // If this alloca is impossible for us to promote, reject it early.
246 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
247 continue;
Chris Lattner79b3bd32007-04-25 06:40:51 +0000248
249 // Check to see if this allocation is only modified by a memcpy/memmove from
250 // a constant global. If this is the case, we can change all users to use
251 // the constant global instead. This is commonly produced by the CFE by
252 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
253 // is only subsequently read.
254 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +0000255 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
256 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner79b3bd32007-04-25 06:40:51 +0000257 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000258 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000259 TheCopy->eraseFromParent(); // Don't mutate the global.
260 AI->eraseFromParent();
261 ++NumGlobals;
262 Changed = true;
263 continue;
264 }
Chris Lattner15c82772009-02-02 20:44:45 +0000265
Chris Lattner7809ecd2009-02-03 01:30:09 +0000266 // Check to see if we can perform the core SROA transformation. We cannot
267 // transform the allocation instruction if it is an array allocation
268 // (allocations OF arrays are ok though), and an allocation of a scalar
269 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000270 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000271
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000272 // Do not promote [0 x %struct].
273 if (AllocaSize == 0) continue;
274
Bill Wendling5a377cb2009-03-03 12:12:58 +0000275 // Do not promote any struct whose size is too big.
Bill Wendling3aaf5d92009-03-03 19:18:49 +0000276 if (AllocaSize > SRThreshold) continue;
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000277
Chris Lattner7809ecd2009-02-03 01:30:09 +0000278 if ((isa<StructType>(AI->getAllocatedType()) ||
279 isa<ArrayType>(AI->getAllocatedType())) &&
Chris Lattner7809ecd2009-02-03 01:30:09 +0000280 // Do not promote any struct into more than "32" separate vars.
Evan Cheng67fca632009-03-06 00:56:43 +0000281 getNumSAElements(AI->getAllocatedType()) <= SRThreshold/4) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000282 // Check that all of the users of the allocation are capable of being
283 // transformed.
284 switch (isSafeAllocaToScalarRepl(AI)) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000285 default: llvm_unreachable("Unexpected value!");
Chris Lattner7809ecd2009-02-03 01:30:09 +0000286 case 0: // Not safe to scalar replace.
287 break;
288 case 1: // Safe, but requires cleanup/canonicalizations first
Devang Patel4afc90d2009-02-10 07:00:59 +0000289 CleanupAllocaUsers(AI);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000290 // FALL THROUGH.
291 case 3: // Safe to scalar replace.
292 DoScalarReplacement(AI, WorkList);
293 Changed = true;
294 continue;
295 }
296 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000297
298 // If we can turn this aggregate value (potentially with casts) into a
299 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000300 // IsNotTrivial tracks whether this is something that mem2reg could have
301 // promoted itself. If so, we don't want to transform it needlessly. Note
302 // that we can't just check based on the type: the alloca may be of an i32
303 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner6e733d32009-01-28 20:16:43 +0000304 bool IsNotTrivial = false;
Chris Lattner7809ecd2009-02-03 01:30:09 +0000305 const Type *VectorTy = 0;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000306 bool HadAVector = false;
307 if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector,
Chris Lattner0ff83ab2009-03-04 19:22:30 +0000308 0, unsigned(AllocaSize)) && IsNotTrivial) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000309 AllocaInst *NewAI;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000310 // If we were able to find a vector type that can handle this with
311 // insert/extract elements, and if there was at least one use that had
312 // a vector type, promote this to a vector. We don't want to promote
313 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
314 // we just get a lot of insert/extracts. If at least one vector is
315 // involved, then we probably really do have a union of vector/array.
316 if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
David Greene504c7d82010-01-05 01:27:09 +0000317 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
Chris Lattnerbdff5482009-08-23 04:37:46 +0000318 << *VectorTy << '\n');
Chris Lattner15c82772009-02-02 20:44:45 +0000319
Chris Lattner7809ecd2009-02-03 01:30:09 +0000320 // Create and insert the vector alloca.
Owen Anderson50dead02009-07-15 23:53:25 +0000321 NewAI = new AllocaInst(VectorTy, 0, "", AI->getParent()->begin());
Chris Lattner15c82772009-02-02 20:44:45 +0000322 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000323 } else {
David Greene504c7d82010-01-05 01:27:09 +0000324 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
Chris Lattner7809ecd2009-02-03 01:30:09 +0000325
326 // Create and insert the integer alloca.
Owen Anderson1d0be152009-08-13 21:58:54 +0000327 const Type *NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
Owen Anderson50dead02009-07-15 23:53:25 +0000328 NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
Chris Lattner7809ecd2009-02-03 01:30:09 +0000329 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner6e733d32009-01-28 20:16:43 +0000330 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000331 NewAI->takeName(AI);
332 AI->eraseFromParent();
333 ++NumConverted;
334 Changed = true;
335 continue;
336 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000337
Chris Lattner7809ecd2009-02-03 01:30:09 +0000338 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +0000339 }
340
341 return Changed;
342}
Chris Lattner5e062a12003-05-30 04:15:41 +0000343
Chris Lattnera10b29b2007-04-25 05:02:56 +0000344/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
345/// predicate, do SROA now.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000346void SROA::DoScalarReplacement(AllocaInst *AI,
347 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +0000348 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +0000349 SmallVector<AllocaInst*, 32> ElementAllocas;
350 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
351 ElementAllocas.reserve(ST->getNumContainedTypes());
352 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000353 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +0000354 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000355 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000356 ElementAllocas.push_back(NA);
357 WorkList.push_back(NA); // Add to worklist for recursive processing
358 }
359 } else {
360 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
361 ElementAllocas.reserve(AT->getNumElements());
362 const Type *ElTy = AT->getElementType();
363 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000364 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000365 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000366 ElementAllocas.push_back(NA);
367 WorkList.push_back(NA); // Add to worklist for recursive processing
368 }
369 }
370
Bob Wilsonb742def2009-12-18 20:14:40 +0000371 // Now that we have created the new alloca instructions, rewrite all the
372 // uses of the old alloca.
373 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +0000374
Bob Wilsonb742def2009-12-18 20:14:40 +0000375 // Now erase any instructions that were made dead while rewriting the alloca.
376 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +0000377 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +0000378
Chris Lattnera10b29b2007-04-25 05:02:56 +0000379 NumReplaced++;
380}
Chris Lattnera59adc42009-12-14 05:11:02 +0000381
Bob Wilsonb742def2009-12-18 20:14:40 +0000382/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
383/// recursively including all their operands that become trivially dead.
384void SROA::DeleteDeadInstructions() {
385 while (!DeadInsts.empty()) {
386 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +0000387
Bob Wilsonb742def2009-12-18 20:14:40 +0000388 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
389 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
390 // Zero out the operand and see if it becomes trivially dead.
391 // (But, don't add allocas to the dead instruction list -- they are
392 // already on the worklist and will be deleted separately.)
393 *OI = 0;
394 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
395 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +0000396 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000397
398 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +0000399 }
Chris Lattnera59adc42009-12-14 05:11:02 +0000400}
Bob Wilsonb742def2009-12-18 20:14:40 +0000401
Bob Wilsonb742def2009-12-18 20:14:40 +0000402/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
403/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000404/// the Info parameter. Offset indicates the position within AI that is
405/// referenced by this instruction.
Bob Wilsonb742def2009-12-18 20:14:40 +0000406void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000407 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000408 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
409 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +0000410
Bob Wilsonb742def2009-12-18 20:14:40 +0000411 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000412 isSafeForScalarRepl(BC, AI, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000413 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000414 uint64_t GEPOffset = Offset;
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000415 isSafeGEP(GEPI, AI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000416 if (!Info.isUnsafe)
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000417 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000418 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
419 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
420 if (Length)
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000421 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
Bob Wilsonb742def2009-12-18 20:14:40 +0000422 UI.getOperandNo() == 1, Info);
423 else
424 MarkUnsafe(Info);
425 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
426 if (!LI->isVolatile()) {
427 const Type *LIType = LI->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000428 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
Bob Wilsonb742def2009-12-18 20:14:40 +0000429 LIType, false, Info);
430 } else
431 MarkUnsafe(Info);
432 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
433 // Store is ok if storing INTO the pointer, not storing the pointer
434 if (!SI->isVolatile() && SI->getOperand(0) != I) {
435 const Type *SIType = SI->getOperand(0)->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000436 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
Bob Wilsonb742def2009-12-18 20:14:40 +0000437 SIType, true, Info);
438 } else
439 MarkUnsafe(Info);
440 } else if (isa<DbgInfoIntrinsic>(UI)) {
441 // If one user is DbgInfoIntrinsic then check if all users are
442 // DbgInfoIntrinsics.
443 if (OnlyUsedByDbgInfoIntrinsics(I)) {
444 Info.needsCleanup = true;
445 return;
446 }
447 MarkUnsafe(Info);
448 } else {
449 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
450 MarkUnsafe(Info);
451 }
452 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +0000453 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000454}
Bob Wilson39c88a62009-12-17 18:34:24 +0000455
Bob Wilsonb742def2009-12-18 20:14:40 +0000456/// isSafeGEP - Check if a GEP instruction can be handled for scalar
457/// replacement. It is safe when all the indices are constant, in-bounds
458/// references, and when the resulting offset corresponds to an element within
459/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000460/// return, Offset is adjusted as specified by the GEP indices.
Bob Wilsonb742def2009-12-18 20:14:40 +0000461void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000462 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000463 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
464 if (GEPIt == E)
465 return;
Bob Wilson39c88a62009-12-17 18:34:24 +0000466
Chris Lattner88e6dc82008-08-23 05:21:06 +0000467 // Walk through the GEP type indices, checking the types that this indexes
468 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +0000469 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +0000470 // Ignore struct elements, no extra checking needed for these.
Bob Wilsonb742def2009-12-18 20:14:40 +0000471 if (isa<StructType>(*GEPIt))
Chris Lattner88e6dc82008-08-23 05:21:06 +0000472 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000473
Bob Wilsonb742def2009-12-18 20:14:40 +0000474 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
475 if (!IdxVal)
476 return MarkUnsafe(Info);
Chris Lattner88e6dc82008-08-23 05:21:06 +0000477 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000478
Bob Wilsonf27a4cd2009-12-22 06:57:14 +0000479 // Compute the offset due to this GEP and check if the alloca has a
480 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000481 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
482 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
483 &Indices[0], Indices.size());
Bob Wilsonb742def2009-12-18 20:14:40 +0000484 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
485 MarkUnsafe(Info);
Chris Lattner5e062a12003-05-30 04:15:41 +0000486}
487
Bob Wilsonb742def2009-12-18 20:14:40 +0000488/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
489/// alloca or has an offset and size that corresponds to a component element
490/// within it. The offset checked here may have been formed from a GEP with a
491/// pointer bitcasted to a different type.
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000492void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +0000493 const Type *MemOpType, bool isStore,
494 AllocaInfo &Info) {
495 // Check if this is a load/store of the entire alloca.
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000496 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000497 bool UsesAggregateType = (MemOpType == AI->getAllocatedType());
498 // This is safe for MemIntrinsics (where MemOpType is 0), integer types
499 // (which are essentially the same as the MemIntrinsics, especially with
500 // regard to copying padding between elements), or references using the
501 // aggregate type of the alloca.
502 if (!MemOpType || isa<IntegerType>(MemOpType) || UsesAggregateType) {
503 if (!UsesAggregateType) {
504 if (isStore)
505 Info.isMemCpyDst = true;
506 else
507 Info.isMemCpySrc = true;
508 }
509 return;
510 }
511 }
512 // Check if the offset/size correspond to a component within the alloca type.
513 const Type *T = AI->getAllocatedType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000514 if (TypeHasComponent(T, Offset, MemSize))
Bob Wilsonb742def2009-12-18 20:14:40 +0000515 return;
516
517 return MarkUnsafe(Info);
518}
519
520/// TypeHasComponent - Return true if T has a component type with the
521/// specified offset and size. If Size is zero, do not check the size.
522bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
523 const Type *EltTy;
524 uint64_t EltSize;
525 if (const StructType *ST = dyn_cast<StructType>(T)) {
526 const StructLayout *Layout = TD->getStructLayout(ST);
527 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
528 EltTy = ST->getContainedType(EltIdx);
529 EltSize = TD->getTypeAllocSize(EltTy);
530 Offset -= Layout->getElementOffset(EltIdx);
531 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
532 EltTy = AT->getElementType();
533 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +0000534 if (Offset >= AT->getNumElements() * EltSize)
535 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +0000536 Offset %= EltSize;
537 } else {
538 return false;
539 }
540 if (Offset == 0 && (Size == 0 || EltSize == Size))
541 return true;
542 // Check if the component spans multiple elements.
543 if (Offset + Size > EltSize)
544 return false;
545 return TypeHasComponent(EltTy, Offset, Size);
546}
547
548/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
549/// the instruction I, which references it, to use the separate elements.
550/// Offset indicates the position within AI that is referenced by this
551/// instruction.
552void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
553 SmallVector<AllocaInst*, 32> &NewElts) {
554 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
555 Instruction *User = cast<Instruction>(*UI);
556
557 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
558 RewriteBitCast(BC, AI, Offset, NewElts);
559 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
560 RewriteGEP(GEPI, AI, Offset, NewElts);
561 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
562 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
563 uint64_t MemSize = Length->getZExtValue();
564 if (Offset == 0 &&
565 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
566 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +0000567 // Otherwise the intrinsic can only touch a single element and the
568 // address operand will be updated, so nothing else needs to be done.
Bob Wilsonb742def2009-12-18 20:14:40 +0000569 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
570 const Type *LIType = LI->getType();
571 if (LIType == AI->getAllocatedType()) {
572 // Replace:
573 // %res = load { i32, i32 }* %alloc
574 // with:
575 // %load.0 = load i32* %alloc.0
576 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
577 // %load.1 = load i32* %alloc.1
578 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
579 // (Also works for arrays instead of structs)
580 Value *Insert = UndefValue::get(LIType);
581 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
582 Value *Load = new LoadInst(NewElts[i], "load", LI);
583 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
584 }
585 LI->replaceAllUsesWith(Insert);
586 DeadInsts.push_back(LI);
587 } else if (isa<IntegerType>(LIType) &&
588 TD->getTypeAllocSize(LIType) ==
589 TD->getTypeAllocSize(AI->getAllocatedType())) {
590 // If this is a load of the entire alloca to an integer, rewrite it.
591 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
592 }
593 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
594 Value *Val = SI->getOperand(0);
595 const Type *SIType = Val->getType();
596 if (SIType == AI->getAllocatedType()) {
597 // Replace:
598 // store { i32, i32 } %val, { i32, i32 }* %alloc
599 // with:
600 // %val.0 = extractvalue { i32, i32 } %val, 0
601 // store i32 %val.0, i32* %alloc.0
602 // %val.1 = extractvalue { i32, i32 } %val, 1
603 // store i32 %val.1, i32* %alloc.1
604 // (Also works for arrays instead of structs)
605 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
606 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
607 new StoreInst(Extract, NewElts[i], SI);
608 }
609 DeadInsts.push_back(SI);
610 } else if (isa<IntegerType>(SIType) &&
611 TD->getTypeAllocSize(SIType) ==
612 TD->getTypeAllocSize(AI->getAllocatedType())) {
613 // If this is a store of the entire alloca from an integer, rewrite it.
614 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
615 }
616 }
Bob Wilson39c88a62009-12-17 18:34:24 +0000617 }
618}
619
Bob Wilsonb742def2009-12-18 20:14:40 +0000620/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
621/// and recursively continue updating all of its uses.
622void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
623 SmallVector<AllocaInst*, 32> &NewElts) {
624 RewriteForScalarRepl(BC, AI, Offset, NewElts);
625 if (BC->getOperand(0) != AI)
626 return;
Bob Wilson39c88a62009-12-17 18:34:24 +0000627
Bob Wilsonb742def2009-12-18 20:14:40 +0000628 // The bitcast references the original alloca. Replace its uses with
629 // references to the first new element alloca.
630 Instruction *Val = NewElts[0];
631 if (Val->getType() != BC->getDestTy()) {
632 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
633 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +0000634 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000635 BC->replaceAllUsesWith(Val);
636 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +0000637}
638
Bob Wilsonb742def2009-12-18 20:14:40 +0000639/// FindElementAndOffset - Return the index of the element containing Offset
640/// within the specified type, which must be either a struct or an array.
641/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +0000642/// element. IdxTy is set to the type of the index result to be used in a
643/// GEP instruction.
644uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
645 const Type *&IdxTy) {
646 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +0000647 if (const StructType *ST = dyn_cast<StructType>(T)) {
648 const StructLayout *Layout = TD->getStructLayout(ST);
649 Idx = Layout->getElementContainingOffset(Offset);
650 T = ST->getContainedType(Idx);
651 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +0000652 IdxTy = Type::getInt32Ty(T->getContext());
653 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +0000654 }
Bob Wilsone88728d2009-12-19 06:53:17 +0000655 const ArrayType *AT = cast<ArrayType>(T);
656 T = AT->getElementType();
657 uint64_t EltSize = TD->getTypeAllocSize(T);
658 Idx = Offset / EltSize;
659 Offset -= Idx * EltSize;
660 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +0000661 return Idx;
662}
663
664/// RewriteGEP - Check if this GEP instruction moves the pointer across
665/// elements of the alloca that are being split apart, and if so, rewrite
666/// the GEP to be relative to the new element.
667void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
668 SmallVector<AllocaInst*, 32> &NewElts) {
669 uint64_t OldOffset = Offset;
670 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
671 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
672 &Indices[0], Indices.size());
673
674 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
675
676 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +0000677 const Type *IdxTy;
678 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +0000679 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +0000680 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +0000681
682 T = AI->getAllocatedType();
683 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +0000684 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +0000685
686 // If this GEP does not move the pointer across elements of the alloca
687 // being split, then it does not needs to be rewritten.
688 if (Idx == OldIdx)
689 return;
690
691 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
692 SmallVector<Value*, 8> NewArgs;
693 NewArgs.push_back(Constant::getNullValue(i32Ty));
694 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +0000695 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
696 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +0000697 }
698 Instruction *Val = NewElts[Idx];
699 if (NewArgs.size() > 1) {
700 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
701 NewArgs.end(), "", GEPI);
702 Val->takeName(GEPI);
703 }
704 if (Val->getType() != GEPI->getType())
705 Val = new BitCastInst(Val, GEPI->getType(), Val->getNameStr(), GEPI);
706 GEPI->replaceAllUsesWith(Val);
707 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000708}
709
710/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
711/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +0000712void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000713 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000714 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000715 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +0000716 // appropriate type. The "Other" pointer is the pointer that goes to memory
717 // that doesn't have anything to do with the alloca that we are promoting. For
718 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +0000719 Value *OtherPtr = 0;
Owen Andersone922c022009-07-22 00:24:57 +0000720 LLVMContext &Context = MI->getContext();
Chris Lattnerdfe964c2009-03-08 03:59:00 +0000721 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +0000722 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +0000723 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +0000724 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000725 else {
Bob Wilsonb742def2009-12-18 20:14:40 +0000726 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +0000727 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000728 }
729 }
Bob Wilson78c50b82009-12-08 18:22:03 +0000730
Chris Lattnerd93afec2009-01-07 07:18:45 +0000731 // If there is an other pointer, we want to convert it to the same pointer
732 // type as AI has, so we can GEP through it safely.
733 if (OtherPtr) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000734
735 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
736 // optimization, but it's also required to detect the corner case where
737 // both pointer operands are referencing the same memory, and where
738 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
739 // function is only called for mem intrinsics that access the whole
740 // aggregate, so non-zero GEPs are not an issue here.)
741 while (1) {
742 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr)) {
743 OtherPtr = BC->getOperand(0);
744 continue;
745 }
746 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr)) {
747 // All zero GEPs are effectively bitcasts.
748 if (GEP->hasAllZeroIndices()) {
749 OtherPtr = GEP->getOperand(0);
750 continue;
751 }
752 }
753 break;
754 }
Bob Wilsona756b1d2010-01-19 04:32:48 +0000755 // Copying the alloca to itself is a no-op: just delete it.
756 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
757 // This code will run twice for a no-op memcpy -- once for each operand.
758 // Put only one reference to MI on the DeadInsts list.
759 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
760 E = DeadInsts.end(); I != E; ++I)
761 if (*I == MI) return;
762 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +0000763 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +0000764 }
Chris Lattner372dda82007-03-05 07:52:57 +0000765
Chris Lattnerd93afec2009-01-07 07:18:45 +0000766 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
767 if (BCE->getOpcode() == Instruction::BitCast)
768 OtherPtr = BCE->getOperand(0);
769
770 // If the pointer is not the right type, insert a bitcast to the right
771 // type.
772 if (OtherPtr->getType() != AI->getType())
773 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
774 MI);
775 }
776
777 // Process each element of the aggregate.
778 Value *TheFn = MI->getOperand(0);
779 const Type *BytePtrTy = MI->getRawDest()->getType();
Bob Wilsonb742def2009-12-18 20:14:40 +0000780 bool SROADest = MI->getRawDest() == Inst;
Chris Lattnerd93afec2009-01-07 07:18:45 +0000781
Owen Anderson1d0be152009-08-13 21:58:54 +0000782 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +0000783
784 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
785 // If this is a memcpy/memmove, emit a GEP of the other element address.
786 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000787 unsigned OtherEltAlign = MemAlignment;
788
Bob Wilsona756b1d2010-01-19 04:32:48 +0000789 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000790 Value *Idx[2] = { Zero,
791 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +0000792 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000793 OtherPtr->getNameStr()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +0000794 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +0000795 uint64_t EltOffset;
796 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
797 if (const StructType *ST =
798 dyn_cast<StructType>(OtherPtrTy->getElementType())) {
799 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
800 } else {
801 const Type *EltTy =
802 cast<SequentialType>(OtherPtr->getType())->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000803 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000804 }
805
806 // The alignment of the other pointer is the guaranteed alignment of the
807 // element, which is affected by both the known alignment of the whole
808 // mem intrinsic and the alignment of the element. If the alignment of
809 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
810 // known alignment is just 4 bytes.
811 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000812 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000813
814 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +0000815 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000816
817 // If we got down to a scalar, insert a load or store as appropriate.
818 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +0000819 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +0000820 if (SROADest) {
821 // From Other to Alloca.
822 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
823 new StoreInst(Elt, EltPtr, MI);
824 } else {
825 // From Alloca to Other.
826 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
827 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
828 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000829 continue;
830 }
831 assert(isa<MemSetInst>(MI));
832
833 // If the stored element is zero (common case), just store a null
834 // constant.
835 Constant *StoreVal;
836 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
837 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000838 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +0000839 } else {
840 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +0000841 const Type *ValTy = EltTy->getScalarType();
842
Chris Lattnerd93afec2009-01-07 07:18:45 +0000843 // Construct an integer with the right value.
844 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
845 APInt OneVal(EltSize, CI->getZExtValue());
846 APInt TotalVal(OneVal);
847 // Set each byte.
848 for (unsigned i = 0; 8*i < EltSize; ++i) {
849 TotalVal = TotalVal.shl(8);
850 TotalVal |= OneVal;
851 }
852
853 // Convert the integer value to the appropriate type.
Owen Andersoneed707b2009-07-24 23:12:02 +0000854 StoreVal = ConstantInt::get(Context, TotalVal);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000855 if (isa<PointerType>(ValTy))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000856 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000857 else if (ValTy->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000858 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000859 assert(StoreVal->getType() == ValTy && "Type mismatch!");
860
861 // If the requested value was a vector constant, create it.
862 if (EltTy != ValTy) {
863 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
864 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +0000865 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000866 }
867 }
868 new StoreInst(StoreVal, EltPtr, MI);
869 continue;
870 }
871 // Otherwise, if we're storing a byte variable, use a memset call for
872 // this element.
873 }
874
875 // Cast the element pointer to BytePtrTy.
876 if (EltPtr->getType() != BytePtrTy)
877 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
878
879 // Cast the other pointer (if we have one) to BytePtrTy.
880 if (OtherElt && OtherElt->getType() != BytePtrTy)
881 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
882 MI);
883
Duncan Sands777d2302009-05-09 07:06:46 +0000884 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000885
886 // Finally, insert the meminst for this element.
Chris Lattner3ce5e882009-03-08 03:37:16 +0000887 if (isa<MemTransferInst>(MI)) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000888 Value *Ops[] = {
889 SROADest ? EltPtr : OtherElt, // Dest ptr
890 SROADest ? OtherElt : EltPtr, // Src ptr
Owen Andersoneed707b2009-07-24 23:12:02 +0000891 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
Owen Anderson1d0be152009-08-13 21:58:54 +0000892 // Align
893 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign)
Chris Lattnerd93afec2009-01-07 07:18:45 +0000894 };
895 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
896 } else {
897 assert(isa<MemSetInst>(MI));
898 Value *Ops[] = {
899 EltPtr, MI->getOperand(2), // Dest, Value,
Owen Andersoneed707b2009-07-24 23:12:02 +0000900 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
Chris Lattnerd93afec2009-01-07 07:18:45 +0000901 Zero // Align
902 };
903 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
904 }
Chris Lattner372dda82007-03-05 07:52:57 +0000905 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000906 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +0000907}
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000908
Bob Wilson39fdd692009-12-04 21:57:37 +0000909/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000910/// overwrites the entire allocation. Extract out the pieces of the stored
911/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000912void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000913 SmallVector<AllocaInst*, 32> &NewElts){
914 // Extract each element out of the integer according to its structure offset
915 // and store the element value to the individual alloca.
916 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +0000917 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +0000918 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000919
Eli Friedman41b33f42009-06-01 09:14:32 +0000920 // Handle tail padding by extending the operand
921 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000922 SrcVal = new ZExtInst(SrcVal,
Owen Anderson1d0be152009-08-13 21:58:54 +0000923 IntegerType::get(SI->getContext(), AllocaSizeBits),
924 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000925
David Greene504c7d82010-01-05 01:27:09 +0000926 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +0000927 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000928
929 // There are two forms here: AI could be an array or struct. Both cases
930 // have different ways to compute the element offset.
931 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
932 const StructLayout *Layout = TD->getStructLayout(EltSTy);
933
934 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
935 // Get the number of bits to shift SrcVal to get the value.
936 const Type *FieldTy = EltSTy->getElementType(i);
937 uint64_t Shift = Layout->getElementOffsetInBits(i);
938
939 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +0000940 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000941
942 Value *EltVal = SrcVal;
943 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000944 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000945 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
946 "sroa.store.elt", SI);
947 }
948
949 // Truncate down to an integer of the right size.
950 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattner583dd602009-01-09 18:18:43 +0000951
952 // Ignore zero sized fields like {}, they obviously contain no data.
953 if (FieldSizeBits == 0) continue;
954
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000955 if (FieldSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000956 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +0000957 IntegerType::get(SI->getContext(), FieldSizeBits),
958 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000959 Value *DestField = NewElts[i];
960 if (EltVal->getType() == FieldTy) {
961 // Storing to an integer field of this size, just do it.
962 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
963 // Bitcast to the right element type (for fp/vector values).
964 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
965 } else {
966 // Otherwise, bitcast the dest pointer (for aggregates).
967 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +0000968 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000969 "", SI);
970 }
971 new StoreInst(EltVal, DestField, SI);
972 }
973
974 } else {
975 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
976 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000977 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000978 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
979
980 uint64_t Shift;
981
982 if (TD->isBigEndian())
983 Shift = AllocaSizeBits-ElementOffset;
984 else
985 Shift = 0;
986
987 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +0000988 // Ignore zero sized fields like {}, they obviously contain no data.
989 if (ElementSizeBits == 0) continue;
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000990
991 Value *EltVal = SrcVal;
992 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000993 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000994 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
995 "sroa.store.elt", SI);
996 }
997
998 // Truncate down to an integer of the right size.
999 if (ElementSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001000 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001001 IntegerType::get(SI->getContext(),
1002 ElementSizeBits),"",SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001003 Value *DestField = NewElts[i];
1004 if (EltVal->getType() == ArrayEltTy) {
1005 // Storing to an integer field of this size, just do it.
1006 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
1007 // Bitcast to the right element type (for fp/vector values).
1008 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1009 } else {
1010 // Otherwise, bitcast the dest pointer (for aggregates).
1011 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001012 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001013 "", SI);
1014 }
1015 new StoreInst(EltVal, DestField, SI);
1016
1017 if (TD->isBigEndian())
1018 Shift -= ElementOffset;
1019 else
1020 Shift += ElementOffset;
1021 }
1022 }
1023
Bob Wilsonb742def2009-12-18 20:14:40 +00001024 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001025}
1026
Bob Wilson39fdd692009-12-04 21:57:37 +00001027/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001028/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001029void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001030 SmallVector<AllocaInst*, 32> &NewElts) {
1031 // Extract each element out of the NewElts according to its structure offset
1032 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00001033 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001034 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001035
David Greene504c7d82010-01-05 01:27:09 +00001036 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00001037 << '\n');
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001038
1039 // There are two forms here: AI could be an array or struct. Both cases
1040 // have different ways to compute the element offset.
1041 const StructLayout *Layout = 0;
1042 uint64_t ArrayEltBitOffset = 0;
1043 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1044 Layout = TD->getStructLayout(EltSTy);
1045 } else {
1046 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001047 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001048 }
Owen Andersone922c022009-07-22 00:24:57 +00001049
Owen Andersone922c022009-07-22 00:24:57 +00001050 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001051 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001052
1053 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1054 // Load the value from the alloca. If the NewElt is an aggregate, cast
1055 // the pointer to an integer of the same size before doing the load.
1056 Value *SrcField = NewElts[i];
1057 const Type *FieldTy =
1058 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001059 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1060
1061 // Ignore zero sized fields like {}, they obviously contain no data.
1062 if (FieldSizeBits == 0) continue;
1063
Owen Anderson1d0be152009-08-13 21:58:54 +00001064 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1065 FieldSizeBits);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001066 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
1067 !isa<VectorType>(FieldTy))
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001068 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001069 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001070 "", LI);
1071 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1072
1073 // If SrcField is a fp or vector of the right size but that isn't an
1074 // integer type, bitcast to an integer so we can shift it.
1075 if (SrcField->getType() != FieldIntTy)
1076 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1077
1078 // Zero extend the field to be the same size as the final alloca so that
1079 // we can shift and insert it.
1080 if (SrcField->getType() != ResultVal->getType())
1081 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1082
1083 // Determine the number of bits to shift SrcField.
1084 uint64_t Shift;
1085 if (Layout) // Struct case.
1086 Shift = Layout->getElementOffsetInBits(i);
1087 else // Array case.
1088 Shift = i*ArrayEltBitOffset;
1089
1090 if (TD->isBigEndian())
1091 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1092
1093 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001094 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001095 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1096 }
1097
1098 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1099 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001100
1101 // Handle tail padding by truncating the result
1102 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1103 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1104
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001105 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00001106 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001107}
1108
Duncan Sands3cb36502007-11-04 14:43:57 +00001109/// HasPadding - Return true if the specified type has any structure or
1110/// alignment padding, false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001111static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner39a1c042007-05-30 06:11:23 +00001112 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1113 const StructLayout *SL = TD.getStructLayout(STy);
1114 unsigned PrevFieldBitOffset = 0;
1115 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001116 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1117
Chris Lattner39a1c042007-05-30 06:11:23 +00001118 // Padding in sub-elements?
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001119 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001120 return true;
Duncan Sands3cb36502007-11-04 14:43:57 +00001121
Chris Lattner39a1c042007-05-30 06:11:23 +00001122 // Check to see if there is any padding between this element and the
1123 // previous one.
1124 if (i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001125 unsigned PrevFieldEnd =
Chris Lattner39a1c042007-05-30 06:11:23 +00001126 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1127 if (PrevFieldEnd < FieldBitOffset)
1128 return true;
1129 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001130
Chris Lattner39a1c042007-05-30 06:11:23 +00001131 PrevFieldBitOffset = FieldBitOffset;
1132 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001133
Chris Lattner39a1c042007-05-30 06:11:23 +00001134 // Check for tail padding.
1135 if (unsigned EltCount = STy->getNumElements()) {
1136 unsigned PrevFieldEnd = PrevFieldBitOffset +
1137 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands3cb36502007-11-04 14:43:57 +00001138 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner39a1c042007-05-30 06:11:23 +00001139 return true;
1140 }
1141
1142 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001143 return HasPadding(ATy->getElementType(), TD);
Duncan Sands3cb36502007-11-04 14:43:57 +00001144 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001145 return HasPadding(VTy->getElementType(), TD);
Chris Lattner39a1c042007-05-30 06:11:23 +00001146 }
Duncan Sands777d2302009-05-09 07:06:46 +00001147 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001148}
Chris Lattner372dda82007-03-05 07:52:57 +00001149
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001150/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1151/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1152/// or 1 if safe after canonicalization has been performed.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001153int SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001154 // Loop over the use list of the alloca. We can only transform it if all of
1155 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001156 AllocaInfo Info;
1157
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001158 isSafeForScalarRepl(AI, AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001159 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00001160 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Bob Wilsonb742def2009-12-18 20:14:40 +00001161 return 0;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001162 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001163
1164 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1165 // source and destination, we have to be careful. In particular, the memcpy
1166 // could be moving around elements that live in structure padding of the LLVM
1167 // types, but may actually be used. In these cases, we refuse to promote the
1168 // struct.
1169 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001170 HasPadding(AI->getAllocatedType(), *TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001171 return 0;
Duncan Sands3cb36502007-11-04 14:43:57 +00001172
Chris Lattner39a1c042007-05-30 06:11:23 +00001173 // If we require cleanup, return 1, otherwise return 3.
Devang Patel4afc90d2009-02-10 07:00:59 +00001174 return Info.needsCleanup ? 1 : 3;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001175}
1176
Devang Patel4afc90d2009-02-10 07:00:59 +00001177/// CleanupAllocaUsers - If SROA reported that it can promote the specified
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001178/// allocation, but only if cleaned up, perform the cleanups required.
Bob Wilsonb742def2009-12-18 20:14:40 +00001179void SROA::CleanupAllocaUsers(Value *V) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001180 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001181 UI != E; ) {
Devang Patel4afc90d2009-02-10 07:00:59 +00001182 User *U = *UI++;
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001183 Instruction *I = cast<Instruction>(U);
1184 SmallVector<DbgInfoIntrinsic *, 2> DbgInUses;
1185 if (!isa<StoreInst>(I) && OnlyUsedByDbgInfoIntrinsics(I, &DbgInUses)) {
1186 // Safe to remove debug info uses.
1187 while (!DbgInUses.empty()) {
Dan Gohman321a8132010-01-05 16:27:25 +00001188 DbgInfoIntrinsic *DI = DbgInUses.pop_back_val();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001189 DI->eraseFromParent();
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001190 }
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001191 I->eraseFromParent();
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001192 }
1193 }
Chris Lattner5e062a12003-05-30 04:15:41 +00001194}
Chris Lattnera1888942005-12-12 07:19:13 +00001195
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001196/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1197/// the offset specified by Offset (which is specified in bytes).
Chris Lattnerde6df882006-04-14 21:42:41 +00001198///
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001199/// There are two cases we handle here:
1200/// 1) A union of vector types of the same size and potentially its elements.
Chris Lattnerd22dbdf2006-12-15 07:32:38 +00001201/// Here we turn element accesses into insert/extract element operations.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001202/// This promotes a <4 x float> with a store of float to the third element
1203/// into a <4 x float> that uses insert element.
1204/// 2) A fully general blob of memory, which we turn into some (potentially
1205/// large) integer type with extract and insert operations where the loads
1206/// and stores would mutate the memory.
Chris Lattner7809ecd2009-02-03 01:30:09 +00001207static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001208 unsigned AllocaSize, const TargetData &TD,
Owen Andersone922c022009-07-22 00:24:57 +00001209 LLVMContext &Context) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001210 // If this could be contributing to a vector, analyze it.
Owen Anderson1d0be152009-08-13 21:58:54 +00001211 if (VecTy != Type::getVoidTy(Context)) { // either null or a vector type.
Chris Lattner996d7a92009-02-02 18:02:59 +00001212
Chris Lattner7809ecd2009-02-03 01:30:09 +00001213 // If the In type is a vector that is the same size as the alloca, see if it
1214 // matches the existing VecTy.
1215 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1216 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1217 // If we're storing/loading a vector of the right size, allow it as a
1218 // vector. If this the first vector we see, remember the type so that
1219 // we know the element size.
1220 if (VecTy == 0)
1221 VecTy = VInTy;
1222 return;
1223 }
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001224 } else if (In->isFloatTy() || In->isDoubleTy() ||
Chris Lattner7809ecd2009-02-03 01:30:09 +00001225 (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1226 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1227 // If we're accessing something that could be an element of a vector, see
1228 // if the implied vector agrees with what we already have and if Offset is
1229 // compatible with it.
1230 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1231 if (Offset % EltSize == 0 &&
1232 AllocaSize % EltSize == 0 &&
1233 (VecTy == 0 ||
1234 cast<VectorType>(VecTy)->getElementType()
1235 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1236 if (VecTy == 0)
Owen Andersondebcb012009-07-29 22:17:13 +00001237 VecTy = VectorType::get(In, AllocaSize/EltSize);
Chris Lattner7809ecd2009-02-03 01:30:09 +00001238 return;
1239 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001240 }
1241 }
1242
Chris Lattner7809ecd2009-02-03 01:30:09 +00001243 // Otherwise, we have a case that we can't handle with an optimized vector
1244 // form. We can still turn this into a large integer.
Owen Anderson1d0be152009-08-13 21:58:54 +00001245 VecTy = Type::getVoidTy(Context);
Chris Lattnera1888942005-12-12 07:19:13 +00001246}
1247
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001248/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
Bob Wilsonefc58e72009-12-09 18:05:27 +00001249/// its accesses to a single vector type, return true and set VecTy to
Chris Lattner7809ecd2009-02-03 01:30:09 +00001250/// the new type. If we could convert the alloca into a single promotable
1251/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1252/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1253/// is the current offset from the base of the alloca being analyzed.
Chris Lattnera1888942005-12-12 07:19:13 +00001254///
Chris Lattner1a3257b2009-02-03 18:15:05 +00001255/// If we see at least one access to the value that is as a vector type, set the
1256/// SawVec flag.
Chris Lattner1a3257b2009-02-03 18:15:05 +00001257bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1258 bool &SawVec, uint64_t Offset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001259 unsigned AllocaSize) {
Chris Lattnera1888942005-12-12 07:19:13 +00001260 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1261 Instruction *User = cast<Instruction>(*UI);
1262
1263 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001264 // Don't break volatile loads.
Chris Lattner6e733d32009-01-28 20:16:43 +00001265 if (LI->isVolatile())
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001266 return false;
Owen Andersone922c022009-07-22 00:24:57 +00001267 MergeInType(LI->getType(), Offset, VecTy,
1268 AllocaSize, *TD, V->getContext());
Chris Lattner1a3257b2009-02-03 18:15:05 +00001269 SawVec |= isa<VectorType>(LI->getType());
Chris Lattnercf321862009-01-07 06:39:58 +00001270 continue;
1271 }
1272
1273 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001274 // Storing the pointer, not into the value?
Chris Lattner6e733d32009-01-28 20:16:43 +00001275 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001276 MergeInType(SI->getOperand(0)->getType(), Offset,
Owen Andersone922c022009-07-22 00:24:57 +00001277 VecTy, AllocaSize, *TD, V->getContext());
Chris Lattner1a3257b2009-02-03 18:15:05 +00001278 SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
Chris Lattnercf321862009-01-07 06:39:58 +00001279 continue;
1280 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001281
1282 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattner1a3257b2009-02-03 18:15:05 +00001283 if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1284 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001285 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001286 IsNotTrivial = true;
Chris Lattnercf321862009-01-07 06:39:58 +00001287 continue;
1288 }
1289
1290 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001291 // If this is a GEP with a variable indices, we can't handle it.
1292 if (!GEP->hasAllConstantIndices())
1293 return false;
Chris Lattnercf321862009-01-07 06:39:58 +00001294
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001295 // Compute the offset that this GEP adds to the pointer.
1296 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Bob Wilsonb742def2009-12-18 20:14:40 +00001297 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getPointerOperandType(),
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001298 &Indices[0], Indices.size());
1299 // See if all uses can be converted.
Chris Lattner1a3257b2009-02-03 18:15:05 +00001300 if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001301 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001302 return false;
1303 IsNotTrivial = true;
1304 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001305 }
Chris Lattner3ce5e882009-03-08 03:37:16 +00001306
Chris Lattner3d730f72009-02-03 02:01:43 +00001307 // If this is a constant sized memset of a constant value (e.g. 0) we can
1308 // handle it.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001309 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1310 // Store of constant value and constant size.
1311 if (isa<ConstantInt>(MSI->getValue()) &&
1312 isa<ConstantInt>(MSI->getLength())) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001313 IsNotTrivial = true;
1314 continue;
1315 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001316 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001317
1318 // If this is a memcpy or memmove into or out of the whole allocation, we
1319 // can handle it like a load or store of the scalar type.
1320 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1321 if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
1322 if (Len->getZExtValue() == AllocaSize && Offset == 0) {
1323 IsNotTrivial = true;
1324 continue;
1325 }
1326 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001327
Devang Patel00e389c2009-03-06 07:03:54 +00001328 // Ignore dbg intrinsic.
1329 if (isa<DbgInfoIntrinsic>(User))
1330 continue;
1331
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001332 // Otherwise, we cannot handle this!
1333 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001334 }
1335
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001336 return true;
Chris Lattnera1888942005-12-12 07:19:13 +00001337}
1338
Chris Lattnera1888942005-12-12 07:19:13 +00001339/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattnerde6df882006-04-14 21:42:41 +00001340/// directly. This happens when we are converting an "integer union" to a
1341/// single integer scalar, or when we are converting a "vector union" to a
1342/// vector with insert/extractelement instructions.
1343///
1344/// Offset is an offset from the original alloca, in bits that need to be
1345/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001346void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
Chris Lattnera1888942005-12-12 07:19:13 +00001347 while (!Ptr->use_empty()) {
1348 Instruction *User = cast<Instruction>(Ptr->use_back());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001349
Chris Lattnercf321862009-01-07 06:39:58 +00001350 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb10e0da2008-01-30 00:39:15 +00001351 ConvertUsesToScalar(CI, NewAI, Offset);
Chris Lattnera1888942005-12-12 07:19:13 +00001352 CI->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001353 continue;
1354 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001355
Chris Lattnercf321862009-01-07 06:39:58 +00001356 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001357 // Compute the offset that this GEP adds to the pointer.
1358 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Bob Wilsonb742def2009-12-18 20:14:40 +00001359 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getPointerOperandType(),
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001360 &Indices[0], Indices.size());
1361 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
Chris Lattnera1888942005-12-12 07:19:13 +00001362 GEP->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001363 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001364 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001365
Chris Lattner9bc67da2009-02-03 19:45:44 +00001366 IRBuilder<> Builder(User->getParent(), User);
1367
1368 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner6e011152009-02-03 21:01:03 +00001369 // The load is a bit extract from NewAI shifted right by Offset bits.
1370 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1371 Value *NewLoadVal
1372 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1373 LI->replaceAllUsesWith(NewLoadVal);
Chris Lattner9bc67da2009-02-03 19:45:44 +00001374 LI->eraseFromParent();
1375 continue;
1376 }
1377
1378 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1379 assert(SI->getOperand(0) != Ptr && "Consistency error!");
Chris Lattneraadadb32009-12-22 19:33:28 +00001380 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
Chris Lattner9bc67da2009-02-03 19:45:44 +00001381 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1382 Builder);
1383 Builder.CreateStore(New, NewAI);
1384 SI->eraseFromParent();
Chris Lattneraadadb32009-12-22 19:33:28 +00001385
1386 // If the load we just inserted is now dead, then the inserted store
1387 // overwrote the entire thing.
1388 if (Old->use_empty())
1389 Old->eraseFromParent();
Chris Lattner9bc67da2009-02-03 19:45:44 +00001390 continue;
1391 }
1392
Chris Lattner3d730f72009-02-03 02:01:43 +00001393 // If this is a constant sized memset of a constant value (e.g. 0) we can
1394 // transform it into a store of the expanded constant value.
1395 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1396 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1397 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
Chris Lattner33e24ad2009-04-21 16:52:12 +00001398 if (NumBytes != 0) {
1399 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1400
1401 // Compute the value replicated the right number of times.
1402 APInt APVal(NumBytes*8, Val);
Chris Lattner3d730f72009-02-03 02:01:43 +00001403
Chris Lattner33e24ad2009-04-21 16:52:12 +00001404 // Splat the value if non-zero.
1405 if (Val)
1406 for (unsigned i = 1; i != NumBytes; ++i)
1407 APVal |= APVal << 8;
Benjamin Kramere6f32942009-11-29 21:17:48 +00001408
Chris Lattneraadadb32009-12-22 19:33:28 +00001409 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
Owen Andersone922c022009-07-22 00:24:57 +00001410 Value *New = ConvertScalar_InsertValue(
Owen Andersoneed707b2009-07-24 23:12:02 +00001411 ConstantInt::get(User->getContext(), APVal),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001412 Old, Offset, Builder);
Chris Lattner33e24ad2009-04-21 16:52:12 +00001413 Builder.CreateStore(New, NewAI);
Chris Lattneraadadb32009-12-22 19:33:28 +00001414
1415 // If the load we just inserted is now dead, then the memset overwrote
1416 // the entire thing.
1417 if (Old->use_empty())
1418 Old->eraseFromParent();
Chris Lattner33e24ad2009-04-21 16:52:12 +00001419 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001420 MSI->eraseFromParent();
1421 continue;
1422 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001423
1424 // If this is a memcpy or memmove into or out of the whole allocation, we
1425 // can handle it like a load or store of the scalar type.
1426 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1427 assert(Offset == 0 && "must be store to start of alloca");
1428
1429 // If the source and destination are both to the same alloca, then this is
1430 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
1431 // as appropriate.
1432 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject());
1433
1434 if (MTI->getSource()->getUnderlyingObject() != OrigAI) {
1435 // Dest must be OrigAI, change this to be a load from the original
1436 // pointer (bitcasted), then a store to our new alloca.
1437 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
1438 Value *SrcPtr = MTI->getSource();
1439 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
1440
1441 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
1442 SrcVal->setAlignment(MTI->getAlignment());
1443 Builder.CreateStore(SrcVal, NewAI);
1444 } else if (MTI->getDest()->getUnderlyingObject() != OrigAI) {
1445 // Src must be OrigAI, change this to be a load from NewAI then a store
1446 // through the original dest pointer (bitcasted).
1447 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
1448 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
1449
1450 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
1451 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
1452 NewStore->setAlignment(MTI->getAlignment());
1453 } else {
1454 // Noop transfer. Src == Dst
1455 }
1456
1457
1458 MTI->eraseFromParent();
1459 continue;
1460 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001461
Devang Patel00e389c2009-03-06 07:03:54 +00001462 // If user is a dbg info intrinsic then it is safe to remove it.
1463 if (isa<DbgInfoIntrinsic>(User)) {
1464 User->eraseFromParent();
1465 continue;
1466 }
1467
Torok Edwinc23197a2009-07-14 16:55:14 +00001468 llvm_unreachable("Unsupported operation!");
Chris Lattnera1888942005-12-12 07:19:13 +00001469 }
1470}
Chris Lattner79b3bd32007-04-25 06:40:51 +00001471
Chris Lattner6e011152009-02-03 21:01:03 +00001472/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1473/// or vector value FromVal, extracting the bits from the offset specified by
1474/// Offset. This returns the value, which is of type ToType.
1475///
1476/// This happens when we are converting an "integer union" to a single
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001477/// integer scalar, or when we are converting a "vector union" to a vector with
1478/// insert/extractelement instructions.
Chris Lattner800de312008-02-29 07:03:13 +00001479///
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001480/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner6e011152009-02-03 21:01:03 +00001481/// shifted to the right.
1482Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1483 uint64_t Offset, IRBuilder<> &Builder) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001484 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattner6e011152009-02-03 21:01:03 +00001485 if (FromVal->getType() == ToType && Offset == 0)
1486 return FromVal;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001487
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001488 // If the result alloca is a vector type, this is either an element
1489 // access or a bitcast to another vector type of the same size.
Chris Lattner6e011152009-02-03 21:01:03 +00001490 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1491 if (isa<VectorType>(ToType))
1492 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001493
1494 // Otherwise it must be an element access.
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001495 unsigned Elt = 0;
1496 if (Offset) {
Duncan Sands777d2302009-05-09 07:06:46 +00001497 unsigned EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001498 Elt = Offset/EltSize;
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001499 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Chris Lattner800de312008-02-29 07:03:13 +00001500 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001501 // Return the element extracted out of it.
Owen Anderson1d0be152009-08-13 21:58:54 +00001502 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
1503 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
Chris Lattner6e011152009-02-03 21:01:03 +00001504 if (V->getType() != ToType)
1505 V = Builder.CreateBitCast(V, ToType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001506 return V;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001507 }
Chris Lattner1aa70562009-02-03 21:08:45 +00001508
1509 // If ToType is a first class aggregate, extract out each of the pieces and
1510 // use insertvalue's to form the FCA.
1511 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1512 const StructLayout &Layout = *TD->getStructLayout(ST);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001513 Value *Res = UndefValue::get(ST);
Chris Lattner1aa70562009-02-03 21:08:45 +00001514 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1515 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
Chris Lattnere991ced2009-02-06 04:34:07 +00001516 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner1aa70562009-02-03 21:08:45 +00001517 Builder);
1518 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1519 }
1520 return Res;
1521 }
1522
1523 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001524 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001525 Value *Res = UndefValue::get(AT);
Chris Lattner1aa70562009-02-03 21:08:45 +00001526 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1527 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1528 Offset+i*EltSize, Builder);
1529 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1530 }
1531 return Res;
1532 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001533
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001534 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattner6e011152009-02-03 21:01:03 +00001535 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001536
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001537 // If this is a big-endian system and the load is narrower than the
1538 // full alloca type, we need to do a shift to get the right bits.
1539 int ShAmt = 0;
Chris Lattner56c38522009-01-07 06:34:28 +00001540 if (TD->isBigEndian()) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001541 // On big-endian machines, the lowest bit is stored at the bit offset
1542 // from the pointer given by getTypeStoreSizeInBits. This matters for
1543 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner56c38522009-01-07 06:34:28 +00001544 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
Chris Lattner6e011152009-02-03 21:01:03 +00001545 TD->getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001546 } else {
1547 ShAmt = Offset;
1548 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001549
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001550 // Note: we support negative bitwidths (with shl) which are not defined.
1551 // We do this to support (f.e.) loads off the end of a structure where
1552 // only some bits are used.
1553 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001554 FromVal = Builder.CreateLShr(FromVal,
Owen Andersoneed707b2009-07-24 23:12:02 +00001555 ConstantInt::get(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001556 ShAmt), "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001557 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001558 FromVal = Builder.CreateShl(FromVal,
Owen Andersoneed707b2009-07-24 23:12:02 +00001559 ConstantInt::get(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001560 -ShAmt), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001561
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001562 // Finally, unconditionally truncate the integer to the right width.
Chris Lattner6e011152009-02-03 21:01:03 +00001563 unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001564 if (LIBitWidth < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001565 FromVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001566 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
1567 LIBitWidth), "tmp");
Chris Lattner55a683d2009-02-03 07:08:57 +00001568 else if (LIBitWidth > NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001569 FromVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001570 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
1571 LIBitWidth), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001572
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001573 // If the result is an integer, this is a trunc or bitcast.
Chris Lattner6e011152009-02-03 21:01:03 +00001574 if (isa<IntegerType>(ToType)) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001575 // Should be done.
Chris Lattner6e011152009-02-03 21:01:03 +00001576 } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001577 // Just do a bitcast, we know the sizes match up.
Chris Lattner6e011152009-02-03 21:01:03 +00001578 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001579 } else {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001580 // Otherwise must be a pointer.
Chris Lattner6e011152009-02-03 21:01:03 +00001581 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001582 }
Chris Lattner6e011152009-02-03 21:01:03 +00001583 assert(FromVal->getType() == ToType && "Didn't convert right?");
1584 return FromVal;
Chris Lattner800de312008-02-29 07:03:13 +00001585}
1586
Chris Lattner9b872db2009-02-03 19:30:11 +00001587/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1588/// or vector value "Old" at the offset specified by Offset.
1589///
1590/// This happens when we are converting an "integer union" to a
Chris Lattner800de312008-02-29 07:03:13 +00001591/// single integer scalar, or when we are converting a "vector union" to a
1592/// vector with insert/extractelement instructions.
1593///
1594/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner9b872db2009-02-03 19:30:11 +00001595/// shifted to the right.
1596Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
Chris Lattner65a65022009-02-03 19:41:50 +00001597 uint64_t Offset, IRBuilder<> &Builder) {
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001598
Chris Lattner800de312008-02-29 07:03:13 +00001599 // Convert the stored type to the actual type, shift it left to insert
1600 // then 'or' into place.
Chris Lattner9b872db2009-02-03 19:30:11 +00001601 const Type *AllocaType = Old->getType();
Owen Andersone922c022009-07-22 00:24:57 +00001602 LLVMContext &Context = Old->getContext();
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001603
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001604 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001605 uint64_t VecSize = TD->getTypeAllocSizeInBits(VTy);
1606 uint64_t ValSize = TD->getTypeAllocSizeInBits(SV->getType());
Chris Lattner29e64172009-03-08 04:17:04 +00001607
1608 // Changing the whole vector with memset or with an access of a different
1609 // vector type?
1610 if (ValSize == VecSize)
1611 return Builder.CreateBitCast(SV, AllocaType, "tmp");
1612
Duncan Sands777d2302009-05-09 07:06:46 +00001613 uint64_t EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner29e64172009-03-08 04:17:04 +00001614
1615 // Must be an element insertion.
1616 unsigned Elt = Offset/EltSize;
1617
1618 if (SV->getType() != VTy->getElementType())
1619 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1620
1621 SV = Builder.CreateInsertElement(Old, SV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001622 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
Chris Lattner29e64172009-03-08 04:17:04 +00001623 "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001624 return SV;
1625 }
Chris Lattner9b872db2009-02-03 19:30:11 +00001626
1627 // If SV is a first-class aggregate value, insert each value recursively.
1628 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1629 const StructLayout &Layout = *TD->getStructLayout(ST);
1630 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001631 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Chris Lattner9b872db2009-02-03 19:30:11 +00001632 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattnere991ced2009-02-06 04:34:07 +00001633 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner65a65022009-02-03 19:41:50 +00001634 Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001635 }
1636 return Old;
1637 }
1638
1639 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Duncan Sands777d2302009-05-09 07:06:46 +00001640 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner9b872db2009-02-03 19:30:11 +00001641 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001642 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1643 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001644 }
1645 return Old;
1646 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001647
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001648 // If SV is a float, convert it to the appropriate integer type.
Chris Lattner9b872db2009-02-03 19:30:11 +00001649 // If it is a pointer, do the same.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001650 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1651 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1652 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1653 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1654 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
Owen Anderson1d0be152009-08-13 21:58:54 +00001655 SV = Builder.CreateBitCast(SV,
1656 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001657 else if (isa<PointerType>(SV->getType()))
Owen Anderson1d0be152009-08-13 21:58:54 +00001658 SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(SV->getContext()), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001659
Chris Lattner7809ecd2009-02-03 01:30:09 +00001660 // Zero extend or truncate the value if needed.
1661 if (SV->getType() != AllocaType) {
1662 if (SV->getType()->getPrimitiveSizeInBits() <
1663 AllocaType->getPrimitiveSizeInBits())
Chris Lattner65a65022009-02-03 19:41:50 +00001664 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001665 else {
1666 // Truncation may be needed if storing more than the alloca can hold
1667 // (undefined behavior).
Chris Lattner65a65022009-02-03 19:41:50 +00001668 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001669 SrcWidth = DestWidth;
1670 SrcStoreWidth = DestStoreWidth;
1671 }
1672 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001673
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001674 // If this is a big-endian system and the store is narrower than the
1675 // full alloca type, we need to do a shift to get the right bits.
1676 int ShAmt = 0;
1677 if (TD->isBigEndian()) {
1678 // On big-endian machines, the lowest bit is stored at the bit offset
1679 // from the pointer given by getTypeStoreSizeInBits. This matters for
1680 // integers with a bitwidth that is not a multiple of 8.
1681 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
Chris Lattner800de312008-02-29 07:03:13 +00001682 } else {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001683 ShAmt = Offset;
1684 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001685
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001686 // Note: we support negative bitwidths (with shr) which are not defined.
1687 // We do this to support (f.e.) stores off the end of a structure where
1688 // only some bits in the structure are set.
1689 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1690 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001691 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001692 ShAmt), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001693 Mask <<= ShAmt;
1694 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001695 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001696 -ShAmt), "tmp");
Duncan Sands0e7c46b2009-02-02 09:53:14 +00001697 Mask = Mask.lshr(-ShAmt);
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001698 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001699
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001700 // Mask out the bits we are about to insert from the old value, and or
1701 // in the new bits.
1702 if (SrcWidth != DestWidth) {
1703 assert(DestWidth > SrcWidth);
Owen Andersoneed707b2009-07-24 23:12:02 +00001704 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
Chris Lattner65a65022009-02-03 19:41:50 +00001705 SV = Builder.CreateOr(Old, SV, "ins");
Chris Lattner800de312008-02-29 07:03:13 +00001706 }
1707 return SV;
1708}
1709
1710
Chris Lattner79b3bd32007-04-25 06:40:51 +00001711
1712/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1713/// some part of a constant global variable. This intentionally only accepts
1714/// constant expressions because we don't can't rewrite arbitrary instructions.
1715static bool PointsToConstantGlobal(Value *V) {
1716 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1717 return GV->isConstant();
1718 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1719 if (CE->getOpcode() == Instruction::BitCast ||
1720 CE->getOpcode() == Instruction::GetElementPtr)
1721 return PointsToConstantGlobal(CE->getOperand(0));
1722 return false;
1723}
1724
1725/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1726/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1727/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1728/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1729/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1730/// the alloca, and if the source pointer is a pointer to a constant global, we
1731/// can optimize this.
1732static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1733 bool isOffset) {
1734 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Chris Lattner6e733d32009-01-28 20:16:43 +00001735 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1736 // Ignore non-volatile loads, they are always ok.
1737 if (!LI->isVolatile())
1738 continue;
1739
Chris Lattner79b3bd32007-04-25 06:40:51 +00001740 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1741 // If uses of the bitcast are ok, we are ok.
1742 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1743 return false;
1744 continue;
1745 }
1746 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1747 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1748 // doesn't, it does.
1749 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1750 isOffset || !GEP->hasAllZeroIndices()))
1751 return false;
1752 continue;
1753 }
1754
1755 // If this is isn't our memcpy/memmove, reject it as something we can't
1756 // handle.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001757 if (!isa<MemTransferInst>(*UI))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001758 return false;
1759
1760 // If we already have seen a copy, reject the second one.
1761 if (TheCopy) return false;
1762
1763 // If the pointer has been offset from the start of the alloca, we can't
1764 // safely handle this.
1765 if (isOffset) return false;
1766
1767 // If the memintrinsic isn't using the alloca as the dest, reject it.
1768 if (UI.getOperandNo() != 1) return false;
1769
1770 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1771
1772 // If the source of the memcpy/move is not a constant global, reject it.
1773 if (!PointsToConstantGlobal(MI->getOperand(2)))
1774 return false;
1775
1776 // Otherwise, the transform is safe. Remember the copy instruction.
1777 TheCopy = MI;
1778 }
1779 return true;
1780}
1781
1782/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1783/// modified by a copy from a constant global. If we can prove this, we can
1784/// replace any uses of the alloca with uses of the global directly.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001785Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001786 Instruction *TheCopy = 0;
1787 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1788 return TheCopy;
1789 return 0;
1790}