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(&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>();
75 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
76 /// information about the uses. All these fields are initialized to false
77 /// and set to true when something is learned.
79 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
82 /// needsCanon - This is set to true if there is some use of the alloca
83 /// that requires canonicalization.
86 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
89 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
93 : isUnsafe(false), needsCanon(false),
94 isMemCpySrc(false), isMemCpyDst(false) {}
99 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
101 int isSafeAllocaToScalarRepl(AllocationInst *AI);
103 void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
105 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
107 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
108 unsigned OpNo, AllocaInfo &Info);
109 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
112 void DoScalarReplacement(AllocationInst *AI,
113 std::vector<AllocationInst*> &WorkList);
114 void CanonicalizeAllocaUsers(AllocationInst *AI);
115 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
117 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
118 SmallVector<AllocaInst*, 32> &NewElts);
120 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
122 SmallVector<AllocaInst*, 32> &NewElts);
123 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocationInst *AI,
124 SmallVector<AllocaInst*, 32> &NewElts);
125 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
126 SmallVector<AllocaInst*, 32> &NewElts);
128 bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&ResTy,
130 void ConvertToScalar(AllocationInst *AI, const Type *Ty);
131 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
132 Value *ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
134 Value *ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
136 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
141 static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
143 // Public interface to the ScalarReplAggregates pass
144 FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
145 return new SROA(Threshold);
149 bool SROA::runOnFunction(Function &F) {
150 TD = &getAnalysis<TargetData>();
152 bool Changed = performPromotion(F);
154 bool LocalChange = performScalarRepl(F);
155 if (!LocalChange) break; // No need to repromote if no scalarrepl
157 LocalChange = performPromotion(F);
158 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
165 bool SROA::performPromotion(Function &F) {
166 std::vector<AllocaInst*> Allocas;
167 DominatorTree &DT = getAnalysis<DominatorTree>();
168 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
170 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
172 bool Changed = false;
177 // Find allocas that are safe to promote, by looking at all instructions in
179 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
180 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
181 if (isAllocaPromotable(AI))
182 Allocas.push_back(AI);
184 if (Allocas.empty()) break;
186 PromoteMemToReg(Allocas, DT, DF);
187 NumPromoted += Allocas.size();
194 /// getNumSAElements - Return the number of elements in the specific struct or
196 static uint64_t getNumSAElements(const Type *T) {
197 if (const StructType *ST = dyn_cast<StructType>(T))
198 return ST->getNumElements();
199 return cast<ArrayType>(T)->getNumElements();
202 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
203 // which runs on all of the malloc/alloca instructions in the function, removing
204 // them if they are only used by getelementptr instructions.
206 bool SROA::performScalarRepl(Function &F) {
207 std::vector<AllocationInst*> WorkList;
209 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
210 BasicBlock &BB = F.getEntryBlock();
211 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
212 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
213 WorkList.push_back(A);
215 // Process the worklist
216 bool Changed = false;
217 while (!WorkList.empty()) {
218 AllocationInst *AI = WorkList.back();
221 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
222 // with unused elements.
223 if (AI->use_empty()) {
224 AI->eraseFromParent();
228 // Check to see if we can perform the core SROA transformation. We cannot
229 // transform the allocation instruction if it is an array allocation
230 // (allocations OF arrays are ok though), and an allocation of a scalar
231 // value cannot be decomposed at all.
232 if (!AI->isArrayAllocation() &&
233 (isa<StructType>(AI->getAllocatedType()) ||
234 isa<ArrayType>(AI->getAllocatedType())) &&
235 AI->getAllocatedType()->isSized() &&
236 // Do not promote any struct whose size is larger than "128" bytes.
237 TD->getTypePaddedSize(AI->getAllocatedType()) < SRThreshold &&
238 // Do not promote any struct into more than "32" separate vars.
239 getNumSAElements(AI->getAllocatedType()) < SRThreshold/4) {
240 // Check that all of the users of the allocation are capable of being
242 switch (isSafeAllocaToScalarRepl(AI)) {
243 default: assert(0 && "Unexpected value!");
244 case 0: // Not safe to scalar replace.
246 case 1: // Safe, but requires cleanup/canonicalizations first
247 CanonicalizeAllocaUsers(AI);
249 case 3: // Safe to scalar replace.
250 DoScalarReplacement(AI, WorkList);
256 // Check to see if this allocation is only modified by a memcpy/memmove from
257 // a constant global. If this is the case, we can change all users to use
258 // the constant global instead. This is commonly produced by the CFE by
259 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
260 // is only subsequently read.
261 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
262 DOUT << "Found alloca equal to global: " << *AI;
263 DOUT << " memcpy = " << *TheCopy;
264 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
265 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
266 TheCopy->eraseFromParent(); // Don't mutate the global.
267 AI->eraseFromParent();
273 // If we can turn this aggregate value (potentially with casts) into a
274 // simple scalar value that can be mem2reg'd into a register value.
275 // IsNotTrivial tracks whether this is something that mem2reg could have
276 // promoted itself. If so, we don't want to transform it needlessly. Note
277 // that we can't just check based on the type: the alloca may be of an i32
278 // but that has pointer arithmetic to set byte 3 of it or something.
279 bool IsNotTrivial = false;
280 const Type *ActualType = 0;
281 if (CanConvertToScalar(AI, IsNotTrivial, ActualType, 0))
282 if (IsNotTrivial && ActualType &&
283 TD->getTypeSizeInBits(ActualType) < SRThreshold*8) {
284 ConvertToScalar(AI, ActualType);
289 // Otherwise, couldn't process this.
295 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
296 /// predicate, do SROA now.
297 void SROA::DoScalarReplacement(AllocationInst *AI,
298 std::vector<AllocationInst*> &WorkList) {
299 DOUT << "Found inst to SROA: " << *AI;
300 SmallVector<AllocaInst*, 32> ElementAllocas;
301 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
302 ElementAllocas.reserve(ST->getNumContainedTypes());
303 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
304 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
306 AI->getName() + "." + utostr(i), AI);
307 ElementAllocas.push_back(NA);
308 WorkList.push_back(NA); // Add to worklist for recursive processing
311 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
312 ElementAllocas.reserve(AT->getNumElements());
313 const Type *ElTy = AT->getElementType();
314 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
315 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
316 AI->getName() + "." + utostr(i), AI);
317 ElementAllocas.push_back(NA);
318 WorkList.push_back(NA); // Add to worklist for recursive processing
322 // Now that we have created the alloca instructions that we want to use,
323 // expand the getelementptr instructions to use them.
325 while (!AI->use_empty()) {
326 Instruction *User = cast<Instruction>(AI->use_back());
327 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
328 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
329 BCInst->eraseFromParent();
334 // %res = load { i32, i32 }* %alloc
336 // %load.0 = load i32* %alloc.0
337 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
338 // %load.1 = load i32* %alloc.1
339 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
340 // (Also works for arrays instead of structs)
341 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
342 Value *Insert = UndefValue::get(LI->getType());
343 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
344 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
345 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
347 LI->replaceAllUsesWith(Insert);
348 LI->eraseFromParent();
353 // store { i32, i32 } %val, { i32, i32 }* %alloc
355 // %val.0 = extractvalue { i32, i32 } %val, 0
356 // store i32 %val.0, i32* %alloc.0
357 // %val.1 = extractvalue { i32, i32 } %val, 1
358 // store i32 %val.1, i32* %alloc.1
359 // (Also works for arrays instead of structs)
360 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
361 Value *Val = SI->getOperand(0);
362 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
363 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
364 new StoreInst(Extract, ElementAllocas[i], SI);
366 SI->eraseFromParent();
370 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
371 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
373 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
375 assert(Idx < ElementAllocas.size() && "Index out of range?");
376 AllocaInst *AllocaToUse = ElementAllocas[Idx];
379 if (GEPI->getNumOperands() == 3) {
380 // Do not insert a new getelementptr instruction with zero indices, only
381 // to have it optimized out later.
382 RepValue = AllocaToUse;
384 // We are indexing deeply into the structure, so we still need a
385 // getelement ptr instruction to finish the indexing. This may be
386 // expanded itself once the worklist is rerun.
388 SmallVector<Value*, 8> NewArgs;
389 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
390 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
391 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
392 NewArgs.end(), "", GEPI);
393 RepValue->takeName(GEPI);
396 // If this GEP is to the start of the aggregate, check for memcpys.
397 if (Idx == 0 && GEPI->hasAllZeroIndices())
398 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
400 // Move all of the users over to the new GEP.
401 GEPI->replaceAllUsesWith(RepValue);
402 // Delete the old GEP
403 GEPI->eraseFromParent();
406 // Finally, delete the Alloca instruction
407 AI->eraseFromParent();
412 /// isSafeElementUse - Check to see if this use is an allowed use for a
413 /// getelementptr instruction of an array aggregate allocation. isFirstElt
414 /// indicates whether Ptr is known to the start of the aggregate.
416 void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
418 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
420 Instruction *User = cast<Instruction>(*I);
421 switch (User->getOpcode()) {
422 case Instruction::Load: break;
423 case Instruction::Store:
424 // Store is ok if storing INTO the pointer, not storing the pointer
425 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
427 case Instruction::GetElementPtr: {
428 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
429 bool AreAllZeroIndices = isFirstElt;
430 if (GEP->getNumOperands() > 1) {
431 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
432 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
433 // Using pointer arithmetic to navigate the array.
434 return MarkUnsafe(Info);
436 if (AreAllZeroIndices)
437 AreAllZeroIndices = GEP->hasAllZeroIndices();
439 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
440 if (Info.isUnsafe) return;
443 case Instruction::BitCast:
445 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
446 if (Info.isUnsafe) return;
449 DOUT << " Transformation preventing inst: " << *User;
450 return MarkUnsafe(Info);
451 case Instruction::Call:
452 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
454 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
455 if (Info.isUnsafe) return;
459 DOUT << " Transformation preventing inst: " << *User;
460 return MarkUnsafe(Info);
462 DOUT << " Transformation preventing inst: " << *User;
463 return MarkUnsafe(Info);
466 return; // All users look ok :)
469 /// AllUsersAreLoads - Return true if all users of this value are loads.
470 static bool AllUsersAreLoads(Value *Ptr) {
471 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
473 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
478 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
479 /// aggregate allocation.
481 void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
483 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
484 return isSafeUseOfBitCastedAllocation(C, AI, Info);
486 if (LoadInst *LI = dyn_cast<LoadInst>(User))
487 if (!LI->isVolatile())
488 return;// Loads (returning a first class aggregrate) are always rewritable
490 if (StoreInst *SI = dyn_cast<StoreInst>(User))
491 if (!SI->isVolatile() && SI->getOperand(0) != AI)
492 return;// Store is ok if storing INTO the pointer, not storing the pointer
494 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
496 return MarkUnsafe(Info);
498 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
500 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
502 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
503 return MarkUnsafe(Info);
507 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
509 bool IsAllZeroIndices = true;
511 // If the first index is a non-constant index into an array, see if we can
512 // handle it as a special case.
513 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
514 if (!isa<ConstantInt>(I.getOperand())) {
515 IsAllZeroIndices = 0;
516 uint64_t NumElements = AT->getNumElements();
518 // If this is an array index and the index is not constant, we cannot
519 // promote... that is unless the array has exactly one or two elements in
520 // it, in which case we CAN promote it, but we have to canonicalize this
521 // out if this is the only problem.
522 if ((NumElements == 1 || NumElements == 2) &&
523 AllUsersAreLoads(GEPI)) {
524 Info.needsCanon = true;
525 return; // Canonicalization required!
527 return MarkUnsafe(Info);
531 // Walk through the GEP type indices, checking the types that this indexes
533 for (; I != E; ++I) {
534 // Ignore struct elements, no extra checking needed for these.
535 if (isa<StructType>(*I))
538 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
539 if (!IdxVal) return MarkUnsafe(Info);
541 // Are all indices still zero?
542 IsAllZeroIndices &= IdxVal->isZero();
544 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
545 // This GEP indexes an array. Verify that this is an in-range constant
546 // integer. Specifically, consider A[0][i]. We cannot know that the user
547 // isn't doing invalid things like allowing i to index an out-of-range
548 // subscript that accesses A[1]. Because of this, we have to reject SROA
549 // of any accesses into structs where any of the components are variables.
550 if (IdxVal->getZExtValue() >= AT->getNumElements())
551 return MarkUnsafe(Info);
552 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
553 if (IdxVal->getZExtValue() >= VT->getNumElements())
554 return MarkUnsafe(Info);
558 // If there are any non-simple uses of this getelementptr, make sure to reject
560 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
563 /// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
564 /// intrinsic can be promoted by SROA. At this point, we know that the operand
565 /// of the memintrinsic is a pointer to the beginning of the allocation.
566 void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
567 unsigned OpNo, AllocaInfo &Info) {
568 // If not constant length, give up.
569 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
570 if (!Length) return MarkUnsafe(Info);
572 // If not the whole aggregate, give up.
573 if (Length->getZExtValue() !=
574 TD->getTypePaddedSize(AI->getType()->getElementType()))
575 return MarkUnsafe(Info);
577 // We only know about memcpy/memset/memmove.
578 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
579 return MarkUnsafe(Info);
581 // Otherwise, we can transform it. Determine whether this is a memcpy/set
582 // into or out of the aggregate.
584 Info.isMemCpyDst = true;
587 Info.isMemCpySrc = true;
591 /// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
593 void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
595 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
597 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
598 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
599 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
600 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
601 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
602 if (SI->isVolatile())
603 return MarkUnsafe(Info);
605 // If storing the entire alloca in one chunk through a bitcasted pointer
606 // to integer, we can transform it. This happens (for example) when you
607 // cast a {i32,i32}* to i64* and store through it. This is similar to the
608 // memcpy case and occurs in various "byval" cases and emulated memcpys.
609 if (isa<IntegerType>(SI->getOperand(0)->getType()) &&
610 TD->getTypePaddedSize(SI->getOperand(0)->getType()) ==
611 TD->getTypePaddedSize(AI->getType()->getElementType())) {
612 Info.isMemCpyDst = true;
615 return MarkUnsafe(Info);
616 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
617 if (LI->isVolatile())
618 return MarkUnsafe(Info);
620 // If loading the entire alloca in one chunk through a bitcasted pointer
621 // to integer, we can transform it. This happens (for example) when you
622 // cast a {i32,i32}* to i64* and load through it. This is similar to the
623 // memcpy case and occurs in various "byval" cases and emulated memcpys.
624 if (isa<IntegerType>(LI->getType()) &&
625 TD->getTypePaddedSize(LI->getType()) ==
626 TD->getTypePaddedSize(AI->getType()->getElementType())) {
627 Info.isMemCpySrc = true;
630 return MarkUnsafe(Info);
632 return MarkUnsafe(Info);
634 if (Info.isUnsafe) return;
638 /// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
639 /// to its first element. Transform users of the cast to use the new values
641 void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
642 SmallVector<AllocaInst*, 32> &NewElts) {
643 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
645 Instruction *User = cast<Instruction>(*UI++);
646 if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) {
647 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
648 if (BCU->use_empty()) BCU->eraseFromParent();
652 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
653 // This must be memcpy/memmove/memset of the entire aggregate.
654 // Split into one per element.
655 RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts);
659 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
660 // If this is a store of the entire alloca from an integer, rewrite it.
661 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
665 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
666 // If this is a load of the entire alloca to an integer, rewrite it.
667 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
671 // Otherwise it must be some other user of a gep of the first pointer. Just
672 // leave these alone.
677 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
678 /// Rewrite it to copy or set the elements of the scalarized memory.
679 void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
681 SmallVector<AllocaInst*, 32> &NewElts) {
683 // If this is a memcpy/memmove, construct the other pointer as the
686 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
687 if (BCInst == MCI->getRawDest())
688 OtherPtr = MCI->getRawSource();
690 assert(BCInst == MCI->getRawSource());
691 OtherPtr = MCI->getRawDest();
693 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
694 if (BCInst == MMI->getRawDest())
695 OtherPtr = MMI->getRawSource();
697 assert(BCInst == MMI->getRawSource());
698 OtherPtr = MMI->getRawDest();
702 // If there is an other pointer, we want to convert it to the same pointer
703 // type as AI has, so we can GEP through it safely.
705 // It is likely that OtherPtr is a bitcast, if so, remove it.
706 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
707 OtherPtr = BC->getOperand(0);
708 // All zero GEPs are effectively bitcasts.
709 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
710 if (GEP->hasAllZeroIndices())
711 OtherPtr = GEP->getOperand(0);
713 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
714 if (BCE->getOpcode() == Instruction::BitCast)
715 OtherPtr = BCE->getOperand(0);
717 // If the pointer is not the right type, insert a bitcast to the right
719 if (OtherPtr->getType() != AI->getType())
720 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
724 // Process each element of the aggregate.
725 Value *TheFn = MI->getOperand(0);
726 const Type *BytePtrTy = MI->getRawDest()->getType();
727 bool SROADest = MI->getRawDest() == BCInst;
729 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
731 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
732 // If this is a memcpy/memmove, emit a GEP of the other element address.
735 Value *Idx[2] = { Zero, ConstantInt::get(Type::Int32Ty, i) };
736 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
737 OtherPtr->getNameStr()+"."+utostr(i),
741 Value *EltPtr = NewElts[i];
742 const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
744 // If we got down to a scalar, insert a load or store as appropriate.
745 if (EltTy->isSingleValueType()) {
746 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
747 Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
749 new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
752 assert(isa<MemSetInst>(MI));
754 // If the stored element is zero (common case), just store a null
757 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
759 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
761 // If EltTy is a vector type, get the element type.
762 const Type *ValTy = EltTy;
763 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
764 ValTy = VTy->getElementType();
766 // Construct an integer with the right value.
767 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
768 APInt OneVal(EltSize, CI->getZExtValue());
769 APInt TotalVal(OneVal);
771 for (unsigned i = 0; 8*i < EltSize; ++i) {
772 TotalVal = TotalVal.shl(8);
776 // Convert the integer value to the appropriate type.
777 StoreVal = ConstantInt::get(TotalVal);
778 if (isa<PointerType>(ValTy))
779 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
780 else if (ValTy->isFloatingPoint())
781 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
782 assert(StoreVal->getType() == ValTy && "Type mismatch!");
784 // If the requested value was a vector constant, create it.
785 if (EltTy != ValTy) {
786 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
787 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
788 StoreVal = ConstantVector::get(&Elts[0], NumElts);
791 new StoreInst(StoreVal, EltPtr, MI);
794 // Otherwise, if we're storing a byte variable, use a memset call for
798 // Cast the element pointer to BytePtrTy.
799 if (EltPtr->getType() != BytePtrTy)
800 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
802 // Cast the other pointer (if we have one) to BytePtrTy.
803 if (OtherElt && OtherElt->getType() != BytePtrTy)
804 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
807 unsigned EltSize = TD->getTypePaddedSize(EltTy);
809 // Finally, insert the meminst for this element.
810 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
812 SROADest ? EltPtr : OtherElt, // Dest ptr
813 SROADest ? OtherElt : EltPtr, // Src ptr
814 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
817 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
819 assert(isa<MemSetInst>(MI));
821 EltPtr, MI->getOperand(2), // Dest, Value,
822 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
825 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
828 MI->eraseFromParent();
831 /// RewriteStoreUserOfWholeAlloca - We found an store of an integer that
832 /// overwrites the entire allocation. Extract out the pieces of the stored
833 /// integer and store them individually.
834 void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI,
836 SmallVector<AllocaInst*, 32> &NewElts){
837 // Extract each element out of the integer according to its structure offset
838 // and store the element value to the individual alloca.
839 Value *SrcVal = SI->getOperand(0);
840 const Type *AllocaEltTy = AI->getType()->getElementType();
841 uint64_t AllocaSizeBits = TD->getTypePaddedSizeInBits(AllocaEltTy);
843 // If this isn't a store of an integer to the whole alloca, it may be a store
844 // to the first element. Just ignore the store in this case and normal SROA
846 if (!isa<IntegerType>(SrcVal->getType()) ||
847 TD->getTypePaddedSizeInBits(SrcVal->getType()) != AllocaSizeBits)
850 DOUT << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << *SI;
852 // There are two forms here: AI could be an array or struct. Both cases
853 // have different ways to compute the element offset.
854 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
855 const StructLayout *Layout = TD->getStructLayout(EltSTy);
857 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
858 // Get the number of bits to shift SrcVal to get the value.
859 const Type *FieldTy = EltSTy->getElementType(i);
860 uint64_t Shift = Layout->getElementOffsetInBits(i);
862 if (TD->isBigEndian())
863 Shift = AllocaSizeBits-Shift-TD->getTypePaddedSizeInBits(FieldTy);
865 Value *EltVal = SrcVal;
867 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
868 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
869 "sroa.store.elt", SI);
872 // Truncate down to an integer of the right size.
873 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
875 // Ignore zero sized fields like {}, they obviously contain no data.
876 if (FieldSizeBits == 0) continue;
878 if (FieldSizeBits != AllocaSizeBits)
879 EltVal = new TruncInst(EltVal, IntegerType::get(FieldSizeBits), "", SI);
880 Value *DestField = NewElts[i];
881 if (EltVal->getType() == FieldTy) {
882 // Storing to an integer field of this size, just do it.
883 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
884 // Bitcast to the right element type (for fp/vector values).
885 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
887 // Otherwise, bitcast the dest pointer (for aggregates).
888 DestField = new BitCastInst(DestField,
889 PointerType::getUnqual(EltVal->getType()),
892 new StoreInst(EltVal, DestField, SI);
896 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
897 const Type *ArrayEltTy = ATy->getElementType();
898 uint64_t ElementOffset = TD->getTypePaddedSizeInBits(ArrayEltTy);
899 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
903 if (TD->isBigEndian())
904 Shift = AllocaSizeBits-ElementOffset;
908 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
909 // Ignore zero sized fields like {}, they obviously contain no data.
910 if (ElementSizeBits == 0) continue;
912 Value *EltVal = SrcVal;
914 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
915 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
916 "sroa.store.elt", SI);
919 // Truncate down to an integer of the right size.
920 if (ElementSizeBits != AllocaSizeBits)
921 EltVal = new TruncInst(EltVal, IntegerType::get(ElementSizeBits),"",SI);
922 Value *DestField = NewElts[i];
923 if (EltVal->getType() == ArrayEltTy) {
924 // Storing to an integer field of this size, just do it.
925 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
926 // Bitcast to the right element type (for fp/vector values).
927 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
929 // Otherwise, bitcast the dest pointer (for aggregates).
930 DestField = new BitCastInst(DestField,
931 PointerType::getUnqual(EltVal->getType()),
934 new StoreInst(EltVal, DestField, SI);
936 if (TD->isBigEndian())
937 Shift -= ElementOffset;
939 Shift += ElementOffset;
943 SI->eraseFromParent();
946 /// RewriteLoadUserOfWholeAlloca - We found an load of the entire allocation to
947 /// an integer. Load the individual pieces to form the aggregate value.
948 void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
949 SmallVector<AllocaInst*, 32> &NewElts) {
950 // Extract each element out of the NewElts according to its structure offset
951 // and form the result value.
952 const Type *AllocaEltTy = AI->getType()->getElementType();
953 uint64_t AllocaSizeBits = TD->getTypePaddedSizeInBits(AllocaEltTy);
955 // If this isn't a load of the whole alloca to an integer, it may be a load
956 // of the first element. Just ignore the load in this case and normal SROA
958 if (!isa<IntegerType>(LI->getType()) ||
959 TD->getTypePaddedSizeInBits(LI->getType()) != AllocaSizeBits)
962 DOUT << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << *LI;
964 // There are two forms here: AI could be an array or struct. Both cases
965 // have different ways to compute the element offset.
966 const StructLayout *Layout = 0;
967 uint64_t ArrayEltBitOffset = 0;
968 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
969 Layout = TD->getStructLayout(EltSTy);
971 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
972 ArrayEltBitOffset = TD->getTypePaddedSizeInBits(ArrayEltTy);
975 Value *ResultVal = Constant::getNullValue(LI->getType());
977 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
978 // Load the value from the alloca. If the NewElt is an aggregate, cast
979 // the pointer to an integer of the same size before doing the load.
980 Value *SrcField = NewElts[i];
981 const Type *FieldTy =
982 cast<PointerType>(SrcField->getType())->getElementType();
983 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
985 // Ignore zero sized fields like {}, they obviously contain no data.
986 if (FieldSizeBits == 0) continue;
988 const IntegerType *FieldIntTy = IntegerType::get(FieldSizeBits);
989 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
990 !isa<VectorType>(FieldTy))
991 SrcField = new BitCastInst(SrcField, PointerType::getUnqual(FieldIntTy),
993 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
995 // If SrcField is a fp or vector of the right size but that isn't an
996 // integer type, bitcast to an integer so we can shift it.
997 if (SrcField->getType() != FieldIntTy)
998 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1000 // Zero extend the field to be the same size as the final alloca so that
1001 // we can shift and insert it.
1002 if (SrcField->getType() != ResultVal->getType())
1003 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1005 // Determine the number of bits to shift SrcField.
1007 if (Layout) // Struct case.
1008 Shift = Layout->getElementOffsetInBits(i);
1010 Shift = i*ArrayEltBitOffset;
1012 if (TD->isBigEndian())
1013 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1016 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
1017 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1020 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1023 LI->replaceAllUsesWith(ResultVal);
1024 LI->eraseFromParent();
1028 /// HasPadding - Return true if the specified type has any structure or
1029 /// alignment padding, false otherwise.
1030 static bool HasPadding(const Type *Ty, const TargetData &TD) {
1031 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1032 const StructLayout *SL = TD.getStructLayout(STy);
1033 unsigned PrevFieldBitOffset = 0;
1034 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1035 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1037 // Padding in sub-elements?
1038 if (HasPadding(STy->getElementType(i), TD))
1041 // Check to see if there is any padding between this element and the
1044 unsigned PrevFieldEnd =
1045 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1046 if (PrevFieldEnd < FieldBitOffset)
1050 PrevFieldBitOffset = FieldBitOffset;
1053 // Check for tail padding.
1054 if (unsigned EltCount = STy->getNumElements()) {
1055 unsigned PrevFieldEnd = PrevFieldBitOffset +
1056 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
1057 if (PrevFieldEnd < SL->getSizeInBits())
1061 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1062 return HasPadding(ATy->getElementType(), TD);
1063 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1064 return HasPadding(VTy->getElementType(), TD);
1066 return TD.getTypeSizeInBits(Ty) != TD.getTypePaddedSizeInBits(Ty);
1069 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1070 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1071 /// or 1 if safe after canonicalization has been performed.
1073 int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
1074 // Loop over the use list of the alloca. We can only transform it if all of
1075 // the users are safe to transform.
1078 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
1080 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
1081 if (Info.isUnsafe) {
1082 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
1087 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1088 // source and destination, we have to be careful. In particular, the memcpy
1089 // could be moving around elements that live in structure padding of the LLVM
1090 // types, but may actually be used. In these cases, we refuse to promote the
1092 if (Info.isMemCpySrc && Info.isMemCpyDst &&
1093 HasPadding(AI->getType()->getElementType(), *TD))
1096 // If we require cleanup, return 1, otherwise return 3.
1097 return Info.needsCanon ? 1 : 3;
1100 /// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
1101 /// allocation, but only if cleaned up, perform the cleanups required.
1102 void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
1103 // At this point, we know that the end result will be SROA'd and promoted, so
1104 // we can insert ugly code if required so long as sroa+mem2reg will clean it
1106 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1108 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI++);
1109 if (!GEPI) continue;
1110 gep_type_iterator I = gep_type_begin(GEPI);
1113 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
1114 uint64_t NumElements = AT->getNumElements();
1116 if (!isa<ConstantInt>(I.getOperand())) {
1117 if (NumElements == 1) {
1118 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
1120 assert(NumElements == 2 && "Unhandled case!");
1121 // All users of the GEP must be loads. At each use of the GEP, insert
1122 // two loads of the appropriate indexed GEP and select between them.
1123 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
1124 Constant::getNullValue(I.getOperand()->getType()),
1126 // Insert the new GEP instructions, which are properly indexed.
1127 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
1128 Indices[1] = Constant::getNullValue(Type::Int32Ty);
1129 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1132 GEPI->getName()+".0", GEPI);
1133 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
1134 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1137 GEPI->getName()+".1", GEPI);
1138 // Replace all loads of the variable index GEP with loads from both
1139 // indexes and a select.
1140 while (!GEPI->use_empty()) {
1141 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1142 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1143 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
1144 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
1145 LI->replaceAllUsesWith(R);
1146 LI->eraseFromParent();
1148 GEPI->eraseFromParent();
1155 /// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1156 /// the offset specified by Offset (which is specified in bytes).
1158 /// There are two cases we handle here:
1159 /// 1) A union of vector types of the same size and potentially its elements.
1160 /// Here we turn element accesses into insert/extract element operations.
1161 /// This promotes a <4 x float> with a store of float to the third element
1162 /// into a <4 x float> that uses insert element.
1163 /// 2) A fully general blob of memory, which we turn into some (potentially
1164 /// large) integer type with extract and insert operations where the loads
1165 /// and stores would mutate the memory.
1166 static void MergeInType(const Type *In, uint64_t Offset, const Type *&Accum,
1167 const TargetData &TD) {
1168 // If this is our first type, just use it.
1169 if (Accum == 0 || In == Type::VoidTy ||
1170 // Or if this is a same type, keep it.
1171 (In == Accum && Offset == 0)) {
1176 if (const VectorType *VATy = dyn_cast<VectorType>(Accum)) {
1177 if (VATy->getElementType() == In &&
1178 Offset % TD.getTypePaddedSize(In) == 0 &&
1179 Offset < TD.getTypePaddedSize(VATy))
1180 return; // Accum is a vector, and we are accessing an element: ok.
1181 if (const VectorType *VInTy = dyn_cast<VectorType>(In))
1182 if (VInTy->getBitWidth() == VATy->getBitWidth() && Offset == 0)
1183 return; // Two vectors of the same size: keep either one of them.
1186 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1187 // In is a vector, and we are accessing an element: keep V.
1188 if (VInTy->getElementType() == Accum &&
1189 Offset % TD.getTypePaddedSize(Accum) == 0 &&
1190 Offset < TD.getTypePaddedSize(VInTy)) {
1196 // Otherwise, we have a case that we can't handle with an optimized form.
1197 // Convert the alloca to an integer that is as large as the largest store size
1198 // of the value values.
1199 uint64_t InSize = TD.getTypeStoreSizeInBits(In)+8*Offset;
1200 uint64_t ASize = TD.getTypeStoreSizeInBits(Accum);
1201 if (InSize > ASize) ASize = InSize;
1202 Accum = IntegerType::get(ASize);
1205 /// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
1206 /// its accesses to use a to single scalar type, return true, and set ResTy to
1207 /// the new type. Further, if the use is not a completely trivial use that
1208 /// mem2reg could promote, set IsNotTrivial. Offset is the current offset from
1209 /// the base of the alloca being analyzed.
1211 bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial,
1212 const Type *&ResTy, uint64_t Offset) {
1213 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1214 Instruction *User = cast<Instruction>(*UI);
1216 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1217 // Don't break volatile loads.
1218 if (LI->isVolatile())
1220 MergeInType(LI->getType(), Offset, ResTy, *TD);
1224 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1225 // Storing the pointer, not into the value?
1226 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
1227 MergeInType(SI->getOperand(0)->getType(), Offset, ResTy, *TD);
1231 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
1232 if (!CanConvertToScalar(BCI, IsNotTrivial, ResTy, Offset))
1234 IsNotTrivial = true;
1238 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1239 // If this is a GEP with a variable indices, we can't handle it.
1240 if (!GEP->hasAllConstantIndices())
1243 // Compute the offset that this GEP adds to the pointer.
1244 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1245 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1246 &Indices[0], Indices.size());
1247 // See if all uses can be converted.
1248 if (!CanConvertToScalar(GEP, IsNotTrivial, ResTy, Offset+GEPOffset))
1250 IsNotTrivial = true;
1254 // Otherwise, we cannot handle this!
1261 /// ConvertToScalar - The specified alloca passes the CanConvertToScalar
1262 /// predicate and is non-trivial. Convert it to something that can be trivially
1263 /// promoted into a register by mem2reg.
1264 void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
1265 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = " << *ActualTy << "\n";
1268 // Create and insert the alloca.
1269 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
1270 AI->getParent()->begin());
1271 ConvertUsesToScalar(AI, NewAI, 0);
1272 AI->eraseFromParent();
1276 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1277 /// directly. This happens when we are converting an "integer union" to a
1278 /// single integer scalar, or when we are converting a "vector union" to a
1279 /// vector with insert/extractelement instructions.
1281 /// Offset is an offset from the original alloca, in bits that need to be
1282 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1283 void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
1284 while (!Ptr->use_empty()) {
1285 Instruction *User = cast<Instruction>(Ptr->use_back());
1287 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1288 LI->replaceAllUsesWith(ConvertUsesOfLoadToScalar(LI, NewAI, Offset));
1289 LI->eraseFromParent();
1293 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1294 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1295 new StoreInst(ConvertUsesOfStoreToScalar(SI, NewAI, Offset), NewAI, SI);
1296 SI->eraseFromParent();
1300 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1301 ConvertUsesToScalar(CI, NewAI, Offset);
1302 CI->eraseFromParent();
1306 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1307 // Compute the offset that this GEP adds to the pointer.
1308 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1309 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1310 &Indices[0], Indices.size());
1311 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
1312 GEP->eraseFromParent();
1315 assert(0 && "Unsupported operation!");
1320 /// ConvertUsesOfLoadToScalar - Convert all of the users of the specified load
1321 /// to use the new alloca directly, returning the value that should replace the
1322 /// load. This happens when we are converting an "integer union" to a single
1323 /// integer scalar, or when we are converting a "vector union" to a vector with
1324 /// insert/extractelement instructions.
1326 /// Offset is an offset from the original alloca, in bits that need to be
1327 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1328 Value *SROA::ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
1330 // The load is a bit extract from NewAI shifted right by Offset bits.
1331 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
1333 // If the load is of the whole new alloca, no conversion is needed.
1334 if (NV->getType() == LI->getType() && Offset == 0)
1337 // If the result alloca is a vector type, this is either an element
1338 // access or a bitcast to another vector type of the same size.
1339 if (const VectorType *VTy = dyn_cast<VectorType>(NV->getType())) {
1340 if (isa<VectorType>(LI->getType()))
1341 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1343 // Otherwise it must be an element access.
1346 unsigned EltSize = TD->getTypePaddedSizeInBits(VTy->getElementType());
1347 Elt = Offset/EltSize;
1348 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
1350 // Return the element extracted out of it.
1351 return new ExtractElementInst(NV, ConstantInt::get(Type::Int32Ty, Elt),
1355 // Otherwise, this must be a union that was converted to an integer value.
1356 const IntegerType *NTy = cast<IntegerType>(NV->getType());
1358 // If this is a big-endian system and the load is narrower than the
1359 // full alloca type, we need to do a shift to get the right bits.
1361 if (TD->isBigEndian()) {
1362 // On big-endian machines, the lowest bit is stored at the bit offset
1363 // from the pointer given by getTypeStoreSizeInBits. This matters for
1364 // integers with a bitwidth that is not a multiple of 8.
1365 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
1366 TD->getTypeStoreSizeInBits(LI->getType()) - Offset;
1371 // Note: we support negative bitwidths (with shl) which are not defined.
1372 // We do this to support (f.e.) loads off the end of a structure where
1373 // only some bits are used.
1374 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
1375 NV = BinaryOperator::CreateLShr(NV,
1376 ConstantInt::get(NV->getType(), ShAmt),
1378 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
1379 NV = BinaryOperator::CreateShl(NV,
1380 ConstantInt::get(NV->getType(), -ShAmt),
1383 // Finally, unconditionally truncate the integer to the right width.
1384 unsigned LIBitWidth = TD->getTypeSizeInBits(LI->getType());
1385 if (LIBitWidth < NTy->getBitWidth())
1386 NV = new TruncInst(NV, IntegerType::get(LIBitWidth),
1389 // If the result is an integer, this is a trunc or bitcast.
1390 if (isa<IntegerType>(LI->getType())) {
1392 } else if (LI->getType()->isFloatingPoint() ||
1393 isa<VectorType>(LI->getType())) {
1394 // Just do a bitcast, we know the sizes match up.
1395 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1397 // Otherwise must be a pointer.
1398 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
1400 assert(NV->getType() == LI->getType() && "Didn't convert right?");
1405 /// ConvertUsesOfStoreToScalar - Convert the specified store to a load+store
1406 /// pair of the new alloca directly, returning the value that should be stored
1407 /// to the alloca. This happens when we are converting an "integer union" to a
1408 /// single integer scalar, or when we are converting a "vector union" to a
1409 /// vector with insert/extractelement instructions.
1411 /// Offset is an offset from the original alloca, in bits that need to be
1412 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1413 Value *SROA::ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
1416 // Convert the stored type to the actual type, shift it left to insert
1417 // then 'or' into place.
1418 Value *SV = SI->getOperand(0);
1419 const Type *AllocaType = NewAI->getType()->getElementType();
1420 if (SV->getType() == AllocaType && Offset == 0) {
1424 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
1425 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1427 // If the result alloca is a vector type, this is either an element
1428 // access or a bitcast to another vector type.
1429 if (isa<VectorType>(SV->getType())) {
1430 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1432 // Must be an element insertion.
1433 unsigned Elt = Offset/TD->getTypePaddedSizeInBits(VTy->getElementType());
1434 SV = InsertElementInst::Create(Old, SV,
1435 ConstantInt::get(Type::Int32Ty, Elt),
1442 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1444 // If SV is a float, convert it to the appropriate integer type.
1445 // If it is a pointer, do the same, and also handle ptr->ptr casts
1447 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1448 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1449 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1450 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1451 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
1452 SV = new BitCastInst(SV, IntegerType::get(SrcWidth), SV->getName(), SI);
1453 else if (isa<PointerType>(SV->getType()))
1454 SV = new PtrToIntInst(SV, TD->getIntPtrType(), SV->getName(), SI);
1456 // Always zero extend the value if needed.
1457 if (SV->getType() != AllocaType)
1458 SV = new ZExtInst(SV, AllocaType, SV->getName(), SI);
1460 // If this is a big-endian system and the store is narrower than the
1461 // full alloca type, we need to do a shift to get the right bits.
1463 if (TD->isBigEndian()) {
1464 // On big-endian machines, the lowest bit is stored at the bit offset
1465 // from the pointer given by getTypeStoreSizeInBits. This matters for
1466 // integers with a bitwidth that is not a multiple of 8.
1467 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1472 // Note: we support negative bitwidths (with shr) which are not defined.
1473 // We do this to support (f.e.) stores off the end of a structure where
1474 // only some bits in the structure are set.
1475 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1476 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1477 SV = BinaryOperator::CreateShl(SV,
1478 ConstantInt::get(SV->getType(), ShAmt),
1481 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1482 SV = BinaryOperator::CreateLShr(SV,
1483 ConstantInt::get(SV->getType(),-ShAmt),
1485 Mask = Mask.lshr(-ShAmt);
1488 // Mask out the bits we are about to insert from the old value, and or
1490 if (SrcWidth != DestWidth) {
1491 assert(DestWidth > SrcWidth);
1492 Old = BinaryOperator::CreateAnd(Old, ConstantInt::get(~Mask),
1493 Old->getName()+".mask", SI);
1494 SV = BinaryOperator::CreateOr(Old, SV, SV->getName()+".ins", SI);
1501 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1502 /// some part of a constant global variable. This intentionally only accepts
1503 /// constant expressions because we don't can't rewrite arbitrary instructions.
1504 static bool PointsToConstantGlobal(Value *V) {
1505 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1506 return GV->isConstant();
1507 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1508 if (CE->getOpcode() == Instruction::BitCast ||
1509 CE->getOpcode() == Instruction::GetElementPtr)
1510 return PointsToConstantGlobal(CE->getOperand(0));
1514 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1515 /// pointer to an alloca. Ignore any reads of the pointer, return false if we
1516 /// see any stores or other unknown uses. If we see pointer arithmetic, keep
1517 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
1518 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1519 /// the alloca, and if the source pointer is a pointer to a constant global, we
1520 /// can optimize this.
1521 static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1523 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1524 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1525 // Ignore non-volatile loads, they are always ok.
1526 if (!LI->isVolatile())
1529 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1530 // If uses of the bitcast are ok, we are ok.
1531 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1535 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1536 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1537 // doesn't, it does.
1538 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1539 isOffset || !GEP->hasAllZeroIndices()))
1544 // If this is isn't our memcpy/memmove, reject it as something we can't
1546 if (!isa<MemCpyInst>(*UI) && !isa<MemMoveInst>(*UI))
1549 // If we already have seen a copy, reject the second one.
1550 if (TheCopy) return false;
1552 // If the pointer has been offset from the start of the alloca, we can't
1553 // safely handle this.
1554 if (isOffset) return false;
1556 // If the memintrinsic isn't using the alloca as the dest, reject it.
1557 if (UI.getOperandNo() != 1) return false;
1559 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1561 // If the source of the memcpy/move is not a constant global, reject it.
1562 if (!PointsToConstantGlobal(MI->getOperand(2)))
1565 // Otherwise, the transform is safe. Remember the copy instruction.
1571 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1572 /// modified by a copy from a constant global. If we can prove this, we can
1573 /// replace any uses of the alloca with uses of the global directly.
1574 Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1575 Instruction *TheCopy = 0;
1576 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))