1 //===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
20 //===----------------------------------------------------------------------===//
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/Transforms/Utils/Local.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/GetElementPtrTypeIterator.h"
37 #include "llvm/Support/IRBuilder.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/Compiler.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/ADT/StringExtras.h"
45 STATISTIC(NumReplaced, "Number of allocas broken up");
46 STATISTIC(NumPromoted, "Number of allocas promoted");
47 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
48 STATISTIC(NumGlobals, "Number of allocas copied from constant global");
51 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
52 static char ID; // Pass identification, replacement for typeid
53 explicit SROA(signed T = -1) : FunctionPass(&ID) {
60 bool runOnFunction(Function &F);
62 bool performScalarRepl(Function &F);
63 bool performPromotion(Function &F);
65 // getAnalysisUsage - This pass does not require any passes, but we know it
66 // will not alter the CFG, so say so.
67 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68 AU.addRequired<DominatorTree>();
69 AU.addRequired<DominanceFrontier>();
70 AU.addRequired<TargetData>();
77 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
78 /// information about the uses. All these fields are initialized to false
79 /// and set to true when something is learned.
81 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
84 /// needsCleanup - This is set to true if there is some use of the alloca
85 /// that requires cleanup.
86 bool needsCleanup : 1;
88 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
91 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
95 : isUnsafe(false), needsCleanup(false),
96 isMemCpySrc(false), isMemCpyDst(false) {}
101 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
103 int isSafeAllocaToScalarRepl(AllocationInst *AI);
105 void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
107 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
109 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
110 unsigned OpNo, AllocaInfo &Info);
111 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
114 void DoScalarReplacement(AllocationInst *AI,
115 std::vector<AllocationInst*> &WorkList);
116 void CleanupGEP(GetElementPtrInst *GEP);
117 void CleanupAllocaUsers(AllocationInst *AI);
118 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
120 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
121 SmallVector<AllocaInst*, 32> &NewElts);
123 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
125 SmallVector<AllocaInst*, 32> &NewElts);
126 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocationInst *AI,
127 SmallVector<AllocaInst*, 32> &NewElts);
128 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
129 SmallVector<AllocaInst*, 32> &NewElts);
131 bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
132 bool &SawVec, uint64_t Offset, unsigned AllocaSize);
133 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
134 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
135 uint64_t Offset, IRBuilder<> &Builder);
136 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
137 uint64_t Offset, IRBuilder<> &Builder);
138 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
143 static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
145 // Public interface to the ScalarReplAggregates pass
146 FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
147 return new SROA(Threshold);
151 bool SROA::runOnFunction(Function &F) {
152 TD = &getAnalysis<TargetData>();
154 bool Changed = performPromotion(F);
156 bool LocalChange = performScalarRepl(F);
157 if (!LocalChange) break; // No need to repromote if no scalarrepl
159 LocalChange = performPromotion(F);
160 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
167 bool SROA::performPromotion(Function &F) {
168 std::vector<AllocaInst*> Allocas;
169 DominatorTree &DT = getAnalysis<DominatorTree>();
170 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
172 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
174 bool Changed = false;
179 // Find allocas that are safe to promote, by looking at all instructions in
181 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
182 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
183 if (isAllocaPromotable(AI))
184 Allocas.push_back(AI);
186 if (Allocas.empty()) break;
188 PromoteMemToReg(Allocas, DT, DF);
189 NumPromoted += Allocas.size();
196 /// getNumSAElements - Return the number of elements in the specific struct or
198 static uint64_t getNumSAElements(const Type *T) {
199 if (const StructType *ST = dyn_cast<StructType>(T))
200 return ST->getNumElements();
201 return cast<ArrayType>(T)->getNumElements();
204 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
205 // which runs on all of the malloc/alloca instructions in the function, removing
206 // them if they are only used by getelementptr instructions.
208 bool SROA::performScalarRepl(Function &F) {
209 std::vector<AllocationInst*> WorkList;
211 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
212 BasicBlock &BB = F.getEntryBlock();
213 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
214 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
215 WorkList.push_back(A);
217 // Process the worklist
218 bool Changed = false;
219 while (!WorkList.empty()) {
220 AllocationInst *AI = WorkList.back();
223 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
224 // with unused elements.
225 if (AI->use_empty()) {
226 AI->eraseFromParent();
230 // If this alloca is impossible for us to promote, reject it early.
231 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
234 // Check to see if this allocation is only modified by a memcpy/memmove from
235 // a constant global. If this is the case, we can change all users to use
236 // the constant global instead. This is commonly produced by the CFE by
237 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
238 // is only subsequently read.
239 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
240 DOUT << "Found alloca equal to global: " << *AI;
241 DOUT << " memcpy = " << *TheCopy;
242 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
243 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
244 TheCopy->eraseFromParent(); // Don't mutate the global.
245 AI->eraseFromParent();
251 // Check to see if we can perform the core SROA transformation. We cannot
252 // transform the allocation instruction if it is an array allocation
253 // (allocations OF arrays are ok though), and an allocation of a scalar
254 // value cannot be decomposed at all.
255 uint64_t AllocaSize = TD->getTypePaddedSize(AI->getAllocatedType());
257 // Do not promote any struct whose size is too big.
258 if (AllocaSize > SRThreshold) continue;
260 if ((isa<StructType>(AI->getAllocatedType()) ||
261 isa<ArrayType>(AI->getAllocatedType())) &&
262 // Do not promote any struct into more than "32" separate vars.
263 getNumSAElements(AI->getAllocatedType()) < SRThreshold/4) {
264 // Check that all of the users of the allocation are capable of being
266 switch (isSafeAllocaToScalarRepl(AI)) {
267 default: assert(0 && "Unexpected value!");
268 case 0: // Not safe to scalar replace.
270 case 1: // Safe, but requires cleanup/canonicalizations first
271 CleanupAllocaUsers(AI);
273 case 3: // Safe to scalar replace.
274 DoScalarReplacement(AI, WorkList);
280 // If we can turn this aggregate value (potentially with casts) into a
281 // simple scalar value that can be mem2reg'd into a register value.
282 // IsNotTrivial tracks whether this is something that mem2reg could have
283 // promoted itself. If so, we don't want to transform it needlessly. Note
284 // that we can't just check based on the type: the alloca may be of an i32
285 // but that has pointer arithmetic to set byte 3 of it or something.
286 bool IsNotTrivial = false;
287 const Type *VectorTy = 0;
288 bool HadAVector = false;
289 if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector,
290 0, unsigned(AllocaSize)) && IsNotTrivial) {
292 // If we were able to find a vector type that can handle this with
293 // insert/extract elements, and if there was at least one use that had
294 // a vector type, promote this to a vector. We don't want to promote
295 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
296 // we just get a lot of insert/extracts. If at least one vector is
297 // involved, then we probably really do have a union of vector/array.
298 if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
299 DOUT << "CONVERT TO VECTOR: " << *AI << " TYPE = " << *VectorTy <<"\n";
301 // Create and insert the vector alloca.
302 NewAI = new AllocaInst(VectorTy, 0, "", AI->getParent()->begin());
303 ConvertUsesToScalar(AI, NewAI, 0);
305 DOUT << "CONVERT TO SCALAR INTEGER: " << *AI << "\n";
307 // Create and insert the integer alloca.
308 const Type *NewTy = IntegerType::get(AllocaSize*8);
309 NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
310 ConvertUsesToScalar(AI, NewAI, 0);
313 AI->eraseFromParent();
319 // Otherwise, couldn't process this alloca.
325 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
326 /// predicate, do SROA now.
327 void SROA::DoScalarReplacement(AllocationInst *AI,
328 std::vector<AllocationInst*> &WorkList) {
329 DOUT << "Found inst to SROA: " << *AI;
330 SmallVector<AllocaInst*, 32> ElementAllocas;
331 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
332 ElementAllocas.reserve(ST->getNumContainedTypes());
333 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
334 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
336 AI->getName() + "." + utostr(i), AI);
337 ElementAllocas.push_back(NA);
338 WorkList.push_back(NA); // Add to worklist for recursive processing
341 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
342 ElementAllocas.reserve(AT->getNumElements());
343 const Type *ElTy = AT->getElementType();
344 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
345 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
346 AI->getName() + "." + utostr(i), AI);
347 ElementAllocas.push_back(NA);
348 WorkList.push_back(NA); // Add to worklist for recursive processing
352 // Now that we have created the alloca instructions that we want to use,
353 // expand the getelementptr instructions to use them.
355 while (!AI->use_empty()) {
356 Instruction *User = cast<Instruction>(AI->use_back());
357 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
358 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
359 BCInst->eraseFromParent();
364 // %res = load { i32, i32 }* %alloc
366 // %load.0 = load i32* %alloc.0
367 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
368 // %load.1 = load i32* %alloc.1
369 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
370 // (Also works for arrays instead of structs)
371 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
372 Value *Insert = UndefValue::get(LI->getType());
373 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
374 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
375 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
377 LI->replaceAllUsesWith(Insert);
378 LI->eraseFromParent();
383 // store { i32, i32 } %val, { i32, i32 }* %alloc
385 // %val.0 = extractvalue { i32, i32 } %val, 0
386 // store i32 %val.0, i32* %alloc.0
387 // %val.1 = extractvalue { i32, i32 } %val, 1
388 // store i32 %val.1, i32* %alloc.1
389 // (Also works for arrays instead of structs)
390 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
391 Value *Val = SI->getOperand(0);
392 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
393 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
394 new StoreInst(Extract, ElementAllocas[i], SI);
396 SI->eraseFromParent();
400 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
401 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
403 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
405 assert(Idx < ElementAllocas.size() && "Index out of range?");
406 AllocaInst *AllocaToUse = ElementAllocas[Idx];
409 if (GEPI->getNumOperands() == 3) {
410 // Do not insert a new getelementptr instruction with zero indices, only
411 // to have it optimized out later.
412 RepValue = AllocaToUse;
414 // We are indexing deeply into the structure, so we still need a
415 // getelement ptr instruction to finish the indexing. This may be
416 // expanded itself once the worklist is rerun.
418 SmallVector<Value*, 8> NewArgs;
419 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
420 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
421 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
422 NewArgs.end(), "", GEPI);
423 RepValue->takeName(GEPI);
426 // If this GEP is to the start of the aggregate, check for memcpys.
427 if (Idx == 0 && GEPI->hasAllZeroIndices())
428 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
430 // Move all of the users over to the new GEP.
431 GEPI->replaceAllUsesWith(RepValue);
432 // Delete the old GEP
433 GEPI->eraseFromParent();
436 // Finally, delete the Alloca instruction
437 AI->eraseFromParent();
442 /// isSafeElementUse - Check to see if this use is an allowed use for a
443 /// getelementptr instruction of an array aggregate allocation. isFirstElt
444 /// indicates whether Ptr is known to the start of the aggregate.
446 void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
448 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
450 Instruction *User = cast<Instruction>(*I);
451 switch (User->getOpcode()) {
452 case Instruction::Load: break;
453 case Instruction::Store:
454 // Store is ok if storing INTO the pointer, not storing the pointer
455 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
457 case Instruction::GetElementPtr: {
458 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
459 bool AreAllZeroIndices = isFirstElt;
460 if (GEP->getNumOperands() > 1) {
461 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
462 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
463 // Using pointer arithmetic to navigate the array.
464 return MarkUnsafe(Info);
466 if (AreAllZeroIndices)
467 AreAllZeroIndices = GEP->hasAllZeroIndices();
469 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
470 if (Info.isUnsafe) return;
473 case Instruction::BitCast:
475 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
476 if (Info.isUnsafe) return;
479 DOUT << " Transformation preventing inst: " << *User;
480 return MarkUnsafe(Info);
481 case Instruction::Call:
482 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
484 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
485 if (Info.isUnsafe) return;
489 DOUT << " Transformation preventing inst: " << *User;
490 return MarkUnsafe(Info);
492 DOUT << " Transformation preventing inst: " << *User;
493 return MarkUnsafe(Info);
496 return; // All users look ok :)
499 /// AllUsersAreLoads - Return true if all users of this value are loads.
500 static bool AllUsersAreLoads(Value *Ptr) {
501 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
503 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
508 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
509 /// aggregate allocation.
511 void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
513 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
514 return isSafeUseOfBitCastedAllocation(C, AI, Info);
516 if (LoadInst *LI = dyn_cast<LoadInst>(User))
517 if (!LI->isVolatile())
518 return;// Loads (returning a first class aggregrate) are always rewritable
520 if (StoreInst *SI = dyn_cast<StoreInst>(User))
521 if (!SI->isVolatile() && SI->getOperand(0) != AI)
522 return;// Store is ok if storing INTO the pointer, not storing the pointer
524 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
526 return MarkUnsafe(Info);
528 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
530 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
532 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
533 return MarkUnsafe(Info);
537 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
539 bool IsAllZeroIndices = true;
541 // If the first index is a non-constant index into an array, see if we can
542 // handle it as a special case.
543 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
544 if (!isa<ConstantInt>(I.getOperand())) {
545 IsAllZeroIndices = 0;
546 uint64_t NumElements = AT->getNumElements();
548 // If this is an array index and the index is not constant, we cannot
549 // promote... that is unless the array has exactly one or two elements in
550 // it, in which case we CAN promote it, but we have to canonicalize this
551 // out if this is the only problem.
552 if ((NumElements == 1 || NumElements == 2) &&
553 AllUsersAreLoads(GEPI)) {
554 Info.needsCleanup = true;
555 return; // Canonicalization required!
557 return MarkUnsafe(Info);
561 // Walk through the GEP type indices, checking the types that this indexes
563 for (; I != E; ++I) {
564 // Ignore struct elements, no extra checking needed for these.
565 if (isa<StructType>(*I))
568 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
569 if (!IdxVal) return MarkUnsafe(Info);
571 // Are all indices still zero?
572 IsAllZeroIndices &= IdxVal->isZero();
574 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
575 // This GEP indexes an array. Verify that this is an in-range constant
576 // integer. Specifically, consider A[0][i]. We cannot know that the user
577 // isn't doing invalid things like allowing i to index an out-of-range
578 // subscript that accesses A[1]. Because of this, we have to reject SROA
579 // of any accesses into structs where any of the components are variables.
580 if (IdxVal->getZExtValue() >= AT->getNumElements())
581 return MarkUnsafe(Info);
582 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
583 if (IdxVal->getZExtValue() >= VT->getNumElements())
584 return MarkUnsafe(Info);
588 // If there are any non-simple uses of this getelementptr, make sure to reject
590 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
593 /// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
594 /// intrinsic can be promoted by SROA. At this point, we know that the operand
595 /// of the memintrinsic is a pointer to the beginning of the allocation.
596 void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
597 unsigned OpNo, AllocaInfo &Info) {
598 // If not constant length, give up.
599 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
600 if (!Length) return MarkUnsafe(Info);
602 // If not the whole aggregate, give up.
603 if (Length->getZExtValue() !=
604 TD->getTypePaddedSize(AI->getType()->getElementType()))
605 return MarkUnsafe(Info);
607 // We only know about memcpy/memset/memmove.
608 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
609 return MarkUnsafe(Info);
611 // Otherwise, we can transform it. Determine whether this is a memcpy/set
612 // into or out of the aggregate.
614 Info.isMemCpyDst = true;
617 Info.isMemCpySrc = true;
621 /// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
623 void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
625 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
627 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
628 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
629 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
630 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
631 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
632 if (SI->isVolatile())
633 return MarkUnsafe(Info);
635 // If storing the entire alloca in one chunk through a bitcasted pointer
636 // to integer, we can transform it. This happens (for example) when you
637 // cast a {i32,i32}* to i64* and store through it. This is similar to the
638 // memcpy case and occurs in various "byval" cases and emulated memcpys.
639 if (isa<IntegerType>(SI->getOperand(0)->getType()) &&
640 TD->getTypePaddedSize(SI->getOperand(0)->getType()) ==
641 TD->getTypePaddedSize(AI->getType()->getElementType())) {
642 Info.isMemCpyDst = true;
645 return MarkUnsafe(Info);
646 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
647 if (LI->isVolatile())
648 return MarkUnsafe(Info);
650 // If loading the entire alloca in one chunk through a bitcasted pointer
651 // to integer, we can transform it. This happens (for example) when you
652 // cast a {i32,i32}* to i64* and load through it. This is similar to the
653 // memcpy case and occurs in various "byval" cases and emulated memcpys.
654 if (isa<IntegerType>(LI->getType()) &&
655 TD->getTypePaddedSize(LI->getType()) ==
656 TD->getTypePaddedSize(AI->getType()->getElementType())) {
657 Info.isMemCpySrc = true;
660 return MarkUnsafe(Info);
661 } else if (isa<DbgInfoIntrinsic>(UI)) {
662 // If one user is DbgInfoIntrinsic then check if all users are
663 // DbgInfoIntrinsics.
664 if (OnlyUsedByDbgInfoIntrinsics(BC)) {
665 Info.needsCleanup = true;
672 return MarkUnsafe(Info);
674 if (Info.isUnsafe) return;
678 /// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
679 /// to its first element. Transform users of the cast to use the new values
681 void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
682 SmallVector<AllocaInst*, 32> &NewElts) {
683 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
685 Instruction *User = cast<Instruction>(*UI++);
686 if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) {
687 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
688 if (BCU->use_empty()) BCU->eraseFromParent();
692 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
693 // This must be memcpy/memmove/memset of the entire aggregate.
694 // Split into one per element.
695 RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts);
699 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
700 // If this is a store of the entire alloca from an integer, rewrite it.
701 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
705 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
706 // If this is a load of the entire alloca to an integer, rewrite it.
707 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
711 // Otherwise it must be some other user of a gep of the first pointer. Just
712 // leave these alone.
717 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
718 /// Rewrite it to copy or set the elements of the scalarized memory.
719 void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
721 SmallVector<AllocaInst*, 32> &NewElts) {
723 // If this is a memcpy/memmove, construct the other pointer as the
724 // appropriate type. The "Other" pointer is the pointer that goes to
726 unsigned MemAlignment = MI->getAlignment()->getZExtValue();
727 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
728 if (BCInst == MCI->getRawDest())
729 OtherPtr = MCI->getRawSource();
731 assert(BCInst == MCI->getRawSource());
732 OtherPtr = MCI->getRawDest();
734 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
735 if (BCInst == MMI->getRawDest())
736 OtherPtr = MMI->getRawSource();
738 assert(BCInst == MMI->getRawSource());
739 OtherPtr = MMI->getRawDest();
743 // If there is an other pointer, we want to convert it to the same pointer
744 // type as AI has, so we can GEP through it safely.
746 // It is likely that OtherPtr is a bitcast, if so, remove it.
747 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
748 OtherPtr = BC->getOperand(0);
749 // All zero GEPs are effectively bitcasts.
750 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
751 if (GEP->hasAllZeroIndices())
752 OtherPtr = GEP->getOperand(0);
754 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
755 if (BCE->getOpcode() == Instruction::BitCast)
756 OtherPtr = BCE->getOperand(0);
758 // If the pointer is not the right type, insert a bitcast to the right
760 if (OtherPtr->getType() != AI->getType())
761 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
765 // Process each element of the aggregate.
766 Value *TheFn = MI->getOperand(0);
767 const Type *BytePtrTy = MI->getRawDest()->getType();
768 bool SROADest = MI->getRawDest() == BCInst;
770 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
772 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
773 // If this is a memcpy/memmove, emit a GEP of the other element address.
775 unsigned OtherEltAlign = MemAlignment;
778 Value *Idx[2] = { Zero, ConstantInt::get(Type::Int32Ty, i) };
779 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
780 OtherPtr->getNameStr()+"."+utostr(i),
783 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
784 if (const StructType *ST =
785 dyn_cast<StructType>(OtherPtrTy->getElementType())) {
786 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
789 cast<SequentialType>(OtherPtr->getType())->getElementType();
790 EltOffset = TD->getTypePaddedSize(EltTy)*i;
793 // The alignment of the other pointer is the guaranteed alignment of the
794 // element, which is affected by both the known alignment of the whole
795 // mem intrinsic and the alignment of the element. If the alignment of
796 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
797 // known alignment is just 4 bytes.
798 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
801 Value *EltPtr = NewElts[i];
802 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
804 // If we got down to a scalar, insert a load or store as appropriate.
805 if (EltTy->isSingleValueType()) {
806 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
808 // From Other to Alloca.
809 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
810 new StoreInst(Elt, EltPtr, MI);
812 // From Alloca to Other.
813 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
814 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
818 assert(isa<MemSetInst>(MI));
820 // If the stored element is zero (common case), just store a null
823 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
825 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
827 // If EltTy is a vector type, get the element type.
828 const Type *ValTy = EltTy;
829 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
830 ValTy = VTy->getElementType();
832 // Construct an integer with the right value.
833 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
834 APInt OneVal(EltSize, CI->getZExtValue());
835 APInt TotalVal(OneVal);
837 for (unsigned i = 0; 8*i < EltSize; ++i) {
838 TotalVal = TotalVal.shl(8);
842 // Convert the integer value to the appropriate type.
843 StoreVal = ConstantInt::get(TotalVal);
844 if (isa<PointerType>(ValTy))
845 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
846 else if (ValTy->isFloatingPoint())
847 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
848 assert(StoreVal->getType() == ValTy && "Type mismatch!");
850 // If the requested value was a vector constant, create it.
851 if (EltTy != ValTy) {
852 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
853 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
854 StoreVal = ConstantVector::get(&Elts[0], NumElts);
857 new StoreInst(StoreVal, EltPtr, MI);
860 // Otherwise, if we're storing a byte variable, use a memset call for
864 // Cast the element pointer to BytePtrTy.
865 if (EltPtr->getType() != BytePtrTy)
866 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
868 // Cast the other pointer (if we have one) to BytePtrTy.
869 if (OtherElt && OtherElt->getType() != BytePtrTy)
870 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
873 unsigned EltSize = TD->getTypePaddedSize(EltTy);
875 // Finally, insert the meminst for this element.
876 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
878 SROADest ? EltPtr : OtherElt, // Dest ptr
879 SROADest ? OtherElt : EltPtr, // Src ptr
880 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
881 ConstantInt::get(Type::Int32Ty, OtherEltAlign) // Align
883 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
885 assert(isa<MemSetInst>(MI));
887 EltPtr, MI->getOperand(2), // Dest, Value,
888 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
891 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
894 MI->eraseFromParent();
897 /// RewriteStoreUserOfWholeAlloca - We found an store of an integer that
898 /// overwrites the entire allocation. Extract out the pieces of the stored
899 /// integer and store them individually.
900 void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI,
902 SmallVector<AllocaInst*, 32> &NewElts){
903 // Extract each element out of the integer according to its structure offset
904 // and store the element value to the individual alloca.
905 Value *SrcVal = SI->getOperand(0);
906 const Type *AllocaEltTy = AI->getType()->getElementType();
907 uint64_t AllocaSizeBits = TD->getTypePaddedSizeInBits(AllocaEltTy);
909 // If this isn't a store of an integer to the whole alloca, it may be a store
910 // to the first element. Just ignore the store in this case and normal SROA
912 if (!isa<IntegerType>(SrcVal->getType()) ||
913 TD->getTypePaddedSizeInBits(SrcVal->getType()) != AllocaSizeBits)
916 DOUT << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << *SI;
918 // There are two forms here: AI could be an array or struct. Both cases
919 // have different ways to compute the element offset.
920 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
921 const StructLayout *Layout = TD->getStructLayout(EltSTy);
923 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
924 // Get the number of bits to shift SrcVal to get the value.
925 const Type *FieldTy = EltSTy->getElementType(i);
926 uint64_t Shift = Layout->getElementOffsetInBits(i);
928 if (TD->isBigEndian())
929 Shift = AllocaSizeBits-Shift-TD->getTypePaddedSizeInBits(FieldTy);
931 Value *EltVal = SrcVal;
933 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
934 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
935 "sroa.store.elt", SI);
938 // Truncate down to an integer of the right size.
939 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
941 // Ignore zero sized fields like {}, they obviously contain no data.
942 if (FieldSizeBits == 0) continue;
944 if (FieldSizeBits != AllocaSizeBits)
945 EltVal = new TruncInst(EltVal, IntegerType::get(FieldSizeBits), "", SI);
946 Value *DestField = NewElts[i];
947 if (EltVal->getType() == FieldTy) {
948 // Storing to an integer field of this size, just do it.
949 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
950 // Bitcast to the right element type (for fp/vector values).
951 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
953 // Otherwise, bitcast the dest pointer (for aggregates).
954 DestField = new BitCastInst(DestField,
955 PointerType::getUnqual(EltVal->getType()),
958 new StoreInst(EltVal, DestField, SI);
962 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
963 const Type *ArrayEltTy = ATy->getElementType();
964 uint64_t ElementOffset = TD->getTypePaddedSizeInBits(ArrayEltTy);
965 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
969 if (TD->isBigEndian())
970 Shift = AllocaSizeBits-ElementOffset;
974 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
975 // Ignore zero sized fields like {}, they obviously contain no data.
976 if (ElementSizeBits == 0) continue;
978 Value *EltVal = SrcVal;
980 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
981 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
982 "sroa.store.elt", SI);
985 // Truncate down to an integer of the right size.
986 if (ElementSizeBits != AllocaSizeBits)
987 EltVal = new TruncInst(EltVal, IntegerType::get(ElementSizeBits),"",SI);
988 Value *DestField = NewElts[i];
989 if (EltVal->getType() == ArrayEltTy) {
990 // Storing to an integer field of this size, just do it.
991 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
992 // Bitcast to the right element type (for fp/vector values).
993 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
995 // Otherwise, bitcast the dest pointer (for aggregates).
996 DestField = new BitCastInst(DestField,
997 PointerType::getUnqual(EltVal->getType()),
1000 new StoreInst(EltVal, DestField, SI);
1002 if (TD->isBigEndian())
1003 Shift -= ElementOffset;
1005 Shift += ElementOffset;
1009 SI->eraseFromParent();
1012 /// RewriteLoadUserOfWholeAlloca - We found an load of the entire allocation to
1013 /// an integer. Load the individual pieces to form the aggregate value.
1014 void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
1015 SmallVector<AllocaInst*, 32> &NewElts) {
1016 // Extract each element out of the NewElts according to its structure offset
1017 // and form the result value.
1018 const Type *AllocaEltTy = AI->getType()->getElementType();
1019 uint64_t AllocaSizeBits = TD->getTypePaddedSizeInBits(AllocaEltTy);
1021 // If this isn't a load of the whole alloca to an integer, it may be a load
1022 // of the first element. Just ignore the load in this case and normal SROA
1024 if (!isa<IntegerType>(LI->getType()) ||
1025 TD->getTypePaddedSizeInBits(LI->getType()) != AllocaSizeBits)
1028 DOUT << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << *LI;
1030 // There are two forms here: AI could be an array or struct. Both cases
1031 // have different ways to compute the element offset.
1032 const StructLayout *Layout = 0;
1033 uint64_t ArrayEltBitOffset = 0;
1034 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1035 Layout = TD->getStructLayout(EltSTy);
1037 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
1038 ArrayEltBitOffset = TD->getTypePaddedSizeInBits(ArrayEltTy);
1041 Value *ResultVal = Constant::getNullValue(LI->getType());
1043 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1044 // Load the value from the alloca. If the NewElt is an aggregate, cast
1045 // the pointer to an integer of the same size before doing the load.
1046 Value *SrcField = NewElts[i];
1047 const Type *FieldTy =
1048 cast<PointerType>(SrcField->getType())->getElementType();
1049 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1051 // Ignore zero sized fields like {}, they obviously contain no data.
1052 if (FieldSizeBits == 0) continue;
1054 const IntegerType *FieldIntTy = IntegerType::get(FieldSizeBits);
1055 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
1056 !isa<VectorType>(FieldTy))
1057 SrcField = new BitCastInst(SrcField, PointerType::getUnqual(FieldIntTy),
1059 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1061 // If SrcField is a fp or vector of the right size but that isn't an
1062 // integer type, bitcast to an integer so we can shift it.
1063 if (SrcField->getType() != FieldIntTy)
1064 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1066 // Zero extend the field to be the same size as the final alloca so that
1067 // we can shift and insert it.
1068 if (SrcField->getType() != ResultVal->getType())
1069 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1071 // Determine the number of bits to shift SrcField.
1073 if (Layout) // Struct case.
1074 Shift = Layout->getElementOffsetInBits(i);
1076 Shift = i*ArrayEltBitOffset;
1078 if (TD->isBigEndian())
1079 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1082 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
1083 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1086 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1089 LI->replaceAllUsesWith(ResultVal);
1090 LI->eraseFromParent();
1094 /// HasPadding - Return true if the specified type has any structure or
1095 /// alignment padding, false otherwise.
1096 static bool HasPadding(const Type *Ty, const TargetData &TD) {
1097 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1098 const StructLayout *SL = TD.getStructLayout(STy);
1099 unsigned PrevFieldBitOffset = 0;
1100 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1101 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1103 // Padding in sub-elements?
1104 if (HasPadding(STy->getElementType(i), TD))
1107 // Check to see if there is any padding between this element and the
1110 unsigned PrevFieldEnd =
1111 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1112 if (PrevFieldEnd < FieldBitOffset)
1116 PrevFieldBitOffset = FieldBitOffset;
1119 // Check for tail padding.
1120 if (unsigned EltCount = STy->getNumElements()) {
1121 unsigned PrevFieldEnd = PrevFieldBitOffset +
1122 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
1123 if (PrevFieldEnd < SL->getSizeInBits())
1127 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1128 return HasPadding(ATy->getElementType(), TD);
1129 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1130 return HasPadding(VTy->getElementType(), TD);
1132 return TD.getTypeSizeInBits(Ty) != TD.getTypePaddedSizeInBits(Ty);
1135 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1136 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1137 /// or 1 if safe after canonicalization has been performed.
1139 int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
1140 // Loop over the use list of the alloca. We can only transform it if all of
1141 // the users are safe to transform.
1144 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
1146 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
1147 if (Info.isUnsafe) {
1148 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
1153 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1154 // source and destination, we have to be careful. In particular, the memcpy
1155 // could be moving around elements that live in structure padding of the LLVM
1156 // types, but may actually be used. In these cases, we refuse to promote the
1158 if (Info.isMemCpySrc && Info.isMemCpyDst &&
1159 HasPadding(AI->getType()->getElementType(), *TD))
1162 // If we require cleanup, return 1, otherwise return 3.
1163 return Info.needsCleanup ? 1 : 3;
1166 /// CleanupGEP - GEP is used by an Alloca, which can be prompted after the GEP
1167 /// is canonicalized here.
1168 void SROA::CleanupGEP(GetElementPtrInst *GEPI) {
1169 gep_type_iterator I = gep_type_begin(GEPI);
1172 const ArrayType *AT = dyn_cast<ArrayType>(*I);
1176 uint64_t NumElements = AT->getNumElements();
1178 if (isa<ConstantInt>(I.getOperand()))
1181 if (NumElements == 1) {
1182 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
1186 assert(NumElements == 2 && "Unhandled case!");
1187 // All users of the GEP must be loads. At each use of the GEP, insert
1188 // two loads of the appropriate indexed GEP and select between them.
1189 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
1190 Constant::getNullValue(I.getOperand()->getType()),
1192 // Insert the new GEP instructions, which are properly indexed.
1193 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
1194 Indices[1] = Constant::getNullValue(Type::Int32Ty);
1195 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1198 GEPI->getName()+".0", GEPI);
1199 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
1200 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1203 GEPI->getName()+".1", GEPI);
1204 // Replace all loads of the variable index GEP with loads from both
1205 // indexes and a select.
1206 while (!GEPI->use_empty()) {
1207 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1208 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1209 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
1210 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
1211 LI->replaceAllUsesWith(R);
1212 LI->eraseFromParent();
1214 GEPI->eraseFromParent();
1218 /// CleanupAllocaUsers - If SROA reported that it can promote the specified
1219 /// allocation, but only if cleaned up, perform the cleanups required.
1220 void SROA::CleanupAllocaUsers(AllocationInst *AI) {
1221 // At this point, we know that the end result will be SROA'd and promoted, so
1222 // we can insert ugly code if required so long as sroa+mem2reg will clean it
1224 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1227 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U))
1229 else if (Instruction *I = dyn_cast<Instruction>(U)) {
1230 SmallVector<DbgInfoIntrinsic *, 2> DbgInUses;
1231 if (OnlyUsedByDbgInfoIntrinsics(I, &DbgInUses)) {
1232 // Safe to remove debug info uses.
1233 while (!DbgInUses.empty()) {
1234 DbgInfoIntrinsic *DI = DbgInUses.back(); DbgInUses.pop_back();
1235 DI->eraseFromParent();
1237 I->eraseFromParent();
1243 /// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1244 /// the offset specified by Offset (which is specified in bytes).
1246 /// There are two cases we handle here:
1247 /// 1) A union of vector types of the same size and potentially its elements.
1248 /// Here we turn element accesses into insert/extract element operations.
1249 /// This promotes a <4 x float> with a store of float to the third element
1250 /// into a <4 x float> that uses insert element.
1251 /// 2) A fully general blob of memory, which we turn into some (potentially
1252 /// large) integer type with extract and insert operations where the loads
1253 /// and stores would mutate the memory.
1254 static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
1255 unsigned AllocaSize, const TargetData &TD) {
1256 // If this could be contributing to a vector, analyze it.
1257 if (VecTy != Type::VoidTy) { // either null or a vector type.
1259 // If the In type is a vector that is the same size as the alloca, see if it
1260 // matches the existing VecTy.
1261 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1262 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1263 // If we're storing/loading a vector of the right size, allow it as a
1264 // vector. If this the first vector we see, remember the type so that
1265 // we know the element size.
1270 } else if (In == Type::FloatTy || In == Type::DoubleTy ||
1271 (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1272 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1273 // If we're accessing something that could be an element of a vector, see
1274 // if the implied vector agrees with what we already have and if Offset is
1275 // compatible with it.
1276 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1277 if (Offset % EltSize == 0 &&
1278 AllocaSize % EltSize == 0 &&
1280 cast<VectorType>(VecTy)->getElementType()
1281 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1283 VecTy = VectorType::get(In, AllocaSize/EltSize);
1289 // Otherwise, we have a case that we can't handle with an optimized vector
1290 // form. We can still turn this into a large integer.
1291 VecTy = Type::VoidTy;
1294 /// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
1295 /// its accesses to use a to single vector type, return true, and set VecTy to
1296 /// the new type. If we could convert the alloca into a single promotable
1297 /// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1298 /// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1299 /// is the current offset from the base of the alloca being analyzed.
1301 /// If we see at least one access to the value that is as a vector type, set the
1304 bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1305 bool &SawVec, uint64_t Offset,
1306 unsigned AllocaSize) {
1307 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1308 Instruction *User = cast<Instruction>(*UI);
1310 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1311 // Don't break volatile loads.
1312 if (LI->isVolatile())
1314 MergeInType(LI->getType(), Offset, VecTy, AllocaSize, *TD);
1315 SawVec |= isa<VectorType>(LI->getType());
1319 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1320 // Storing the pointer, not into the value?
1321 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
1322 MergeInType(SI->getOperand(0)->getType(), Offset, VecTy, AllocaSize, *TD);
1323 SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
1327 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
1328 if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1331 IsNotTrivial = true;
1335 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1336 // If this is a GEP with a variable indices, we can't handle it.
1337 if (!GEP->hasAllConstantIndices())
1340 // Compute the offset that this GEP adds to the pointer.
1341 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1342 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1343 &Indices[0], Indices.size());
1344 // See if all uses can be converted.
1345 if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
1348 IsNotTrivial = true;
1352 // If this is a constant sized memset of a constant value (e.g. 0) we can
1354 if (isa<MemSetInst>(User) &&
1355 // Store of constant value.
1356 isa<ConstantInt>(User->getOperand(2)) &&
1357 // Store with constant size.
1358 isa<ConstantInt>(User->getOperand(3))) {
1359 VecTy = Type::VoidTy;
1360 IsNotTrivial = true;
1364 // Otherwise, we cannot handle this!
1372 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1373 /// directly. This happens when we are converting an "integer union" to a
1374 /// single integer scalar, or when we are converting a "vector union" to a
1375 /// vector with insert/extractelement instructions.
1377 /// Offset is an offset from the original alloca, in bits that need to be
1378 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1379 void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
1380 while (!Ptr->use_empty()) {
1381 Instruction *User = cast<Instruction>(Ptr->use_back());
1383 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1384 ConvertUsesToScalar(CI, NewAI, Offset);
1385 CI->eraseFromParent();
1389 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1390 // Compute the offset that this GEP adds to the pointer.
1391 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1392 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1393 &Indices[0], Indices.size());
1394 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
1395 GEP->eraseFromParent();
1399 IRBuilder<> Builder(User->getParent(), User);
1401 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1402 // The load is a bit extract from NewAI shifted right by Offset bits.
1403 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1405 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1406 LI->replaceAllUsesWith(NewLoadVal);
1407 LI->eraseFromParent();
1411 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1412 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1413 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").c_str());
1414 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1416 Builder.CreateStore(New, NewAI);
1417 SI->eraseFromParent();
1421 // If this is a constant sized memset of a constant value (e.g. 0) we can
1422 // transform it into a store of the expanded constant value.
1423 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1424 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1425 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
1426 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1428 // Compute the value replicated the right number of times.
1429 APInt APVal(NumBytes*8, Val);
1431 // Splat the value if non-zero.
1433 for (unsigned i = 1; i != NumBytes; ++i)
1434 APVal |= APVal << 8;
1436 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").c_str());
1437 Value *New = ConvertScalar_InsertValue(ConstantInt::get(APVal), Old,
1439 Builder.CreateStore(New, NewAI);
1440 MSI->eraseFromParent();
1445 assert(0 && "Unsupported operation!");
1450 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1451 /// or vector value FromVal, extracting the bits from the offset specified by
1452 /// Offset. This returns the value, which is of type ToType.
1454 /// This happens when we are converting an "integer union" to a single
1455 /// integer scalar, or when we are converting a "vector union" to a vector with
1456 /// insert/extractelement instructions.
1458 /// Offset is an offset from the original alloca, in bits that need to be
1459 /// shifted to the right.
1460 Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1461 uint64_t Offset, IRBuilder<> &Builder) {
1462 // If the load is of the whole new alloca, no conversion is needed.
1463 if (FromVal->getType() == ToType && Offset == 0)
1466 // If the result alloca is a vector type, this is either an element
1467 // access or a bitcast to another vector type of the same size.
1468 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1469 if (isa<VectorType>(ToType))
1470 return Builder.CreateBitCast(FromVal, ToType, "tmp");
1472 // Otherwise it must be an element access.
1475 unsigned EltSize = TD->getTypePaddedSizeInBits(VTy->getElementType());
1476 Elt = Offset/EltSize;
1477 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
1479 // Return the element extracted out of it.
1480 Value *V = Builder.CreateExtractElement(FromVal,
1481 ConstantInt::get(Type::Int32Ty,Elt),
1483 if (V->getType() != ToType)
1484 V = Builder.CreateBitCast(V, ToType, "tmp");
1488 // If ToType is a first class aggregate, extract out each of the pieces and
1489 // use insertvalue's to form the FCA.
1490 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1491 const StructLayout &Layout = *TD->getStructLayout(ST);
1492 Value *Res = UndefValue::get(ST);
1493 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1494 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
1495 Offset+Layout.getElementOffsetInBits(i),
1497 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1502 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
1503 uint64_t EltSize = TD->getTypePaddedSizeInBits(AT->getElementType());
1504 Value *Res = UndefValue::get(AT);
1505 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1506 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1507 Offset+i*EltSize, Builder);
1508 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1513 // Otherwise, this must be a union that was converted to an integer value.
1514 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
1516 // If this is a big-endian system and the load is narrower than the
1517 // full alloca type, we need to do a shift to get the right bits.
1519 if (TD->isBigEndian()) {
1520 // On big-endian machines, the lowest bit is stored at the bit offset
1521 // from the pointer given by getTypeStoreSizeInBits. This matters for
1522 // integers with a bitwidth that is not a multiple of 8.
1523 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
1524 TD->getTypeStoreSizeInBits(ToType) - Offset;
1529 // Note: we support negative bitwidths (with shl) which are not defined.
1530 // We do this to support (f.e.) loads off the end of a structure where
1531 // only some bits are used.
1532 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
1533 FromVal = Builder.CreateLShr(FromVal, ConstantInt::get(FromVal->getType(),
1535 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
1536 FromVal = Builder.CreateShl(FromVal, ConstantInt::get(FromVal->getType(),
1539 // Finally, unconditionally truncate the integer to the right width.
1540 unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
1541 if (LIBitWidth < NTy->getBitWidth())
1542 FromVal = Builder.CreateTrunc(FromVal, IntegerType::get(LIBitWidth), "tmp");
1543 else if (LIBitWidth > NTy->getBitWidth())
1544 FromVal = Builder.CreateZExt(FromVal, IntegerType::get(LIBitWidth), "tmp");
1546 // If the result is an integer, this is a trunc or bitcast.
1547 if (isa<IntegerType>(ToType)) {
1549 } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
1550 // Just do a bitcast, we know the sizes match up.
1551 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
1553 // Otherwise must be a pointer.
1554 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
1556 assert(FromVal->getType() == ToType && "Didn't convert right?");
1561 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1562 /// or vector value "Old" at the offset specified by Offset.
1564 /// This happens when we are converting an "integer union" to a
1565 /// single integer scalar, or when we are converting a "vector union" to a
1566 /// vector with insert/extractelement instructions.
1568 /// Offset is an offset from the original alloca, in bits that need to be
1569 /// shifted to the right.
1570 Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
1571 uint64_t Offset, IRBuilder<> &Builder) {
1573 // Convert the stored type to the actual type, shift it left to insert
1574 // then 'or' into place.
1575 const Type *AllocaType = Old->getType();
1577 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
1578 // If the result alloca is a vector type, this is either an element
1579 // access or a bitcast to another vector type.
1580 if (isa<VectorType>(SV->getType())) {
1581 SV = Builder.CreateBitCast(SV, AllocaType, "tmp");
1583 // Must be an element insertion.
1584 unsigned Elt = Offset/TD->getTypePaddedSizeInBits(VTy->getElementType());
1586 if (SV->getType() != VTy->getElementType())
1587 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1589 SV = Builder.CreateInsertElement(Old, SV,
1590 ConstantInt::get(Type::Int32Ty, Elt),
1596 // If SV is a first-class aggregate value, insert each value recursively.
1597 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1598 const StructLayout &Layout = *TD->getStructLayout(ST);
1599 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1600 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1601 Old = ConvertScalar_InsertValue(Elt, Old,
1602 Offset+Layout.getElementOffsetInBits(i),
1608 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
1609 uint64_t EltSize = TD->getTypePaddedSizeInBits(AT->getElementType());
1610 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1611 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1612 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
1617 // If SV is a float, convert it to the appropriate integer type.
1618 // If it is a pointer, do the same.
1619 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1620 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1621 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1622 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1623 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
1624 SV = Builder.CreateBitCast(SV, IntegerType::get(SrcWidth), "tmp");
1625 else if (isa<PointerType>(SV->getType()))
1626 SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(), "tmp");
1628 // Zero extend or truncate the value if needed.
1629 if (SV->getType() != AllocaType) {
1630 if (SV->getType()->getPrimitiveSizeInBits() <
1631 AllocaType->getPrimitiveSizeInBits())
1632 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
1634 // Truncation may be needed if storing more than the alloca can hold
1635 // (undefined behavior).
1636 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
1637 SrcWidth = DestWidth;
1638 SrcStoreWidth = DestStoreWidth;
1642 // If this is a big-endian system and the store is narrower than the
1643 // full alloca type, we need to do a shift to get the right bits.
1645 if (TD->isBigEndian()) {
1646 // On big-endian machines, the lowest bit is stored at the bit offset
1647 // from the pointer given by getTypeStoreSizeInBits. This matters for
1648 // integers with a bitwidth that is not a multiple of 8.
1649 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1654 // Note: we support negative bitwidths (with shr) which are not defined.
1655 // We do this to support (f.e.) stores off the end of a structure where
1656 // only some bits in the structure are set.
1657 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1658 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1659 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt), "tmp");
1661 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1662 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt), "tmp");
1663 Mask = Mask.lshr(-ShAmt);
1666 // Mask out the bits we are about to insert from the old value, and or
1668 if (SrcWidth != DestWidth) {
1669 assert(DestWidth > SrcWidth);
1670 Old = Builder.CreateAnd(Old, ConstantInt::get(~Mask), "mask");
1671 SV = Builder.CreateOr(Old, SV, "ins");
1678 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1679 /// some part of a constant global variable. This intentionally only accepts
1680 /// constant expressions because we don't can't rewrite arbitrary instructions.
1681 static bool PointsToConstantGlobal(Value *V) {
1682 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1683 return GV->isConstant();
1684 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1685 if (CE->getOpcode() == Instruction::BitCast ||
1686 CE->getOpcode() == Instruction::GetElementPtr)
1687 return PointsToConstantGlobal(CE->getOperand(0));
1691 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1692 /// pointer to an alloca. Ignore any reads of the pointer, return false if we
1693 /// see any stores or other unknown uses. If we see pointer arithmetic, keep
1694 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
1695 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1696 /// the alloca, and if the source pointer is a pointer to a constant global, we
1697 /// can optimize this.
1698 static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1700 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1701 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1702 // Ignore non-volatile loads, they are always ok.
1703 if (!LI->isVolatile())
1706 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1707 // If uses of the bitcast are ok, we are ok.
1708 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1712 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1713 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1714 // doesn't, it does.
1715 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1716 isOffset || !GEP->hasAllZeroIndices()))
1721 // If this is isn't our memcpy/memmove, reject it as something we can't
1723 if (!isa<MemCpyInst>(*UI) && !isa<MemMoveInst>(*UI))
1726 // If we already have seen a copy, reject the second one.
1727 if (TheCopy) return false;
1729 // If the pointer has been offset from the start of the alloca, we can't
1730 // safely handle this.
1731 if (isOffset) return false;
1733 // If the memintrinsic isn't using the alloca as the dest, reject it.
1734 if (UI.getOperandNo() != 1) return false;
1736 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1738 // If the source of the memcpy/move is not a constant global, reject it.
1739 if (!PointsToConstantGlobal(MI->getOperand(2)))
1742 // Otherwise, the transform is safe. Remember the copy instruction.
1748 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1749 /// modified by a copy from a constant global. If we can prove this, we can
1750 /// replace any uses of the alloca with uses of the global directly.
1751 Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1752 Instruction *TheCopy = 0;
1753 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))