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/Support/Debug.h"
35 #include "llvm/Support/GetElementPtrTypeIterator.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/ADT/StringExtras.h"
43 STATISTIC(NumReplaced, "Number of allocas broken up");
44 STATISTIC(NumPromoted, "Number of allocas promoted");
45 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
46 STATISTIC(NumGlobals, "Number of allocas copied from constant global");
49 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
50 static char ID; // Pass identification, replacement for typeid
51 explicit SROA(signed T = -1) : FunctionPass((intptr_t)&ID) {
58 bool runOnFunction(Function &F);
60 bool performScalarRepl(Function &F);
61 bool performPromotion(Function &F);
63 // getAnalysisUsage - This pass does not require any passes, but we know it
64 // will not alter the CFG, so say so.
65 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
66 AU.addRequired<DominatorTree>();
67 AU.addRequired<DominanceFrontier>();
68 AU.addRequired<TargetData>();
73 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
74 /// information about the uses. All these fields are initialized to false
75 /// and set to true when something is learned.
77 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
80 /// needsCanon - This is set to true if there is some use of the alloca
81 /// that requires canonicalization.
84 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
87 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
91 : isUnsafe(false), needsCanon(false),
92 isMemCpySrc(false), isMemCpyDst(false) {}
97 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
99 int isSafeAllocaToScalarRepl(AllocationInst *AI);
101 void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
103 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
105 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
106 unsigned OpNo, AllocaInfo &Info);
107 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
110 void DoScalarReplacement(AllocationInst *AI,
111 std::vector<AllocationInst*> &WorkList);
112 void CanonicalizeAllocaUsers(AllocationInst *AI);
113 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
115 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
116 SmallVector<AllocaInst*, 32> &NewElts);
118 const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
119 void ConvertToScalar(AllocationInst *AI, const Type *Ty);
120 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
121 Value *ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
123 Value *ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
125 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
130 static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
132 // Public interface to the ScalarReplAggregates pass
133 FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
134 return new SROA(Threshold);
138 bool SROA::runOnFunction(Function &F) {
139 bool Changed = performPromotion(F);
141 bool LocalChange = performScalarRepl(F);
142 if (!LocalChange) break; // No need to repromote if no scalarrepl
144 LocalChange = performPromotion(F);
145 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
152 bool SROA::performPromotion(Function &F) {
153 std::vector<AllocaInst*> Allocas;
154 DominatorTree &DT = getAnalysis<DominatorTree>();
155 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
157 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
159 bool Changed = false;
164 // Find allocas that are safe to promote, by looking at all instructions in
166 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
167 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
168 if (isAllocaPromotable(AI))
169 Allocas.push_back(AI);
171 if (Allocas.empty()) break;
173 PromoteMemToReg(Allocas, DT, DF);
174 NumPromoted += Allocas.size();
181 /// getNumSAElements - Return the number of elements in the specific struct or
183 static uint64_t getNumSAElements(const Type *T) {
184 if (const StructType *ST = dyn_cast<StructType>(T))
185 return ST->getNumElements();
186 return cast<ArrayType>(T)->getNumElements();
189 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
190 // which runs on all of the malloc/alloca instructions in the function, removing
191 // them if they are only used by getelementptr instructions.
193 bool SROA::performScalarRepl(Function &F) {
194 std::vector<AllocationInst*> WorkList;
196 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
197 BasicBlock &BB = F.getEntryBlock();
198 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
199 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
200 WorkList.push_back(A);
202 const TargetData &TD = getAnalysis<TargetData>();
204 // Process the worklist
205 bool Changed = false;
206 while (!WorkList.empty()) {
207 AllocationInst *AI = WorkList.back();
210 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
211 // with unused elements.
212 if (AI->use_empty()) {
213 AI->eraseFromParent();
217 // If we can turn this aggregate value (potentially with casts) into a
218 // simple scalar value that can be mem2reg'd into a register value.
219 bool IsNotTrivial = false;
220 if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
221 if (IsNotTrivial && ActualType != Type::VoidTy) {
222 ConvertToScalar(AI, ActualType);
227 // Check to see if we can perform the core SROA transformation. We cannot
228 // transform the allocation instruction if it is an array allocation
229 // (allocations OF arrays are ok though), and an allocation of a scalar
230 // value cannot be decomposed at all.
231 if (!AI->isArrayAllocation() &&
232 (isa<StructType>(AI->getAllocatedType()) ||
233 isa<ArrayType>(AI->getAllocatedType())) &&
234 AI->getAllocatedType()->isSized() &&
235 // Do not promote any struct whose size is larger than "128" bytes.
236 TD.getABITypeSize(AI->getAllocatedType()) < SRThreshold &&
237 // Do not promote any struct into more than "32" separate vars.
238 getNumSAElements(AI->getAllocatedType()) < SRThreshold/4) {
239 // Check that all of the users of the allocation are capable of being
241 switch (isSafeAllocaToScalarRepl(AI)) {
242 default: assert(0 && "Unexpected value!");
243 case 0: // Not safe to scalar replace.
245 case 1: // Safe, but requires cleanup/canonicalizations first
246 CanonicalizeAllocaUsers(AI);
248 case 3: // Safe to scalar replace.
249 DoScalarReplacement(AI, WorkList);
255 // Check to see if this allocation is only modified by a memcpy/memmove from
256 // a constant global. If this is the case, we can change all users to use
257 // the constant global instead. This is commonly produced by the CFE by
258 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
259 // is only subsequently read.
260 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
261 DOUT << "Found alloca equal to global: " << *AI;
262 DOUT << " memcpy = " << *TheCopy;
263 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
264 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
265 TheCopy->eraseFromParent(); // Don't mutate the global.
266 AI->eraseFromParent();
272 // Otherwise, couldn't process this.
278 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
279 /// predicate, do SROA now.
280 void SROA::DoScalarReplacement(AllocationInst *AI,
281 std::vector<AllocationInst*> &WorkList) {
282 DOUT << "Found inst to SROA: " << *AI;
283 SmallVector<AllocaInst*, 32> ElementAllocas;
284 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
285 ElementAllocas.reserve(ST->getNumContainedTypes());
286 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
287 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
289 AI->getName() + "." + utostr(i), AI);
290 ElementAllocas.push_back(NA);
291 WorkList.push_back(NA); // Add to worklist for recursive processing
294 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
295 ElementAllocas.reserve(AT->getNumElements());
296 const Type *ElTy = AT->getElementType();
297 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
298 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
299 AI->getName() + "." + utostr(i), AI);
300 ElementAllocas.push_back(NA);
301 WorkList.push_back(NA); // Add to worklist for recursive processing
305 // Now that we have created the alloca instructions that we want to use,
306 // expand the getelementptr instructions to use them.
308 while (!AI->use_empty()) {
309 Instruction *User = cast<Instruction>(AI->use_back());
310 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
311 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
312 BCInst->eraseFromParent();
316 // Replace %res = load { i32, i32 }* %alloc
318 // %load.0 = load i32* %alloc.0
319 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
320 // %load.1 = load i32* %alloc.1
321 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
322 // (Also works for arrays instead of structs)
323 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
324 Value *Insert = UndefValue::get(LI->getType());
325 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
326 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
327 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
329 LI->replaceAllUsesWith(Insert);
330 LI->eraseFromParent();
334 // Replace store { i32, i32 } %val, { i32, i32 }* %alloc
336 // %val.0 = extractvalue { i32, i32 } %val, 0
337 // store i32 %val.0, i32* %alloc.0
338 // %val.1 = extractvalue { i32, i32 } %val, 1
339 // store i32 %val.1, i32* %alloc.1
340 // (Also works for arrays instead of structs)
341 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
342 Value *Val = SI->getOperand(0);
343 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
344 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
345 new StoreInst(Extract, ElementAllocas[i], SI);
347 SI->eraseFromParent();
351 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
352 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
354 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
356 assert(Idx < ElementAllocas.size() && "Index out of range?");
357 AllocaInst *AllocaToUse = ElementAllocas[Idx];
360 if (GEPI->getNumOperands() == 3) {
361 // Do not insert a new getelementptr instruction with zero indices, only
362 // to have it optimized out later.
363 RepValue = AllocaToUse;
365 // We are indexing deeply into the structure, so we still need a
366 // getelement ptr instruction to finish the indexing. This may be
367 // expanded itself once the worklist is rerun.
369 SmallVector<Value*, 8> NewArgs;
370 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
371 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
372 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
373 NewArgs.end(), "", GEPI);
374 RepValue->takeName(GEPI);
377 // If this GEP is to the start of the aggregate, check for memcpys.
379 bool IsStartOfAggregateGEP = true;
380 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i) {
381 if (!isa<ConstantInt>(GEPI->getOperand(i))) {
382 IsStartOfAggregateGEP = false;
385 if (!cast<ConstantInt>(GEPI->getOperand(i))->isZero()) {
386 IsStartOfAggregateGEP = false;
391 if (IsStartOfAggregateGEP)
392 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
396 // Move all of the users over to the new GEP.
397 GEPI->replaceAllUsesWith(RepValue);
398 // Delete the old GEP
399 GEPI->eraseFromParent();
402 // Finally, delete the Alloca instruction
403 AI->eraseFromParent();
408 /// isSafeElementUse - Check to see if this use is an allowed use for a
409 /// getelementptr instruction of an array aggregate allocation. isFirstElt
410 /// indicates whether Ptr is known to the start of the aggregate.
412 void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
414 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
416 Instruction *User = cast<Instruction>(*I);
417 switch (User->getOpcode()) {
418 case Instruction::Load: break;
419 case Instruction::Store:
420 // Store is ok if storing INTO the pointer, not storing the pointer
421 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
423 case Instruction::GetElementPtr: {
424 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
425 bool AreAllZeroIndices = isFirstElt;
426 if (GEP->getNumOperands() > 1) {
427 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
428 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
429 // Using pointer arithmetic to navigate the array.
430 return MarkUnsafe(Info);
432 if (AreAllZeroIndices) {
433 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
434 if (!isa<ConstantInt>(GEP->getOperand(i)) ||
435 !cast<ConstantInt>(GEP->getOperand(i))->isZero()) {
436 AreAllZeroIndices = false;
442 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
443 if (Info.isUnsafe) return;
446 case Instruction::BitCast:
448 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
449 if (Info.isUnsafe) return;
452 DOUT << " Transformation preventing inst: " << *User;
453 return MarkUnsafe(Info);
454 case Instruction::Call:
455 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
457 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
458 if (Info.isUnsafe) return;
462 DOUT << " Transformation preventing inst: " << *User;
463 return MarkUnsafe(Info);
465 DOUT << " Transformation preventing inst: " << *User;
466 return MarkUnsafe(Info);
469 return; // All users look ok :)
472 /// AllUsersAreLoads - Return true if all users of this value are loads.
473 static bool AllUsersAreLoads(Value *Ptr) {
474 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
476 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
481 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
482 /// aggregate allocation.
484 void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
486 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
487 return isSafeUseOfBitCastedAllocation(C, AI, Info);
489 if (isa<LoadInst>(User))
490 return; // Loads (returning a first class aggregrate) are always rewritable
492 if (isa<StoreInst>(User) && User->getOperand(0) != AI)
493 return; // Store is ok if storing INTO the pointer, not storing the pointer
495 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
497 return MarkUnsafe(Info);
499 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
501 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
503 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
504 return MarkUnsafe(Info);
508 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
510 bool IsAllZeroIndices = true;
512 // If this is a use of an array allocation, do a bit more checking for sanity.
513 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
514 uint64_t NumElements = AT->getNumElements();
516 if (ConstantInt *Idx = dyn_cast<ConstantInt>(I.getOperand())) {
517 IsAllZeroIndices &= Idx->isZero();
519 // Check to make sure that index falls within the array. If not,
520 // something funny is going on, so we won't do the optimization.
522 if (Idx->getZExtValue() >= NumElements)
523 return MarkUnsafe(Info);
525 // We cannot scalar repl this level of the array unless any array
526 // sub-indices are in-range constants. In particular, consider:
527 // A[0][i]. We cannot know that the user isn't doing invalid things like
528 // allowing i to index an out-of-range subscript that accesses A[1].
530 // Scalar replacing *just* the outer index of the array is probably not
531 // going to be a win anyway, so just give up.
532 for (++I; I != E && (isa<ArrayType>(*I) || isa<VectorType>(*I)); ++I) {
533 uint64_t NumElements;
534 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*I))
535 NumElements = SubArrayTy->getNumElements();
537 NumElements = cast<VectorType>(*I)->getNumElements();
539 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
540 if (!IdxVal) return MarkUnsafe(Info);
541 if (IdxVal->getZExtValue() >= NumElements)
542 return MarkUnsafe(Info);
543 IsAllZeroIndices &= IdxVal->isZero();
547 IsAllZeroIndices = 0;
549 // If this is an array index and the index is not constant, we cannot
550 // promote... that is unless the array has exactly one or two elements in
551 // it, in which case we CAN promote it, but we have to canonicalize this
552 // out if this is the only problem.
553 if ((NumElements == 1 || NumElements == 2) &&
554 AllUsersAreLoads(GEPI)) {
555 Info.needsCanon = true;
556 return; // Canonicalization required!
558 return MarkUnsafe(Info);
562 // If there are any non-simple uses of this getelementptr, make sure to reject
564 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
567 /// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
568 /// intrinsic can be promoted by SROA. At this point, we know that the operand
569 /// of the memintrinsic is a pointer to the beginning of the allocation.
570 void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
571 unsigned OpNo, AllocaInfo &Info) {
572 // If not constant length, give up.
573 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
574 if (!Length) return MarkUnsafe(Info);
576 // If not the whole aggregate, give up.
577 const TargetData &TD = getAnalysis<TargetData>();
578 if (Length->getZExtValue() !=
579 TD.getABITypeSize(AI->getType()->getElementType()))
580 return MarkUnsafe(Info);
582 // We only know about memcpy/memset/memmove.
583 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
584 return MarkUnsafe(Info);
586 // Otherwise, we can transform it. Determine whether this is a memcpy/set
587 // into or out of the aggregate.
589 Info.isMemCpyDst = true;
592 Info.isMemCpySrc = true;
596 /// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
598 void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
600 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
602 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
603 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
604 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
605 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
607 return MarkUnsafe(Info);
609 if (Info.isUnsafe) return;
613 /// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
614 /// to its first element. Transform users of the cast to use the new values
616 void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
617 SmallVector<AllocaInst*, 32> &NewElts) {
618 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
619 const TargetData &TD = getAnalysis<TargetData>();
621 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
623 if (BitCastInst *BCU = dyn_cast<BitCastInst>(*UI)) {
624 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
626 BCU->eraseFromParent();
630 // Otherwise, must be memcpy/memmove/memset of the entire aggregate. Split
631 // into one per element.
632 MemIntrinsic *MI = dyn_cast<MemIntrinsic>(*UI);
634 // If it's not a mem intrinsic, it must be some other user of a gep of the
635 // first pointer. Just leave these alone.
641 // If this is a memcpy/memmove, construct the other pointer as the
644 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
645 if (BCInst == MCI->getRawDest())
646 OtherPtr = MCI->getRawSource();
648 assert(BCInst == MCI->getRawSource());
649 OtherPtr = MCI->getRawDest();
651 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
652 if (BCInst == MMI->getRawDest())
653 OtherPtr = MMI->getRawSource();
655 assert(BCInst == MMI->getRawSource());
656 OtherPtr = MMI->getRawDest();
660 // If there is an other pointer, we want to convert it to the same pointer
661 // type as AI has, so we can GEP through it.
663 // It is likely that OtherPtr is a bitcast, if so, remove it.
664 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
665 OtherPtr = BC->getOperand(0);
666 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
667 if (BCE->getOpcode() == Instruction::BitCast)
668 OtherPtr = BCE->getOperand(0);
670 // If the pointer is not the right type, insert a bitcast to the right
672 if (OtherPtr->getType() != AI->getType())
673 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
677 // Process each element of the aggregate.
678 Value *TheFn = MI->getOperand(0);
679 const Type *BytePtrTy = MI->getRawDest()->getType();
680 bool SROADest = MI->getRawDest() == BCInst;
682 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
683 // If this is a memcpy/memmove, emit a GEP of the other element address.
686 Value *Idx[2] = { Zero, ConstantInt::get(Type::Int32Ty, i) };
687 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
688 OtherPtr->getNameStr()+"."+utostr(i),
692 Value *EltPtr = NewElts[i];
693 const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
695 // If we got down to a scalar, insert a load or store as appropriate.
696 if (EltTy->isSingleValueType()) {
697 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
698 Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
700 new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
703 assert(isa<MemSetInst>(MI));
705 // If the stored element is zero (common case), just store a null
708 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
710 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
712 // If EltTy is a vector type, get the element type.
713 const Type *ValTy = EltTy;
714 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
715 ValTy = VTy->getElementType();
717 // Construct an integer with the right value.
718 unsigned EltSize = TD.getTypeSizeInBits(ValTy);
719 APInt OneVal(EltSize, CI->getZExtValue());
720 APInt TotalVal(OneVal);
722 for (unsigned i = 0; 8*i < EltSize; ++i) {
723 TotalVal = TotalVal.shl(8);
727 // Convert the integer value to the appropriate type.
728 StoreVal = ConstantInt::get(TotalVal);
729 if (isa<PointerType>(ValTy))
730 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
731 else if (ValTy->isFloatingPoint())
732 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
733 assert(StoreVal->getType() == ValTy && "Type mismatch!");
735 // If the requested value was a vector constant, create it.
736 if (EltTy != ValTy) {
737 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
738 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
739 StoreVal = ConstantVector::get(&Elts[0], NumElts);
742 new StoreInst(StoreVal, EltPtr, MI);
745 // Otherwise, if we're storing a byte variable, use a memset call for
750 // Cast the element pointer to BytePtrTy.
751 if (EltPtr->getType() != BytePtrTy)
752 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
754 // Cast the other pointer (if we have one) to BytePtrTy.
755 if (OtherElt && OtherElt->getType() != BytePtrTy)
756 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
759 unsigned EltSize = TD.getABITypeSize(EltTy);
761 // Finally, insert the meminst for this element.
762 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
764 SROADest ? EltPtr : OtherElt, // Dest ptr
765 SROADest ? OtherElt : EltPtr, // Src ptr
766 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
769 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
771 assert(isa<MemSetInst>(MI));
773 EltPtr, MI->getOperand(2), // Dest, Value,
774 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
777 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
781 // Finally, MI is now dead, as we've modified its actions to occur on all of
782 // the elements of the aggregate.
784 MI->eraseFromParent();
788 /// HasPadding - Return true if the specified type has any structure or
789 /// alignment padding, false otherwise.
790 static bool HasPadding(const Type *Ty, const TargetData &TD) {
791 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
792 const StructLayout *SL = TD.getStructLayout(STy);
793 unsigned PrevFieldBitOffset = 0;
794 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
795 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
797 // Padding in sub-elements?
798 if (HasPadding(STy->getElementType(i), TD))
801 // Check to see if there is any padding between this element and the
804 unsigned PrevFieldEnd =
805 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
806 if (PrevFieldEnd < FieldBitOffset)
810 PrevFieldBitOffset = FieldBitOffset;
813 // Check for tail padding.
814 if (unsigned EltCount = STy->getNumElements()) {
815 unsigned PrevFieldEnd = PrevFieldBitOffset +
816 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
817 if (PrevFieldEnd < SL->getSizeInBits())
821 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
822 return HasPadding(ATy->getElementType(), TD);
823 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
824 return HasPadding(VTy->getElementType(), TD);
826 return TD.getTypeSizeInBits(Ty) != TD.getABITypeSizeInBits(Ty);
829 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
830 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
831 /// or 1 if safe after canonicalization has been performed.
833 int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
834 // Loop over the use list of the alloca. We can only transform it if all of
835 // the users are safe to transform.
838 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
840 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
842 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
847 // Okay, we know all the users are promotable. If the aggregate is a memcpy
848 // source and destination, we have to be careful. In particular, the memcpy
849 // could be moving around elements that live in structure padding of the LLVM
850 // types, but may actually be used. In these cases, we refuse to promote the
852 if (Info.isMemCpySrc && Info.isMemCpyDst &&
853 HasPadding(AI->getType()->getElementType(), getAnalysis<TargetData>()))
856 // If we require cleanup, return 1, otherwise return 3.
857 return Info.needsCanon ? 1 : 3;
860 /// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
861 /// allocation, but only if cleaned up, perform the cleanups required.
862 void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
863 // At this point, we know that the end result will be SROA'd and promoted, so
864 // we can insert ugly code if required so long as sroa+mem2reg will clean it
866 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
868 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI++);
870 gep_type_iterator I = gep_type_begin(GEPI);
873 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
874 uint64_t NumElements = AT->getNumElements();
876 if (!isa<ConstantInt>(I.getOperand())) {
877 if (NumElements == 1) {
878 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
880 assert(NumElements == 2 && "Unhandled case!");
881 // All users of the GEP must be loads. At each use of the GEP, insert
882 // two loads of the appropriate indexed GEP and select between them.
883 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
884 Constant::getNullValue(I.getOperand()->getType()),
886 // Insert the new GEP instructions, which are properly indexed.
887 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
888 Indices[1] = Constant::getNullValue(Type::Int32Ty);
889 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
892 GEPI->getName()+".0", GEPI);
893 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
894 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
897 GEPI->getName()+".1", GEPI);
898 // Replace all loads of the variable index GEP with loads from both
899 // indexes and a select.
900 while (!GEPI->use_empty()) {
901 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
902 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
903 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
904 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
905 LI->replaceAllUsesWith(R);
906 LI->eraseFromParent();
908 GEPI->eraseFromParent();
915 /// MergeInType - Add the 'In' type to the accumulated type so far. If the
916 /// types are incompatible, return true, otherwise update Accum and return
919 /// There are three cases we handle here:
920 /// 1) An effectively-integer union, where the pieces are stored into as
921 /// smaller integers (common with byte swap and other idioms).
922 /// 2) A union of vector types of the same size and potentially its elements.
923 /// Here we turn element accesses into insert/extract element operations.
924 /// 3) A union of scalar types, such as int/float or int/pointer. Here we
925 /// merge together into integers, allowing the xform to work with #1 as
927 static bool MergeInType(const Type *In, const Type *&Accum,
928 const TargetData &TD) {
929 // If this is our first type, just use it.
930 const VectorType *PTy;
931 if (Accum == Type::VoidTy || In == Accum) {
933 } else if (In == Type::VoidTy) {
935 } else if (In->isInteger() && Accum->isInteger()) { // integer union.
936 // Otherwise pick whichever type is larger.
937 if (cast<IntegerType>(In)->getBitWidth() >
938 cast<IntegerType>(Accum)->getBitWidth())
940 } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
941 // Pointer unions just stay as one of the pointers.
942 } else if (isa<VectorType>(In) || isa<VectorType>(Accum)) {
943 if ((PTy = dyn_cast<VectorType>(Accum)) &&
944 PTy->getElementType() == In) {
945 // Accum is a vector, and we are accessing an element: ok.
946 } else if ((PTy = dyn_cast<VectorType>(In)) &&
947 PTy->getElementType() == Accum) {
948 // In is a vector, and accum is an element: ok, remember In.
950 } else if ((PTy = dyn_cast<VectorType>(In)) && isa<VectorType>(Accum) &&
951 PTy->getBitWidth() == cast<VectorType>(Accum)->getBitWidth()) {
952 // Two vectors of the same size: keep Accum.
954 // Cannot insert an short into a <4 x int> or handle
955 // <2 x int> -> <4 x int>
959 // Pointer/FP/Integer unions merge together as integers.
960 switch (Accum->getTypeID()) {
961 case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
962 case Type::FloatTyID: Accum = Type::Int32Ty; break;
963 case Type::DoubleTyID: Accum = Type::Int64Ty; break;
964 case Type::X86_FP80TyID: return true;
965 case Type::FP128TyID: return true;
966 case Type::PPC_FP128TyID: return true;
968 assert(Accum->isInteger() && "Unknown FP type!");
972 switch (In->getTypeID()) {
973 case Type::PointerTyID: In = TD.getIntPtrType(); break;
974 case Type::FloatTyID: In = Type::Int32Ty; break;
975 case Type::DoubleTyID: In = Type::Int64Ty; break;
976 case Type::X86_FP80TyID: return true;
977 case Type::FP128TyID: return true;
978 case Type::PPC_FP128TyID: return true;
980 assert(In->isInteger() && "Unknown FP type!");
983 return MergeInType(In, Accum, TD);
988 /// getUIntAtLeastAsBigAs - Return an unsigned integer type that is at least
989 /// as big as the specified type. If there is no suitable type, this returns
991 const Type *getUIntAtLeastAsBigAs(unsigned NumBits) {
992 if (NumBits > 64) return 0;
993 if (NumBits > 32) return Type::Int64Ty;
994 if (NumBits > 16) return Type::Int32Ty;
995 if (NumBits > 8) return Type::Int16Ty;
999 /// CanConvertToScalar - V is a pointer. If we can convert the pointee to a
1000 /// single scalar integer type, return that type. Further, if the use is not
1001 /// a completely trivial use that mem2reg could promote, set IsNotTrivial. If
1002 /// there are no uses of this pointer, return Type::VoidTy to differentiate from
1005 const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
1006 const Type *UsedType = Type::VoidTy; // No uses, no forced type.
1007 const TargetData &TD = getAnalysis<TargetData>();
1008 const PointerType *PTy = cast<PointerType>(V->getType());
1010 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1011 Instruction *User = cast<Instruction>(*UI);
1013 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1014 // FIXME: Loads of a first class aggregrate value could be converted to a
1015 // series of loads and insertvalues
1016 if (!LI->getType()->isSingleValueType())
1019 if (MergeInType(LI->getType(), UsedType, TD))
1022 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1023 // Storing the pointer, not into the value?
1024 if (SI->getOperand(0) == V) return 0;
1026 // FIXME: Stores of a first class aggregrate value could be converted to a
1027 // series of extractvalues and stores
1028 if (!SI->getOperand(0)->getType()->isSingleValueType())
1031 // NOTE: We could handle storing of FP imms into integers here!
1033 if (MergeInType(SI->getOperand(0)->getType(), UsedType, TD))
1035 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1036 IsNotTrivial = true;
1037 const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
1038 if (!SubTy || MergeInType(SubTy, UsedType, TD)) return 0;
1039 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1040 // Check to see if this is stepping over an element: GEP Ptr, int C
1041 if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
1042 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
1043 unsigned ElSize = TD.getABITypeSize(PTy->getElementType());
1044 unsigned BitOffset = Idx*ElSize*8;
1045 if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
1047 IsNotTrivial = true;
1048 const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
1049 if (SubElt == 0) return 0;
1050 if (SubElt != Type::VoidTy && SubElt->isInteger()) {
1052 getUIntAtLeastAsBigAs(TD.getABITypeSizeInBits(SubElt)+BitOffset);
1053 if (NewTy == 0 || MergeInType(NewTy, UsedType, TD)) return 0;
1056 } else if (GEP->getNumOperands() == 3 &&
1057 isa<ConstantInt>(GEP->getOperand(1)) &&
1058 isa<ConstantInt>(GEP->getOperand(2)) &&
1059 cast<ConstantInt>(GEP->getOperand(1))->isZero()) {
1060 // We are stepping into an element, e.g. a structure or an array:
1061 // GEP Ptr, int 0, uint C
1062 const Type *AggTy = PTy->getElementType();
1063 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1065 if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
1066 if (Idx >= ATy->getNumElements()) return 0; // Out of range.
1067 } else if (const VectorType *VectorTy = dyn_cast<VectorType>(AggTy)) {
1068 // Getting an element of the vector.
1069 if (Idx >= VectorTy->getNumElements()) return 0; // Out of range.
1071 // Merge in the vector type.
1072 if (MergeInType(VectorTy, UsedType, TD)) return 0;
1074 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1075 if (SubTy == 0) return 0;
1077 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
1080 // We'll need to change this to an insert/extract element operation.
1081 IsNotTrivial = true;
1082 continue; // Everything looks ok
1084 } else if (isa<StructType>(AggTy)) {
1085 // Structs are always ok.
1089 const Type *NTy = getUIntAtLeastAsBigAs(TD.getABITypeSizeInBits(AggTy));
1090 if (NTy == 0 || MergeInType(NTy, UsedType, TD)) return 0;
1091 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1092 if (SubTy == 0) return 0;
1093 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
1095 continue; // Everything looks ok
1099 // Cannot handle this!
1107 /// ConvertToScalar - The specified alloca passes the CanConvertToScalar
1108 /// predicate and is non-trivial. Convert it to something that can be trivially
1109 /// promoted into a register by mem2reg.
1110 void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
1111 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = "
1112 << *ActualTy << "\n";
1115 BasicBlock *EntryBlock = AI->getParent();
1116 assert(EntryBlock == &EntryBlock->getParent()->getEntryBlock() &&
1117 "Not in the entry block!");
1118 EntryBlock->getInstList().remove(AI); // Take the alloca out of the program.
1120 // Create and insert the alloca.
1121 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
1122 EntryBlock->begin());
1123 ConvertUsesToScalar(AI, NewAI, 0);
1128 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1129 /// directly. This happens when we are converting an "integer union" to a
1130 /// single integer scalar, or when we are converting a "vector union" to a
1131 /// vector with insert/extractelement instructions.
1133 /// Offset is an offset from the original alloca, in bits that need to be
1134 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1135 void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
1136 while (!Ptr->use_empty()) {
1137 Instruction *User = cast<Instruction>(Ptr->use_back());
1139 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1140 Value *NV = ConvertUsesOfLoadToScalar(LI, NewAI, Offset);
1141 LI->replaceAllUsesWith(NV);
1142 LI->eraseFromParent();
1143 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1144 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1146 Value *SV = ConvertUsesOfStoreToScalar(SI, NewAI, Offset);
1147 new StoreInst(SV, NewAI, SI);
1148 SI->eraseFromParent();
1150 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1151 ConvertUsesToScalar(CI, NewAI, Offset);
1152 CI->eraseFromParent();
1153 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1154 const PointerType *AggPtrTy =
1155 cast<PointerType>(GEP->getOperand(0)->getType());
1156 const TargetData &TD = getAnalysis<TargetData>();
1157 unsigned AggSizeInBits =
1158 TD.getABITypeSizeInBits(AggPtrTy->getElementType());
1160 // Check to see if this is stepping over an element: GEP Ptr, int C
1161 unsigned NewOffset = Offset;
1162 if (GEP->getNumOperands() == 2) {
1163 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
1164 unsigned BitOffset = Idx*AggSizeInBits;
1166 NewOffset += BitOffset;
1167 } else if (GEP->getNumOperands() == 3) {
1168 // We know that operand #2 is zero.
1169 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1170 const Type *AggTy = AggPtrTy->getElementType();
1171 if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
1172 unsigned ElSizeBits =
1173 TD.getABITypeSizeInBits(SeqTy->getElementType());
1175 NewOffset += ElSizeBits*Idx;
1176 } else if (const StructType *STy = dyn_cast<StructType>(AggTy)) {
1177 unsigned EltBitOffset =
1178 TD.getStructLayout(STy)->getElementOffsetInBits(Idx);
1180 NewOffset += EltBitOffset;
1182 assert(0 && "Unsupported operation!");
1186 assert(0 && "Unsupported operation!");
1189 ConvertUsesToScalar(GEP, NewAI, NewOffset);
1190 GEP->eraseFromParent();
1192 assert(0 && "Unsupported operation!");
1198 /// ConvertUsesOfLoadToScalar - Convert all of the users the specified load to
1199 /// use the new alloca directly, returning the value that should replace the
1200 /// load. This happens when we are converting an "integer union" to a
1201 /// single integer scalar, or when we are converting a "vector union" to a
1202 /// vector with insert/extractelement instructions.
1204 /// Offset is an offset from the original alloca, in bits that need to be
1205 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1206 Value *SROA::ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
1208 // The load is a bit extract from NewAI shifted right by Offset bits.
1209 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
1211 if (NV->getType() == LI->getType() && Offset == 0) {
1212 // We win, no conversion needed.
1216 // If the result type of the 'union' is a pointer, then this must be ptr->ptr
1217 // cast. Anything else would result in NV being an integer.
1218 if (isa<PointerType>(NV->getType())) {
1219 assert(isa<PointerType>(LI->getType()));
1220 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1223 if (const VectorType *VTy = dyn_cast<VectorType>(NV->getType())) {
1224 // If the result alloca is a vector type, this is either an element
1225 // access or a bitcast to another vector type.
1226 if (isa<VectorType>(LI->getType()))
1227 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1229 // Otherwise it must be an element access.
1230 const TargetData &TD = getAnalysis<TargetData>();
1233 unsigned EltSize = TD.getABITypeSizeInBits(VTy->getElementType());
1234 Elt = Offset/EltSize;
1235 Offset -= EltSize*Elt;
1237 NV = new ExtractElementInst(NV, ConstantInt::get(Type::Int32Ty, Elt),
1240 // If we're done, return this element.
1241 if (NV->getType() == LI->getType() && Offset == 0)
1245 const IntegerType *NTy = cast<IntegerType>(NV->getType());
1247 // If this is a big-endian system and the load is narrower than the
1248 // full alloca type, we need to do a shift to get the right bits.
1250 const TargetData &TD = getAnalysis<TargetData>();
1251 if (TD.isBigEndian()) {
1252 // On big-endian machines, the lowest bit is stored at the bit offset
1253 // from the pointer given by getTypeStoreSizeInBits. This matters for
1254 // integers with a bitwidth that is not a multiple of 8.
1255 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
1256 TD.getTypeStoreSizeInBits(LI->getType()) - Offset;
1261 // Note: we support negative bitwidths (with shl) which are not defined.
1262 // We do this to support (f.e.) loads off the end of a structure where
1263 // only some bits are used.
1264 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
1265 NV = BinaryOperator::CreateLShr(NV,
1266 ConstantInt::get(NV->getType(),ShAmt),
1268 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
1269 NV = BinaryOperator::CreateShl(NV,
1270 ConstantInt::get(NV->getType(),-ShAmt),
1273 // Finally, unconditionally truncate the integer to the right width.
1274 unsigned LIBitWidth = TD.getTypeSizeInBits(LI->getType());
1275 if (LIBitWidth < NTy->getBitWidth())
1276 NV = new TruncInst(NV, IntegerType::get(LIBitWidth),
1279 // If the result is an integer, this is a trunc or bitcast.
1280 if (isa<IntegerType>(LI->getType())) {
1282 } else if (LI->getType()->isFloatingPoint()) {
1283 // Just do a bitcast, we know the sizes match up.
1284 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1286 // Otherwise must be a pointer.
1287 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
1289 assert(NV->getType() == LI->getType() && "Didn't convert right?");
1294 /// ConvertUsesOfStoreToScalar - Convert the specified store to a load+store
1295 /// pair of the new alloca directly, returning the value that should be stored
1296 /// to the alloca. This happens when we are converting an "integer union" to a
1297 /// single integer scalar, or when we are converting a "vector union" to a
1298 /// vector with insert/extractelement instructions.
1300 /// Offset is an offset from the original alloca, in bits that need to be
1301 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1302 Value *SROA::ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
1305 // Convert the stored type to the actual type, shift it left to insert
1306 // then 'or' into place.
1307 Value *SV = SI->getOperand(0);
1308 const Type *AllocaType = NewAI->getType()->getElementType();
1309 if (SV->getType() == AllocaType && Offset == 0) {
1311 } else if (const VectorType *PTy = dyn_cast<VectorType>(AllocaType)) {
1312 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1314 // If the result alloca is a vector type, this is either an element
1315 // access or a bitcast to another vector type.
1316 if (isa<VectorType>(SV->getType())) {
1317 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1319 // Must be an element insertion.
1320 const TargetData &TD = getAnalysis<TargetData>();
1321 unsigned Elt = Offset/TD.getABITypeSizeInBits(PTy->getElementType());
1322 SV = InsertElementInst::Create(Old, SV,
1323 ConstantInt::get(Type::Int32Ty, Elt),
1326 } else if (isa<PointerType>(AllocaType)) {
1327 // If the alloca type is a pointer, then all the elements must be
1329 if (SV->getType() != AllocaType)
1330 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1332 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1334 // If SV is a float, convert it to the appropriate integer type.
1335 // If it is a pointer, do the same, and also handle ptr->ptr casts
1337 const TargetData &TD = getAnalysis<TargetData>();
1338 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
1339 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
1340 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
1341 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
1342 if (SV->getType()->isFloatingPoint())
1343 SV = new BitCastInst(SV, IntegerType::get(SrcWidth),
1345 else if (isa<PointerType>(SV->getType()))
1346 SV = new PtrToIntInst(SV, TD.getIntPtrType(), SV->getName(), SI);
1348 // Always zero extend the value if needed.
1349 if (SV->getType() != AllocaType)
1350 SV = new ZExtInst(SV, AllocaType, SV->getName(), SI);
1352 // If this is a big-endian system and the store is narrower than the
1353 // full alloca type, we need to do a shift to get the right bits.
1355 if (TD.isBigEndian()) {
1356 // On big-endian machines, the lowest bit is stored at the bit offset
1357 // from the pointer given by getTypeStoreSizeInBits. This matters for
1358 // integers with a bitwidth that is not a multiple of 8.
1359 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1364 // Note: we support negative bitwidths (with shr) which are not defined.
1365 // We do this to support (f.e.) stores off the end of a structure where
1366 // only some bits in the structure are set.
1367 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1368 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1369 SV = BinaryOperator::CreateShl(SV,
1370 ConstantInt::get(SV->getType(), ShAmt),
1373 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1374 SV = BinaryOperator::CreateLShr(SV,
1375 ConstantInt::get(SV->getType(),-ShAmt),
1377 Mask = Mask.lshr(ShAmt);
1380 // Mask out the bits we are about to insert from the old value, and or
1382 if (SrcWidth != DestWidth) {
1383 assert(DestWidth > SrcWidth);
1384 Old = BinaryOperator::CreateAnd(Old, ConstantInt::get(~Mask),
1385 Old->getName()+".mask", SI);
1386 SV = BinaryOperator::CreateOr(Old, SV, SV->getName()+".ins", SI);
1394 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1395 /// some part of a constant global variable. This intentionally only accepts
1396 /// constant expressions because we don't can't rewrite arbitrary instructions.
1397 static bool PointsToConstantGlobal(Value *V) {
1398 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1399 return GV->isConstant();
1400 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1401 if (CE->getOpcode() == Instruction::BitCast ||
1402 CE->getOpcode() == Instruction::GetElementPtr)
1403 return PointsToConstantGlobal(CE->getOperand(0));
1407 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1408 /// pointer to an alloca. Ignore any reads of the pointer, return false if we
1409 /// see any stores or other unknown uses. If we see pointer arithmetic, keep
1410 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
1411 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1412 /// the alloca, and if the source pointer is a pointer to a constant global, we
1413 /// can optimize this.
1414 static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1416 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1417 if (isa<LoadInst>(*UI)) {
1418 // Ignore loads, they are always ok.
1421 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1422 // If uses of the bitcast are ok, we are ok.
1423 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1427 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1428 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1429 // doesn't, it does.
1430 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1431 isOffset || !GEP->hasAllZeroIndices()))
1436 // If this is isn't our memcpy/memmove, reject it as something we can't
1438 if (!isa<MemCpyInst>(*UI) && !isa<MemMoveInst>(*UI))
1441 // If we already have seen a copy, reject the second one.
1442 if (TheCopy) return false;
1444 // If the pointer has been offset from the start of the alloca, we can't
1445 // safely handle this.
1446 if (isOffset) return false;
1448 // If the memintrinsic isn't using the alloca as the dest, reject it.
1449 if (UI.getOperandNo() != 1) return false;
1451 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1453 // If the source of the memcpy/move is not a constant global, reject it.
1454 if (!PointsToConstantGlobal(MI->getOperand(2)))
1457 // Otherwise, the transform is safe. Remember the copy instruction.
1463 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1464 /// modified by a copy from a constant global. If we can prove this, we can
1465 /// replace any uses of the alloca with uses of the global directly.
1466 Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1467 Instruction *TheCopy = 0;
1468 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))