blob: d999f9d8a948795e0bdc1aa839567f137e28a6c4 [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 Lattnera4f0b3a2006-08-27 12:54:02 +000041#include "llvm/Support/Compiler.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"
44#include "llvm/ADT/StringExtras.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000045using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000046
Chris Lattner0e5f4992006-12-19 21:40:18 +000047STATISTIC(NumReplaced, "Number of allocas broken up");
48STATISTIC(NumPromoted, "Number of allocas promoted");
49STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000050STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000051
Chris Lattner0e5f4992006-12-19 21:40:18 +000052namespace {
Chris Lattner95255282006-06-28 23:17:24 +000053 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000054 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000055 explicit SROA(signed T = -1) : FunctionPass(&ID) {
Devang Patelff366852007-07-09 21:19:23 +000056 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000057 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000058 else
59 SRThreshold = T;
60 }
Devang Patel794fd752007-05-01 21:15:47 +000061
Chris Lattnered7b41e2003-05-27 15:45:27 +000062 bool runOnFunction(Function &F);
63
Chris Lattner38aec322003-09-11 16:45:55 +000064 bool performScalarRepl(Function &F);
65 bool performPromotion(Function &F);
66
Chris Lattnera15854c2003-08-31 00:45:13 +000067 // getAnalysisUsage - This pass does not require any passes, but we know it
68 // will not alter the CFG, so say so.
69 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patel326821e2007-06-07 21:57:03 +000070 AU.addRequired<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +000071 AU.addRequired<DominanceFrontier>();
72 AU.addRequired<TargetData>();
Chris Lattnera15854c2003-08-31 00:45:13 +000073 AU.setPreservesCFG();
74 }
75
Chris Lattnered7b41e2003-05-27 15:45:27 +000076 private:
Chris Lattner56c38522009-01-07 06:34:28 +000077 TargetData *TD;
78
Chris Lattner39a1c042007-05-30 06:11:23 +000079 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
80 /// information about the uses. All these fields are initialized to false
81 /// and set to true when something is learned.
82 struct AllocaInfo {
83 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
84 bool isUnsafe : 1;
85
Devang Patel4afc90d2009-02-10 07:00:59 +000086 /// needsCleanup - This is set to true if there is some use of the alloca
87 /// that requires cleanup.
88 bool needsCleanup : 1;
Chris Lattner39a1c042007-05-30 06:11:23 +000089
90 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
91 bool isMemCpySrc : 1;
92
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000093 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000094 bool isMemCpyDst : 1;
95
96 AllocaInfo()
Devang Patel4afc90d2009-02-10 07:00:59 +000097 : isUnsafe(false), needsCleanup(false),
Chris Lattner39a1c042007-05-30 06:11:23 +000098 isMemCpySrc(false), isMemCpyDst(false) {}
99 };
100
Devang Patelff366852007-07-09 21:19:23 +0000101 unsigned SRThreshold;
102
Chris Lattner39a1c042007-05-30 06:11:23 +0000103 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
104
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000105 int isSafeAllocaToScalarRepl(AllocationInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000106
107 void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
108 AllocaInfo &Info);
109 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
110 AllocaInfo &Info);
111 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
112 unsigned OpNo, AllocaInfo &Info);
113 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
114 AllocaInfo &Info);
115
Chris Lattnera10b29b2007-04-25 05:02:56 +0000116 void DoScalarReplacement(AllocationInst *AI,
117 std::vector<AllocationInst*> &WorkList);
Devang Patel4afc90d2009-02-10 07:00:59 +0000118 void CleanupGEP(GetElementPtrInst *GEP);
119 void CleanupAllocaUsers(AllocationInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000120 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
Chris Lattnera1888942005-12-12 07:19:13 +0000121
Chris Lattner8bf99112007-03-19 00:16:43 +0000122 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
Chris Lattner372dda82007-03-05 07:52:57 +0000123 SmallVector<AllocaInst*, 32> &NewElts);
124
Chris Lattnerd93afec2009-01-07 07:18:45 +0000125 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
126 AllocationInst *AI,
127 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000128 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocationInst *AI,
129 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000130 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000131 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000132
Chris Lattner7809ecd2009-02-03 01:30:09 +0000133 bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
Chris Lattner1a3257b2009-02-03 18:15:05 +0000134 bool &SawVec, uint64_t Offset, unsigned AllocaSize);
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000135 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Chris Lattner6e011152009-02-03 21:01:03 +0000136 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
Chris Lattner9bc67da2009-02-03 19:45:44 +0000137 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +0000138 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
Chris Lattner65a65022009-02-03 19:41:50 +0000139 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattner79b3bd32007-04-25 06:40:51 +0000140 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000141 };
Chris Lattnered7b41e2003-05-27 15:45:27 +0000142}
143
Dan Gohman844731a2008-05-13 00:00:25 +0000144char SROA::ID = 0;
145static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
146
Brian Gaeked0fde302003-11-11 22:41:34 +0000147// Public interface to the ScalarReplAggregates pass
Devang Patelff366852007-07-09 21:19:23 +0000148FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
149 return new SROA(Threshold);
150}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000151
152
Chris Lattnered7b41e2003-05-27 15:45:27 +0000153bool SROA::runOnFunction(Function &F) {
Chris Lattner56c38522009-01-07 06:34:28 +0000154 TD = &getAnalysis<TargetData>();
155
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000156 bool Changed = performPromotion(F);
157 while (1) {
158 bool LocalChange = performScalarRepl(F);
159 if (!LocalChange) break; // No need to repromote if no scalarrepl
160 Changed = true;
161 LocalChange = performPromotion(F);
162 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
163 }
Chris Lattner38aec322003-09-11 16:45:55 +0000164
165 return Changed;
166}
167
168
169bool SROA::performPromotion(Function &F) {
170 std::vector<AllocaInst*> Allocas;
Devang Patel326821e2007-06-07 21:57:03 +0000171 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000172 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner38aec322003-09-11 16:45:55 +0000173
Chris Lattner02a3be02003-09-20 14:39:18 +0000174 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000175
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000176 bool Changed = false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000177
Chris Lattner38aec322003-09-11 16:45:55 +0000178 while (1) {
179 Allocas.clear();
180
181 // Find allocas that are safe to promote, by looking at all instructions in
182 // the entry node
183 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
184 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000185 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000186 Allocas.push_back(AI);
187
188 if (Allocas.empty()) break;
189
Owen Anderson0a205a42009-07-05 22:41:43 +0000190 PromoteMemToReg(Allocas, DT, DF, Context);
Chris Lattner38aec322003-09-11 16:45:55 +0000191 NumPromoted += Allocas.size();
192 Changed = true;
193 }
194
195 return Changed;
196}
197
Chris Lattner963a97f2008-06-22 17:46:21 +0000198/// getNumSAElements - Return the number of elements in the specific struct or
199/// array.
200static uint64_t getNumSAElements(const Type *T) {
201 if (const StructType *ST = dyn_cast<StructType>(T))
202 return ST->getNumElements();
203 return cast<ArrayType>(T)->getNumElements();
204}
205
Chris Lattner38aec322003-09-11 16:45:55 +0000206// performScalarRepl - This algorithm is a simple worklist driven algorithm,
207// which runs on all of the malloc/alloca instructions in the function, removing
208// them if they are only used by getelementptr instructions.
209//
210bool SROA::performScalarRepl(Function &F) {
Chris Lattnered7b41e2003-05-27 15:45:27 +0000211 std::vector<AllocationInst*> WorkList;
212
213 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
Chris Lattner02a3be02003-09-20 14:39:18 +0000214 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000215 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
216 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
217 WorkList.push_back(A);
218
219 // Process the worklist
220 bool Changed = false;
221 while (!WorkList.empty()) {
222 AllocationInst *AI = WorkList.back();
223 WorkList.pop_back();
Chris Lattnera1888942005-12-12 07:19:13 +0000224
Chris Lattneradd2bd72006-12-22 23:14:42 +0000225 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
226 // with unused elements.
227 if (AI->use_empty()) {
228 AI->eraseFromParent();
229 continue;
230 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000231
232 // If this alloca is impossible for us to promote, reject it early.
233 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
234 continue;
Chris Lattner79b3bd32007-04-25 06:40:51 +0000235
236 // Check to see if this allocation is only modified by a memcpy/memmove from
237 // a constant global. If this is the case, we can change all users to use
238 // the constant global instead. This is commonly produced by the CFE by
239 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
240 // is only subsequently read.
241 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
242 DOUT << "Found alloca equal to global: " << *AI;
243 DOUT << " memcpy = " << *TheCopy;
244 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000245 AI->replaceAllUsesWith(
246 Context->getConstantExprBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000247 TheCopy->eraseFromParent(); // Don't mutate the global.
248 AI->eraseFromParent();
249 ++NumGlobals;
250 Changed = true;
251 continue;
252 }
Chris Lattner15c82772009-02-02 20:44:45 +0000253
Chris Lattner7809ecd2009-02-03 01:30:09 +0000254 // Check to see if we can perform the core SROA transformation. We cannot
255 // transform the allocation instruction if it is an array allocation
256 // (allocations OF arrays are ok though), and an allocation of a scalar
257 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000258 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000259
260 // Do not promote any struct whose size is too big.
Bill Wendling3aaf5d92009-03-03 19:18:49 +0000261 if (AllocaSize > SRThreshold) continue;
Bill Wendling8fe40812009-03-01 03:55:12 +0000262
Chris Lattner7809ecd2009-02-03 01:30:09 +0000263 if ((isa<StructType>(AI->getAllocatedType()) ||
264 isa<ArrayType>(AI->getAllocatedType())) &&
Chris Lattner7809ecd2009-02-03 01:30:09 +0000265 // Do not promote any struct into more than "32" separate vars.
Evan Cheng67fca632009-03-06 00:56:43 +0000266 getNumSAElements(AI->getAllocatedType()) <= SRThreshold/4) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000267 // Check that all of the users of the allocation are capable of being
268 // transformed.
269 switch (isSafeAllocaToScalarRepl(AI)) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000270 default: llvm_unreachable("Unexpected value!");
Chris Lattner7809ecd2009-02-03 01:30:09 +0000271 case 0: // Not safe to scalar replace.
272 break;
273 case 1: // Safe, but requires cleanup/canonicalizations first
Devang Patel4afc90d2009-02-10 07:00:59 +0000274 CleanupAllocaUsers(AI);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000275 // FALL THROUGH.
276 case 3: // Safe to scalar replace.
277 DoScalarReplacement(AI, WorkList);
278 Changed = true;
279 continue;
280 }
281 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000282
283 // If we can turn this aggregate value (potentially with casts) into a
284 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000285 // IsNotTrivial tracks whether this is something that mem2reg could have
286 // promoted itself. If so, we don't want to transform it needlessly. Note
287 // that we can't just check based on the type: the alloca may be of an i32
288 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner6e733d32009-01-28 20:16:43 +0000289 bool IsNotTrivial = false;
Chris Lattner7809ecd2009-02-03 01:30:09 +0000290 const Type *VectorTy = 0;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000291 bool HadAVector = false;
292 if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector,
Chris Lattner0ff83ab2009-03-04 19:22:30 +0000293 0, unsigned(AllocaSize)) && IsNotTrivial) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000294 AllocaInst *NewAI;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000295 // If we were able to find a vector type that can handle this with
296 // insert/extract elements, and if there was at least one use that had
297 // a vector type, promote this to a vector. We don't want to promote
298 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
299 // we just get a lot of insert/extracts. If at least one vector is
300 // involved, then we probably really do have a union of vector/array.
301 if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000302 DOUT << "CONVERT TO VECTOR: " << *AI << " TYPE = " << *VectorTy <<"\n";
Chris Lattner15c82772009-02-02 20:44:45 +0000303
Chris Lattner7809ecd2009-02-03 01:30:09 +0000304 // Create and insert the vector alloca.
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000305 NewAI = new AllocaInst(*Context, VectorTy, 0, "",
306 AI->getParent()->begin());
Chris Lattner15c82772009-02-02 20:44:45 +0000307 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000308 } else {
309 DOUT << "CONVERT TO SCALAR INTEGER: " << *AI << "\n";
310
311 // Create and insert the integer alloca.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000312 const Type *NewTy = Context->getIntegerType(AllocaSize*8);
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000313 NewAI = new AllocaInst(*Context, NewTy, 0, "",
314 AI->getParent()->begin());
Chris Lattner7809ecd2009-02-03 01:30:09 +0000315 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner6e733d32009-01-28 20:16:43 +0000316 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000317 NewAI->takeName(AI);
318 AI->eraseFromParent();
319 ++NumConverted;
320 Changed = true;
321 continue;
322 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000323
Chris Lattner7809ecd2009-02-03 01:30:09 +0000324 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +0000325 }
326
327 return Changed;
328}
Chris Lattner5e062a12003-05-30 04:15:41 +0000329
Chris Lattnera10b29b2007-04-25 05:02:56 +0000330/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
331/// predicate, do SROA now.
332void SROA::DoScalarReplacement(AllocationInst *AI,
333 std::vector<AllocationInst*> &WorkList) {
Chris Lattner79b3bd32007-04-25 06:40:51 +0000334 DOUT << "Found inst to SROA: " << *AI;
Chris Lattnera10b29b2007-04-25 05:02:56 +0000335 SmallVector<AllocaInst*, 32> ElementAllocas;
336 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
337 ElementAllocas.reserve(ST->getNumContainedTypes());
338 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000339 AllocaInst *NA = new AllocaInst(*Context,
340 ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +0000341 AI->getAlignment(),
342 AI->getName() + "." + utostr(i), AI);
343 ElementAllocas.push_back(NA);
344 WorkList.push_back(NA); // Add to worklist for recursive processing
345 }
346 } else {
347 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
348 ElementAllocas.reserve(AT->getNumElements());
349 const Type *ElTy = AT->getElementType();
350 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000351 AllocaInst *NA = new AllocaInst(*Context, ElTy, 0, AI->getAlignment(),
Chris Lattnera10b29b2007-04-25 05:02:56 +0000352 AI->getName() + "." + utostr(i), AI);
353 ElementAllocas.push_back(NA);
354 WorkList.push_back(NA); // Add to worklist for recursive processing
355 }
356 }
357
358 // Now that we have created the alloca instructions that we want to use,
359 // expand the getelementptr instructions to use them.
360 //
361 while (!AI->use_empty()) {
362 Instruction *User = cast<Instruction>(AI->use_back());
363 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
364 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
365 BCInst->eraseFromParent();
366 continue;
367 }
368
Chris Lattner2a6a6452008-06-23 17:11:23 +0000369 // Replace:
370 // %res = load { i32, i32 }* %alloc
371 // with:
372 // %load.0 = load i32* %alloc.0
373 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
374 // %load.1 = load i32* %alloc.1
375 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
Matthijs Kooijman02518142008-06-05 12:51:53 +0000376 // (Also works for arrays instead of structs)
377 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000378 Value *Insert = Context->getUndef(LI->getType());
Matthijs Kooijman02518142008-06-05 12:51:53 +0000379 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
380 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
381 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
382 }
383 LI->replaceAllUsesWith(Insert);
384 LI->eraseFromParent();
385 continue;
386 }
387
Chris Lattner2a6a6452008-06-23 17:11:23 +0000388 // Replace:
389 // store { i32, i32 } %val, { i32, i32 }* %alloc
390 // with:
391 // %val.0 = extractvalue { i32, i32 } %val, 0
392 // store i32 %val.0, i32* %alloc.0
393 // %val.1 = extractvalue { i32, i32 } %val, 1
394 // store i32 %val.1, i32* %alloc.1
Matthijs Kooijman02518142008-06-05 12:51:53 +0000395 // (Also works for arrays instead of structs)
396 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
397 Value *Val = SI->getOperand(0);
398 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
399 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
400 new StoreInst(Extract, ElementAllocas[i], SI);
401 }
402 SI->eraseFromParent();
403 continue;
404 }
405
Chris Lattnera10b29b2007-04-25 05:02:56 +0000406 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
407 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
408 unsigned Idx =
409 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
410
411 assert(Idx < ElementAllocas.size() && "Index out of range?");
412 AllocaInst *AllocaToUse = ElementAllocas[Idx];
413
414 Value *RepValue;
415 if (GEPI->getNumOperands() == 3) {
416 // Do not insert a new getelementptr instruction with zero indices, only
417 // to have it optimized out later.
418 RepValue = AllocaToUse;
419 } else {
420 // We are indexing deeply into the structure, so we still need a
421 // getelement ptr instruction to finish the indexing. This may be
422 // expanded itself once the worklist is rerun.
423 //
424 SmallVector<Value*, 8> NewArgs;
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000425 NewArgs.push_back(Context->getNullValue(Type::Int32Ty));
Chris Lattnera10b29b2007-04-25 05:02:56 +0000426 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
Gabor Greif051a9502008-04-06 20:25:17 +0000427 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
428 NewArgs.end(), "", GEPI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000429 RepValue->takeName(GEPI);
430 }
431
432 // If this GEP is to the start of the aggregate, check for memcpys.
Chris Lattnerd356a7e2009-01-07 06:25:07 +0000433 if (Idx == 0 && GEPI->hasAllZeroIndices())
434 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000435
436 // Move all of the users over to the new GEP.
437 GEPI->replaceAllUsesWith(RepValue);
438 // Delete the old GEP
439 GEPI->eraseFromParent();
440 }
441
442 // Finally, delete the Alloca instruction
443 AI->eraseFromParent();
444 NumReplaced++;
445}
446
Chris Lattner5e062a12003-05-30 04:15:41 +0000447
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000448/// isSafeElementUse - Check to see if this use is an allowed use for a
Chris Lattner8bf99112007-03-19 00:16:43 +0000449/// getelementptr instruction of an array aggregate allocation. isFirstElt
450/// indicates whether Ptr is known to the start of the aggregate.
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000451///
Chris Lattner39a1c042007-05-30 06:11:23 +0000452void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
453 AllocaInfo &Info) {
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000454 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
455 I != E; ++I) {
456 Instruction *User = cast<Instruction>(*I);
457 switch (User->getOpcode()) {
458 case Instruction::Load: break;
459 case Instruction::Store:
460 // Store is ok if storing INTO the pointer, not storing the pointer
Chris Lattner39a1c042007-05-30 06:11:23 +0000461 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000462 break;
463 case Instruction::GetElementPtr: {
464 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
Chris Lattner8bf99112007-03-19 00:16:43 +0000465 bool AreAllZeroIndices = isFirstElt;
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000466 if (GEP->getNumOperands() > 1) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000467 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
468 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
Chris Lattner39a1c042007-05-30 06:11:23 +0000469 // Using pointer arithmetic to navigate the array.
470 return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000471
Chris Lattnerd356a7e2009-01-07 06:25:07 +0000472 if (AreAllZeroIndices)
473 AreAllZeroIndices = GEP->hasAllZeroIndices();
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000474 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000475 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
476 if (Info.isUnsafe) return;
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000477 break;
478 }
Chris Lattner8bf99112007-03-19 00:16:43 +0000479 case Instruction::BitCast:
Chris Lattner39a1c042007-05-30 06:11:23 +0000480 if (isFirstElt) {
481 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
482 if (Info.isUnsafe) return;
Chris Lattner8bf99112007-03-19 00:16:43 +0000483 break;
Chris Lattner8bf99112007-03-19 00:16:43 +0000484 }
485 DOUT << " Transformation preventing inst: " << *User;
Chris Lattner39a1c042007-05-30 06:11:23 +0000486 return MarkUnsafe(Info);
487 case Instruction::Call:
488 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
489 if (isFirstElt) {
490 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
491 if (Info.isUnsafe) return;
492 break;
493 }
494 }
495 DOUT << " Transformation preventing inst: " << *User;
496 return MarkUnsafe(Info);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000497 default:
Bill Wendlingb7427032006-11-26 09:46:52 +0000498 DOUT << " Transformation preventing inst: " << *User;
Chris Lattner39a1c042007-05-30 06:11:23 +0000499 return MarkUnsafe(Info);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000500 }
501 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000502 return; // All users look ok :)
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000503}
504
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000505/// AllUsersAreLoads - Return true if all users of this value are loads.
506static bool AllUsersAreLoads(Value *Ptr) {
507 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
508 I != E; ++I)
509 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
510 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000511 return true;
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000512}
513
Chris Lattner5e062a12003-05-30 04:15:41 +0000514/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
515/// aggregate allocation.
516///
Chris Lattner39a1c042007-05-30 06:11:23 +0000517void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
518 AllocaInfo &Info) {
Chris Lattner372dda82007-03-05 07:52:57 +0000519 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
Chris Lattner39a1c042007-05-30 06:11:23 +0000520 return isSafeUseOfBitCastedAllocation(C, AI, Info);
Chris Lattnerbe883a22003-11-25 21:09:18 +0000521
Chris Lattner6e733d32009-01-28 20:16:43 +0000522 if (LoadInst *LI = dyn_cast<LoadInst>(User))
523 if (!LI->isVolatile())
524 return;// Loads (returning a first class aggregrate) are always rewritable
Matthijs Kooijman02518142008-06-05 12:51:53 +0000525
Chris Lattner6e733d32009-01-28 20:16:43 +0000526 if (StoreInst *SI = dyn_cast<StoreInst>(User))
527 if (!SI->isVolatile() && SI->getOperand(0) != AI)
528 return;// Store is ok if storing INTO the pointer, not storing the pointer
Matthijs Kooijman02518142008-06-05 12:51:53 +0000529
Chris Lattner39a1c042007-05-30 06:11:23 +0000530 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
531 if (GEPI == 0)
532 return MarkUnsafe(Info);
533
Chris Lattnerbe883a22003-11-25 21:09:18 +0000534 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
535
Chris Lattner25de4862006-03-08 01:05:29 +0000536 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
Chris Lattnerbe883a22003-11-25 21:09:18 +0000537 if (I == E ||
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000538 I.getOperand() != Context->getNullValue(I.getOperand()->getType())) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000539 return MarkUnsafe(Info);
540 }
Chris Lattnerbe883a22003-11-25 21:09:18 +0000541
542 ++I;
Chris Lattner39a1c042007-05-30 06:11:23 +0000543 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
Chris Lattnerbe883a22003-11-25 21:09:18 +0000544
Chris Lattner8bf99112007-03-19 00:16:43 +0000545 bool IsAllZeroIndices = true;
546
Chris Lattner88e6dc82008-08-23 05:21:06 +0000547 // If the first index is a non-constant index into an array, see if we can
548 // handle it as a special case.
Chris Lattnerbe883a22003-11-25 21:09:18 +0000549 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
Chris Lattner88e6dc82008-08-23 05:21:06 +0000550 if (!isa<ConstantInt>(I.getOperand())) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000551 IsAllZeroIndices = 0;
Chris Lattner88e6dc82008-08-23 05:21:06 +0000552 uint64_t NumElements = AT->getNumElements();
Chris Lattner8bf99112007-03-19 00:16:43 +0000553
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000554 // If this is an array index and the index is not constant, we cannot
555 // promote... that is unless the array has exactly one or two elements in
556 // it, in which case we CAN promote it, but we have to canonicalize this
557 // out if this is the only problem.
Chris Lattner25de4862006-03-08 01:05:29 +0000558 if ((NumElements == 1 || NumElements == 2) &&
Chris Lattner39a1c042007-05-30 06:11:23 +0000559 AllUsersAreLoads(GEPI)) {
Devang Patel4afc90d2009-02-10 07:00:59 +0000560 Info.needsCleanup = true;
Chris Lattner39a1c042007-05-30 06:11:23 +0000561 return; // Canonicalization required!
562 }
563 return MarkUnsafe(Info);
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000564 }
Chris Lattner5e062a12003-05-30 04:15:41 +0000565 }
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000566
Chris Lattner88e6dc82008-08-23 05:21:06 +0000567 // Walk through the GEP type indices, checking the types that this indexes
568 // into.
569 for (; I != E; ++I) {
570 // Ignore struct elements, no extra checking needed for these.
571 if (isa<StructType>(*I))
572 continue;
573
Chris Lattner88e6dc82008-08-23 05:21:06 +0000574 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
575 if (!IdxVal) return MarkUnsafe(Info);
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000576
577 // Are all indices still zero?
Chris Lattner88e6dc82008-08-23 05:21:06 +0000578 IsAllZeroIndices &= IdxVal->isZero();
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000579
580 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
581 // This GEP indexes an array. Verify that this is an in-range constant
582 // integer. Specifically, consider A[0][i]. We cannot know that the user
583 // isn't doing invalid things like allowing i to index an out-of-range
584 // subscript that accesses A[1]. Because of this, we have to reject SROA
Dale Johannesenc0bc5472008-11-04 20:54:03 +0000585 // of any accesses into structs where any of the components are variables.
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000586 if (IdxVal->getZExtValue() >= AT->getNumElements())
587 return MarkUnsafe(Info);
Dale Johannesenc0bc5472008-11-04 20:54:03 +0000588 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
589 if (IdxVal->getZExtValue() >= VT->getNumElements())
590 return MarkUnsafe(Info);
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000591 }
Chris Lattner88e6dc82008-08-23 05:21:06 +0000592 }
593
Chris Lattnerbe883a22003-11-25 21:09:18 +0000594 // If there are any non-simple uses of this getelementptr, make sure to reject
595 // them.
Chris Lattner39a1c042007-05-30 06:11:23 +0000596 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000597}
598
599/// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
600/// intrinsic can be promoted by SROA. At this point, we know that the operand
601/// of the memintrinsic is a pointer to the beginning of the allocation.
Chris Lattner39a1c042007-05-30 06:11:23 +0000602void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
603 unsigned OpNo, AllocaInfo &Info) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000604 // If not constant length, give up.
605 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattner39a1c042007-05-30 06:11:23 +0000606 if (!Length) return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000607
608 // If not the whole aggregate, give up.
Duncan Sands3cb36502007-11-04 14:43:57 +0000609 if (Length->getZExtValue() !=
Duncan Sands777d2302009-05-09 07:06:46 +0000610 TD->getTypeAllocSize(AI->getType()->getElementType()))
Chris Lattner39a1c042007-05-30 06:11:23 +0000611 return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000612
613 // We only know about memcpy/memset/memmove.
Chris Lattner3ce5e882009-03-08 03:37:16 +0000614 if (!isa<MemIntrinsic>(MI))
Chris Lattner39a1c042007-05-30 06:11:23 +0000615 return MarkUnsafe(Info);
616
617 // Otherwise, we can transform it. Determine whether this is a memcpy/set
618 // into or out of the aggregate.
619 if (OpNo == 1)
620 Info.isMemCpyDst = true;
621 else {
622 assert(OpNo == 2);
623 Info.isMemCpySrc = true;
624 }
Chris Lattner5e062a12003-05-30 04:15:41 +0000625}
626
Chris Lattner372dda82007-03-05 07:52:57 +0000627/// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
628/// are
Chris Lattner39a1c042007-05-30 06:11:23 +0000629void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
630 AllocaInfo &Info) {
Chris Lattner372dda82007-03-05 07:52:57 +0000631 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
632 UI != E; ++UI) {
633 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000634 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
Chris Lattner372dda82007-03-05 07:52:57 +0000635 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000636 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000637 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner6e733d32009-01-28 20:16:43 +0000638 if (SI->isVolatile())
639 return MarkUnsafe(Info);
640
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000641 // If storing the entire alloca in one chunk through a bitcasted pointer
642 // to integer, we can transform it. This happens (for example) when you
643 // cast a {i32,i32}* to i64* and store through it. This is similar to the
644 // memcpy case and occurs in various "byval" cases and emulated memcpys.
645 if (isa<IntegerType>(SI->getOperand(0)->getType()) &&
Duncan Sands777d2302009-05-09 07:06:46 +0000646 TD->getTypeAllocSize(SI->getOperand(0)->getType()) ==
647 TD->getTypeAllocSize(AI->getType()->getElementType())) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000648 Info.isMemCpyDst = true;
649 continue;
650 }
651 return MarkUnsafe(Info);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000652 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
Chris Lattner6e733d32009-01-28 20:16:43 +0000653 if (LI->isVolatile())
654 return MarkUnsafe(Info);
655
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000656 // If loading the entire alloca in one chunk through a bitcasted pointer
657 // to integer, we can transform it. This happens (for example) when you
658 // cast a {i32,i32}* to i64* and load through it. This is similar to the
659 // memcpy case and occurs in various "byval" cases and emulated memcpys.
660 if (isa<IntegerType>(LI->getType()) &&
Duncan Sands777d2302009-05-09 07:06:46 +0000661 TD->getTypeAllocSize(LI->getType()) ==
662 TD->getTypeAllocSize(AI->getType()->getElementType())) {
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000663 Info.isMemCpySrc = true;
664 continue;
665 }
666 return MarkUnsafe(Info);
Devang Patel4afc90d2009-02-10 07:00:59 +0000667 } else if (isa<DbgInfoIntrinsic>(UI)) {
668 // If one user is DbgInfoIntrinsic then check if all users are
669 // DbgInfoIntrinsics.
670 if (OnlyUsedByDbgInfoIntrinsics(BC)) {
671 Info.needsCleanup = true;
672 return;
673 }
674 else
675 MarkUnsafe(Info);
676 }
677 else {
Chris Lattner39a1c042007-05-30 06:11:23 +0000678 return MarkUnsafe(Info);
Chris Lattner372dda82007-03-05 07:52:57 +0000679 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000680 if (Info.isUnsafe) return;
Chris Lattner372dda82007-03-05 07:52:57 +0000681 }
Chris Lattner372dda82007-03-05 07:52:57 +0000682}
683
Chris Lattner8bf99112007-03-19 00:16:43 +0000684/// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
685/// to its first element. Transform users of the cast to use the new values
686/// instead.
687void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
Chris Lattner372dda82007-03-05 07:52:57 +0000688 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000689 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
690 while (UI != UE) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000691 Instruction *User = cast<Instruction>(*UI++);
692 if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) {
Chris Lattner372dda82007-03-05 07:52:57 +0000693 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000694 if (BCU->use_empty()) BCU->eraseFromParent();
Chris Lattner372dda82007-03-05 07:52:57 +0000695 continue;
696 }
697
Chris Lattnerd93afec2009-01-07 07:18:45 +0000698 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
699 // This must be memcpy/memmove/memset of the entire aggregate.
700 // Split into one per element.
701 RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts);
Chris Lattner8bf99112007-03-19 00:16:43 +0000702 continue;
703 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000704
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000705 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000706 // If this is a store of the entire alloca from an integer, rewrite it.
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000707 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
708 continue;
709 }
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000710
711 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
712 // If this is a load of the entire alloca to an integer, rewrite it.
713 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
714 continue;
715 }
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000716
717 // Otherwise it must be some other user of a gep of the first pointer. Just
718 // leave these alone.
Chris Lattnerd93afec2009-01-07 07:18:45 +0000719 continue;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000720 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000721}
722
723/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
724/// Rewrite it to copy or set the elements of the scalarized memory.
725void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
726 AllocationInst *AI,
727 SmallVector<AllocaInst*, 32> &NewElts) {
728
729 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +0000730 // appropriate type. The "Other" pointer is the pointer that goes to memory
731 // that doesn't have anything to do with the alloca that we are promoting. For
732 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +0000733 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +0000734 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +0000735 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
736 if (BCInst == MTI->getRawDest())
737 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000738 else {
Chris Lattner3ce5e882009-03-08 03:37:16 +0000739 assert(BCInst == MTI->getRawSource());
740 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000741 }
742 }
743
744 // If there is an other pointer, we want to convert it to the same pointer
745 // type as AI has, so we can GEP through it safely.
746 if (OtherPtr) {
747 // It is likely that OtherPtr is a bitcast, if so, remove it.
748 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
749 OtherPtr = BC->getOperand(0);
750 // All zero GEPs are effectively bitcasts.
751 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
752 if (GEP->hasAllZeroIndices())
753 OtherPtr = GEP->getOperand(0);
Chris Lattner372dda82007-03-05 07:52:57 +0000754
Chris Lattnerd93afec2009-01-07 07:18:45 +0000755 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
756 if (BCE->getOpcode() == Instruction::BitCast)
757 OtherPtr = BCE->getOperand(0);
758
759 // If the pointer is not the right type, insert a bitcast to the right
760 // type.
761 if (OtherPtr->getType() != AI->getType())
762 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
763 MI);
764 }
765
766 // Process each element of the aggregate.
767 Value *TheFn = MI->getOperand(0);
768 const Type *BytePtrTy = MI->getRawDest()->getType();
769 bool SROADest = MI->getRawDest() == BCInst;
770
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000771 Constant *Zero = Context->getNullValue(Type::Int32Ty);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000772
773 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
774 // If this is a memcpy/memmove, emit a GEP of the other element address.
775 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000776 unsigned OtherEltAlign = MemAlignment;
777
Chris Lattner372dda82007-03-05 07:52:57 +0000778 if (OtherPtr) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000779 Value *Idx[2] = { Zero, Context->getConstantInt(Type::Int32Ty, i) };
Chris Lattnerd93afec2009-01-07 07:18:45 +0000780 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
Chris Lattner963a97f2008-06-22 17:46:21 +0000781 OtherPtr->getNameStr()+"."+utostr(i),
Chris Lattnerd93afec2009-01-07 07:18:45 +0000782 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +0000783 uint64_t EltOffset;
784 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
785 if (const StructType *ST =
786 dyn_cast<StructType>(OtherPtrTy->getElementType())) {
787 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
788 } else {
789 const Type *EltTy =
790 cast<SequentialType>(OtherPtr->getType())->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000791 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000792 }
793
794 // The alignment of the other pointer is the guaranteed alignment of the
795 // element, which is affected by both the known alignment of the whole
796 // mem intrinsic and the alignment of the element. If the alignment of
797 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
798 // known alignment is just 4 bytes.
799 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000800 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000801
802 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +0000803 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000804
805 // If we got down to a scalar, insert a load or store as appropriate.
806 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +0000807 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +0000808 if (SROADest) {
809 // From Other to Alloca.
810 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
811 new StoreInst(Elt, EltPtr, MI);
812 } else {
813 // From Alloca to Other.
814 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
815 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
816 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000817 continue;
818 }
819 assert(isa<MemSetInst>(MI));
820
821 // If the stored element is zero (common case), just store a null
822 // constant.
823 Constant *StoreVal;
824 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
825 if (CI->isZero()) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000826 StoreVal = Context->getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +0000827 } else {
828 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +0000829 const Type *ValTy = EltTy->getScalarType();
830
Chris Lattnerd93afec2009-01-07 07:18:45 +0000831 // Construct an integer with the right value.
832 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
833 APInt OneVal(EltSize, CI->getZExtValue());
834 APInt TotalVal(OneVal);
835 // Set each byte.
836 for (unsigned i = 0; 8*i < EltSize; ++i) {
837 TotalVal = TotalVal.shl(8);
838 TotalVal |= OneVal;
839 }
840
841 // Convert the integer value to the appropriate type.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000842 StoreVal = Context->getConstantInt(TotalVal);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000843 if (isa<PointerType>(ValTy))
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000844 StoreVal = Context->getConstantExprIntToPtr(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000845 else if (ValTy->isFloatingPoint())
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000846 StoreVal = Context->getConstantExprBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000847 assert(StoreVal->getType() == ValTy && "Type mismatch!");
848
849 // If the requested value was a vector constant, create it.
850 if (EltTy != ValTy) {
851 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
852 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000853 StoreVal = Context->getConstantVector(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000854 }
855 }
856 new StoreInst(StoreVal, EltPtr, MI);
857 continue;
858 }
859 // Otherwise, if we're storing a byte variable, use a memset call for
860 // this element.
861 }
862
863 // Cast the element pointer to BytePtrTy.
864 if (EltPtr->getType() != BytePtrTy)
865 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
866
867 // Cast the other pointer (if we have one) to BytePtrTy.
868 if (OtherElt && OtherElt->getType() != BytePtrTy)
869 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
870 MI);
871
Duncan Sands777d2302009-05-09 07:06:46 +0000872 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000873
874 // Finally, insert the meminst for this element.
Chris Lattner3ce5e882009-03-08 03:37:16 +0000875 if (isa<MemTransferInst>(MI)) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000876 Value *Ops[] = {
877 SROADest ? EltPtr : OtherElt, // Dest ptr
878 SROADest ? OtherElt : EltPtr, // Src ptr
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000879 Context->getConstantInt(MI->getOperand(3)->getType(), EltSize), // Size
880 Context->getConstantInt(Type::Int32Ty, OtherEltAlign) // Align
Chris Lattnerd93afec2009-01-07 07:18:45 +0000881 };
882 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
883 } else {
884 assert(isa<MemSetInst>(MI));
885 Value *Ops[] = {
886 EltPtr, MI->getOperand(2), // Dest, Value,
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000887 Context->getConstantInt(MI->getOperand(3)->getType(), EltSize), // Size
Chris Lattnerd93afec2009-01-07 07:18:45 +0000888 Zero // Align
889 };
890 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
891 }
Chris Lattner372dda82007-03-05 07:52:57 +0000892 }
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000893 MI->eraseFromParent();
Chris Lattner372dda82007-03-05 07:52:57 +0000894}
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000895
896/// RewriteStoreUserOfWholeAlloca - We found an store of an integer that
897/// overwrites the entire allocation. Extract out the pieces of the stored
898/// integer and store them individually.
899void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI,
900 AllocationInst *AI,
901 SmallVector<AllocaInst*, 32> &NewElts){
902 // Extract each element out of the integer according to its structure offset
903 // and store the element value to the individual alloca.
904 Value *SrcVal = SI->getOperand(0);
905 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000906 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000907
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000908 // If this isn't a store of an integer to the whole alloca, it may be a store
909 // to the first element. Just ignore the store in this case and normal SROA
Eli Friedman41b33f42009-06-01 09:14:32 +0000910 // will handle it.
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000911 if (!isa<IntegerType>(SrcVal->getType()) ||
Eli Friedman41b33f42009-06-01 09:14:32 +0000912 TD->getTypeAllocSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000913 return;
Eli Friedman41b33f42009-06-01 09:14:32 +0000914 // Handle tail padding by extending the operand
915 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000916 SrcVal = new ZExtInst(SrcVal,
917 Context->getIntegerType(AllocaSizeBits), "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000918
919 DOUT << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << *SI;
920
921 // There are two forms here: AI could be an array or struct. Both cases
922 // have different ways to compute the element offset.
923 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
924 const StructLayout *Layout = TD->getStructLayout(EltSTy);
925
926 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
927 // Get the number of bits to shift SrcVal to get the value.
928 const Type *FieldTy = EltSTy->getElementType(i);
929 uint64_t Shift = Layout->getElementOffsetInBits(i);
930
931 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +0000932 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000933
934 Value *EltVal = SrcVal;
935 if (Shift) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000936 Value *ShiftVal = Context->getConstantInt(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000937 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
938 "sroa.store.elt", SI);
939 }
940
941 // Truncate down to an integer of the right size.
942 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattner583dd602009-01-09 18:18:43 +0000943
944 // Ignore zero sized fields like {}, they obviously contain no data.
945 if (FieldSizeBits == 0) continue;
946
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000947 if (FieldSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000948 EltVal = new TruncInst(EltVal,
949 Context->getIntegerType(FieldSizeBits), "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000950 Value *DestField = NewElts[i];
951 if (EltVal->getType() == FieldTy) {
952 // Storing to an integer field of this size, just do it.
953 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
954 // Bitcast to the right element type (for fp/vector values).
955 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
956 } else {
957 // Otherwise, bitcast the dest pointer (for aggregates).
958 DestField = new BitCastInst(DestField,
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000959 Context->getPointerTypeUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000960 "", SI);
961 }
962 new StoreInst(EltVal, DestField, SI);
963 }
964
965 } else {
966 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
967 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000968 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000969 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
970
971 uint64_t Shift;
972
973 if (TD->isBigEndian())
974 Shift = AllocaSizeBits-ElementOffset;
975 else
976 Shift = 0;
977
978 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +0000979 // Ignore zero sized fields like {}, they obviously contain no data.
980 if (ElementSizeBits == 0) continue;
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000981
982 Value *EltVal = SrcVal;
983 if (Shift) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000984 Value *ShiftVal = Context->getConstantInt(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000985 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
986 "sroa.store.elt", SI);
987 }
988
989 // Truncate down to an integer of the right size.
990 if (ElementSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000991 EltVal = new TruncInst(EltVal,
992 Context->getIntegerType(ElementSizeBits),"",SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000993 Value *DestField = NewElts[i];
994 if (EltVal->getType() == ArrayEltTy) {
995 // Storing to an integer field of this size, just do it.
996 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
997 // Bitcast to the right element type (for fp/vector values).
998 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
999 } else {
1000 // Otherwise, bitcast the dest pointer (for aggregates).
1001 DestField = new BitCastInst(DestField,
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001002 Context->getPointerTypeUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001003 "", SI);
1004 }
1005 new StoreInst(EltVal, DestField, SI);
1006
1007 if (TD->isBigEndian())
1008 Shift -= ElementOffset;
1009 else
1010 Shift += ElementOffset;
1011 }
1012 }
1013
1014 SI->eraseFromParent();
1015}
1016
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001017/// RewriteLoadUserOfWholeAlloca - We found an load of the entire allocation to
1018/// an integer. Load the individual pieces to form the aggregate value.
1019void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
1020 SmallVector<AllocaInst*, 32> &NewElts) {
1021 // Extract each element out of the NewElts according to its structure offset
1022 // and form the result value.
1023 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001024 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001025
1026 // If this isn't a load of the whole alloca to an integer, it may be a load
1027 // of the first element. Just ignore the load in this case and normal SROA
Eli Friedman41b33f42009-06-01 09:14:32 +00001028 // will handle it.
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001029 if (!isa<IntegerType>(LI->getType()) ||
Eli Friedman41b33f42009-06-01 09:14:32 +00001030 TD->getTypeAllocSizeInBits(LI->getType()) != AllocaSizeBits)
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001031 return;
1032
1033 DOUT << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << *LI;
1034
1035 // There are two forms here: AI could be an array or struct. Both cases
1036 // have different ways to compute the element offset.
1037 const StructLayout *Layout = 0;
1038 uint64_t ArrayEltBitOffset = 0;
1039 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1040 Layout = TD->getStructLayout(EltSTy);
1041 } else {
1042 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001043 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001044 }
1045
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001046 Value *ResultVal =
1047 Context->getNullValue(Context->getIntegerType(AllocaSizeBits));
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001048
1049 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1050 // Load the value from the alloca. If the NewElt is an aggregate, cast
1051 // the pointer to an integer of the same size before doing the load.
1052 Value *SrcField = NewElts[i];
1053 const Type *FieldTy =
1054 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001055 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1056
1057 // Ignore zero sized fields like {}, they obviously contain no data.
1058 if (FieldSizeBits == 0) continue;
1059
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001060 const IntegerType *FieldIntTy = Context->getIntegerType(FieldSizeBits);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001061 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
1062 !isa<VectorType>(FieldTy))
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001063 SrcField = new BitCastInst(SrcField,
1064 Context->getPointerTypeUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001065 "", LI);
1066 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1067
1068 // If SrcField is a fp or vector of the right size but that isn't an
1069 // integer type, bitcast to an integer so we can shift it.
1070 if (SrcField->getType() != FieldIntTy)
1071 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1072
1073 // Zero extend the field to be the same size as the final alloca so that
1074 // we can shift and insert it.
1075 if (SrcField->getType() != ResultVal->getType())
1076 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1077
1078 // Determine the number of bits to shift SrcField.
1079 uint64_t Shift;
1080 if (Layout) // Struct case.
1081 Shift = Layout->getElementOffsetInBits(i);
1082 else // Array case.
1083 Shift = i*ArrayEltBitOffset;
1084
1085 if (TD->isBigEndian())
1086 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1087
1088 if (Shift) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001089 Value *ShiftVal = Context->getConstantInt(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001090 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1091 }
1092
1093 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1094 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001095
1096 // Handle tail padding by truncating the result
1097 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1098 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1099
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001100 LI->replaceAllUsesWith(ResultVal);
1101 LI->eraseFromParent();
1102}
1103
Chris Lattner372dda82007-03-05 07:52:57 +00001104
Duncan Sands3cb36502007-11-04 14:43:57 +00001105/// HasPadding - Return true if the specified type has any structure or
1106/// alignment padding, false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001107static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner39a1c042007-05-30 06:11:23 +00001108 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1109 const StructLayout *SL = TD.getStructLayout(STy);
1110 unsigned PrevFieldBitOffset = 0;
1111 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001112 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1113
Chris Lattner39a1c042007-05-30 06:11:23 +00001114 // Padding in sub-elements?
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001115 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001116 return true;
Duncan Sands3cb36502007-11-04 14:43:57 +00001117
Chris Lattner39a1c042007-05-30 06:11:23 +00001118 // Check to see if there is any padding between this element and the
1119 // previous one.
1120 if (i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001121 unsigned PrevFieldEnd =
Chris Lattner39a1c042007-05-30 06:11:23 +00001122 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1123 if (PrevFieldEnd < FieldBitOffset)
1124 return true;
1125 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001126
Chris Lattner39a1c042007-05-30 06:11:23 +00001127 PrevFieldBitOffset = FieldBitOffset;
1128 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001129
Chris Lattner39a1c042007-05-30 06:11:23 +00001130 // Check for tail padding.
1131 if (unsigned EltCount = STy->getNumElements()) {
1132 unsigned PrevFieldEnd = PrevFieldBitOffset +
1133 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands3cb36502007-11-04 14:43:57 +00001134 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner39a1c042007-05-30 06:11:23 +00001135 return true;
1136 }
1137
1138 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001139 return HasPadding(ATy->getElementType(), TD);
Duncan Sands3cb36502007-11-04 14:43:57 +00001140 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001141 return HasPadding(VTy->getElementType(), TD);
Chris Lattner39a1c042007-05-30 06:11:23 +00001142 }
Duncan Sands777d2302009-05-09 07:06:46 +00001143 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001144}
Chris Lattner372dda82007-03-05 07:52:57 +00001145
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001146/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1147/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1148/// or 1 if safe after canonicalization has been performed.
Chris Lattner5e062a12003-05-30 04:15:41 +00001149///
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001150int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001151 // Loop over the use list of the alloca. We can only transform it if all of
1152 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001153 AllocaInfo Info;
1154
Chris Lattner5e062a12003-05-30 04:15:41 +00001155 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001156 I != E; ++I) {
Chris Lattner39a1c042007-05-30 06:11:23 +00001157 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
1158 if (Info.isUnsafe) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001159 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001160 return 0;
Chris Lattner5e062a12003-05-30 04:15:41 +00001161 }
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 &&
Chris Lattner56c38522009-01-07 06:34:28 +00001170 HasPadding(AI->getType()->getElementType(), *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/// CleanupGEP - GEP is used by an Alloca, which can be prompted after the GEP
1178/// is canonicalized here.
1179void SROA::CleanupGEP(GetElementPtrInst *GEPI) {
1180 gep_type_iterator I = gep_type_begin(GEPI);
1181 ++I;
1182
Devang Patel7afe8fa2009-02-10 19:28:07 +00001183 const ArrayType *AT = dyn_cast<ArrayType>(*I);
1184 if (!AT)
1185 return;
1186
1187 uint64_t NumElements = AT->getNumElements();
1188
1189 if (isa<ConstantInt>(I.getOperand()))
1190 return;
1191
1192 if (NumElements == 1) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001193 GEPI->setOperand(2, Context->getNullValue(Type::Int32Ty));
Devang Patel7afe8fa2009-02-10 19:28:07 +00001194 return;
1195 }
Devang Patel4afc90d2009-02-10 07:00:59 +00001196
Devang Patel7afe8fa2009-02-10 19:28:07 +00001197 assert(NumElements == 2 && "Unhandled case!");
1198 // All users of the GEP must be loads. At each use of the GEP, insert
1199 // two loads of the appropriate indexed GEP and select between them.
Owen Anderson333c4002009-07-09 23:48:35 +00001200 Value *IsOne = new ICmpInst(GEPI, ICmpInst::ICMP_NE, I.getOperand(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001201 Context->getNullValue(I.getOperand()->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001202 "isone");
Devang Patel7afe8fa2009-02-10 19:28:07 +00001203 // Insert the new GEP instructions, which are properly indexed.
1204 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001205 Indices[1] = Context->getNullValue(Type::Int32Ty);
Devang Patel7afe8fa2009-02-10 19:28:07 +00001206 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1207 Indices.begin(),
1208 Indices.end(),
1209 GEPI->getName()+".0", GEPI);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001210 Indices[1] = Context->getConstantInt(Type::Int32Ty, 1);
Devang Patel7afe8fa2009-02-10 19:28:07 +00001211 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1212 Indices.begin(),
1213 Indices.end(),
1214 GEPI->getName()+".1", GEPI);
1215 // Replace all loads of the variable index GEP with loads from both
1216 // indexes and a select.
1217 while (!GEPI->use_empty()) {
1218 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1219 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1220 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
1221 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
1222 LI->replaceAllUsesWith(R);
1223 LI->eraseFromParent();
Devang Patel4afc90d2009-02-10 07:00:59 +00001224 }
Devang Patel7afe8fa2009-02-10 19:28:07 +00001225 GEPI->eraseFromParent();
Devang Patel4afc90d2009-02-10 07:00:59 +00001226}
1227
Devang Patel7afe8fa2009-02-10 19:28:07 +00001228
Devang Patel4afc90d2009-02-10 07:00:59 +00001229/// CleanupAllocaUsers - If SROA reported that it can promote the specified
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001230/// allocation, but only if cleaned up, perform the cleanups required.
Devang Patel4afc90d2009-02-10 07:00:59 +00001231void SROA::CleanupAllocaUsers(AllocationInst *AI) {
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001232 // At this point, we know that the end result will be SROA'd and promoted, so
1233 // we can insert ugly code if required so long as sroa+mem2reg will clean it
1234 // up.
1235 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1236 UI != E; ) {
Devang Patel4afc90d2009-02-10 07:00:59 +00001237 User *U = *UI++;
1238 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U))
1239 CleanupGEP(GEPI);
Jay Foad0906b1b2009-06-06 17:49:35 +00001240 else {
1241 Instruction *I = cast<Instruction>(U);
Devang Patel4afc90d2009-02-10 07:00:59 +00001242 SmallVector<DbgInfoIntrinsic *, 2> DbgInUses;
Zhou Shengb0c41992009-03-18 12:48:48 +00001243 if (!isa<StoreInst>(I) && OnlyUsedByDbgInfoIntrinsics(I, &DbgInUses)) {
Devang Patel4afc90d2009-02-10 07:00:59 +00001244 // Safe to remove debug info uses.
1245 while (!DbgInUses.empty()) {
1246 DbgInfoIntrinsic *DI = DbgInUses.back(); DbgInUses.pop_back();
1247 DI->eraseFromParent();
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001248 }
Devang Patel4afc90d2009-02-10 07:00:59 +00001249 I->eraseFromParent();
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001250 }
1251 }
1252 }
Chris Lattner5e062a12003-05-30 04:15:41 +00001253}
Chris Lattnera1888942005-12-12 07:19:13 +00001254
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001255/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1256/// the offset specified by Offset (which is specified in bytes).
Chris Lattnerde6df882006-04-14 21:42:41 +00001257///
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001258/// There are two cases we handle here:
1259/// 1) A union of vector types of the same size and potentially its elements.
Chris Lattnerd22dbdf2006-12-15 07:32:38 +00001260/// Here we turn element accesses into insert/extract element operations.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001261/// This promotes a <4 x float> with a store of float to the third element
1262/// into a <4 x float> that uses insert element.
1263/// 2) A fully general blob of memory, which we turn into some (potentially
1264/// large) integer type with extract and insert operations where the loads
1265/// and stores would mutate the memory.
Chris Lattner7809ecd2009-02-03 01:30:09 +00001266static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001267 unsigned AllocaSize, const TargetData &TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001268 LLVMContext *Context) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001269 // If this could be contributing to a vector, analyze it.
1270 if (VecTy != Type::VoidTy) { // either null or a vector type.
Chris Lattner996d7a92009-02-02 18:02:59 +00001271
Chris Lattner7809ecd2009-02-03 01:30:09 +00001272 // If the In type is a vector that is the same size as the alloca, see if it
1273 // matches the existing VecTy.
1274 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1275 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1276 // If we're storing/loading a vector of the right size, allow it as a
1277 // vector. If this the first vector we see, remember the type so that
1278 // we know the element size.
1279 if (VecTy == 0)
1280 VecTy = VInTy;
1281 return;
1282 }
1283 } else if (In == Type::FloatTy || In == Type::DoubleTy ||
1284 (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1285 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1286 // If we're accessing something that could be an element of a vector, see
1287 // if the implied vector agrees with what we already have and if Offset is
1288 // compatible with it.
1289 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1290 if (Offset % EltSize == 0 &&
1291 AllocaSize % EltSize == 0 &&
1292 (VecTy == 0 ||
1293 cast<VectorType>(VecTy)->getElementType()
1294 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1295 if (VecTy == 0)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001296 VecTy = Context->getVectorType(In, AllocaSize/EltSize);
Chris Lattner7809ecd2009-02-03 01:30:09 +00001297 return;
1298 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001299 }
1300 }
1301
Chris Lattner7809ecd2009-02-03 01:30:09 +00001302 // Otherwise, we have a case that we can't handle with an optimized vector
1303 // form. We can still turn this into a large integer.
1304 VecTy = Type::VoidTy;
Chris Lattnera1888942005-12-12 07:19:13 +00001305}
1306
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001307/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
Chris Lattner7809ecd2009-02-03 01:30:09 +00001308/// its accesses to use a to single vector type, return true, and set VecTy to
1309/// the new type. If we could convert the alloca into a single promotable
1310/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1311/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1312/// is the current offset from the base of the alloca being analyzed.
Chris Lattnera1888942005-12-12 07:19:13 +00001313///
Chris Lattner1a3257b2009-02-03 18:15:05 +00001314/// If we see at least one access to the value that is as a vector type, set the
1315/// SawVec flag.
1316///
1317bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1318 bool &SawVec, uint64_t Offset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001319 unsigned AllocaSize) {
Chris Lattnera1888942005-12-12 07:19:13 +00001320 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1321 Instruction *User = cast<Instruction>(*UI);
1322
1323 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001324 // Don't break volatile loads.
Chris Lattner6e733d32009-01-28 20:16:43 +00001325 if (LI->isVolatile())
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001326 return false;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001327 MergeInType(LI->getType(), Offset, VecTy, AllocaSize, *TD, Context);
Chris Lattner1a3257b2009-02-03 18:15:05 +00001328 SawVec |= isa<VectorType>(LI->getType());
Chris Lattnercf321862009-01-07 06:39:58 +00001329 continue;
1330 }
1331
1332 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001333 // Storing the pointer, not into the value?
Chris Lattner6e733d32009-01-28 20:16:43 +00001334 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001335 MergeInType(SI->getOperand(0)->getType(), Offset,
1336 VecTy, AllocaSize, *TD, Context);
Chris Lattner1a3257b2009-02-03 18:15:05 +00001337 SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
Chris Lattnercf321862009-01-07 06:39:58 +00001338 continue;
1339 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001340
1341 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattner1a3257b2009-02-03 18:15:05 +00001342 if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1343 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001344 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001345 IsNotTrivial = true;
Chris Lattnercf321862009-01-07 06:39:58 +00001346 continue;
1347 }
1348
1349 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001350 // If this is a GEP with a variable indices, we can't handle it.
1351 if (!GEP->hasAllConstantIndices())
1352 return false;
Chris Lattnercf321862009-01-07 06:39:58 +00001353
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001354 // Compute the offset that this GEP adds to the pointer.
1355 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1356 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1357 &Indices[0], Indices.size());
1358 // See if all uses can be converted.
Chris Lattner1a3257b2009-02-03 18:15:05 +00001359 if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001360 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001361 return false;
1362 IsNotTrivial = true;
1363 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001364 }
Chris Lattner3ce5e882009-03-08 03:37:16 +00001365
Chris Lattner3d730f72009-02-03 02:01:43 +00001366 // If this is a constant sized memset of a constant value (e.g. 0) we can
1367 // handle it.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001368 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1369 // Store of constant value and constant size.
1370 if (isa<ConstantInt>(MSI->getValue()) &&
1371 isa<ConstantInt>(MSI->getLength())) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001372 IsNotTrivial = true;
1373 continue;
1374 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001375 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001376
1377 // If this is a memcpy or memmove into or out of the whole allocation, we
1378 // can handle it like a load or store of the scalar type.
1379 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1380 if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
1381 if (Len->getZExtValue() == AllocaSize && Offset == 0) {
1382 IsNotTrivial = true;
1383 continue;
1384 }
1385 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001386
Devang Patel00e389c2009-03-06 07:03:54 +00001387 // Ignore dbg intrinsic.
1388 if (isa<DbgInfoIntrinsic>(User))
1389 continue;
1390
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001391 // Otherwise, we cannot handle this!
1392 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001393 }
1394
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001395 return true;
Chris Lattnera1888942005-12-12 07:19:13 +00001396}
1397
Chris Lattnera1888942005-12-12 07:19:13 +00001398
1399/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattnerde6df882006-04-14 21:42:41 +00001400/// directly. This happens when we are converting an "integer union" to a
1401/// single integer scalar, or when we are converting a "vector union" to a
1402/// vector with insert/extractelement instructions.
1403///
1404/// Offset is an offset from the original alloca, in bits that need to be
1405/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001406void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
Chris Lattnera1888942005-12-12 07:19:13 +00001407 while (!Ptr->use_empty()) {
1408 Instruction *User = cast<Instruction>(Ptr->use_back());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001409
Chris Lattnercf321862009-01-07 06:39:58 +00001410 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb10e0da2008-01-30 00:39:15 +00001411 ConvertUsesToScalar(CI, NewAI, Offset);
Chris Lattnera1888942005-12-12 07:19:13 +00001412 CI->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001413 continue;
1414 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001415
Chris Lattnercf321862009-01-07 06:39:58 +00001416 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001417 // Compute the offset that this GEP adds to the pointer.
1418 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1419 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1420 &Indices[0], Indices.size());
1421 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
Chris Lattnera1888942005-12-12 07:19:13 +00001422 GEP->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001423 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001424 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001425
Chris Lattner9bc67da2009-02-03 19:45:44 +00001426 IRBuilder<> Builder(User->getParent(), User);
1427
1428 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner6e011152009-02-03 21:01:03 +00001429 // The load is a bit extract from NewAI shifted right by Offset bits.
1430 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1431 Value *NewLoadVal
1432 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1433 LI->replaceAllUsesWith(NewLoadVal);
Chris Lattner9bc67da2009-02-03 19:45:44 +00001434 LI->eraseFromParent();
1435 continue;
1436 }
1437
1438 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1439 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1440 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").c_str());
1441 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1442 Builder);
1443 Builder.CreateStore(New, NewAI);
1444 SI->eraseFromParent();
1445 continue;
1446 }
1447
Chris Lattner3d730f72009-02-03 02:01:43 +00001448 // If this is a constant sized memset of a constant value (e.g. 0) we can
1449 // transform it into a store of the expanded constant value.
1450 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1451 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1452 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
Chris Lattner33e24ad2009-04-21 16:52:12 +00001453 if (NumBytes != 0) {
1454 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1455
1456 // Compute the value replicated the right number of times.
1457 APInt APVal(NumBytes*8, Val);
Chris Lattner3d730f72009-02-03 02:01:43 +00001458
Chris Lattner33e24ad2009-04-21 16:52:12 +00001459 // Splat the value if non-zero.
1460 if (Val)
1461 for (unsigned i = 1; i != NumBytes; ++i)
1462 APVal |= APVal << 8;
1463
1464 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").c_str());
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001465 Value *New = ConvertScalar_InsertValue(Context->getConstantInt(APVal),
1466 Old, Offset, Builder);
Chris Lattner33e24ad2009-04-21 16:52:12 +00001467 Builder.CreateStore(New, NewAI);
1468 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001469 MSI->eraseFromParent();
1470 continue;
1471 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001472
1473 // If this is a memcpy or memmove into or out of the whole allocation, we
1474 // can handle it like a load or store of the scalar type.
1475 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1476 assert(Offset == 0 && "must be store to start of alloca");
1477
1478 // If the source and destination are both to the same alloca, then this is
1479 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
1480 // as appropriate.
1481 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject());
1482
1483 if (MTI->getSource()->getUnderlyingObject() != OrigAI) {
1484 // Dest must be OrigAI, change this to be a load from the original
1485 // pointer (bitcasted), then a store to our new alloca.
1486 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
1487 Value *SrcPtr = MTI->getSource();
1488 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
1489
1490 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
1491 SrcVal->setAlignment(MTI->getAlignment());
1492 Builder.CreateStore(SrcVal, NewAI);
1493 } else if (MTI->getDest()->getUnderlyingObject() != OrigAI) {
1494 // Src must be OrigAI, change this to be a load from NewAI then a store
1495 // through the original dest pointer (bitcasted).
1496 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
1497 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
1498
1499 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
1500 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
1501 NewStore->setAlignment(MTI->getAlignment());
1502 } else {
1503 // Noop transfer. Src == Dst
1504 }
1505
1506
1507 MTI->eraseFromParent();
1508 continue;
1509 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001510
Devang Patel00e389c2009-03-06 07:03:54 +00001511 // If user is a dbg info intrinsic then it is safe to remove it.
1512 if (isa<DbgInfoIntrinsic>(User)) {
1513 User->eraseFromParent();
1514 continue;
1515 }
1516
Torok Edwinc23197a2009-07-14 16:55:14 +00001517 llvm_unreachable("Unsupported operation!");
Chris Lattnera1888942005-12-12 07:19:13 +00001518 }
1519}
Chris Lattner79b3bd32007-04-25 06:40:51 +00001520
Chris Lattner6e011152009-02-03 21:01:03 +00001521/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1522/// or vector value FromVal, extracting the bits from the offset specified by
1523/// Offset. This returns the value, which is of type ToType.
1524///
1525/// This happens when we are converting an "integer union" to a single
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001526/// integer scalar, or when we are converting a "vector union" to a vector with
1527/// insert/extractelement instructions.
Chris Lattner800de312008-02-29 07:03:13 +00001528///
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001529/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner6e011152009-02-03 21:01:03 +00001530/// shifted to the right.
1531Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1532 uint64_t Offset, IRBuilder<> &Builder) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001533 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattner6e011152009-02-03 21:01:03 +00001534 if (FromVal->getType() == ToType && Offset == 0)
1535 return FromVal;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001536
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001537 // If the result alloca is a vector type, this is either an element
1538 // access or a bitcast to another vector type of the same size.
Chris Lattner6e011152009-02-03 21:01:03 +00001539 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1540 if (isa<VectorType>(ToType))
1541 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001542
1543 // Otherwise it must be an element access.
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001544 unsigned Elt = 0;
1545 if (Offset) {
Duncan Sands777d2302009-05-09 07:06:46 +00001546 unsigned EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001547 Elt = Offset/EltSize;
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001548 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Chris Lattner800de312008-02-29 07:03:13 +00001549 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001550 // Return the element extracted out of it.
Chris Lattner6e011152009-02-03 21:01:03 +00001551 Value *V = Builder.CreateExtractElement(FromVal,
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001552 Context->getConstantInt(Type::Int32Ty,Elt),
Chris Lattner9bc67da2009-02-03 19:45:44 +00001553 "tmp");
Chris Lattner6e011152009-02-03 21:01:03 +00001554 if (V->getType() != ToType)
1555 V = Builder.CreateBitCast(V, ToType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001556 return V;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001557 }
Chris Lattner1aa70562009-02-03 21:08:45 +00001558
1559 // If ToType is a first class aggregate, extract out each of the pieces and
1560 // use insertvalue's to form the FCA.
1561 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1562 const StructLayout &Layout = *TD->getStructLayout(ST);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001563 Value *Res = Context->getUndef(ST);
Chris Lattner1aa70562009-02-03 21:08:45 +00001564 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1565 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
Chris Lattnere991ced2009-02-06 04:34:07 +00001566 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner1aa70562009-02-03 21:08:45 +00001567 Builder);
1568 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1569 }
1570 return Res;
1571 }
1572
1573 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001574 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001575 Value *Res = Context->getUndef(AT);
Chris Lattner1aa70562009-02-03 21:08:45 +00001576 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1577 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1578 Offset+i*EltSize, Builder);
1579 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1580 }
1581 return Res;
1582 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001583
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001584 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattner6e011152009-02-03 21:01:03 +00001585 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001586
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001587 // If this is a big-endian system and the load is narrower than the
1588 // full alloca type, we need to do a shift to get the right bits.
1589 int ShAmt = 0;
Chris Lattner56c38522009-01-07 06:34:28 +00001590 if (TD->isBigEndian()) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001591 // On big-endian machines, the lowest bit is stored at the bit offset
1592 // from the pointer given by getTypeStoreSizeInBits. This matters for
1593 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner56c38522009-01-07 06:34:28 +00001594 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
Chris Lattner6e011152009-02-03 21:01:03 +00001595 TD->getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001596 } else {
1597 ShAmt = Offset;
1598 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001599
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001600 // Note: we support negative bitwidths (with shl) which are not defined.
1601 // We do this to support (f.e.) loads off the end of a structure where
1602 // only some bits are used.
1603 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001604 FromVal = Builder.CreateLShr(FromVal,
1605 Context->getConstantInt(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001606 ShAmt), "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001607 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001608 FromVal = Builder.CreateShl(FromVal,
1609 Context->getConstantInt(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001610 -ShAmt), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001611
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001612 // Finally, unconditionally truncate the integer to the right width.
Chris Lattner6e011152009-02-03 21:01:03 +00001613 unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001614 if (LIBitWidth < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001615 FromVal =
1616 Builder.CreateTrunc(FromVal, Context->getIntegerType(LIBitWidth), "tmp");
Chris Lattner55a683d2009-02-03 07:08:57 +00001617 else if (LIBitWidth > NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001618 FromVal =
1619 Builder.CreateZExt(FromVal, Context->getIntegerType(LIBitWidth), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001620
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001621 // If the result is an integer, this is a trunc or bitcast.
Chris Lattner6e011152009-02-03 21:01:03 +00001622 if (isa<IntegerType>(ToType)) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001623 // Should be done.
Chris Lattner6e011152009-02-03 21:01:03 +00001624 } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001625 // Just do a bitcast, we know the sizes match up.
Chris Lattner6e011152009-02-03 21:01:03 +00001626 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001627 } else {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001628 // Otherwise must be a pointer.
Chris Lattner6e011152009-02-03 21:01:03 +00001629 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001630 }
Chris Lattner6e011152009-02-03 21:01:03 +00001631 assert(FromVal->getType() == ToType && "Didn't convert right?");
1632 return FromVal;
Chris Lattner800de312008-02-29 07:03:13 +00001633}
1634
1635
Chris Lattner9b872db2009-02-03 19:30:11 +00001636/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1637/// or vector value "Old" at the offset specified by Offset.
1638///
1639/// This happens when we are converting an "integer union" to a
Chris Lattner800de312008-02-29 07:03:13 +00001640/// single integer scalar, or when we are converting a "vector union" to a
1641/// vector with insert/extractelement instructions.
1642///
1643/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner9b872db2009-02-03 19:30:11 +00001644/// shifted to the right.
1645Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
Chris Lattner65a65022009-02-03 19:41:50 +00001646 uint64_t Offset, IRBuilder<> &Builder) {
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001647
Chris Lattner800de312008-02-29 07:03:13 +00001648 // Convert the stored type to the actual type, shift it left to insert
1649 // then 'or' into place.
Chris Lattner9b872db2009-02-03 19:30:11 +00001650 const Type *AllocaType = Old->getType();
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001651
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001652 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001653 uint64_t VecSize = TD->getTypeAllocSizeInBits(VTy);
1654 uint64_t ValSize = TD->getTypeAllocSizeInBits(SV->getType());
Chris Lattner29e64172009-03-08 04:17:04 +00001655
1656 // Changing the whole vector with memset or with an access of a different
1657 // vector type?
1658 if (ValSize == VecSize)
1659 return Builder.CreateBitCast(SV, AllocaType, "tmp");
1660
Duncan Sands777d2302009-05-09 07:06:46 +00001661 uint64_t EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner29e64172009-03-08 04:17:04 +00001662
1663 // Must be an element insertion.
1664 unsigned Elt = Offset/EltSize;
1665
1666 if (SV->getType() != VTy->getElementType())
1667 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1668
1669 SV = Builder.CreateInsertElement(Old, SV,
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001670 Context->getConstantInt(Type::Int32Ty, Elt),
Chris Lattner29e64172009-03-08 04:17:04 +00001671 "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001672 return SV;
1673 }
Chris Lattner9b872db2009-02-03 19:30:11 +00001674
1675 // If SV is a first-class aggregate value, insert each value recursively.
1676 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1677 const StructLayout &Layout = *TD->getStructLayout(ST);
1678 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001679 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Chris Lattner9b872db2009-02-03 19:30:11 +00001680 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattnere991ced2009-02-06 04:34:07 +00001681 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner65a65022009-02-03 19:41:50 +00001682 Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001683 }
1684 return Old;
1685 }
1686
1687 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Duncan Sands777d2302009-05-09 07:06:46 +00001688 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner9b872db2009-02-03 19:30:11 +00001689 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001690 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1691 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001692 }
1693 return Old;
1694 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001695
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001696 // If SV is a float, convert it to the appropriate integer type.
Chris Lattner9b872db2009-02-03 19:30:11 +00001697 // If it is a pointer, do the same.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001698 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1699 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1700 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1701 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1702 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001703 SV = Builder.CreateBitCast(SV, Context->getIntegerType(SrcWidth), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001704 else if (isa<PointerType>(SV->getType()))
Chris Lattner65a65022009-02-03 19:41:50 +00001705 SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001706
Chris Lattner7809ecd2009-02-03 01:30:09 +00001707 // Zero extend or truncate the value if needed.
1708 if (SV->getType() != AllocaType) {
1709 if (SV->getType()->getPrimitiveSizeInBits() <
1710 AllocaType->getPrimitiveSizeInBits())
Chris Lattner65a65022009-02-03 19:41:50 +00001711 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001712 else {
1713 // Truncation may be needed if storing more than the alloca can hold
1714 // (undefined behavior).
Chris Lattner65a65022009-02-03 19:41:50 +00001715 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001716 SrcWidth = DestWidth;
1717 SrcStoreWidth = DestStoreWidth;
1718 }
1719 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001720
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001721 // If this is a big-endian system and the store is narrower than the
1722 // full alloca type, we need to do a shift to get the right bits.
1723 int ShAmt = 0;
1724 if (TD->isBigEndian()) {
1725 // On big-endian machines, the lowest bit is stored at the bit offset
1726 // from the pointer given by getTypeStoreSizeInBits. This matters for
1727 // integers with a bitwidth that is not a multiple of 8.
1728 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
Chris Lattner800de312008-02-29 07:03:13 +00001729 } else {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001730 ShAmt = Offset;
1731 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001732
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001733 // Note: we support negative bitwidths (with shr) which are not defined.
1734 // We do this to support (f.e.) stores off the end of a structure where
1735 // only some bits in the structure are set.
1736 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1737 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001738 SV = Builder.CreateShl(SV, Context->getConstantInt(SV->getType(),
1739 ShAmt), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001740 Mask <<= ShAmt;
1741 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001742 SV = Builder.CreateLShr(SV, Context->getConstantInt(SV->getType(),
1743 -ShAmt), "tmp");
Duncan Sands0e7c46b2009-02-02 09:53:14 +00001744 Mask = Mask.lshr(-ShAmt);
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001745 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001746
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001747 // Mask out the bits we are about to insert from the old value, and or
1748 // in the new bits.
1749 if (SrcWidth != DestWidth) {
1750 assert(DestWidth > SrcWidth);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001751 Old = Builder.CreateAnd(Old, Context->getConstantInt(~Mask), "mask");
Chris Lattner65a65022009-02-03 19:41:50 +00001752 SV = Builder.CreateOr(Old, SV, "ins");
Chris Lattner800de312008-02-29 07:03:13 +00001753 }
1754 return SV;
1755}
1756
1757
Chris Lattner79b3bd32007-04-25 06:40:51 +00001758
1759/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1760/// some part of a constant global variable. This intentionally only accepts
1761/// constant expressions because we don't can't rewrite arbitrary instructions.
1762static bool PointsToConstantGlobal(Value *V) {
1763 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1764 return GV->isConstant();
1765 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1766 if (CE->getOpcode() == Instruction::BitCast ||
1767 CE->getOpcode() == Instruction::GetElementPtr)
1768 return PointsToConstantGlobal(CE->getOperand(0));
1769 return false;
1770}
1771
1772/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1773/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1774/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1775/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1776/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1777/// the alloca, and if the source pointer is a pointer to a constant global, we
1778/// can optimize this.
1779static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1780 bool isOffset) {
1781 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Chris Lattner6e733d32009-01-28 20:16:43 +00001782 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1783 // Ignore non-volatile loads, they are always ok.
1784 if (!LI->isVolatile())
1785 continue;
1786
Chris Lattner79b3bd32007-04-25 06:40:51 +00001787 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1788 // If uses of the bitcast are ok, we are ok.
1789 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1790 return false;
1791 continue;
1792 }
1793 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1794 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1795 // doesn't, it does.
1796 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1797 isOffset || !GEP->hasAllZeroIndices()))
1798 return false;
1799 continue;
1800 }
1801
1802 // If this is isn't our memcpy/memmove, reject it as something we can't
1803 // handle.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001804 if (!isa<MemTransferInst>(*UI))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001805 return false;
1806
1807 // If we already have seen a copy, reject the second one.
1808 if (TheCopy) return false;
1809
1810 // If the pointer has been offset from the start of the alloca, we can't
1811 // safely handle this.
1812 if (isOffset) return false;
1813
1814 // If the memintrinsic isn't using the alloca as the dest, reject it.
1815 if (UI.getOperandNo() != 1) return false;
1816
1817 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1818
1819 // If the source of the memcpy/move is not a constant global, reject it.
1820 if (!PointsToConstantGlobal(MI->getOperand(2)))
1821 return false;
1822
1823 // Otherwise, the transform is safe. Remember the copy instruction.
1824 TheCopy = MI;
1825 }
1826 return true;
1827}
1828
1829/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1830/// modified by a copy from a constant global. If we can prove this, we can
1831/// replace any uses of the alloca with uses of the global directly.
1832Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1833 Instruction *TheCopy = 0;
1834 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1835 return TheCopy;
1836 return 0;
1837}