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/Pass.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Analysis/Dominators.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/GetElementPtrTypeIterator.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/StringExtras.h"
40 STATISTIC(NumReplaced, "Number of allocas broken up");
41 STATISTIC(NumPromoted, "Number of allocas promoted");
42 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
45 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
46 bool runOnFunction(Function &F);
48 bool performScalarRepl(Function &F);
49 bool performPromotion(Function &F);
51 // getAnalysisUsage - This pass does not require any passes, but we know it
52 // will not alter the CFG, so say so.
53 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
54 AU.addRequired<DominatorTree>();
55 AU.addRequired<DominanceFrontier>();
56 AU.addRequired<TargetData>();
61 int isSafeElementUse(Value *Ptr);
62 int isSafeUseOfAllocation(Instruction *User);
63 int isSafeAllocaToScalarRepl(AllocationInst *AI);
64 void CanonicalizeAllocaUsers(AllocationInst *AI);
65 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
67 const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
68 void ConvertToScalar(AllocationInst *AI, const Type *Ty);
69 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
72 RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
75 // Public interface to the ScalarReplAggregates pass
76 FunctionPass *llvm::createScalarReplAggregatesPass() { return new SROA(); }
79 bool SROA::runOnFunction(Function &F) {
80 bool Changed = performPromotion(F);
82 bool LocalChange = performScalarRepl(F);
83 if (!LocalChange) break; // No need to repromote if no scalarrepl
85 LocalChange = performPromotion(F);
86 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
93 bool SROA::performPromotion(Function &F) {
94 std::vector<AllocaInst*> Allocas;
95 const TargetData &TD = getAnalysis<TargetData>();
96 DominatorTree &DT = getAnalysis<DominatorTree>();
97 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
99 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
101 bool Changed = false;
106 // Find allocas that are safe to promote, by looking at all instructions in
108 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
109 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
110 if (isAllocaPromotable(AI, TD))
111 Allocas.push_back(AI);
113 if (Allocas.empty()) break;
115 PromoteMemToReg(Allocas, DT, DF, TD);
116 NumPromoted += Allocas.size();
123 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
124 // which runs on all of the malloc/alloca instructions in the function, removing
125 // them if they are only used by getelementptr instructions.
127 bool SROA::performScalarRepl(Function &F) {
128 std::vector<AllocationInst*> WorkList;
130 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
131 BasicBlock &BB = F.getEntryBlock();
132 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
133 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
134 WorkList.push_back(A);
136 // Process the worklist
137 bool Changed = false;
138 while (!WorkList.empty()) {
139 AllocationInst *AI = WorkList.back();
142 // If we can turn this aggregate value (potentially with casts) into a
143 // simple scalar value that can be mem2reg'd into a register value.
144 bool IsNotTrivial = false;
145 if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
146 if (IsNotTrivial && ActualType != Type::VoidTy) {
147 ConvertToScalar(AI, ActualType);
152 // We cannot transform the allocation instruction if it is an array
153 // allocation (allocations OF arrays are ok though), and an allocation of a
154 // scalar value cannot be decomposed at all.
156 if (AI->isArrayAllocation() ||
157 (!isa<StructType>(AI->getAllocatedType()) &&
158 !isa<ArrayType>(AI->getAllocatedType()))) continue;
160 // Check that all of the users of the allocation are capable of being
162 switch (isSafeAllocaToScalarRepl(AI)) {
163 default: assert(0 && "Unexpected value!");
164 case 0: // Not safe to scalar replace.
166 case 1: // Safe, but requires cleanup/canonicalizations first
167 CanonicalizeAllocaUsers(AI);
168 case 3: // Safe to scalar replace.
172 DOUT << "Found inst to xform: " << *AI;
175 std::vector<AllocaInst*> ElementAllocas;
176 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
177 ElementAllocas.reserve(ST->getNumContainedTypes());
178 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
179 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
181 AI->getName() + "." + utostr(i), AI);
182 ElementAllocas.push_back(NA);
183 WorkList.push_back(NA); // Add to worklist for recursive processing
186 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
187 ElementAllocas.reserve(AT->getNumElements());
188 const Type *ElTy = AT->getElementType();
189 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
190 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
191 AI->getName() + "." + utostr(i), AI);
192 ElementAllocas.push_back(NA);
193 WorkList.push_back(NA); // Add to worklist for recursive processing
197 // Now that we have created the alloca instructions that we want to use,
198 // expand the getelementptr instructions to use them.
200 while (!AI->use_empty()) {
201 Instruction *User = cast<Instruction>(AI->use_back());
202 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
203 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
205 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
207 assert(Idx < ElementAllocas.size() && "Index out of range?");
208 AllocaInst *AllocaToUse = ElementAllocas[Idx];
211 if (GEPI->getNumOperands() == 3) {
212 // Do not insert a new getelementptr instruction with zero indices, only
213 // to have it optimized out later.
214 RepValue = AllocaToUse;
216 // We are indexing deeply into the structure, so we still need a
217 // getelement ptr instruction to finish the indexing. This may be
218 // expanded itself once the worklist is rerun.
220 std::string OldName = GEPI->getName(); // Steal the old name.
221 std::vector<Value*> NewArgs;
222 NewArgs.push_back(Constant::getNullValue(Type::IntTy));
223 NewArgs.insert(NewArgs.end(), GEPI->op_begin()+3, GEPI->op_end());
225 RepValue = new GetElementPtrInst(AllocaToUse, NewArgs, OldName, GEPI);
228 // Move all of the users over to the new GEP.
229 GEPI->replaceAllUsesWith(RepValue);
230 // Delete the old GEP
231 GEPI->eraseFromParent();
234 // Finally, delete the Alloca instruction
235 AI->getParent()->getInstList().erase(AI);
243 /// isSafeElementUse - Check to see if this use is an allowed use for a
244 /// getelementptr instruction of an array aggregate allocation.
246 int SROA::isSafeElementUse(Value *Ptr) {
247 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
249 Instruction *User = cast<Instruction>(*I);
250 switch (User->getOpcode()) {
251 case Instruction::Load: break;
252 case Instruction::Store:
253 // Store is ok if storing INTO the pointer, not storing the pointer
254 if (User->getOperand(0) == Ptr) return 0;
256 case Instruction::GetElementPtr: {
257 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
258 if (GEP->getNumOperands() > 1) {
259 if (!isa<Constant>(GEP->getOperand(1)) ||
260 !cast<Constant>(GEP->getOperand(1))->isNullValue())
261 return 0; // Using pointer arithmetic to navigate the array...
263 if (!isSafeElementUse(GEP)) return 0;
267 DOUT << " Transformation preventing inst: " << *User;
271 return 3; // All users look ok :)
274 /// AllUsersAreLoads - Return true if all users of this value are loads.
275 static bool AllUsersAreLoads(Value *Ptr) {
276 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
278 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
283 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
284 /// aggregate allocation.
286 int SROA::isSafeUseOfAllocation(Instruction *User) {
287 if (!isa<GetElementPtrInst>(User)) return 0;
289 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
290 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
292 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
294 I.getOperand() != Constant::getNullValue(I.getOperand()->getType()))
298 if (I == E) return 0; // ran out of GEP indices??
300 // If this is a use of an array allocation, do a bit more checking for sanity.
301 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
302 uint64_t NumElements = AT->getNumElements();
304 if (isa<ConstantInt>(I.getOperand())) {
305 // Check to make sure that index falls within the array. If not,
306 // something funny is going on, so we won't do the optimization.
308 if (cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue() >= NumElements)
311 // We cannot scalar repl this level of the array unless any array
312 // sub-indices are in-range constants. In particular, consider:
313 // A[0][i]. We cannot know that the user isn't doing invalid things like
314 // allowing i to index an out-of-range subscript that accesses A[1].
316 // Scalar replacing *just* the outer index of the array is probably not
317 // going to be a win anyway, so just give up.
318 for (++I; I != E && (isa<ArrayType>(*I) || isa<PackedType>(*I)); ++I) {
319 uint64_t NumElements;
320 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*I))
321 NumElements = SubArrayTy->getNumElements();
323 NumElements = cast<PackedType>(*I)->getNumElements();
325 if (!isa<ConstantInt>(I.getOperand())) return 0;
326 if (cast<ConstantInt>(I.getOperand())->getZExtValue() >= NumElements)
331 // If this is an array index and the index is not constant, we cannot
332 // promote... that is unless the array has exactly one or two elements in
333 // it, in which case we CAN promote it, but we have to canonicalize this
334 // out if this is the only problem.
335 if ((NumElements == 1 || NumElements == 2) &&
336 AllUsersAreLoads(GEPI))
337 return 1; // Canonicalization required!
342 // If there are any non-simple uses of this getelementptr, make sure to reject
344 return isSafeElementUse(GEPI);
347 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
348 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
349 /// or 1 if safe after canonicalization has been performed.
351 int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
352 // Loop over the use list of the alloca. We can only transform it if all of
353 // the users are safe to transform.
356 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
358 isSafe &= isSafeUseOfAllocation(cast<Instruction>(*I));
360 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
364 // If we require cleanup, isSafe is now 1, otherwise it is 3.
368 /// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
369 /// allocation, but only if cleaned up, perform the cleanups required.
370 void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
371 // At this point, we know that the end result will be SROA'd and promoted, so
372 // we can insert ugly code if required so long as sroa+mem2reg will clean it
374 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
376 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(*UI++);
377 gep_type_iterator I = gep_type_begin(GEPI);
380 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
381 uint64_t NumElements = AT->getNumElements();
383 if (!isa<ConstantInt>(I.getOperand())) {
384 if (NumElements == 1) {
385 GEPI->setOperand(2, Constant::getNullValue(Type::IntTy));
387 assert(NumElements == 2 && "Unhandled case!");
388 // All users of the GEP must be loads. At each use of the GEP, insert
389 // two loads of the appropriate indexed GEP and select between them.
390 Value *IsOne = BinaryOperator::createSetNE(I.getOperand(),
391 Constant::getNullValue(I.getOperand()->getType()),
393 // Insert the new GEP instructions, which are properly indexed.
394 std::vector<Value*> Indices(GEPI->op_begin()+1, GEPI->op_end());
395 Indices[1] = Constant::getNullValue(Type::IntTy);
396 Value *ZeroIdx = new GetElementPtrInst(GEPI->getOperand(0), Indices,
397 GEPI->getName()+".0", GEPI);
398 Indices[1] = ConstantInt::get(Type::IntTy, 1);
399 Value *OneIdx = new GetElementPtrInst(GEPI->getOperand(0), Indices,
400 GEPI->getName()+".1", GEPI);
401 // Replace all loads of the variable index GEP with loads from both
402 // indexes and a select.
403 while (!GEPI->use_empty()) {
404 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
405 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
406 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
407 Value *R = new SelectInst(IsOne, One, Zero, LI->getName(), LI);
408 LI->replaceAllUsesWith(R);
409 LI->eraseFromParent();
411 GEPI->eraseFromParent();
418 /// MergeInType - Add the 'In' type to the accumulated type so far. If the
419 /// types are incompatible, return true, otherwise update Accum and return
422 /// There are three cases we handle here:
423 /// 1) An effectively-integer union, where the pieces are stored into as
424 /// smaller integers (common with byte swap and other idioms).
425 /// 2) A union of vector types of the same size and potentially its elements.
426 /// Here we turn element accesses into insert/extract element operations.
427 /// 3) A union of scalar types, such as int/float or int/pointer. Here we
428 /// merge together into integers, allowing the xform to work with #1 as
430 static bool MergeInType(const Type *In, const Type *&Accum,
431 const TargetData &TD) {
432 // If this is our first type, just use it.
433 const PackedType *PTy;
434 if (Accum == Type::VoidTy || In == Accum) {
436 } else if (In == Type::VoidTy) {
438 } else if (In->isIntegral() && Accum->isIntegral()) { // integer union.
439 // Otherwise pick whichever type is larger.
440 if (In->getTypeID() > Accum->getTypeID())
442 } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
443 // Pointer unions just stay as one of the pointers.
444 } else if (isa<PackedType>(In) || isa<PackedType>(Accum)) {
445 if ((PTy = dyn_cast<PackedType>(Accum)) &&
446 PTy->getElementType() == In) {
447 // Accum is a vector, and we are accessing an element: ok.
448 } else if ((PTy = dyn_cast<PackedType>(In)) &&
449 PTy->getElementType() == Accum) {
450 // In is a vector, and accum is an element: ok, remember In.
452 } else if ((PTy = dyn_cast<PackedType>(In)) && isa<PackedType>(Accum) &&
453 PTy->getBitWidth() == cast<PackedType>(Accum)->getBitWidth()) {
454 // Two vectors of the same size: keep Accum.
456 // Cannot insert an short into a <4 x int> or handle
457 // <2 x int> -> <4 x int>
461 // Pointer/FP/Integer unions merge together as integers.
462 switch (Accum->getTypeID()) {
463 case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
464 case Type::FloatTyID: Accum = Type::UIntTy; break;
465 case Type::DoubleTyID: Accum = Type::ULongTy; break;
467 assert(Accum->isIntegral() && "Unknown FP type!");
471 switch (In->getTypeID()) {
472 case Type::PointerTyID: In = TD.getIntPtrType(); break;
473 case Type::FloatTyID: In = Type::UIntTy; break;
474 case Type::DoubleTyID: In = Type::ULongTy; break;
476 assert(In->isIntegral() && "Unknown FP type!");
479 return MergeInType(In, Accum, TD);
484 /// getUIntAtLeastAsBitAs - Return an unsigned integer type that is at least
485 /// as big as the specified type. If there is no suitable type, this returns
487 const Type *getUIntAtLeastAsBitAs(unsigned NumBits) {
488 if (NumBits > 64) return 0;
489 if (NumBits > 32) return Type::ULongTy;
490 if (NumBits > 16) return Type::UIntTy;
491 if (NumBits > 8) return Type::UShortTy;
492 return Type::UByteTy;
495 /// CanConvertToScalar - V is a pointer. If we can convert the pointee to a
496 /// single scalar integer type, return that type. Further, if the use is not
497 /// a completely trivial use that mem2reg could promote, set IsNotTrivial. If
498 /// there are no uses of this pointer, return Type::VoidTy to differentiate from
501 const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
502 const Type *UsedType = Type::VoidTy; // No uses, no forced type.
503 const TargetData &TD = getAnalysis<TargetData>();
504 const PointerType *PTy = cast<PointerType>(V->getType());
506 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
507 Instruction *User = cast<Instruction>(*UI);
509 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
510 if (MergeInType(LI->getType(), UsedType, TD))
513 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
514 // Storing the pointer, not the into the value?
515 if (SI->getOperand(0) == V) return 0;
517 // NOTE: We could handle storing of FP imms into integers here!
519 if (MergeInType(SI->getOperand(0)->getType(), UsedType, TD))
521 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
523 const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
524 if (!SubTy || MergeInType(SubTy, UsedType, TD)) return 0;
525 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
526 // Check to see if this is stepping over an element: GEP Ptr, int C
527 if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
528 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
529 unsigned ElSize = TD.getTypeSize(PTy->getElementType());
530 unsigned BitOffset = Idx*ElSize*8;
531 if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
534 const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
535 if (SubElt == 0) return 0;
536 if (SubElt != Type::VoidTy && SubElt->isInteger()) {
538 getUIntAtLeastAsBitAs(TD.getTypeSize(SubElt)*8+BitOffset);
539 if (NewTy == 0 || MergeInType(NewTy, UsedType, TD)) return 0;
542 } else if (GEP->getNumOperands() == 3 &&
543 isa<ConstantInt>(GEP->getOperand(1)) &&
544 isa<ConstantInt>(GEP->getOperand(2)) &&
545 cast<Constant>(GEP->getOperand(1))->isNullValue()) {
546 // We are stepping into an element, e.g. a structure or an array:
547 // GEP Ptr, int 0, uint C
548 const Type *AggTy = PTy->getElementType();
549 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
551 if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
552 if (Idx >= ATy->getNumElements()) return 0; // Out of range.
553 } else if (const PackedType *PackedTy = dyn_cast<PackedType>(AggTy)) {
554 // Getting an element of the packed vector.
555 if (Idx >= PackedTy->getNumElements()) return 0; // Out of range.
557 // Merge in the packed type.
558 if (MergeInType(PackedTy, UsedType, TD)) return 0;
560 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
561 if (SubTy == 0) return 0;
563 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
566 // We'll need to change this to an insert/extract element operation.
568 continue; // Everything looks ok
570 } else if (isa<StructType>(AggTy)) {
571 // Structs are always ok.
575 const Type *NTy = getUIntAtLeastAsBitAs(TD.getTypeSize(AggTy)*8);
576 if (NTy == 0 || MergeInType(NTy, UsedType, TD)) return 0;
577 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
578 if (SubTy == 0) return 0;
579 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
581 continue; // Everything looks ok
585 // Cannot handle this!
593 /// ConvertToScalar - The specified alloca passes the CanConvertToScalar
594 /// predicate and is non-trivial. Convert it to something that can be trivially
595 /// promoted into a register by mem2reg.
596 void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
597 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = "
598 << *ActualTy << "\n";
601 BasicBlock *EntryBlock = AI->getParent();
602 assert(EntryBlock == &EntryBlock->getParent()->front() &&
603 "Not in the entry block!");
604 EntryBlock->getInstList().remove(AI); // Take the alloca out of the program.
606 if (ActualTy->isInteger())
607 ActualTy = ActualTy->getUnsignedVersion();
609 // Create and insert the alloca.
610 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
611 EntryBlock->begin());
612 ConvertUsesToScalar(AI, NewAI, 0);
617 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
618 /// directly. This happens when we are converting an "integer union" to a
619 /// single integer scalar, or when we are converting a "vector union" to a
620 /// vector with insert/extractelement instructions.
622 /// Offset is an offset from the original alloca, in bits that need to be
623 /// shifted to the right. By the end of this, there should be no uses of Ptr.
624 void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
625 bool isVectorInsert = isa<PackedType>(NewAI->getType()->getElementType());
626 const TargetData &TD = getAnalysis<TargetData>();
627 while (!Ptr->use_empty()) {
628 Instruction *User = cast<Instruction>(Ptr->use_back());
630 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
631 // The load is a bit extract from NewAI shifted right by Offset bits.
632 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
633 if (NV->getType() != LI->getType()) {
634 if (const PackedType *PTy = dyn_cast<PackedType>(NV->getType())) {
635 // If the result alloca is a packed type, this is either an element
636 // access or a bitcast to another packed type.
637 if (isa<PackedType>(LI->getType())) {
638 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
640 // Must be an element access.
641 unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
642 NV = new ExtractElementInst(NV, ConstantInt::get(Type::UIntTy, Elt),
645 } else if (isa<PointerType>(NV->getType())) {
646 assert(isa<PointerType>(LI->getType()));
647 // Must be ptr->ptr cast. Anything else would result in NV being
649 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
651 assert(NV->getType()->isInteger() && "Unknown promotion!");
652 if (Offset && Offset < TD.getTypeSize(NV->getType())*8) {
653 NV = new ShiftInst(Instruction::LShr, NV,
654 ConstantInt::get(Type::UByteTy, Offset),
658 // If the result is an integer, this is a trunc or bitcast.
659 if (LI->getType()->isIntegral()) {
660 NV = CastInst::createTruncOrBitCast(NV, LI->getType(),
662 } else if (LI->getType()->isFloatingPoint()) {
663 // If needed, truncate the integer to the appropriate size.
664 if (NV->getType()->getPrimitiveSize() >
665 LI->getType()->getPrimitiveSize()) {
666 switch (LI->getType()->getTypeID()) {
667 default: assert(0 && "Unknown FP type!");
668 case Type::FloatTyID:
669 NV = new TruncInst(NV, Type::UIntTy, LI->getName(), LI);
671 case Type::DoubleTyID:
672 NV = new TruncInst(NV, Type::ULongTy, LI->getName(), LI);
677 // Then do a bitcast.
678 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
680 // Otherwise must be a pointer.
681 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
685 LI->replaceAllUsesWith(NV);
686 LI->eraseFromParent();
687 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
688 assert(SI->getOperand(0) != Ptr && "Consistency error!");
690 // Convert the stored type to the actual type, shift it left to insert
691 // then 'or' into place.
692 Value *SV = SI->getOperand(0);
693 const Type *AllocaType = NewAI->getType()->getElementType();
694 if (SV->getType() != AllocaType) {
695 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
697 if (const PackedType *PTy = dyn_cast<PackedType>(AllocaType)) {
698 // If the result alloca is a packed type, this is either an element
699 // access or a bitcast to another packed type.
700 if (isa<PackedType>(SV->getType())) {
701 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
703 // Must be an element insertion.
704 unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
705 SV = new InsertElementInst(Old, SV,
706 ConstantInt::get(Type::UIntTy, Elt),
710 // If SV is a float, convert it to the appropriate integer type.
711 // If it is a pointer, do the same, and also handle ptr->ptr casts
713 switch (SV->getType()->getTypeID()) {
715 assert(!SV->getType()->isFloatingPoint() && "Unknown FP type!");
717 case Type::FloatTyID:
718 SV = new BitCastInst(SV, Type::UIntTy, SV->getName(), SI);
720 case Type::DoubleTyID:
721 SV = new BitCastInst(SV, Type::ULongTy, SV->getName(), SI);
723 case Type::PointerTyID:
724 if (isa<PointerType>(AllocaType))
725 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
727 SV = new PtrToIntInst(SV, TD.getIntPtrType(), SV->getName(), SI);
731 unsigned SrcSize = TD.getTypeSize(SV->getType())*8;
733 // Always zero extend the value if needed.
734 if (SV->getType() != AllocaType)
735 SV = CastInst::createZExtOrBitCast(SV, AllocaType,
737 if (Offset && Offset < AllocaType->getPrimitiveSizeInBits())
738 SV = new ShiftInst(Instruction::Shl, SV,
739 ConstantInt::get(Type::UByteTy, Offset),
740 SV->getName()+".adj", SI);
741 // Mask out the bits we are about to insert from the old value.
742 unsigned TotalBits = TD.getTypeSize(SV->getType())*8;
743 if (TotalBits != SrcSize) {
744 assert(TotalBits > SrcSize);
745 uint64_t Mask = ~(((1ULL << SrcSize)-1) << Offset);
746 Mask = Mask & SV->getType()->getIntegralTypeMask();
747 Old = BinaryOperator::createAnd(Old,
748 ConstantInt::get(Old->getType(), Mask),
749 Old->getName()+".mask", SI);
750 SV = BinaryOperator::createOr(Old, SV, SV->getName()+".ins", SI);
754 new StoreInst(SV, NewAI, SI);
755 SI->eraseFromParent();
757 } else if (CastInst *CI = dyn_cast<CastInst>(User)) {
758 unsigned NewOff = Offset;
759 const TargetData &TD = getAnalysis<TargetData>();
760 if (TD.isBigEndian() && !isVectorInsert) {
761 // Adjust the pointer. For example, storing 16-bits into a 32-bit
762 // alloca with just a cast makes it modify the top 16-bits.
763 const Type *SrcTy = cast<PointerType>(Ptr->getType())->getElementType();
764 const Type *DstTy = cast<PointerType>(CI->getType())->getElementType();
765 int PtrDiffBits = TD.getTypeSize(SrcTy)*8-TD.getTypeSize(DstTy)*8;
766 NewOff += PtrDiffBits;
768 ConvertUsesToScalar(CI, NewAI, NewOff);
769 CI->eraseFromParent();
770 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
771 const PointerType *AggPtrTy =
772 cast<PointerType>(GEP->getOperand(0)->getType());
773 const TargetData &TD = getAnalysis<TargetData>();
774 unsigned AggSizeInBits = TD.getTypeSize(AggPtrTy->getElementType())*8;
776 // Check to see if this is stepping over an element: GEP Ptr, int C
777 unsigned NewOffset = Offset;
778 if (GEP->getNumOperands() == 2) {
779 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
780 unsigned BitOffset = Idx*AggSizeInBits;
782 if (TD.isLittleEndian() || isVectorInsert)
783 NewOffset += BitOffset;
785 NewOffset -= BitOffset;
787 } else if (GEP->getNumOperands() == 3) {
788 // We know that operand #2 is zero.
789 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
790 const Type *AggTy = AggPtrTy->getElementType();
791 if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
792 unsigned ElSizeBits = TD.getTypeSize(SeqTy->getElementType())*8;
794 if (TD.isLittleEndian() || isVectorInsert)
795 NewOffset += ElSizeBits*Idx;
797 NewOffset += AggSizeInBits-ElSizeBits*(Idx+1);
798 } else if (const StructType *STy = dyn_cast<StructType>(AggTy)) {
799 unsigned EltBitOffset = TD.getStructLayout(STy)->MemberOffsets[Idx]*8;
801 if (TD.isLittleEndian() || isVectorInsert)
802 NewOffset += EltBitOffset;
804 const PointerType *ElPtrTy = cast<PointerType>(GEP->getType());
805 unsigned ElSizeBits = TD.getTypeSize(ElPtrTy->getElementType())*8;
806 NewOffset += AggSizeInBits-(EltBitOffset+ElSizeBits);
810 assert(0 && "Unsupported operation!");
814 assert(0 && "Unsupported operation!");
817 ConvertUsesToScalar(GEP, NewAI, NewOffset);
818 GEP->eraseFromParent();
820 assert(0 && "Unsupported operation!");