1 //===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Instructions.h"
28 #include "llvm/IntrinsicInst.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Analysis/Dominators.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/GetElementPtrTypeIterator.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/ADT/Statistic.h"
39 #include "llvm/ADT/StringExtras.h"
42 STATISTIC(NumReplaced, "Number of allocas broken up");
43 STATISTIC(NumPromoted, "Number of allocas promoted");
44 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
47 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
48 bool runOnFunction(Function &F);
50 bool performScalarRepl(Function &F);
51 bool performPromotion(Function &F);
53 // getAnalysisUsage - This pass does not require any passes, but we know it
54 // will not alter the CFG, so say so.
55 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56 AU.addRequired<ETForest>();
57 AU.addRequired<DominanceFrontier>();
58 AU.addRequired<TargetData>();
63 int isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI);
64 int isSafeUseOfAllocation(Instruction *User, AllocationInst *AI);
65 bool isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI);
66 bool isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI);
67 int isSafeAllocaToScalarRepl(AllocationInst *AI);
68 void DoScalarReplacement(AllocationInst *AI,
69 std::vector<AllocationInst*> &WorkList);
70 void CanonicalizeAllocaUsers(AllocationInst *AI);
71 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
73 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
74 SmallVector<AllocaInst*, 32> &NewElts);
76 const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
77 void ConvertToScalar(AllocationInst *AI, const Type *Ty);
78 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
81 RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
84 // Public interface to the ScalarReplAggregates pass
85 FunctionPass *llvm::createScalarReplAggregatesPass() { return new SROA(); }
88 bool SROA::runOnFunction(Function &F) {
89 bool Changed = performPromotion(F);
91 bool LocalChange = performScalarRepl(F);
92 if (!LocalChange) break; // No need to repromote if no scalarrepl
94 LocalChange = performPromotion(F);
95 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
102 bool SROA::performPromotion(Function &F) {
103 std::vector<AllocaInst*> Allocas;
104 const TargetData &TD = getAnalysis<TargetData>();
105 ETForest &ET = getAnalysis<ETForest>();
106 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
108 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
110 bool Changed = false;
115 // Find allocas that are safe to promote, by looking at all instructions in
117 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
118 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
119 if (isAllocaPromotable(AI, TD))
120 Allocas.push_back(AI);
122 if (Allocas.empty()) break;
124 PromoteMemToReg(Allocas, ET, DF, TD);
125 NumPromoted += Allocas.size();
132 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
133 // which runs on all of the malloc/alloca instructions in the function, removing
134 // them if they are only used by getelementptr instructions.
136 bool SROA::performScalarRepl(Function &F) {
137 std::vector<AllocationInst*> WorkList;
139 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
140 BasicBlock &BB = F.getEntryBlock();
141 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
142 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
143 WorkList.push_back(A);
145 // Process the worklist
146 bool Changed = false;
147 while (!WorkList.empty()) {
148 AllocationInst *AI = WorkList.back();
151 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
152 // with unused elements.
153 if (AI->use_empty()) {
154 AI->eraseFromParent();
158 // If we can turn this aggregate value (potentially with casts) into a
159 // simple scalar value that can be mem2reg'd into a register value.
160 bool IsNotTrivial = false;
161 if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
162 if (IsNotTrivial && ActualType != Type::VoidTy) {
163 ConvertToScalar(AI, ActualType);
168 // We cannot transform the allocation instruction if it is an array
169 // allocation (allocations OF arrays are ok though), and an allocation of a
170 // scalar value cannot be decomposed at all.
171 if (!AI->isArrayAllocation() &&
172 (isa<StructType>(AI->getAllocatedType()) ||
173 isa<ArrayType>(AI->getAllocatedType()))) {
174 // Check that all of the users of the allocation are capable of being
176 switch (isSafeAllocaToScalarRepl(AI)) {
177 default: assert(0 && "Unexpected value!");
178 case 0: // Not safe to scalar replace.
180 case 1: // Safe, but requires cleanup/canonicalizations first
181 CanonicalizeAllocaUsers(AI);
183 case 3: // Safe to scalar replace.
184 DoScalarReplacement(AI, WorkList);
190 // Otherwise, couldn't process this.
196 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
197 /// predicate, do SROA now.
198 void SROA::DoScalarReplacement(AllocationInst *AI,
199 std::vector<AllocationInst*> &WorkList) {
200 DOUT << "Found inst to xform: " << *AI;
201 SmallVector<AllocaInst*, 32> ElementAllocas;
202 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
203 ElementAllocas.reserve(ST->getNumContainedTypes());
204 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
205 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
207 AI->getName() + "." + utostr(i), AI);
208 ElementAllocas.push_back(NA);
209 WorkList.push_back(NA); // Add to worklist for recursive processing
212 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
213 ElementAllocas.reserve(AT->getNumElements());
214 const Type *ElTy = AT->getElementType();
215 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
216 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
217 AI->getName() + "." + utostr(i), AI);
218 ElementAllocas.push_back(NA);
219 WorkList.push_back(NA); // Add to worklist for recursive processing
223 // Now that we have created the alloca instructions that we want to use,
224 // expand the getelementptr instructions to use them.
226 while (!AI->use_empty()) {
227 Instruction *User = cast<Instruction>(AI->use_back());
228 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
229 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
230 BCInst->eraseFromParent();
234 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
235 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
237 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
239 assert(Idx < ElementAllocas.size() && "Index out of range?");
240 AllocaInst *AllocaToUse = ElementAllocas[Idx];
243 if (GEPI->getNumOperands() == 3) {
244 // Do not insert a new getelementptr instruction with zero indices, only
245 // to have it optimized out later.
246 RepValue = AllocaToUse;
248 // We are indexing deeply into the structure, so we still need a
249 // getelement ptr instruction to finish the indexing. This may be
250 // expanded itself once the worklist is rerun.
252 SmallVector<Value*, 8> NewArgs;
253 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
254 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
255 RepValue = new GetElementPtrInst(AllocaToUse, &NewArgs[0],
256 NewArgs.size(), "", GEPI);
257 RepValue->takeName(GEPI);
260 // If this GEP is to the start of the aggregate, check for memcpys.
262 bool IsStartOfAggregateGEP = true;
263 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i) {
264 if (!isa<ConstantInt>(GEPI->getOperand(i))) {
265 IsStartOfAggregateGEP = false;
268 if (!cast<ConstantInt>(GEPI->getOperand(i))->isZero()) {
269 IsStartOfAggregateGEP = false;
274 if (IsStartOfAggregateGEP)
275 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
279 // Move all of the users over to the new GEP.
280 GEPI->replaceAllUsesWith(RepValue);
281 // Delete the old GEP
282 GEPI->eraseFromParent();
285 // Finally, delete the Alloca instruction
286 AI->eraseFromParent();
291 /// isSafeElementUse - Check to see if this use is an allowed use for a
292 /// getelementptr instruction of an array aggregate allocation. isFirstElt
293 /// indicates whether Ptr is known to the start of the aggregate.
295 int SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI) {
296 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
298 Instruction *User = cast<Instruction>(*I);
299 switch (User->getOpcode()) {
300 case Instruction::Load: break;
301 case Instruction::Store:
302 // Store is ok if storing INTO the pointer, not storing the pointer
303 if (User->getOperand(0) == Ptr) return 0;
305 case Instruction::GetElementPtr: {
306 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
307 bool AreAllZeroIndices = isFirstElt;
308 if (GEP->getNumOperands() > 1) {
309 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
310 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
311 return 0; // Using pointer arithmetic to navigate the array.
313 if (AreAllZeroIndices) {
314 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
315 if (!isa<ConstantInt>(GEP->getOperand(i)) ||
316 !cast<ConstantInt>(GEP->getOperand(i))->isZero()) {
317 AreAllZeroIndices = false;
323 if (!isSafeElementUse(GEP, AreAllZeroIndices, AI)) return 0;
326 case Instruction::BitCast:
328 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI))
330 DOUT << " Transformation preventing inst: " << *User;
332 case Instruction::Call:
333 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
334 if (isFirstElt && isSafeMemIntrinsicOnAllocation(MI, AI))
337 DOUT << " Transformation preventing inst: " << *User;
340 DOUT << " Transformation preventing inst: " << *User;
344 return 3; // All users look ok :)
347 /// AllUsersAreLoads - Return true if all users of this value are loads.
348 static bool AllUsersAreLoads(Value *Ptr) {
349 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
351 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
356 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
357 /// aggregate allocation.
359 int SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI) {
360 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
361 return isSafeUseOfBitCastedAllocation(C, AI) ? 3 : 0;
362 if (!isa<GetElementPtrInst>(User)) return 0;
364 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
365 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
367 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
369 I.getOperand() != Constant::getNullValue(I.getOperand()->getType()))
373 if (I == E) return 0; // ran out of GEP indices??
375 bool IsAllZeroIndices = true;
377 // If this is a use of an array allocation, do a bit more checking for sanity.
378 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
379 uint64_t NumElements = AT->getNumElements();
381 if (ConstantInt *Idx = dyn_cast<ConstantInt>(I.getOperand())) {
382 IsAllZeroIndices &= Idx->isZero();
384 // Check to make sure that index falls within the array. If not,
385 // something funny is going on, so we won't do the optimization.
387 if (Idx->getZExtValue() >= NumElements)
390 // We cannot scalar repl this level of the array unless any array
391 // sub-indices are in-range constants. In particular, consider:
392 // A[0][i]. We cannot know that the user isn't doing invalid things like
393 // allowing i to index an out-of-range subscript that accesses A[1].
395 // Scalar replacing *just* the outer index of the array is probably not
396 // going to be a win anyway, so just give up.
397 for (++I; I != E && (isa<ArrayType>(*I) || isa<VectorType>(*I)); ++I) {
398 uint64_t NumElements;
399 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*I))
400 NumElements = SubArrayTy->getNumElements();
402 NumElements = cast<VectorType>(*I)->getNumElements();
404 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
405 if (!IdxVal) return 0;
406 if (IdxVal->getZExtValue() >= NumElements)
408 IsAllZeroIndices &= IdxVal->isZero();
412 IsAllZeroIndices = 0;
414 // If this is an array index and the index is not constant, we cannot
415 // promote... that is unless the array has exactly one or two elements in
416 // it, in which case we CAN promote it, but we have to canonicalize this
417 // out if this is the only problem.
418 if ((NumElements == 1 || NumElements == 2) &&
419 AllUsersAreLoads(GEPI))
420 return 1; // Canonicalization required!
425 // If there are any non-simple uses of this getelementptr, make sure to reject
427 return isSafeElementUse(GEPI, IsAllZeroIndices, AI);
430 /// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
431 /// intrinsic can be promoted by SROA. At this point, we know that the operand
432 /// of the memintrinsic is a pointer to the beginning of the allocation.
433 bool SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI){
434 // If not constant length, give up.
435 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
436 if (!Length) return false;
438 // If not the whole aggregate, give up.
439 const TargetData &TD = getAnalysis<TargetData>();
440 if (Length->getZExtValue() != TD.getTypeSize(AI->getType()->getElementType()))
443 // We only know about memcpy/memset/memmove.
444 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
446 // Otherwise, we can transform it.
450 /// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
452 bool SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI) {
453 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
455 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
456 if (!isSafeUseOfBitCastedAllocation(BCU, AI))
458 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
459 if (!isSafeMemIntrinsicOnAllocation(MI, AI))
468 /// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
469 /// to its first element. Transform users of the cast to use the new values
471 void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
472 SmallVector<AllocaInst*, 32> &NewElts) {
473 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
474 const TargetData &TD = getAnalysis<TargetData>();
476 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
478 if (BitCastInst *BCU = dyn_cast<BitCastInst>(*UI)) {
479 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
481 BCU->eraseFromParent();
485 // Otherwise, must be memcpy/memmove/memset of the entire aggregate. Split
486 // into one per element.
487 MemIntrinsic *MI = dyn_cast<MemIntrinsic>(*UI);
489 // If it's not a mem intrinsic, it must be some other user of a gep of the
490 // first pointer. Just leave these alone.
496 // If this is a memcpy/memmove, construct the other pointer as the
499 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
500 if (BCInst == MCI->getRawDest())
501 OtherPtr = MCI->getRawSource();
503 assert(BCInst == MCI->getRawSource());
504 OtherPtr = MCI->getRawDest();
506 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
507 if (BCInst == MMI->getRawDest())
508 OtherPtr = MMI->getRawSource();
510 assert(BCInst == MMI->getRawSource());
511 OtherPtr = MMI->getRawDest();
515 // If there is an other pointer, we want to convert it to the same pointer
516 // type as AI has, so we can GEP through it.
518 // It is likely that OtherPtr is a bitcast, if so, remove it.
519 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
520 OtherPtr = BC->getOperand(0);
521 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
522 if (BCE->getOpcode() == Instruction::BitCast)
523 OtherPtr = BCE->getOperand(0);
525 // If the pointer is not the right type, insert a bitcast to the right
527 if (OtherPtr->getType() != AI->getType())
528 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
532 // Process each element of the aggregate.
533 Value *TheFn = MI->getOperand(0);
534 const Type *BytePtrTy = MI->getRawDest()->getType();
535 bool SROADest = MI->getRawDest() == BCInst;
537 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
538 // If this is a memcpy/memmove, emit a GEP of the other element address.
541 OtherElt = new GetElementPtrInst(OtherPtr, Zero,
542 ConstantInt::get(Type::Int32Ty, i),
543 OtherPtr->getNameStr()+"."+utostr(i),
547 Value *EltPtr = NewElts[i];
548 const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
550 // If we got down to a scalar, insert a load or store as appropriate.
551 if (EltTy->isFirstClassType()) {
552 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
553 Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
555 new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
558 assert(isa<MemSetInst>(MI));
560 // If the stored element is zero (common case), just store a null
563 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
565 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
567 // If EltTy is a packed type, get the element type.
568 const Type *ValTy = EltTy;
569 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
570 ValTy = VTy->getElementType();
572 // Construct an integer with the right value.
573 unsigned EltSize = TD.getTypeSize(ValTy);
574 APInt OneVal(EltSize*8, CI->getZExtValue());
575 APInt TotalVal(OneVal);
577 for (unsigned i = 0; i != EltSize-1; ++i) {
578 TotalVal = TotalVal.shl(8);
582 // Convert the integer value to the appropriate type.
583 StoreVal = ConstantInt::get(TotalVal);
584 if (isa<PointerType>(ValTy))
585 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
586 else if (ValTy->isFloatingPoint())
587 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
588 assert(StoreVal->getType() == ValTy && "Type mismatch!");
590 // If the requested value was a vector constant, create it.
591 if (EltTy != ValTy) {
592 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
593 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
594 StoreVal = ConstantVector::get(&Elts[0], NumElts);
597 new StoreInst(StoreVal, EltPtr, MI);
600 // Otherwise, if we're storing a byte variable, use a memset call for
605 // Cast the element pointer to BytePtrTy.
606 if (EltPtr->getType() != BytePtrTy)
607 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
609 // Cast the other pointer (if we have one) to BytePtrTy.
610 if (OtherElt && OtherElt->getType() != BytePtrTy)
611 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
614 unsigned EltSize = TD.getTypeSize(EltTy);
616 // Finally, insert the meminst for this element.
617 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
619 SROADest ? EltPtr : OtherElt, // Dest ptr
620 SROADest ? OtherElt : EltPtr, // Src ptr
621 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
624 new CallInst(TheFn, Ops, 4, "", MI);
626 assert(isa<MemSetInst>(MI));
628 EltPtr, MI->getOperand(2), // Dest, Value,
629 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
632 new CallInst(TheFn, Ops, 4, "", MI);
636 // Finally, MI is now dead, as we've modified its actions to occur on all of
637 // the elements of the aggregate.
639 MI->eraseFromParent();
644 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
645 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
646 /// or 1 if safe after canonicalization has been performed.
648 int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
649 // Loop over the use list of the alloca. We can only transform it if all of
650 // the users are safe to transform.
653 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
655 isSafe &= isSafeUseOfAllocation(cast<Instruction>(*I), AI);
657 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
661 // If we require cleanup, isSafe is now 1, otherwise it is 3.
665 /// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
666 /// allocation, but only if cleaned up, perform the cleanups required.
667 void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
668 // At this point, we know that the end result will be SROA'd and promoted, so
669 // we can insert ugly code if required so long as sroa+mem2reg will clean it
671 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
673 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI++);
675 gep_type_iterator I = gep_type_begin(GEPI);
678 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
679 uint64_t NumElements = AT->getNumElements();
681 if (!isa<ConstantInt>(I.getOperand())) {
682 if (NumElements == 1) {
683 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
685 assert(NumElements == 2 && "Unhandled case!");
686 // All users of the GEP must be loads. At each use of the GEP, insert
687 // two loads of the appropriate indexed GEP and select between them.
688 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
689 Constant::getNullValue(I.getOperand()->getType()),
691 // Insert the new GEP instructions, which are properly indexed.
692 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
693 Indices[1] = Constant::getNullValue(Type::Int32Ty);
694 Value *ZeroIdx = new GetElementPtrInst(GEPI->getOperand(0),
695 &Indices[0], Indices.size(),
696 GEPI->getName()+".0", GEPI);
697 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
698 Value *OneIdx = new GetElementPtrInst(GEPI->getOperand(0),
699 &Indices[0], Indices.size(),
700 GEPI->getName()+".1", GEPI);
701 // Replace all loads of the variable index GEP with loads from both
702 // indexes and a select.
703 while (!GEPI->use_empty()) {
704 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
705 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
706 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
707 Value *R = new SelectInst(IsOne, One, Zero, LI->getName(), LI);
708 LI->replaceAllUsesWith(R);
709 LI->eraseFromParent();
711 GEPI->eraseFromParent();
718 /// MergeInType - Add the 'In' type to the accumulated type so far. If the
719 /// types are incompatible, return true, otherwise update Accum and return
722 /// There are three cases we handle here:
723 /// 1) An effectively-integer union, where the pieces are stored into as
724 /// smaller integers (common with byte swap and other idioms).
725 /// 2) A union of vector types of the same size and potentially its elements.
726 /// Here we turn element accesses into insert/extract element operations.
727 /// 3) A union of scalar types, such as int/float or int/pointer. Here we
728 /// merge together into integers, allowing the xform to work with #1 as
730 static bool MergeInType(const Type *In, const Type *&Accum,
731 const TargetData &TD) {
732 // If this is our first type, just use it.
733 const VectorType *PTy;
734 if (Accum == Type::VoidTy || In == Accum) {
736 } else if (In == Type::VoidTy) {
738 } else if (In->isInteger() && Accum->isInteger()) { // integer union.
739 // Otherwise pick whichever type is larger.
740 if (cast<IntegerType>(In)->getBitWidth() >
741 cast<IntegerType>(Accum)->getBitWidth())
743 } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
744 // Pointer unions just stay as one of the pointers.
745 } else if (isa<VectorType>(In) || isa<VectorType>(Accum)) {
746 if ((PTy = dyn_cast<VectorType>(Accum)) &&
747 PTy->getElementType() == In) {
748 // Accum is a vector, and we are accessing an element: ok.
749 } else if ((PTy = dyn_cast<VectorType>(In)) &&
750 PTy->getElementType() == Accum) {
751 // In is a vector, and accum is an element: ok, remember In.
753 } else if ((PTy = dyn_cast<VectorType>(In)) && isa<VectorType>(Accum) &&
754 PTy->getBitWidth() == cast<VectorType>(Accum)->getBitWidth()) {
755 // Two vectors of the same size: keep Accum.
757 // Cannot insert an short into a <4 x int> or handle
758 // <2 x int> -> <4 x int>
762 // Pointer/FP/Integer unions merge together as integers.
763 switch (Accum->getTypeID()) {
764 case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
765 case Type::FloatTyID: Accum = Type::Int32Ty; break;
766 case Type::DoubleTyID: Accum = Type::Int64Ty; break;
768 assert(Accum->isInteger() && "Unknown FP type!");
772 switch (In->getTypeID()) {
773 case Type::PointerTyID: In = TD.getIntPtrType(); break;
774 case Type::FloatTyID: In = Type::Int32Ty; break;
775 case Type::DoubleTyID: In = Type::Int64Ty; break;
777 assert(In->isInteger() && "Unknown FP type!");
780 return MergeInType(In, Accum, TD);
785 /// getUIntAtLeastAsBitAs - Return an unsigned integer type that is at least
786 /// as big as the specified type. If there is no suitable type, this returns
788 const Type *getUIntAtLeastAsBitAs(unsigned NumBits) {
789 if (NumBits > 64) return 0;
790 if (NumBits > 32) return Type::Int64Ty;
791 if (NumBits > 16) return Type::Int32Ty;
792 if (NumBits > 8) return Type::Int16Ty;
796 /// CanConvertToScalar - V is a pointer. If we can convert the pointee to a
797 /// single scalar integer type, return that type. Further, if the use is not
798 /// a completely trivial use that mem2reg could promote, set IsNotTrivial. If
799 /// there are no uses of this pointer, return Type::VoidTy to differentiate from
802 const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
803 const Type *UsedType = Type::VoidTy; // No uses, no forced type.
804 const TargetData &TD = getAnalysis<TargetData>();
805 const PointerType *PTy = cast<PointerType>(V->getType());
807 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
808 Instruction *User = cast<Instruction>(*UI);
810 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
811 if (MergeInType(LI->getType(), UsedType, TD))
814 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
815 // Storing the pointer, not into the value?
816 if (SI->getOperand(0) == V) return 0;
818 // NOTE: We could handle storing of FP imms into integers here!
820 if (MergeInType(SI->getOperand(0)->getType(), UsedType, TD))
822 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
824 const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
825 if (!SubTy || MergeInType(SubTy, UsedType, TD)) return 0;
826 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
827 // Check to see if this is stepping over an element: GEP Ptr, int C
828 if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
829 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
830 unsigned ElSize = TD.getTypeSize(PTy->getElementType());
831 unsigned BitOffset = Idx*ElSize*8;
832 if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
835 const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
836 if (SubElt == 0) return 0;
837 if (SubElt != Type::VoidTy && SubElt->isInteger()) {
839 getUIntAtLeastAsBitAs(TD.getTypeSize(SubElt)*8+BitOffset);
840 if (NewTy == 0 || MergeInType(NewTy, UsedType, TD)) return 0;
843 } else if (GEP->getNumOperands() == 3 &&
844 isa<ConstantInt>(GEP->getOperand(1)) &&
845 isa<ConstantInt>(GEP->getOperand(2)) &&
846 cast<ConstantInt>(GEP->getOperand(1))->isZero()) {
847 // We are stepping into an element, e.g. a structure or an array:
848 // GEP Ptr, int 0, uint C
849 const Type *AggTy = PTy->getElementType();
850 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
852 if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
853 if (Idx >= ATy->getNumElements()) return 0; // Out of range.
854 } else if (const VectorType *VectorTy = dyn_cast<VectorType>(AggTy)) {
855 // Getting an element of the packed vector.
856 if (Idx >= VectorTy->getNumElements()) return 0; // Out of range.
858 // Merge in the vector type.
859 if (MergeInType(VectorTy, UsedType, TD)) return 0;
861 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
862 if (SubTy == 0) return 0;
864 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
867 // We'll need to change this to an insert/extract element operation.
869 continue; // Everything looks ok
871 } else if (isa<StructType>(AggTy)) {
872 // Structs are always ok.
876 const Type *NTy = getUIntAtLeastAsBitAs(TD.getTypeSize(AggTy)*8);
877 if (NTy == 0 || MergeInType(NTy, UsedType, TD)) return 0;
878 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
879 if (SubTy == 0) return 0;
880 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
882 continue; // Everything looks ok
886 // Cannot handle this!
894 /// ConvertToScalar - The specified alloca passes the CanConvertToScalar
895 /// predicate and is non-trivial. Convert it to something that can be trivially
896 /// promoted into a register by mem2reg.
897 void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
898 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = "
899 << *ActualTy << "\n";
902 BasicBlock *EntryBlock = AI->getParent();
903 assert(EntryBlock == &EntryBlock->getParent()->getEntryBlock() &&
904 "Not in the entry block!");
905 EntryBlock->getInstList().remove(AI); // Take the alloca out of the program.
907 // Create and insert the alloca.
908 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
909 EntryBlock->begin());
910 ConvertUsesToScalar(AI, NewAI, 0);
915 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
916 /// directly. This happens when we are converting an "integer union" to a
917 /// single integer scalar, or when we are converting a "vector union" to a
918 /// vector with insert/extractelement instructions.
920 /// Offset is an offset from the original alloca, in bits that need to be
921 /// shifted to the right. By the end of this, there should be no uses of Ptr.
922 void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
923 const TargetData &TD = getAnalysis<TargetData>();
924 while (!Ptr->use_empty()) {
925 Instruction *User = cast<Instruction>(Ptr->use_back());
927 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
928 // The load is a bit extract from NewAI shifted right by Offset bits.
929 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
930 if (NV->getType() == LI->getType()) {
931 // We win, no conversion needed.
932 } else if (const VectorType *PTy = dyn_cast<VectorType>(NV->getType())) {
933 // If the result alloca is a vector type, this is either an element
934 // access or a bitcast to another vector type.
935 if (isa<VectorType>(LI->getType())) {
936 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
938 // Must be an element access.
939 unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
940 NV = new ExtractElementInst(
941 NV, ConstantInt::get(Type::Int32Ty, Elt), "tmp", LI);
943 } else if (isa<PointerType>(NV->getType())) {
944 assert(isa<PointerType>(LI->getType()));
945 // Must be ptr->ptr cast. Anything else would result in NV being
947 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
949 const IntegerType *NTy = cast<IntegerType>(NV->getType());
950 unsigned LIBitWidth = TD.getTypeSizeInBits(LI->getType());
952 // If this is a big-endian system and the load is narrower than the
953 // full alloca type, we need to do a shift to get the right bits.
955 if (TD.isBigEndian()) {
956 ShAmt = NTy->getBitWidth()-LIBitWidth-Offset;
961 // Note: we support negative bitwidths (with shl) which are not defined.
962 // We do this to support (f.e.) loads off the end of a structure where
963 // only some bits are used.
964 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
965 NV = BinaryOperator::createLShr(NV,
966 ConstantInt::get(NV->getType(),ShAmt),
968 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
969 NV = BinaryOperator::createShl(NV,
970 ConstantInt::get(NV->getType(),-ShAmt),
973 // Finally, unconditionally truncate the integer to the right width.
974 if (LIBitWidth < NTy->getBitWidth())
975 NV = new TruncInst(NV, IntegerType::get(LIBitWidth),
978 // If the result is an integer, this is a trunc or bitcast.
979 if (isa<IntegerType>(LI->getType())) {
980 assert(NV->getType() == LI->getType() && "Truncate wasn't enough?");
981 } else if (LI->getType()->isFloatingPoint()) {
982 // Just do a bitcast, we know the sizes match up.
983 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
985 // Otherwise must be a pointer.
986 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
989 LI->replaceAllUsesWith(NV);
990 LI->eraseFromParent();
991 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
992 assert(SI->getOperand(0) != Ptr && "Consistency error!");
994 // Convert the stored type to the actual type, shift it left to insert
995 // then 'or' into place.
996 Value *SV = SI->getOperand(0);
997 const Type *AllocaType = NewAI->getType()->getElementType();
998 if (SV->getType() == AllocaType) {
1000 } else if (const VectorType *PTy = dyn_cast<VectorType>(AllocaType)) {
1001 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1003 // If the result alloca is a vector type, this is either an element
1004 // access or a bitcast to another vector type.
1005 if (isa<VectorType>(SV->getType())) {
1006 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1008 // Must be an element insertion.
1009 unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
1010 SV = new InsertElementInst(Old, SV,
1011 ConstantInt::get(Type::Int32Ty, Elt),
1014 } else if (isa<PointerType>(AllocaType)) {
1015 // If the alloca type is a pointer, then all the elements must be
1017 if (SV->getType() != AllocaType)
1018 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1020 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1022 // If SV is a float, convert it to the appropriate integer type.
1023 // If it is a pointer, do the same, and also handle ptr->ptr casts
1025 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
1026 unsigned DestWidth = AllocaType->getPrimitiveSizeInBits();
1027 if (SV->getType()->isFloatingPoint())
1028 SV = new BitCastInst(SV, IntegerType::get(SrcWidth),
1030 else if (isa<PointerType>(SV->getType()))
1031 SV = new PtrToIntInst(SV, TD.getIntPtrType(), SV->getName(), SI);
1033 // Always zero extend the value if needed.
1034 if (SV->getType() != AllocaType)
1035 SV = new ZExtInst(SV, AllocaType, SV->getName(), SI);
1037 // If this is a big-endian system and the store is narrower than the
1038 // full alloca type, we need to do a shift to get the right bits.
1040 if (TD.isBigEndian()) {
1041 ShAmt = DestWidth-SrcWidth-Offset;
1046 // Note: we support negative bitwidths (with shr) which are not defined.
1047 // We do this to support (f.e.) stores off the end of a structure where
1048 // only some bits in the structure are set.
1049 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1050 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1051 SV = BinaryOperator::createShl(SV,
1052 ConstantInt::get(SV->getType(), ShAmt),
1055 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1056 SV = BinaryOperator::createLShr(SV,
1057 ConstantInt::get(SV->getType(),-ShAmt),
1059 Mask = Mask.lshr(ShAmt);
1062 // Mask out the bits we are about to insert from the old value, and or
1064 if (SrcWidth != DestWidth) {
1065 assert(DestWidth > SrcWidth);
1066 Old = BinaryOperator::createAnd(Old, ConstantInt::get(~Mask),
1067 Old->getName()+".mask", SI);
1068 SV = BinaryOperator::createOr(Old, SV, SV->getName()+".ins", SI);
1071 new StoreInst(SV, NewAI, SI);
1072 SI->eraseFromParent();
1074 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1075 ConvertUsesToScalar(CI, NewAI, Offset);
1076 CI->eraseFromParent();
1077 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1078 const PointerType *AggPtrTy =
1079 cast<PointerType>(GEP->getOperand(0)->getType());
1080 const TargetData &TD = getAnalysis<TargetData>();
1081 unsigned AggSizeInBits = TD.getTypeSize(AggPtrTy->getElementType())*8;
1083 // Check to see if this is stepping over an element: GEP Ptr, int C
1084 unsigned NewOffset = Offset;
1085 if (GEP->getNumOperands() == 2) {
1086 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
1087 unsigned BitOffset = Idx*AggSizeInBits;
1089 NewOffset += BitOffset;
1090 } else if (GEP->getNumOperands() == 3) {
1091 // We know that operand #2 is zero.
1092 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1093 const Type *AggTy = AggPtrTy->getElementType();
1094 if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
1095 unsigned ElSizeBits = TD.getTypeSize(SeqTy->getElementType())*8;
1097 NewOffset += ElSizeBits*Idx;
1098 } else if (const StructType *STy = dyn_cast<StructType>(AggTy)) {
1099 unsigned EltBitOffset =
1100 TD.getStructLayout(STy)->getElementOffset(Idx)*8;
1102 NewOffset += EltBitOffset;
1104 assert(0 && "Unsupported operation!");
1108 assert(0 && "Unsupported operation!");
1111 ConvertUsesToScalar(GEP, NewAI, NewOffset);
1112 GEP->eraseFromParent();
1114 assert(0 && "Unsupported operation!");