blob: 29970ecb444fcd6e13caa854ef83e869b247aa01 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
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
13// 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.
19//
20//===----------------------------------------------------------------------===//
21
22#define DEBUG_TYPE "scalarrepl"
23#include "llvm/Transforms/Scalar.h"
24#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
26#include "llvm/Function.h"
27#include "llvm/GlobalVariable.h"
28#include "llvm/Instructions.h"
29#include "llvm/IntrinsicInst.h"
30#include "llvm/Pass.h"
31#include "llvm/Analysis/Dominators.h"
32#include "llvm/Target/TargetData.h"
33#include "llvm/Transforms/Utils/PromoteMemToReg.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/GetElementPtrTypeIterator.h"
36#include "llvm/Support/MathExtras.h"
37#include "llvm/Support/Compiler.h"
38#include "llvm/ADT/SmallVector.h"
39#include "llvm/ADT/Statistic.h"
40#include "llvm/ADT/StringExtras.h"
41using namespace llvm;
42
43STATISTIC(NumReplaced, "Number of allocas broken up");
44STATISTIC(NumPromoted, "Number of allocas promoted");
45STATISTIC(NumConverted, "Number of aggregates converted to scalar");
46STATISTIC(NumGlobals, "Number of allocas copied from constant global");
47
48namespace {
49 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
50 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000051 explicit SROA(signed T = -1) : FunctionPass(&ID) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000052 if (T == -1)
Chris Lattner6d7faec2007-08-02 21:33:36 +000053 SRThreshold = 128;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000054 else
55 SRThreshold = T;
56 }
57
58 bool runOnFunction(Function &F);
59
60 bool performScalarRepl(Function &F);
61 bool performPromotion(Function &F);
62
63 // getAnalysisUsage - This pass does not require any passes, but we know it
64 // will not alter the CFG, so say so.
65 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
66 AU.addRequired<DominatorTree>();
67 AU.addRequired<DominanceFrontier>();
68 AU.addRequired<TargetData>();
69 AU.setPreservesCFG();
70 }
71
72 private:
Chris Lattner3fd59362009-01-07 06:34:28 +000073 TargetData *TD;
74
Dan Gohmanf17a25c2007-07-18 16:29:46 +000075 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
76 /// information about the uses. All these fields are initialized to false
77 /// and set to true when something is learned.
78 struct AllocaInfo {
79 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
80 bool isUnsafe : 1;
81
82 /// needsCanon - This is set to true if there is some use of the alloca
83 /// that requires canonicalization.
84 bool needsCanon : 1;
85
86 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
87 bool isMemCpySrc : 1;
88
89 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
90 bool isMemCpyDst : 1;
91
92 AllocaInfo()
93 : isUnsafe(false), needsCanon(false),
94 isMemCpySrc(false), isMemCpyDst(false) {}
95 };
96
97 unsigned SRThreshold;
98
99 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
100
101 int isSafeAllocaToScalarRepl(AllocationInst *AI);
102
103 void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
104 AllocaInfo &Info);
105 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
106 AllocaInfo &Info);
107 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
108 unsigned OpNo, AllocaInfo &Info);
109 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
110 AllocaInfo &Info);
111
112 void DoScalarReplacement(AllocationInst *AI,
113 std::vector<AllocationInst*> &WorkList);
114 void CanonicalizeAllocaUsers(AllocationInst *AI);
115 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
116
117 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
118 SmallVector<AllocaInst*, 32> &NewElts);
119
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000120 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
121 AllocationInst *AI,
122 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattner71c75342009-01-07 08:11:13 +0000123 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocationInst *AI,
124 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattner28401db2009-01-08 05:42:05 +0000125 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
Chris Lattner70ffe572009-01-28 20:16:43 +0000126 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000127
Chris Lattner4b9c8b72009-01-31 02:28:54 +0000128 bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&ResTy,
129 uint64_t Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000130 void ConvertToScalar(AllocationInst *AI, const Type *Ty);
Chris Lattner4b9c8b72009-01-31 02:28:54 +0000131 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Chris Lattner41d58652008-02-29 07:03:13 +0000132 Value *ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
Chris Lattner4b9c8b72009-01-31 02:28:54 +0000133 uint64_t Offset);
Chris Lattner41d58652008-02-29 07:03:13 +0000134 Value *ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
Chris Lattner4b9c8b72009-01-31 02:28:54 +0000135 uint64_t Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
137 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138}
139
Dan Gohman089efff2008-05-13 00:00:25 +0000140char SROA::ID = 0;
141static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
142
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000143// Public interface to the ScalarReplAggregates pass
144FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
145 return new SROA(Threshold);
146}
147
148
149bool SROA::runOnFunction(Function &F) {
Chris Lattner3fd59362009-01-07 06:34:28 +0000150 TD = &getAnalysis<TargetData>();
151
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000152 bool Changed = performPromotion(F);
153 while (1) {
154 bool LocalChange = performScalarRepl(F);
155 if (!LocalChange) break; // No need to repromote if no scalarrepl
156 Changed = true;
157 LocalChange = performPromotion(F);
158 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
159 }
160
161 return Changed;
162}
163
164
165bool SROA::performPromotion(Function &F) {
166 std::vector<AllocaInst*> Allocas;
167 DominatorTree &DT = getAnalysis<DominatorTree>();
168 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
169
170 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
171
172 bool Changed = false;
173
174 while (1) {
175 Allocas.clear();
176
177 // Find allocas that are safe to promote, by looking at all instructions in
178 // the entry node
179 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
180 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
181 if (isAllocaPromotable(AI))
182 Allocas.push_back(AI);
183
184 if (Allocas.empty()) break;
185
186 PromoteMemToReg(Allocas, DT, DF);
187 NumPromoted += Allocas.size();
188 Changed = true;
189 }
190
191 return Changed;
192}
193
Chris Lattner0e99e692008-06-22 17:46:21 +0000194/// getNumSAElements - Return the number of elements in the specific struct or
195/// array.
196static uint64_t getNumSAElements(const Type *T) {
197 if (const StructType *ST = dyn_cast<StructType>(T))
198 return ST->getNumElements();
199 return cast<ArrayType>(T)->getNumElements();
200}
201
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000202// performScalarRepl - This algorithm is a simple worklist driven algorithm,
203// which runs on all of the malloc/alloca instructions in the function, removing
204// them if they are only used by getelementptr instructions.
205//
206bool SROA::performScalarRepl(Function &F) {
207 std::vector<AllocationInst*> WorkList;
208
209 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
210 BasicBlock &BB = F.getEntryBlock();
211 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
212 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
213 WorkList.push_back(A);
214
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215 // Process the worklist
216 bool Changed = false;
217 while (!WorkList.empty()) {
218 AllocationInst *AI = WorkList.back();
219 WorkList.pop_back();
220
221 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
222 // with unused elements.
223 if (AI->use_empty()) {
224 AI->eraseFromParent();
225 continue;
226 }
227
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 // Check to see if we can perform the core SROA transformation. We cannot
229 // transform the allocation instruction if it is an array allocation
230 // (allocations OF arrays are ok though), and an allocation of a scalar
231 // value cannot be decomposed at all.
232 if (!AI->isArrayAllocation() &&
233 (isa<StructType>(AI->getAllocatedType()) ||
234 isa<ArrayType>(AI->getAllocatedType())) &&
235 AI->getAllocatedType()->isSized() &&
Chris Lattner0e99e692008-06-22 17:46:21 +0000236 // Do not promote any struct whose size is larger than "128" bytes.
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000237 TD->getTypePaddedSize(AI->getAllocatedType()) < SRThreshold &&
Chris Lattner0e99e692008-06-22 17:46:21 +0000238 // Do not promote any struct into more than "32" separate vars.
239 getNumSAElements(AI->getAllocatedType()) < SRThreshold/4) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000240 // Check that all of the users of the allocation are capable of being
241 // transformed.
242 switch (isSafeAllocaToScalarRepl(AI)) {
243 default: assert(0 && "Unexpected value!");
244 case 0: // Not safe to scalar replace.
245 break;
246 case 1: // Safe, but requires cleanup/canonicalizations first
247 CanonicalizeAllocaUsers(AI);
248 // FALL THROUGH.
249 case 3: // Safe to scalar replace.
250 DoScalarReplacement(AI, WorkList);
251 Changed = true;
252 continue;
253 }
254 }
255
256 // Check to see if this allocation is only modified by a memcpy/memmove from
257 // a constant global. If this is the case, we can change all users to use
258 // the constant global instead. This is commonly produced by the CFE by
259 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
260 // is only subsequently read.
261 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
262 DOUT << "Found alloca equal to global: " << *AI;
263 DOUT << " memcpy = " << *TheCopy;
264 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
265 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
266 TheCopy->eraseFromParent(); // Don't mutate the global.
267 AI->eraseFromParent();
268 ++NumGlobals;
269 Changed = true;
270 continue;
271 }
Chris Lattner70ffe572009-01-28 20:16:43 +0000272
273 // If we can turn this aggregate value (potentially with casts) into a
274 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner4b9c8b72009-01-31 02:28:54 +0000275 // IsNotTrivial tracks whether this is something that mem2reg could have
276 // promoted itself. If so, we don't want to transform it needlessly. Note
277 // that we can't just check based on the type: the alloca may be of an i32
278 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner70ffe572009-01-28 20:16:43 +0000279 bool IsNotTrivial = false;
Chris Lattner4b9c8b72009-01-31 02:28:54 +0000280 const Type *ActualType = 0;
281 if (CanConvertToScalar(AI, IsNotTrivial, ActualType, 0))
282 if (IsNotTrivial && ActualType &&
283 TD->getTypeSizeInBits(ActualType) < SRThreshold*8) {
Chris Lattner70ffe572009-01-28 20:16:43 +0000284 ConvertToScalar(AI, ActualType);
285 Changed = true;
286 continue;
287 }
288
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000289 // Otherwise, couldn't process this.
290 }
291
292 return Changed;
293}
294
295/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
296/// predicate, do SROA now.
297void SROA::DoScalarReplacement(AllocationInst *AI,
298 std::vector<AllocationInst*> &WorkList) {
299 DOUT << "Found inst to SROA: " << *AI;
300 SmallVector<AllocaInst*, 32> ElementAllocas;
301 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
302 ElementAllocas.reserve(ST->getNumContainedTypes());
303 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
304 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
305 AI->getAlignment(),
306 AI->getName() + "." + utostr(i), AI);
307 ElementAllocas.push_back(NA);
308 WorkList.push_back(NA); // Add to worklist for recursive processing
309 }
310 } else {
311 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
312 ElementAllocas.reserve(AT->getNumElements());
313 const Type *ElTy = AT->getElementType();
314 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
315 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
316 AI->getName() + "." + utostr(i), AI);
317 ElementAllocas.push_back(NA);
318 WorkList.push_back(NA); // Add to worklist for recursive processing
319 }
320 }
321
322 // Now that we have created the alloca instructions that we want to use,
323 // expand the getelementptr instructions to use them.
324 //
325 while (!AI->use_empty()) {
326 Instruction *User = cast<Instruction>(AI->use_back());
327 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
328 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
329 BCInst->eraseFromParent();
330 continue;
331 }
332
Chris Lattner19e61a42008-06-23 17:11:23 +0000333 // Replace:
334 // %res = load { i32, i32 }* %alloc
335 // with:
336 // %load.0 = load i32* %alloc.0
337 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
338 // %load.1 = load i32* %alloc.1
339 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000340 // (Also works for arrays instead of structs)
341 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
342 Value *Insert = UndefValue::get(LI->getType());
343 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
344 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
345 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
346 }
347 LI->replaceAllUsesWith(Insert);
348 LI->eraseFromParent();
349 continue;
350 }
351
Chris Lattner19e61a42008-06-23 17:11:23 +0000352 // Replace:
353 // store { i32, i32 } %val, { i32, i32 }* %alloc
354 // with:
355 // %val.0 = extractvalue { i32, i32 } %val, 0
356 // store i32 %val.0, i32* %alloc.0
357 // %val.1 = extractvalue { i32, i32 } %val, 1
358 // store i32 %val.1, i32* %alloc.1
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000359 // (Also works for arrays instead of structs)
360 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
361 Value *Val = SI->getOperand(0);
362 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
363 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
364 new StoreInst(Extract, ElementAllocas[i], SI);
365 }
366 SI->eraseFromParent();
367 continue;
368 }
369
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000370 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
371 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
372 unsigned Idx =
373 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
374
375 assert(Idx < ElementAllocas.size() && "Index out of range?");
376 AllocaInst *AllocaToUse = ElementAllocas[Idx];
377
378 Value *RepValue;
379 if (GEPI->getNumOperands() == 3) {
380 // Do not insert a new getelementptr instruction with zero indices, only
381 // to have it optimized out later.
382 RepValue = AllocaToUse;
383 } else {
384 // We are indexing deeply into the structure, so we still need a
385 // getelement ptr instruction to finish the indexing. This may be
386 // expanded itself once the worklist is rerun.
387 //
388 SmallVector<Value*, 8> NewArgs;
389 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
390 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
Gabor Greifd6da1d02008-04-06 20:25:17 +0000391 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
392 NewArgs.end(), "", GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393 RepValue->takeName(GEPI);
394 }
395
396 // If this GEP is to the start of the aggregate, check for memcpys.
Chris Lattner85591c62009-01-07 06:25:07 +0000397 if (Idx == 0 && GEPI->hasAllZeroIndices())
398 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399
400 // Move all of the users over to the new GEP.
401 GEPI->replaceAllUsesWith(RepValue);
402 // Delete the old GEP
403 GEPI->eraseFromParent();
404 }
405
406 // Finally, delete the Alloca instruction
407 AI->eraseFromParent();
408 NumReplaced++;
409}
410
411
412/// isSafeElementUse - Check to see if this use is an allowed use for a
413/// getelementptr instruction of an array aggregate allocation. isFirstElt
414/// indicates whether Ptr is known to the start of the aggregate.
415///
416void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
417 AllocaInfo &Info) {
418 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
419 I != E; ++I) {
420 Instruction *User = cast<Instruction>(*I);
421 switch (User->getOpcode()) {
422 case Instruction::Load: break;
423 case Instruction::Store:
424 // Store is ok if storing INTO the pointer, not storing the pointer
425 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
426 break;
427 case Instruction::GetElementPtr: {
428 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
429 bool AreAllZeroIndices = isFirstElt;
430 if (GEP->getNumOperands() > 1) {
431 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
432 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
433 // Using pointer arithmetic to navigate the array.
434 return MarkUnsafe(Info);
435
Chris Lattner85591c62009-01-07 06:25:07 +0000436 if (AreAllZeroIndices)
437 AreAllZeroIndices = GEP->hasAllZeroIndices();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000438 }
439 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
440 if (Info.isUnsafe) return;
441 break;
442 }
443 case Instruction::BitCast:
444 if (isFirstElt) {
445 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
446 if (Info.isUnsafe) return;
447 break;
448 }
449 DOUT << " Transformation preventing inst: " << *User;
450 return MarkUnsafe(Info);
451 case Instruction::Call:
452 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
453 if (isFirstElt) {
454 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
455 if (Info.isUnsafe) return;
456 break;
457 }
458 }
459 DOUT << " Transformation preventing inst: " << *User;
460 return MarkUnsafe(Info);
461 default:
462 DOUT << " Transformation preventing inst: " << *User;
463 return MarkUnsafe(Info);
464 }
465 }
466 return; // All users look ok :)
467}
468
469/// AllUsersAreLoads - Return true if all users of this value are loads.
470static bool AllUsersAreLoads(Value *Ptr) {
471 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
472 I != E; ++I)
473 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
474 return false;
475 return true;
476}
477
478/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
479/// aggregate allocation.
480///
481void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
482 AllocaInfo &Info) {
483 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
484 return isSafeUseOfBitCastedAllocation(C, AI, Info);
485
Chris Lattner70ffe572009-01-28 20:16:43 +0000486 if (LoadInst *LI = dyn_cast<LoadInst>(User))
487 if (!LI->isVolatile())
488 return;// Loads (returning a first class aggregrate) are always rewritable
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000489
Chris Lattner70ffe572009-01-28 20:16:43 +0000490 if (StoreInst *SI = dyn_cast<StoreInst>(User))
491 if (!SI->isVolatile() && SI->getOperand(0) != AI)
492 return;// Store is ok if storing INTO the pointer, not storing the pointer
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000493
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000494 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
495 if (GEPI == 0)
496 return MarkUnsafe(Info);
497
498 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
499
500 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
501 if (I == E ||
502 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
503 return MarkUnsafe(Info);
504 }
505
506 ++I;
507 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
508
509 bool IsAllZeroIndices = true;
510
Chris Lattnerd324da02008-08-23 05:21:06 +0000511 // If the first index is a non-constant index into an array, see if we can
512 // handle it as a special case.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000513 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
Chris Lattnerd324da02008-08-23 05:21:06 +0000514 if (!isa<ConstantInt>(I.getOperand())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000515 IsAllZeroIndices = 0;
Chris Lattnerd324da02008-08-23 05:21:06 +0000516 uint64_t NumElements = AT->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000517
518 // If this is an array index and the index is not constant, we cannot
519 // promote... that is unless the array has exactly one or two elements in
520 // it, in which case we CAN promote it, but we have to canonicalize this
521 // out if this is the only problem.
522 if ((NumElements == 1 || NumElements == 2) &&
523 AllUsersAreLoads(GEPI)) {
524 Info.needsCanon = true;
525 return; // Canonicalization required!
526 }
527 return MarkUnsafe(Info);
528 }
529 }
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000530
Chris Lattnerd324da02008-08-23 05:21:06 +0000531 // Walk through the GEP type indices, checking the types that this indexes
532 // into.
533 for (; I != E; ++I) {
534 // Ignore struct elements, no extra checking needed for these.
535 if (isa<StructType>(*I))
536 continue;
537
Chris Lattnerd324da02008-08-23 05:21:06 +0000538 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
539 if (!IdxVal) return MarkUnsafe(Info);
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000540
541 // Are all indices still zero?
Chris Lattnerd324da02008-08-23 05:21:06 +0000542 IsAllZeroIndices &= IdxVal->isZero();
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000543
544 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
545 // This GEP indexes an array. Verify that this is an in-range constant
546 // integer. Specifically, consider A[0][i]. We cannot know that the user
547 // isn't doing invalid things like allowing i to index an out-of-range
548 // subscript that accesses A[1]. Because of this, we have to reject SROA
Dale Johannesen1f9b1862008-11-04 20:54:03 +0000549 // of any accesses into structs where any of the components are variables.
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000550 if (IdxVal->getZExtValue() >= AT->getNumElements())
551 return MarkUnsafe(Info);
Dale Johannesen1f9b1862008-11-04 20:54:03 +0000552 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
553 if (IdxVal->getZExtValue() >= VT->getNumElements())
554 return MarkUnsafe(Info);
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000555 }
Chris Lattnerd324da02008-08-23 05:21:06 +0000556 }
557
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000558 // If there are any non-simple uses of this getelementptr, make sure to reject
559 // them.
560 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
561}
562
563/// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
564/// intrinsic can be promoted by SROA. At this point, we know that the operand
565/// of the memintrinsic is a pointer to the beginning of the allocation.
566void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
567 unsigned OpNo, AllocaInfo &Info) {
568 // If not constant length, give up.
569 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
570 if (!Length) return MarkUnsafe(Info);
571
572 // If not the whole aggregate, give up.
Duncan Sandsae5fd622007-11-04 14:43:57 +0000573 if (Length->getZExtValue() !=
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000574 TD->getTypePaddedSize(AI->getType()->getElementType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000575 return MarkUnsafe(Info);
576
577 // We only know about memcpy/memset/memmove.
578 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
579 return MarkUnsafe(Info);
580
581 // Otherwise, we can transform it. Determine whether this is a memcpy/set
582 // into or out of the aggregate.
583 if (OpNo == 1)
584 Info.isMemCpyDst = true;
585 else {
586 assert(OpNo == 2);
587 Info.isMemCpySrc = true;
588 }
589}
590
591/// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
592/// are
593void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
594 AllocaInfo &Info) {
595 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
596 UI != E; ++UI) {
597 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
598 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
599 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
600 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
Chris Lattner71c75342009-01-07 08:11:13 +0000601 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner70ffe572009-01-28 20:16:43 +0000602 if (SI->isVolatile())
603 return MarkUnsafe(Info);
604
Chris Lattner71c75342009-01-07 08:11:13 +0000605 // If storing the entire alloca in one chunk through a bitcasted pointer
606 // to integer, we can transform it. This happens (for example) when you
607 // cast a {i32,i32}* to i64* and store through it. This is similar to the
608 // memcpy case and occurs in various "byval" cases and emulated memcpys.
609 if (isa<IntegerType>(SI->getOperand(0)->getType()) &&
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000610 TD->getTypePaddedSize(SI->getOperand(0)->getType()) ==
611 TD->getTypePaddedSize(AI->getType()->getElementType())) {
Chris Lattner71c75342009-01-07 08:11:13 +0000612 Info.isMemCpyDst = true;
613 continue;
614 }
615 return MarkUnsafe(Info);
Chris Lattner28401db2009-01-08 05:42:05 +0000616 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
Chris Lattner70ffe572009-01-28 20:16:43 +0000617 if (LI->isVolatile())
618 return MarkUnsafe(Info);
619
Chris Lattner28401db2009-01-08 05:42:05 +0000620 // If loading the entire alloca in one chunk through a bitcasted pointer
621 // to integer, we can transform it. This happens (for example) when you
622 // cast a {i32,i32}* to i64* and load through it. This is similar to the
623 // memcpy case and occurs in various "byval" cases and emulated memcpys.
624 if (isa<IntegerType>(LI->getType()) &&
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000625 TD->getTypePaddedSize(LI->getType()) ==
626 TD->getTypePaddedSize(AI->getType()->getElementType())) {
Chris Lattner28401db2009-01-08 05:42:05 +0000627 Info.isMemCpySrc = true;
628 continue;
629 }
630 return MarkUnsafe(Info);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000631 } else {
632 return MarkUnsafe(Info);
633 }
634 if (Info.isUnsafe) return;
635 }
636}
637
638/// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
639/// to its first element. Transform users of the cast to use the new values
640/// instead.
641void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
642 SmallVector<AllocaInst*, 32> &NewElts) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000643 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
644 while (UI != UE) {
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000645 Instruction *User = cast<Instruction>(*UI++);
646 if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000647 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
Chris Lattner71c75342009-01-07 08:11:13 +0000648 if (BCU->use_empty()) BCU->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000649 continue;
650 }
651
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000652 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
653 // This must be memcpy/memmove/memset of the entire aggregate.
654 // Split into one per element.
655 RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000656 continue;
657 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000658
Chris Lattner71c75342009-01-07 08:11:13 +0000659 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Chris Lattner28401db2009-01-08 05:42:05 +0000660 // If this is a store of the entire alloca from an integer, rewrite it.
Chris Lattner71c75342009-01-07 08:11:13 +0000661 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
662 continue;
663 }
Chris Lattner28401db2009-01-08 05:42:05 +0000664
665 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
666 // If this is a load of the entire alloca to an integer, rewrite it.
667 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
668 continue;
669 }
Chris Lattner71c75342009-01-07 08:11:13 +0000670
671 // Otherwise it must be some other user of a gep of the first pointer. Just
672 // leave these alone.
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000673 continue;
Chris Lattner28401db2009-01-08 05:42:05 +0000674 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000675}
676
677/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
678/// Rewrite it to copy or set the elements of the scalarized memory.
679void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
680 AllocationInst *AI,
681 SmallVector<AllocaInst*, 32> &NewElts) {
682
683 // If this is a memcpy/memmove, construct the other pointer as the
684 // appropriate type.
685 Value *OtherPtr = 0;
686 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
687 if (BCInst == MCI->getRawDest())
688 OtherPtr = MCI->getRawSource();
689 else {
690 assert(BCInst == MCI->getRawSource());
691 OtherPtr = MCI->getRawDest();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000692 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000693 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
694 if (BCInst == MMI->getRawDest())
695 OtherPtr = MMI->getRawSource();
696 else {
697 assert(BCInst == MMI->getRawSource());
698 OtherPtr = MMI->getRawDest();
699 }
700 }
701
702 // If there is an other pointer, we want to convert it to the same pointer
703 // type as AI has, so we can GEP through it safely.
704 if (OtherPtr) {
705 // It is likely that OtherPtr is a bitcast, if so, remove it.
706 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
707 OtherPtr = BC->getOperand(0);
708 // All zero GEPs are effectively bitcasts.
709 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
710 if (GEP->hasAllZeroIndices())
711 OtherPtr = GEP->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000712
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000713 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
714 if (BCE->getOpcode() == Instruction::BitCast)
715 OtherPtr = BCE->getOperand(0);
716
717 // If the pointer is not the right type, insert a bitcast to the right
718 // type.
719 if (OtherPtr->getType() != AI->getType())
720 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
721 MI);
722 }
723
724 // Process each element of the aggregate.
725 Value *TheFn = MI->getOperand(0);
726 const Type *BytePtrTy = MI->getRawDest()->getType();
727 bool SROADest = MI->getRawDest() == BCInst;
728
729 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
730
731 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
732 // If this is a memcpy/memmove, emit a GEP of the other element address.
733 Value *OtherElt = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000734 if (OtherPtr) {
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000735 Value *Idx[2] = { Zero, ConstantInt::get(Type::Int32Ty, i) };
736 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
Chris Lattner0e99e692008-06-22 17:46:21 +0000737 OtherPtr->getNameStr()+"."+utostr(i),
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000738 MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000739 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000740
741 Value *EltPtr = NewElts[i];
742 const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
743
744 // If we got down to a scalar, insert a load or store as appropriate.
745 if (EltTy->isSingleValueType()) {
746 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
747 Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
748 MI);
749 new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
750 continue;
751 }
752 assert(isa<MemSetInst>(MI));
753
754 // If the stored element is zero (common case), just store a null
755 // constant.
756 Constant *StoreVal;
757 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
758 if (CI->isZero()) {
759 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
760 } else {
761 // If EltTy is a vector type, get the element type.
762 const Type *ValTy = EltTy;
763 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
764 ValTy = VTy->getElementType();
765
766 // Construct an integer with the right value.
767 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
768 APInt OneVal(EltSize, CI->getZExtValue());
769 APInt TotalVal(OneVal);
770 // Set each byte.
771 for (unsigned i = 0; 8*i < EltSize; ++i) {
772 TotalVal = TotalVal.shl(8);
773 TotalVal |= OneVal;
774 }
775
776 // Convert the integer value to the appropriate type.
777 StoreVal = ConstantInt::get(TotalVal);
778 if (isa<PointerType>(ValTy))
779 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
780 else if (ValTy->isFloatingPoint())
781 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
782 assert(StoreVal->getType() == ValTy && "Type mismatch!");
783
784 // If the requested value was a vector constant, create it.
785 if (EltTy != ValTy) {
786 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
787 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
788 StoreVal = ConstantVector::get(&Elts[0], NumElts);
789 }
790 }
791 new StoreInst(StoreVal, EltPtr, MI);
792 continue;
793 }
794 // Otherwise, if we're storing a byte variable, use a memset call for
795 // this element.
796 }
797
798 // Cast the element pointer to BytePtrTy.
799 if (EltPtr->getType() != BytePtrTy)
800 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
801
802 // Cast the other pointer (if we have one) to BytePtrTy.
803 if (OtherElt && OtherElt->getType() != BytePtrTy)
804 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
805 MI);
806
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000807 unsigned EltSize = TD->getTypePaddedSize(EltTy);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000808
809 // Finally, insert the meminst for this element.
810 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
811 Value *Ops[] = {
812 SROADest ? EltPtr : OtherElt, // Dest ptr
813 SROADest ? OtherElt : EltPtr, // Src ptr
814 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
815 Zero // Align
816 };
817 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
818 } else {
819 assert(isa<MemSetInst>(MI));
820 Value *Ops[] = {
821 EltPtr, MI->getOperand(2), // Dest, Value,
822 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
823 Zero // Align
824 };
825 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
826 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000827 }
Chris Lattner71c75342009-01-07 08:11:13 +0000828 MI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000829}
Chris Lattner71c75342009-01-07 08:11:13 +0000830
831/// RewriteStoreUserOfWholeAlloca - We found an store of an integer that
832/// overwrites the entire allocation. Extract out the pieces of the stored
833/// integer and store them individually.
834void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI,
835 AllocationInst *AI,
836 SmallVector<AllocaInst*, 32> &NewElts){
837 // Extract each element out of the integer according to its structure offset
838 // and store the element value to the individual alloca.
839 Value *SrcVal = SI->getOperand(0);
840 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000841 uint64_t AllocaSizeBits = TD->getTypePaddedSizeInBits(AllocaEltTy);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000842
Chris Lattner71c75342009-01-07 08:11:13 +0000843 // If this isn't a store of an integer to the whole alloca, it may be a store
844 // to the first element. Just ignore the store in this case and normal SROA
845 // will handle it.
846 if (!isa<IntegerType>(SrcVal->getType()) ||
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000847 TD->getTypePaddedSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner71c75342009-01-07 08:11:13 +0000848 return;
849
850 DOUT << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << *SI;
851
852 // There are two forms here: AI could be an array or struct. Both cases
853 // have different ways to compute the element offset.
854 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
855 const StructLayout *Layout = TD->getStructLayout(EltSTy);
856
857 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
858 // Get the number of bits to shift SrcVal to get the value.
859 const Type *FieldTy = EltSTy->getElementType(i);
860 uint64_t Shift = Layout->getElementOffsetInBits(i);
861
862 if (TD->isBigEndian())
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000863 Shift = AllocaSizeBits-Shift-TD->getTypePaddedSizeInBits(FieldTy);
Chris Lattner71c75342009-01-07 08:11:13 +0000864
865 Value *EltVal = SrcVal;
866 if (Shift) {
867 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
868 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
869 "sroa.store.elt", SI);
870 }
871
872 // Truncate down to an integer of the right size.
873 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattnerf7a2f092009-01-09 18:18:43 +0000874
875 // Ignore zero sized fields like {}, they obviously contain no data.
876 if (FieldSizeBits == 0) continue;
877
Chris Lattner71c75342009-01-07 08:11:13 +0000878 if (FieldSizeBits != AllocaSizeBits)
879 EltVal = new TruncInst(EltVal, IntegerType::get(FieldSizeBits), "", SI);
880 Value *DestField = NewElts[i];
881 if (EltVal->getType() == FieldTy) {
882 // Storing to an integer field of this size, just do it.
883 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
884 // Bitcast to the right element type (for fp/vector values).
885 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
886 } else {
887 // Otherwise, bitcast the dest pointer (for aggregates).
888 DestField = new BitCastInst(DestField,
889 PointerType::getUnqual(EltVal->getType()),
890 "", SI);
891 }
892 new StoreInst(EltVal, DestField, SI);
893 }
894
895 } else {
896 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
897 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000898 uint64_t ElementOffset = TD->getTypePaddedSizeInBits(ArrayEltTy);
Chris Lattner71c75342009-01-07 08:11:13 +0000899 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
900
901 uint64_t Shift;
902
903 if (TD->isBigEndian())
904 Shift = AllocaSizeBits-ElementOffset;
905 else
906 Shift = 0;
907
908 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattnerf7a2f092009-01-09 18:18:43 +0000909 // Ignore zero sized fields like {}, they obviously contain no data.
910 if (ElementSizeBits == 0) continue;
Chris Lattner71c75342009-01-07 08:11:13 +0000911
912 Value *EltVal = SrcVal;
913 if (Shift) {
914 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
915 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
916 "sroa.store.elt", SI);
917 }
918
919 // Truncate down to an integer of the right size.
920 if (ElementSizeBits != AllocaSizeBits)
921 EltVal = new TruncInst(EltVal, IntegerType::get(ElementSizeBits),"",SI);
922 Value *DestField = NewElts[i];
923 if (EltVal->getType() == ArrayEltTy) {
924 // Storing to an integer field of this size, just do it.
925 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
926 // Bitcast to the right element type (for fp/vector values).
927 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
928 } else {
929 // Otherwise, bitcast the dest pointer (for aggregates).
930 DestField = new BitCastInst(DestField,
931 PointerType::getUnqual(EltVal->getType()),
932 "", SI);
933 }
934 new StoreInst(EltVal, DestField, SI);
935
936 if (TD->isBigEndian())
937 Shift -= ElementOffset;
938 else
939 Shift += ElementOffset;
940 }
941 }
942
943 SI->eraseFromParent();
944}
945
Chris Lattner28401db2009-01-08 05:42:05 +0000946/// RewriteLoadUserOfWholeAlloca - We found an load of the entire allocation to
947/// an integer. Load the individual pieces to form the aggregate value.
948void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
949 SmallVector<AllocaInst*, 32> &NewElts) {
950 // Extract each element out of the NewElts according to its structure offset
951 // and form the result value.
952 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000953 uint64_t AllocaSizeBits = TD->getTypePaddedSizeInBits(AllocaEltTy);
Chris Lattner28401db2009-01-08 05:42:05 +0000954
955 // If this isn't a load of the whole alloca to an integer, it may be a load
956 // of the first element. Just ignore the load in this case and normal SROA
957 // will handle it.
958 if (!isa<IntegerType>(LI->getType()) ||
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000959 TD->getTypePaddedSizeInBits(LI->getType()) != AllocaSizeBits)
Chris Lattner28401db2009-01-08 05:42:05 +0000960 return;
961
962 DOUT << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << *LI;
963
964 // There are two forms here: AI could be an array or struct. Both cases
965 // have different ways to compute the element offset.
966 const StructLayout *Layout = 0;
967 uint64_t ArrayEltBitOffset = 0;
968 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
969 Layout = TD->getStructLayout(EltSTy);
970 } else {
971 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000972 ArrayEltBitOffset = TD->getTypePaddedSizeInBits(ArrayEltTy);
Chris Lattner28401db2009-01-08 05:42:05 +0000973 }
974
975 Value *ResultVal = Constant::getNullValue(LI->getType());
976
977 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
978 // Load the value from the alloca. If the NewElt is an aggregate, cast
979 // the pointer to an integer of the same size before doing the load.
980 Value *SrcField = NewElts[i];
981 const Type *FieldTy =
982 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattnerf7a2f092009-01-09 18:18:43 +0000983 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
984
985 // Ignore zero sized fields like {}, they obviously contain no data.
986 if (FieldSizeBits == 0) continue;
987
988 const IntegerType *FieldIntTy = IntegerType::get(FieldSizeBits);
Chris Lattner28401db2009-01-08 05:42:05 +0000989 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
990 !isa<VectorType>(FieldTy))
991 SrcField = new BitCastInst(SrcField, PointerType::getUnqual(FieldIntTy),
992 "", LI);
993 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
994
995 // If SrcField is a fp or vector of the right size but that isn't an
996 // integer type, bitcast to an integer so we can shift it.
997 if (SrcField->getType() != FieldIntTy)
998 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
999
1000 // Zero extend the field to be the same size as the final alloca so that
1001 // we can shift and insert it.
1002 if (SrcField->getType() != ResultVal->getType())
1003 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1004
1005 // Determine the number of bits to shift SrcField.
1006 uint64_t Shift;
1007 if (Layout) // Struct case.
1008 Shift = Layout->getElementOffsetInBits(i);
1009 else // Array case.
1010 Shift = i*ArrayEltBitOffset;
1011
1012 if (TD->isBigEndian())
1013 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1014
1015 if (Shift) {
1016 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
1017 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1018 }
1019
1020 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1021 }
1022
1023 LI->replaceAllUsesWith(ResultVal);
1024 LI->eraseFromParent();
1025}
1026
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001027
Duncan Sandsae5fd622007-11-04 14:43:57 +00001028/// HasPadding - Return true if the specified type has any structure or
1029/// alignment padding, false otherwise.
Duncan Sands4afc5752008-06-04 08:21:45 +00001030static bool HasPadding(const Type *Ty, const TargetData &TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001031 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1032 const StructLayout *SL = TD.getStructLayout(STy);
1033 unsigned PrevFieldBitOffset = 0;
1034 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sandsae5fd622007-11-04 14:43:57 +00001035 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1036
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001037 // Padding in sub-elements?
Duncan Sands4afc5752008-06-04 08:21:45 +00001038 if (HasPadding(STy->getElementType(i), TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001039 return true;
Duncan Sandsae5fd622007-11-04 14:43:57 +00001040
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001041 // Check to see if there is any padding between this element and the
1042 // previous one.
1043 if (i) {
Duncan Sandsae5fd622007-11-04 14:43:57 +00001044 unsigned PrevFieldEnd =
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001045 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1046 if (PrevFieldEnd < FieldBitOffset)
1047 return true;
1048 }
Duncan Sandsae5fd622007-11-04 14:43:57 +00001049
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001050 PrevFieldBitOffset = FieldBitOffset;
1051 }
Duncan Sandsae5fd622007-11-04 14:43:57 +00001052
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053 // Check for tail padding.
1054 if (unsigned EltCount = STy->getNumElements()) {
1055 unsigned PrevFieldEnd = PrevFieldBitOffset +
1056 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sandsae5fd622007-11-04 14:43:57 +00001057 if (PrevFieldEnd < SL->getSizeInBits())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001058 return true;
1059 }
1060
1061 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sands4afc5752008-06-04 08:21:45 +00001062 return HasPadding(ATy->getElementType(), TD);
Duncan Sandsae5fd622007-11-04 14:43:57 +00001063 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sands4afc5752008-06-04 08:21:45 +00001064 return HasPadding(VTy->getElementType(), TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001065 }
Duncan Sandsd68f13b2009-01-12 20:38:59 +00001066 return TD.getTypeSizeInBits(Ty) != TD.getTypePaddedSizeInBits(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001067}
1068
1069/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1070/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1071/// or 1 if safe after canonicalization has been performed.
1072///
1073int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
1074 // Loop over the use list of the alloca. We can only transform it if all of
1075 // the users are safe to transform.
1076 AllocaInfo Info;
1077
1078 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
1079 I != E; ++I) {
1080 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
1081 if (Info.isUnsafe) {
1082 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
1083 return 0;
1084 }
1085 }
1086
1087 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1088 // source and destination, we have to be careful. In particular, the memcpy
1089 // could be moving around elements that live in structure padding of the LLVM
1090 // types, but may actually be used. In these cases, we refuse to promote the
1091 // struct.
1092 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Chris Lattner3fd59362009-01-07 06:34:28 +00001093 HasPadding(AI->getType()->getElementType(), *TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001094 return 0;
Duncan Sandsae5fd622007-11-04 14:43:57 +00001095
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001096 // If we require cleanup, return 1, otherwise return 3.
1097 return Info.needsCanon ? 1 : 3;
1098}
1099
1100/// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
1101/// allocation, but only if cleaned up, perform the cleanups required.
1102void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
1103 // At this point, we know that the end result will be SROA'd and promoted, so
1104 // we can insert ugly code if required so long as sroa+mem2reg will clean it
1105 // up.
1106 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1107 UI != E; ) {
1108 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI++);
1109 if (!GEPI) continue;
1110 gep_type_iterator I = gep_type_begin(GEPI);
1111 ++I;
1112
1113 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
1114 uint64_t NumElements = AT->getNumElements();
1115
1116 if (!isa<ConstantInt>(I.getOperand())) {
1117 if (NumElements == 1) {
1118 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
1119 } else {
1120 assert(NumElements == 2 && "Unhandled case!");
1121 // All users of the GEP must be loads. At each use of the GEP, insert
1122 // two loads of the appropriate indexed GEP and select between them.
1123 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
1124 Constant::getNullValue(I.getOperand()->getType()),
1125 "isone", GEPI);
1126 // Insert the new GEP instructions, which are properly indexed.
1127 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
1128 Indices[1] = Constant::getNullValue(Type::Int32Ty);
Gabor Greifd6da1d02008-04-06 20:25:17 +00001129 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1130 Indices.begin(),
1131 Indices.end(),
1132 GEPI->getName()+".0", GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001133 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00001134 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1135 Indices.begin(),
1136 Indices.end(),
1137 GEPI->getName()+".1", GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001138 // Replace all loads of the variable index GEP with loads from both
1139 // indexes and a select.
1140 while (!GEPI->use_empty()) {
1141 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1142 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1143 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +00001144 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001145 LI->replaceAllUsesWith(R);
1146 LI->eraseFromParent();
1147 }
1148 GEPI->eraseFromParent();
1149 }
1150 }
1151 }
1152 }
1153}
1154
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001155/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1156/// the offset specified by Offset (which is specified in bytes).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001157///
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001158/// There are two cases we handle here:
1159/// 1) A union of vector types of the same size and potentially its elements.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001160/// Here we turn element accesses into insert/extract element operations.
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001161/// This promotes a <4 x float> with a store of float to the third element
1162/// into a <4 x float> that uses insert element.
1163/// 2) A fully general blob of memory, which we turn into some (potentially
1164/// large) integer type with extract and insert operations where the loads
1165/// and stores would mutate the memory.
1166static void MergeInType(const Type *In, uint64_t Offset, const Type *&Accum,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001167 const TargetData &TD) {
1168 // If this is our first type, just use it.
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001169 if (Accum == 0 || In == Type::VoidTy ||
1170 // Or if this is a same type, keep it.
1171 (In == Accum && Offset == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001172 Accum = In;
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001173 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001174 }
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001175
1176 if (const VectorType *VATy = dyn_cast<VectorType>(Accum)) {
1177 if (VATy->getElementType() == In &&
1178 Offset % TD.getTypePaddedSize(In) == 0 &&
1179 Offset < TD.getTypePaddedSize(VATy))
1180 return; // Accum is a vector, and we are accessing an element: ok.
1181 if (const VectorType *VInTy = dyn_cast<VectorType>(In))
1182 if (VInTy->getBitWidth() == VATy->getBitWidth() && Offset == 0)
1183 return; // Two vectors of the same size: keep either one of them.
1184 }
1185
1186 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1187 // In is a vector, and we are accessing an element: keep V.
1188 if (VInTy->getElementType() == Accum &&
1189 Offset % TD.getTypePaddedSize(Accum) == 0 &&
1190 Offset < TD.getTypePaddedSize(VInTy)) {
1191 Accum = VInTy;
1192 return;
1193 }
1194 }
1195
1196 // Otherwise, we have a case that we can't handle with an optimized form.
1197 // Convert the alloca to an integer that is as large as the largest store size
1198 // of the value values.
1199 uint64_t InSize = TD.getTypeStoreSizeInBits(In)+8*Offset;
1200 uint64_t ASize = TD.getTypeStoreSizeInBits(Accum);
1201 if (InSize > ASize) ASize = InSize;
1202 Accum = IntegerType::get(ASize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001203}
1204
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001205/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
1206/// its accesses to use a to single scalar type, return true, and set ResTy to
1207/// the new type. Further, if the use is not a completely trivial use that
1208/// mem2reg could promote, set IsNotTrivial. Offset is the current offset from
1209/// the base of the alloca being analyzed.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001210///
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001211bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial,
1212 const Type *&ResTy, uint64_t Offset) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001213 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1214 Instruction *User = cast<Instruction>(*UI);
1215
1216 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001217 // Don't break volatile loads.
Chris Lattner70ffe572009-01-28 20:16:43 +00001218 if (LI->isVolatile())
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001219 return false;
1220 MergeInType(LI->getType(), Offset, ResTy, *TD);
Chris Lattner7cc97712009-01-07 06:39:58 +00001221 continue;
1222 }
1223
1224 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001225 // Storing the pointer, not into the value?
Chris Lattner70ffe572009-01-28 20:16:43 +00001226 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001227 MergeInType(SI->getOperand(0)->getType(), Offset, ResTy, *TD);
Chris Lattner7cc97712009-01-07 06:39:58 +00001228 continue;
1229 }
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001230
1231 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
1232 if (!CanConvertToScalar(BCI, IsNotTrivial, ResTy, Offset))
1233 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001234 IsNotTrivial = true;
Chris Lattner7cc97712009-01-07 06:39:58 +00001235 continue;
1236 }
1237
1238 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001239 // If this is a GEP with a variable indices, we can't handle it.
1240 if (!GEP->hasAllConstantIndices())
1241 return false;
Chris Lattner7cc97712009-01-07 06:39:58 +00001242
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001243 // Compute the offset that this GEP adds to the pointer.
1244 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1245 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1246 &Indices[0], Indices.size());
1247 // See if all uses can be converted.
1248 if (!CanConvertToScalar(GEP, IsNotTrivial, ResTy, Offset+GEPOffset))
1249 return false;
1250 IsNotTrivial = true;
1251 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001252 }
Chris Lattner7cc97712009-01-07 06:39:58 +00001253
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001254 // Otherwise, we cannot handle this!
1255 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001256 }
1257
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001258 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001259}
1260
1261/// ConvertToScalar - The specified alloca passes the CanConvertToScalar
1262/// predicate and is non-trivial. Convert it to something that can be trivially
1263/// promoted into a register by mem2reg.
1264void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001265 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = " << *ActualTy << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001266 ++NumConverted;
1267
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001268 // Create and insert the alloca.
1269 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001270 AI->getParent()->begin());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001271 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001272 AI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001273}
1274
1275
1276/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1277/// directly. This happens when we are converting an "integer union" to a
1278/// single integer scalar, or when we are converting a "vector union" to a
1279/// vector with insert/extractelement instructions.
1280///
1281/// Offset is an offset from the original alloca, in bits that need to be
1282/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001283void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001284 while (!Ptr->use_empty()) {
1285 Instruction *User = cast<Instruction>(Ptr->use_back());
Duncan Sands641f12c2009-02-02 10:06:20 +00001286
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001287 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001288 LI->replaceAllUsesWith(ConvertUsesOfLoadToScalar(LI, NewAI, Offset));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001289 LI->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001290 continue;
1291 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001292
Chris Lattner7cc97712009-01-07 06:39:58 +00001293 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001294 assert(SI->getOperand(0) != Ptr && "Consistency error!");
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001295 new StoreInst(ConvertUsesOfStoreToScalar(SI, NewAI, Offset), NewAI, SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001296 SI->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001297 continue;
1298 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001299
Chris Lattner7cc97712009-01-07 06:39:58 +00001300 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb1534532008-01-30 00:39:15 +00001301 ConvertUsesToScalar(CI, NewAI, Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001302 CI->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001303 continue;
1304 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001305
Chris Lattner7cc97712009-01-07 06:39:58 +00001306 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001307 // Compute the offset that this GEP adds to the pointer.
1308 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1309 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1310 &Indices[0], Indices.size());
1311 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001312 GEP->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001313 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001314 }
Chris Lattner7cc97712009-01-07 06:39:58 +00001315 assert(0 && "Unsupported operation!");
1316 abort();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001317 }
1318}
1319
Duncan Sands641f12c2009-02-02 10:06:20 +00001320/// ConvertUsesOfLoadToScalar - Convert all of the users of the specified load
1321/// to use the new alloca directly, returning the value that should replace the
1322/// load. This happens when we are converting an "integer union" to a single
1323/// integer scalar, or when we are converting a "vector union" to a vector with
1324/// insert/extractelement instructions.
Chris Lattner41d58652008-02-29 07:03:13 +00001325///
Duncan Sands641f12c2009-02-02 10:06:20 +00001326/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner41d58652008-02-29 07:03:13 +00001327/// shifted to the right. By the end of this, there should be no uses of Ptr.
Duncan Sands641f12c2009-02-02 10:06:20 +00001328Value *SROA::ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001329 uint64_t Offset) {
Chris Lattner41d58652008-02-29 07:03:13 +00001330 // The load is a bit extract from NewAI shifted right by Offset bits.
1331 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
Duncan Sands641f12c2009-02-02 10:06:20 +00001332
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001333 // If the load is of the whole new alloca, no conversion is needed.
1334 if (NV->getType() == LI->getType() && Offset == 0)
Chris Lattner41d58652008-02-29 07:03:13 +00001335 return NV;
Chris Lattner5f062542008-02-29 07:12:06 +00001336
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001337 // If the result alloca is a vector type, this is either an element
1338 // access or a bitcast to another vector type of the same size.
Chris Lattner5f062542008-02-29 07:12:06 +00001339 if (const VectorType *VTy = dyn_cast<VectorType>(NV->getType())) {
Chris Lattner5f062542008-02-29 07:12:06 +00001340 if (isa<VectorType>(LI->getType()))
1341 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1342
1343 // Otherwise it must be an element access.
Chris Lattner5f062542008-02-29 07:12:06 +00001344 unsigned Elt = 0;
1345 if (Offset) {
Duncan Sandsd68f13b2009-01-12 20:38:59 +00001346 unsigned EltSize = TD->getTypePaddedSizeInBits(VTy->getElementType());
Chris Lattner5f062542008-02-29 07:12:06 +00001347 Elt = Offset/EltSize;
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001348 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Chris Lattner41d58652008-02-29 07:03:13 +00001349 }
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001350 // Return the element extracted out of it.
1351 return new ExtractElementInst(NV, ConstantInt::get(Type::Int32Ty, Elt),
1352 "tmp", LI);
Chris Lattner5f062542008-02-29 07:12:06 +00001353 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001354
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001355 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattner5f062542008-02-29 07:12:06 +00001356 const IntegerType *NTy = cast<IntegerType>(NV->getType());
Duncan Sands641f12c2009-02-02 10:06:20 +00001357
Chris Lattner5f062542008-02-29 07:12:06 +00001358 // If this is a big-endian system and the load is narrower than the
1359 // full alloca type, we need to do a shift to get the right bits.
1360 int ShAmt = 0;
Chris Lattner3fd59362009-01-07 06:34:28 +00001361 if (TD->isBigEndian()) {
Chris Lattner5f062542008-02-29 07:12:06 +00001362 // On big-endian machines, the lowest bit is stored at the bit offset
1363 // from the pointer given by getTypeStoreSizeInBits. This matters for
1364 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner3fd59362009-01-07 06:34:28 +00001365 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
1366 TD->getTypeStoreSizeInBits(LI->getType()) - Offset;
Chris Lattner5f062542008-02-29 07:12:06 +00001367 } else {
1368 ShAmt = Offset;
1369 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001370
Chris Lattner5f062542008-02-29 07:12:06 +00001371 // Note: we support negative bitwidths (with shl) which are not defined.
1372 // We do this to support (f.e.) loads off the end of a structure where
1373 // only some bits are used.
1374 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001375 NV = BinaryOperator::CreateLShr(NV,
1376 ConstantInt::get(NV->getType(), ShAmt),
Chris Lattner5f062542008-02-29 07:12:06 +00001377 LI->getName(), LI);
1378 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001379 NV = BinaryOperator::CreateShl(NV,
1380 ConstantInt::get(NV->getType(), -ShAmt),
Chris Lattner5f062542008-02-29 07:12:06 +00001381 LI->getName(), LI);
Duncan Sands641f12c2009-02-02 10:06:20 +00001382
Chris Lattner5f062542008-02-29 07:12:06 +00001383 // Finally, unconditionally truncate the integer to the right width.
Chris Lattner3fd59362009-01-07 06:34:28 +00001384 unsigned LIBitWidth = TD->getTypeSizeInBits(LI->getType());
Chris Lattner5f062542008-02-29 07:12:06 +00001385 if (LIBitWidth < NTy->getBitWidth())
1386 NV = new TruncInst(NV, IntegerType::get(LIBitWidth),
1387 LI->getName(), LI);
Duncan Sands641f12c2009-02-02 10:06:20 +00001388
Chris Lattner5f062542008-02-29 07:12:06 +00001389 // If the result is an integer, this is a trunc or bitcast.
1390 if (isa<IntegerType>(LI->getType())) {
1391 // Should be done.
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001392 } else if (LI->getType()->isFloatingPoint() ||
1393 isa<VectorType>(LI->getType())) {
Chris Lattner5f062542008-02-29 07:12:06 +00001394 // Just do a bitcast, we know the sizes match up.
Chris Lattner41d58652008-02-29 07:03:13 +00001395 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1396 } else {
Chris Lattner5f062542008-02-29 07:12:06 +00001397 // Otherwise must be a pointer.
1398 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
Chris Lattner41d58652008-02-29 07:03:13 +00001399 }
Chris Lattner5f062542008-02-29 07:12:06 +00001400 assert(NV->getType() == LI->getType() && "Didn't convert right?");
Chris Lattner41d58652008-02-29 07:03:13 +00001401 return NV;
1402}
1403
1404
1405/// ConvertUsesOfStoreToScalar - Convert the specified store to a load+store
1406/// pair of the new alloca directly, returning the value that should be stored
1407/// to the alloca. This happens when we are converting an "integer union" to a
1408/// single integer scalar, or when we are converting a "vector union" to a
1409/// vector with insert/extractelement instructions.
1410///
1411/// Offset is an offset from the original alloca, in bits that need to be
1412/// shifted to the right. By the end of this, there should be no uses of Ptr.
Duncan Sands641f12c2009-02-02 10:06:20 +00001413Value *SROA::ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001414 uint64_t Offset) {
Duncan Sands641f12c2009-02-02 10:06:20 +00001415
Chris Lattner41d58652008-02-29 07:03:13 +00001416 // Convert the stored type to the actual type, shift it left to insert
1417 // then 'or' into place.
1418 Value *SV = SI->getOperand(0);
1419 const Type *AllocaType = NewAI->getType()->getElementType();
1420 if (SV->getType() == AllocaType && Offset == 0) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001421 return SV;
1422 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001423
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001424 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Chris Lattner41d58652008-02-29 07:03:13 +00001425 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
Duncan Sands641f12c2009-02-02 10:06:20 +00001426
Chris Lattner41d58652008-02-29 07:03:13 +00001427 // If the result alloca is a vector type, this is either an element
1428 // access or a bitcast to another vector type.
1429 if (isa<VectorType>(SV->getType())) {
1430 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1431 } else {
1432 // Must be an element insertion.
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001433 unsigned Elt = Offset/TD->getTypePaddedSizeInBits(VTy->getElementType());
Gabor Greifd6da1d02008-04-06 20:25:17 +00001434 SV = InsertElementInst::Create(Old, SV,
1435 ConstantInt::get(Type::Int32Ty, Elt),
1436 "tmp", SI);
Chris Lattner41d58652008-02-29 07:03:13 +00001437 }
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001438 return SV;
1439 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001440
1441
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001442 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
Duncan Sands641f12c2009-02-02 10:06:20 +00001443
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001444 // If SV is a float, convert it to the appropriate integer type.
1445 // If it is a pointer, do the same, and also handle ptr->ptr casts
1446 // here.
1447 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1448 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1449 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1450 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1451 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
1452 SV = new BitCastInst(SV, IntegerType::get(SrcWidth), SV->getName(), SI);
1453 else if (isa<PointerType>(SV->getType()))
1454 SV = new PtrToIntInst(SV, TD->getIntPtrType(), SV->getName(), SI);
Duncan Sands641f12c2009-02-02 10:06:20 +00001455
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001456 // Always zero extend the value if needed.
1457 if (SV->getType() != AllocaType)
1458 SV = new ZExtInst(SV, AllocaType, SV->getName(), SI);
Duncan Sands641f12c2009-02-02 10:06:20 +00001459
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001460 // If this is a big-endian system and the store is narrower than the
1461 // full alloca type, we need to do a shift to get the right bits.
1462 int ShAmt = 0;
1463 if (TD->isBigEndian()) {
1464 // On big-endian machines, the lowest bit is stored at the bit offset
1465 // from the pointer given by getTypeStoreSizeInBits. This matters for
1466 // integers with a bitwidth that is not a multiple of 8.
1467 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
Chris Lattner41d58652008-02-29 07:03:13 +00001468 } else {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001469 ShAmt = Offset;
1470 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001471
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001472 // Note: we support negative bitwidths (with shr) which are not defined.
1473 // We do this to support (f.e.) stores off the end of a structure where
1474 // only some bits in the structure are set.
1475 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1476 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Duncan Sands641f12c2009-02-02 10:06:20 +00001477 SV = BinaryOperator::CreateShl(SV,
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001478 ConstantInt::get(SV->getType(), ShAmt),
1479 SV->getName(), SI);
1480 Mask <<= ShAmt;
1481 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1482 SV = BinaryOperator::CreateLShr(SV,
1483 ConstantInt::get(SV->getType(),-ShAmt),
1484 SV->getName(), SI);
Duncan Sandsced29632009-02-02 09:53:14 +00001485 Mask = Mask.lshr(-ShAmt);
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001486 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001487
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001488 // Mask out the bits we are about to insert from the old value, and or
1489 // in the new bits.
1490 if (SrcWidth != DestWidth) {
1491 assert(DestWidth > SrcWidth);
1492 Old = BinaryOperator::CreateAnd(Old, ConstantInt::get(~Mask),
1493 Old->getName()+".mask", SI);
1494 SV = BinaryOperator::CreateOr(Old, SV, SV->getName()+".ins", SI);
Chris Lattner41d58652008-02-29 07:03:13 +00001495 }
1496 return SV;
1497}
1498
1499
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001500
1501/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1502/// some part of a constant global variable. This intentionally only accepts
1503/// constant expressions because we don't can't rewrite arbitrary instructions.
1504static bool PointsToConstantGlobal(Value *V) {
1505 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1506 return GV->isConstant();
1507 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1508 if (CE->getOpcode() == Instruction::BitCast ||
1509 CE->getOpcode() == Instruction::GetElementPtr)
1510 return PointsToConstantGlobal(CE->getOperand(0));
1511 return false;
1512}
1513
1514/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1515/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1516/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1517/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1518/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1519/// the alloca, and if the source pointer is a pointer to a constant global, we
1520/// can optimize this.
1521static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1522 bool isOffset) {
1523 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Chris Lattner70ffe572009-01-28 20:16:43 +00001524 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1525 // Ignore non-volatile loads, they are always ok.
1526 if (!LI->isVolatile())
1527 continue;
1528
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001529 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1530 // If uses of the bitcast are ok, we are ok.
1531 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1532 return false;
1533 continue;
1534 }
1535 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1536 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1537 // doesn't, it does.
1538 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1539 isOffset || !GEP->hasAllZeroIndices()))
1540 return false;
1541 continue;
1542 }
1543
1544 // If this is isn't our memcpy/memmove, reject it as something we can't
1545 // handle.
1546 if (!isa<MemCpyInst>(*UI) && !isa<MemMoveInst>(*UI))
1547 return false;
1548
1549 // If we already have seen a copy, reject the second one.
1550 if (TheCopy) return false;
1551
1552 // If the pointer has been offset from the start of the alloca, we can't
1553 // safely handle this.
1554 if (isOffset) return false;
1555
1556 // If the memintrinsic isn't using the alloca as the dest, reject it.
1557 if (UI.getOperandNo() != 1) return false;
1558
1559 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1560
1561 // If the source of the memcpy/move is not a constant global, reject it.
1562 if (!PointsToConstantGlobal(MI->getOperand(2)))
1563 return false;
1564
1565 // Otherwise, the transform is safe. Remember the copy instruction.
1566 TheCopy = MI;
1567 }
1568 return true;
1569}
1570
1571/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1572/// modified by a copy from a constant global. If we can prove this, we can
1573/// replace any uses of the alloca with uses of the global directly.
1574Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1575 Instruction *TheCopy = 0;
1576 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1577 return TheCopy;
1578 return 0;
1579}