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/LLVMContext.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Analysis/Dominators.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
35 #include "llvm/Transforms/Utils/Local.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/GetElementPtrTypeIterator.h"
39 #include "llvm/Support/IRBuilder.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/ADT/Statistic.h"
46 STATISTIC(NumReplaced, "Number of allocas broken up");
47 STATISTIC(NumPromoted, "Number of allocas promoted");
48 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
49 STATISTIC(NumGlobals, "Number of allocas copied from constant global");
52 struct SROA : public FunctionPass {
53 static char ID; // Pass identification, replacement for typeid
54 explicit SROA(signed T = -1) : FunctionPass(&ID) {
61 bool runOnFunction(Function &F);
63 bool performScalarRepl(Function &F);
64 bool performPromotion(Function &F);
66 // getAnalysisUsage - This pass does not require any passes, but we know it
67 // will not alter the CFG, so say so.
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69 AU.addRequired<DominatorTree>();
70 AU.addRequired<DominanceFrontier>();
77 /// DeadInsts - Keep track of instructions we have made dead, so that
78 /// we can remove them after we are done working.
79 SmallVector<Value*, 32> DeadInsts;
81 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
82 /// information about the uses. All these fields are initialized to false
83 /// and set to true when something is learned.
85 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
88 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
91 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
95 : isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false) {}
100 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
102 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
104 void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
106 void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
108 void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
109 const Type *MemOpType, bool isStore, AllocaInfo &Info);
110 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
111 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
114 void DoScalarReplacement(AllocaInst *AI,
115 std::vector<AllocaInst*> &WorkList);
116 void DeleteDeadInstructions();
117 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocaInst *Base);
119 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
120 SmallVector<AllocaInst*, 32> &NewElts);
121 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
122 SmallVector<AllocaInst*, 32> &NewElts);
123 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
124 SmallVector<AllocaInst*, 32> &NewElts);
125 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
127 SmallVector<AllocaInst*, 32> &NewElts);
128 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
129 SmallVector<AllocaInst*, 32> &NewElts);
130 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
131 SmallVector<AllocaInst*, 32> &NewElts);
133 bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
134 bool &SawVec, uint64_t Offset, unsigned AllocaSize);
135 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
136 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
137 uint64_t Offset, IRBuilder<> &Builder);
138 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
139 uint64_t Offset, IRBuilder<> &Builder);
140 static Instruction *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
145 static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
147 // Public interface to the ScalarReplAggregates pass
148 FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
149 return new SROA(Threshold);
153 bool SROA::runOnFunction(Function &F) {
154 TD = getAnalysisIfAvailable<TargetData>();
156 bool Changed = performPromotion(F);
158 // FIXME: ScalarRepl currently depends on TargetData more than it
159 // theoretically needs to. It should be refactored in order to support
160 // target-independent IR. Until this is done, just skip the actual
161 // scalar-replacement portion of this pass.
162 if (!TD) return Changed;
165 bool LocalChange = performScalarRepl(F);
166 if (!LocalChange) break; // No need to repromote if no scalarrepl
168 LocalChange = performPromotion(F);
169 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
176 bool SROA::performPromotion(Function &F) {
177 std::vector<AllocaInst*> Allocas;
178 DominatorTree &DT = getAnalysis<DominatorTree>();
179 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
181 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
183 bool Changed = false;
188 // Find allocas that are safe to promote, by looking at all instructions in
190 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
191 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
192 if (isAllocaPromotable(AI))
193 Allocas.push_back(AI);
195 if (Allocas.empty()) break;
197 PromoteMemToReg(Allocas, DT, DF);
198 NumPromoted += Allocas.size();
205 /// getNumSAElements - Return the number of elements in the specific struct or
207 static uint64_t getNumSAElements(const Type *T) {
208 if (const StructType *ST = dyn_cast<StructType>(T))
209 return ST->getNumElements();
210 return cast<ArrayType>(T)->getNumElements();
213 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
214 // which runs on all of the malloc/alloca instructions in the function, removing
215 // them if they are only used by getelementptr instructions.
217 bool SROA::performScalarRepl(Function &F) {
218 std::vector<AllocaInst*> WorkList;
220 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
221 BasicBlock &BB = F.getEntryBlock();
222 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
223 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
224 WorkList.push_back(A);
226 // Process the worklist
227 bool Changed = false;
228 while (!WorkList.empty()) {
229 AllocaInst *AI = WorkList.back();
232 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
233 // with unused elements.
234 if (AI->use_empty()) {
235 AI->eraseFromParent();
239 // If this alloca is impossible for us to promote, reject it early.
240 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
243 // Check to see if this allocation is only modified by a memcpy/memmove from
244 // a constant global. If this is the case, we can change all users to use
245 // the constant global instead. This is commonly produced by the CFE by
246 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
247 // is only subsequently read.
248 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
249 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
250 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
251 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
252 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
253 TheCopy->eraseFromParent(); // Don't mutate the global.
254 AI->eraseFromParent();
260 // Check to see if we can perform the core SROA transformation. We cannot
261 // transform the allocation instruction if it is an array allocation
262 // (allocations OF arrays are ok though), and an allocation of a scalar
263 // value cannot be decomposed at all.
264 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
266 // Do not promote [0 x %struct].
267 if (AllocaSize == 0) continue;
269 // Do not promote any struct whose size is too big.
270 if (AllocaSize > SRThreshold) continue;
272 if ((isa<StructType>(AI->getAllocatedType()) ||
273 isa<ArrayType>(AI->getAllocatedType())) &&
274 // Do not promote any struct into more than "32" separate vars.
275 getNumSAElements(AI->getAllocatedType()) <= SRThreshold/4) {
276 // Check that all of the users of the allocation are capable of being
278 if (isSafeAllocaToScalarRepl(AI)) {
279 DoScalarReplacement(AI, WorkList);
285 // If we can turn this aggregate value (potentially with casts) into a
286 // simple scalar value that can be mem2reg'd into a register value.
287 // IsNotTrivial tracks whether this is something that mem2reg could have
288 // promoted itself. If so, we don't want to transform it needlessly. Note
289 // that we can't just check based on the type: the alloca may be of an i32
290 // but that has pointer arithmetic to set byte 3 of it or something.
291 bool IsNotTrivial = false;
292 const Type *VectorTy = 0;
293 bool HadAVector = false;
294 if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector,
295 0, unsigned(AllocaSize)) && IsNotTrivial) {
297 // If we were able to find a vector type that can handle this with
298 // insert/extract elements, and if there was at least one use that had
299 // a vector type, promote this to a vector. We don't want to promote
300 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
301 // we just get a lot of insert/extracts. If at least one vector is
302 // involved, then we probably really do have a union of vector/array.
303 if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
304 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
305 << *VectorTy << '\n');
307 // Create and insert the vector alloca.
308 NewAI = new AllocaInst(VectorTy, 0, "", AI->getParent()->begin());
309 ConvertUsesToScalar(AI, NewAI, 0);
311 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
313 // Create and insert the integer alloca.
314 const Type *NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
315 NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
316 ConvertUsesToScalar(AI, NewAI, 0);
319 AI->eraseFromParent();
325 // Otherwise, couldn't process this alloca.
331 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
332 /// predicate, do SROA now.
333 void SROA::DoScalarReplacement(AllocaInst *AI,
334 std::vector<AllocaInst*> &WorkList) {
335 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
336 SmallVector<AllocaInst*, 32> ElementAllocas;
337 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
338 ElementAllocas.reserve(ST->getNumContainedTypes());
339 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
340 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
342 AI->getName() + "." + Twine(i), AI);
343 ElementAllocas.push_back(NA);
344 WorkList.push_back(NA); // Add to worklist for recursive processing
347 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
348 ElementAllocas.reserve(AT->getNumElements());
349 const Type *ElTy = AT->getElementType();
350 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
351 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
352 AI->getName() + "." + Twine(i), AI);
353 ElementAllocas.push_back(NA);
354 WorkList.push_back(NA); // Add to worklist for recursive processing
358 // Now that we have created the new alloca instructions, rewrite all the
359 // uses of the old alloca.
360 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
362 // Now erase any instructions that were made dead while rewriting the alloca.
363 DeleteDeadInstructions();
364 AI->eraseFromParent();
369 /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
370 /// recursively including all their operands that become trivially dead.
371 void SROA::DeleteDeadInstructions() {
372 while (!DeadInsts.empty()) {
373 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
375 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
376 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
377 // Zero out the operand and see if it becomes trivially dead.
378 // (But, don't add allocas to the dead instruction list -- they are
379 // already on the worklist and will be deleted separately.)
381 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
382 DeadInsts.push_back(U);
385 I->eraseFromParent();
389 /// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
390 /// performing scalar replacement of alloca AI. The results are flagged in
391 /// the Info parameter. Offset indicates the position within AI that is
392 /// referenced by this instruction.
393 void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
395 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
396 Instruction *User = cast<Instruction>(*UI);
398 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
399 isSafeForScalarRepl(BC, AI, Offset, Info);
400 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
401 uint64_t GEPOffset = Offset;
402 isSafeGEP(GEPI, AI, GEPOffset, Info);
404 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
405 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
406 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
408 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
409 UI.getOperandNo() == 1, Info);
412 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
413 if (!LI->isVolatile()) {
414 const Type *LIType = LI->getType();
415 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
416 LIType, false, Info);
419 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
420 // Store is ok if storing INTO the pointer, not storing the pointer
421 if (!SI->isVolatile() && SI->getOperand(0) != I) {
422 const Type *SIType = SI->getOperand(0)->getType();
423 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
428 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
431 if (Info.isUnsafe) return;
435 /// isSafeGEP - Check if a GEP instruction can be handled for scalar
436 /// replacement. It is safe when all the indices are constant, in-bounds
437 /// references, and when the resulting offset corresponds to an element within
438 /// the alloca type. The results are flagged in the Info parameter. Upon
439 /// return, Offset is adjusted as specified by the GEP indices.
440 void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
441 uint64_t &Offset, AllocaInfo &Info) {
442 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
446 // Walk through the GEP type indices, checking the types that this indexes
448 for (; GEPIt != E; ++GEPIt) {
449 // Ignore struct elements, no extra checking needed for these.
450 if (isa<StructType>(*GEPIt))
453 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
455 return MarkUnsafe(Info);
458 // Compute the offset due to this GEP and check if the alloca has a
459 // component element at that offset.
460 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
461 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
462 &Indices[0], Indices.size());
463 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
467 /// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
468 /// alloca or has an offset and size that corresponds to a component element
469 /// within it. The offset checked here may have been formed from a GEP with a
470 /// pointer bitcasted to a different type.
471 void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
472 const Type *MemOpType, bool isStore,
474 // Check if this is a load/store of the entire alloca.
475 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
476 bool UsesAggregateType = (MemOpType == AI->getAllocatedType());
477 // This is safe for MemIntrinsics (where MemOpType is 0), integer types
478 // (which are essentially the same as the MemIntrinsics, especially with
479 // regard to copying padding between elements), or references using the
480 // aggregate type of the alloca.
481 if (!MemOpType || isa<IntegerType>(MemOpType) || UsesAggregateType) {
482 if (!UsesAggregateType) {
484 Info.isMemCpyDst = true;
486 Info.isMemCpySrc = true;
491 // Check if the offset/size correspond to a component within the alloca type.
492 const Type *T = AI->getAllocatedType();
493 if (TypeHasComponent(T, Offset, MemSize))
496 return MarkUnsafe(Info);
499 /// TypeHasComponent - Return true if T has a component type with the
500 /// specified offset and size. If Size is zero, do not check the size.
501 bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
504 if (const StructType *ST = dyn_cast<StructType>(T)) {
505 const StructLayout *Layout = TD->getStructLayout(ST);
506 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
507 EltTy = ST->getContainedType(EltIdx);
508 EltSize = TD->getTypeAllocSize(EltTy);
509 Offset -= Layout->getElementOffset(EltIdx);
510 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
511 EltTy = AT->getElementType();
512 EltSize = TD->getTypeAllocSize(EltTy);
513 if (Offset >= AT->getNumElements() * EltSize)
519 if (Offset == 0 && (Size == 0 || EltSize == Size))
521 // Check if the component spans multiple elements.
522 if (Offset + Size > EltSize)
524 return TypeHasComponent(EltTy, Offset, Size);
527 /// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
528 /// the instruction I, which references it, to use the separate elements.
529 /// Offset indicates the position within AI that is referenced by this
531 void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
532 SmallVector<AllocaInst*, 32> &NewElts) {
533 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
534 Instruction *User = cast<Instruction>(*UI);
536 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
537 RewriteBitCast(BC, AI, Offset, NewElts);
538 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
539 RewriteGEP(GEPI, AI, Offset, NewElts);
540 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
541 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
542 uint64_t MemSize = Length->getZExtValue();
544 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
545 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
546 // Otherwise the intrinsic can only touch a single element and the
547 // address operand will be updated, so nothing else needs to be done.
548 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
549 const Type *LIType = LI->getType();
550 if (LIType == AI->getAllocatedType()) {
552 // %res = load { i32, i32 }* %alloc
554 // %load.0 = load i32* %alloc.0
555 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
556 // %load.1 = load i32* %alloc.1
557 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
558 // (Also works for arrays instead of structs)
559 Value *Insert = UndefValue::get(LIType);
560 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
561 Value *Load = new LoadInst(NewElts[i], "load", LI);
562 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
564 LI->replaceAllUsesWith(Insert);
565 DeadInsts.push_back(LI);
566 } else if (isa<IntegerType>(LIType) &&
567 TD->getTypeAllocSize(LIType) ==
568 TD->getTypeAllocSize(AI->getAllocatedType())) {
569 // If this is a load of the entire alloca to an integer, rewrite it.
570 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
572 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
573 Value *Val = SI->getOperand(0);
574 const Type *SIType = Val->getType();
575 if (SIType == AI->getAllocatedType()) {
577 // store { i32, i32 } %val, { i32, i32 }* %alloc
579 // %val.0 = extractvalue { i32, i32 } %val, 0
580 // store i32 %val.0, i32* %alloc.0
581 // %val.1 = extractvalue { i32, i32 } %val, 1
582 // store i32 %val.1, i32* %alloc.1
583 // (Also works for arrays instead of structs)
584 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
585 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
586 new StoreInst(Extract, NewElts[i], SI);
588 DeadInsts.push_back(SI);
589 } else if (isa<IntegerType>(SIType) &&
590 TD->getTypeAllocSize(SIType) ==
591 TD->getTypeAllocSize(AI->getAllocatedType())) {
592 // If this is a store of the entire alloca from an integer, rewrite it.
593 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
599 /// RewriteBitCast - Update a bitcast reference to the alloca being replaced
600 /// and recursively continue updating all of its uses.
601 void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
602 SmallVector<AllocaInst*, 32> &NewElts) {
603 RewriteForScalarRepl(BC, AI, Offset, NewElts);
604 if (BC->getOperand(0) != AI)
607 // The bitcast references the original alloca. Replace its uses with
608 // references to the first new element alloca.
609 Instruction *Val = NewElts[0];
610 if (Val->getType() != BC->getDestTy()) {
611 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
614 BC->replaceAllUsesWith(Val);
615 DeadInsts.push_back(BC);
618 /// FindElementAndOffset - Return the index of the element containing Offset
619 /// within the specified type, which must be either a struct or an array.
620 /// Sets T to the type of the element and Offset to the offset within that
621 /// element. IdxTy is set to the type of the index result to be used in a
623 uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
624 const Type *&IdxTy) {
626 if (const StructType *ST = dyn_cast<StructType>(T)) {
627 const StructLayout *Layout = TD->getStructLayout(ST);
628 Idx = Layout->getElementContainingOffset(Offset);
629 T = ST->getContainedType(Idx);
630 Offset -= Layout->getElementOffset(Idx);
631 IdxTy = Type::getInt32Ty(T->getContext());
634 const ArrayType *AT = cast<ArrayType>(T);
635 T = AT->getElementType();
636 uint64_t EltSize = TD->getTypeAllocSize(T);
637 Idx = Offset / EltSize;
638 Offset -= Idx * EltSize;
639 IdxTy = Type::getInt64Ty(T->getContext());
643 /// RewriteGEP - Check if this GEP instruction moves the pointer across
644 /// elements of the alloca that are being split apart, and if so, rewrite
645 /// the GEP to be relative to the new element.
646 void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
647 SmallVector<AllocaInst*, 32> &NewElts) {
648 uint64_t OldOffset = Offset;
649 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
650 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
651 &Indices[0], Indices.size());
653 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
655 const Type *T = AI->getAllocatedType();
657 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
658 if (GEPI->getOperand(0) == AI)
659 OldIdx = ~0ULL; // Force the GEP to be rewritten.
661 T = AI->getAllocatedType();
662 uint64_t EltOffset = Offset;
663 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
665 // If this GEP does not move the pointer across elements of the alloca
666 // being split, then it does not needs to be rewritten.
670 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
671 SmallVector<Value*, 8> NewArgs;
672 NewArgs.push_back(Constant::getNullValue(i32Ty));
673 while (EltOffset != 0) {
674 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
675 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
677 Instruction *Val = NewElts[Idx];
678 if (NewArgs.size() > 1) {
679 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
680 NewArgs.end(), "", GEPI);
683 if (Val->getType() != GEPI->getType())
684 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
685 GEPI->replaceAllUsesWith(Val);
686 DeadInsts.push_back(GEPI);
689 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
690 /// Rewrite it to copy or set the elements of the scalarized memory.
691 void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
693 SmallVector<AllocaInst*, 32> &NewElts) {
694 // If this is a memcpy/memmove, construct the other pointer as the
695 // appropriate type. The "Other" pointer is the pointer that goes to memory
696 // that doesn't have anything to do with the alloca that we are promoting. For
697 // memset, this Value* stays null.
699 LLVMContext &Context = MI->getContext();
700 unsigned MemAlignment = MI->getAlignment();
701 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
702 if (Inst == MTI->getRawDest())
703 OtherPtr = MTI->getRawSource();
705 assert(Inst == MTI->getRawSource());
706 OtherPtr = MTI->getRawDest();
710 // If there is an other pointer, we want to convert it to the same pointer
711 // type as AI has, so we can GEP through it safely.
714 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
715 // optimization, but it's also required to detect the corner case where
716 // both pointer operands are referencing the same memory, and where
717 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
718 // function is only called for mem intrinsics that access the whole
719 // aggregate, so non-zero GEPs are not an issue here.)
721 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr)) {
722 OtherPtr = BC->getOperand(0);
725 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr)) {
726 // All zero GEPs are effectively bitcasts.
727 if (GEP->hasAllZeroIndices()) {
728 OtherPtr = GEP->getOperand(0);
734 // Copying the alloca to itself is a no-op: just delete it.
735 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
736 // This code will run twice for a no-op memcpy -- once for each operand.
737 // Put only one reference to MI on the DeadInsts list.
738 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
739 E = DeadInsts.end(); I != E; ++I)
740 if (*I == MI) return;
741 DeadInsts.push_back(MI);
745 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
746 if (BCE->getOpcode() == Instruction::BitCast)
747 OtherPtr = BCE->getOperand(0);
749 // If the pointer is not the right type, insert a bitcast to the right
751 if (OtherPtr->getType() != AI->getType())
752 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
756 // Process each element of the aggregate.
757 Value *TheFn = MI->getOperand(0);
758 const Type *BytePtrTy = MI->getRawDest()->getType();
759 bool SROADest = MI->getRawDest() == Inst;
761 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
763 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
764 // If this is a memcpy/memmove, emit a GEP of the other element address.
766 unsigned OtherEltAlign = MemAlignment;
769 Value *Idx[2] = { Zero,
770 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
771 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
772 OtherPtr->getName()+"."+Twine(i),
775 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
776 if (const StructType *ST =
777 dyn_cast<StructType>(OtherPtrTy->getElementType())) {
778 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
781 cast<SequentialType>(OtherPtr->getType())->getElementType();
782 EltOffset = TD->getTypeAllocSize(EltTy)*i;
785 // The alignment of the other pointer is the guaranteed alignment of the
786 // element, which is affected by both the known alignment of the whole
787 // mem intrinsic and the alignment of the element. If the alignment of
788 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
789 // known alignment is just 4 bytes.
790 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
793 Value *EltPtr = NewElts[i];
794 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
796 // If we got down to a scalar, insert a load or store as appropriate.
797 if (EltTy->isSingleValueType()) {
798 if (isa<MemTransferInst>(MI)) {
800 // From Other to Alloca.
801 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
802 new StoreInst(Elt, EltPtr, MI);
804 // From Alloca to Other.
805 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
806 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
810 assert(isa<MemSetInst>(MI));
812 // If the stored element is zero (common case), just store a null
815 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
817 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
819 // If EltTy is a vector type, get the element type.
820 const Type *ValTy = EltTy->getScalarType();
822 // Construct an integer with the right value.
823 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
824 APInt OneVal(EltSize, CI->getZExtValue());
825 APInt TotalVal(OneVal);
827 for (unsigned i = 0; 8*i < EltSize; ++i) {
828 TotalVal = TotalVal.shl(8);
832 // Convert the integer value to the appropriate type.
833 StoreVal = ConstantInt::get(Context, TotalVal);
834 if (isa<PointerType>(ValTy))
835 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
836 else if (ValTy->isFloatingPoint())
837 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
838 assert(StoreVal->getType() == ValTy && "Type mismatch!");
840 // If the requested value was a vector constant, create it.
841 if (EltTy != ValTy) {
842 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
843 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
844 StoreVal = ConstantVector::get(&Elts[0], NumElts);
847 new StoreInst(StoreVal, EltPtr, MI);
850 // Otherwise, if we're storing a byte variable, use a memset call for
854 // Cast the element pointer to BytePtrTy.
855 if (EltPtr->getType() != BytePtrTy)
856 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getName(), MI);
858 // Cast the other pointer (if we have one) to BytePtrTy.
859 if (OtherElt && OtherElt->getType() != BytePtrTy)
860 OtherElt = new BitCastInst(OtherElt, BytePtrTy, OtherElt->getName(), MI);
862 unsigned EltSize = TD->getTypeAllocSize(EltTy);
864 // Finally, insert the meminst for this element.
865 if (isa<MemTransferInst>(MI)) {
867 SROADest ? EltPtr : OtherElt, // Dest ptr
868 SROADest ? OtherElt : EltPtr, // Src ptr
869 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
871 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign)
873 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
875 assert(isa<MemSetInst>(MI));
877 EltPtr, MI->getOperand(2), // Dest, Value,
878 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
881 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
884 DeadInsts.push_back(MI);
887 /// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
888 /// overwrites the entire allocation. Extract out the pieces of the stored
889 /// integer and store them individually.
890 void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
891 SmallVector<AllocaInst*, 32> &NewElts){
892 // Extract each element out of the integer according to its structure offset
893 // and store the element value to the individual alloca.
894 Value *SrcVal = SI->getOperand(0);
895 const Type *AllocaEltTy = AI->getAllocatedType();
896 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
898 // Handle tail padding by extending the operand
899 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
900 SrcVal = new ZExtInst(SrcVal,
901 IntegerType::get(SI->getContext(), AllocaSizeBits),
904 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
907 // There are two forms here: AI could be an array or struct. Both cases
908 // have different ways to compute the element offset.
909 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
910 const StructLayout *Layout = TD->getStructLayout(EltSTy);
912 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
913 // Get the number of bits to shift SrcVal to get the value.
914 const Type *FieldTy = EltSTy->getElementType(i);
915 uint64_t Shift = Layout->getElementOffsetInBits(i);
917 if (TD->isBigEndian())
918 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
920 Value *EltVal = SrcVal;
922 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
923 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
924 "sroa.store.elt", SI);
927 // Truncate down to an integer of the right size.
928 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
930 // Ignore zero sized fields like {}, they obviously contain no data.
931 if (FieldSizeBits == 0) continue;
933 if (FieldSizeBits != AllocaSizeBits)
934 EltVal = new TruncInst(EltVal,
935 IntegerType::get(SI->getContext(), FieldSizeBits),
937 Value *DestField = NewElts[i];
938 if (EltVal->getType() == FieldTy) {
939 // Storing to an integer field of this size, just do it.
940 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
941 // Bitcast to the right element type (for fp/vector values).
942 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
944 // Otherwise, bitcast the dest pointer (for aggregates).
945 DestField = new BitCastInst(DestField,
946 PointerType::getUnqual(EltVal->getType()),
949 new StoreInst(EltVal, DestField, SI);
953 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
954 const Type *ArrayEltTy = ATy->getElementType();
955 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
956 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
960 if (TD->isBigEndian())
961 Shift = AllocaSizeBits-ElementOffset;
965 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
966 // Ignore zero sized fields like {}, they obviously contain no data.
967 if (ElementSizeBits == 0) continue;
969 Value *EltVal = SrcVal;
971 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
972 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
973 "sroa.store.elt", SI);
976 // Truncate down to an integer of the right size.
977 if (ElementSizeBits != AllocaSizeBits)
978 EltVal = new TruncInst(EltVal,
979 IntegerType::get(SI->getContext(),
980 ElementSizeBits),"",SI);
981 Value *DestField = NewElts[i];
982 if (EltVal->getType() == ArrayEltTy) {
983 // Storing to an integer field of this size, just do it.
984 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
985 // Bitcast to the right element type (for fp/vector values).
986 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
988 // Otherwise, bitcast the dest pointer (for aggregates).
989 DestField = new BitCastInst(DestField,
990 PointerType::getUnqual(EltVal->getType()),
993 new StoreInst(EltVal, DestField, SI);
995 if (TD->isBigEndian())
996 Shift -= ElementOffset;
998 Shift += ElementOffset;
1002 DeadInsts.push_back(SI);
1005 /// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
1006 /// an integer. Load the individual pieces to form the aggregate value.
1007 void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
1008 SmallVector<AllocaInst*, 32> &NewElts) {
1009 // Extract each element out of the NewElts according to its structure offset
1010 // and form the result value.
1011 const Type *AllocaEltTy = AI->getAllocatedType();
1012 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
1014 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
1017 // There are two forms here: AI could be an array or struct. Both cases
1018 // have different ways to compute the element offset.
1019 const StructLayout *Layout = 0;
1020 uint64_t ArrayEltBitOffset = 0;
1021 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1022 Layout = TD->getStructLayout(EltSTy);
1024 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
1025 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
1029 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
1031 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1032 // Load the value from the alloca. If the NewElt is an aggregate, cast
1033 // the pointer to an integer of the same size before doing the load.
1034 Value *SrcField = NewElts[i];
1035 const Type *FieldTy =
1036 cast<PointerType>(SrcField->getType())->getElementType();
1037 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1039 // Ignore zero sized fields like {}, they obviously contain no data.
1040 if (FieldSizeBits == 0) continue;
1042 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1044 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
1045 !isa<VectorType>(FieldTy))
1046 SrcField = new BitCastInst(SrcField,
1047 PointerType::getUnqual(FieldIntTy),
1049 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1051 // If SrcField is a fp or vector of the right size but that isn't an
1052 // integer type, bitcast to an integer so we can shift it.
1053 if (SrcField->getType() != FieldIntTy)
1054 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1056 // Zero extend the field to be the same size as the final alloca so that
1057 // we can shift and insert it.
1058 if (SrcField->getType() != ResultVal->getType())
1059 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1061 // Determine the number of bits to shift SrcField.
1063 if (Layout) // Struct case.
1064 Shift = Layout->getElementOffsetInBits(i);
1066 Shift = i*ArrayEltBitOffset;
1068 if (TD->isBigEndian())
1069 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1072 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
1073 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1076 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1079 // Handle tail padding by truncating the result
1080 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1081 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1083 LI->replaceAllUsesWith(ResultVal);
1084 DeadInsts.push_back(LI);
1087 /// HasPadding - Return true if the specified type has any structure or
1088 /// alignment padding, false otherwise.
1089 static bool HasPadding(const Type *Ty, const TargetData &TD) {
1090 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1091 const StructLayout *SL = TD.getStructLayout(STy);
1092 unsigned PrevFieldBitOffset = 0;
1093 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1094 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1096 // Padding in sub-elements?
1097 if (HasPadding(STy->getElementType(i), TD))
1100 // Check to see if there is any padding between this element and the
1103 unsigned PrevFieldEnd =
1104 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1105 if (PrevFieldEnd < FieldBitOffset)
1109 PrevFieldBitOffset = FieldBitOffset;
1112 // Check for tail padding.
1113 if (unsigned EltCount = STy->getNumElements()) {
1114 unsigned PrevFieldEnd = PrevFieldBitOffset +
1115 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
1116 if (PrevFieldEnd < SL->getSizeInBits())
1120 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1121 return HasPadding(ATy->getElementType(), TD);
1122 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1123 return HasPadding(VTy->getElementType(), TD);
1125 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
1128 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1129 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1130 /// or 1 if safe after canonicalization has been performed.
1131 bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
1132 // Loop over the use list of the alloca. We can only transform it if all of
1133 // the users are safe to transform.
1136 isSafeForScalarRepl(AI, AI, 0, Info);
1137 if (Info.isUnsafe) {
1138 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
1142 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1143 // source and destination, we have to be careful. In particular, the memcpy
1144 // could be moving around elements that live in structure padding of the LLVM
1145 // types, but may actually be used. In these cases, we refuse to promote the
1147 if (Info.isMemCpySrc && Info.isMemCpyDst &&
1148 HasPadding(AI->getAllocatedType(), *TD))
1154 /// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1155 /// the offset specified by Offset (which is specified in bytes).
1157 /// There are two cases we handle here:
1158 /// 1) A union of vector types of the same size and potentially its elements.
1159 /// Here we turn element accesses into insert/extract element operations.
1160 /// This promotes a <4 x float> with a store of float to the third element
1161 /// into a <4 x float> that uses insert element.
1162 /// 2) A fully general blob of memory, which we turn into some (potentially
1163 /// large) integer type with extract and insert operations where the loads
1164 /// and stores would mutate the memory.
1165 static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
1166 unsigned AllocaSize, const TargetData &TD,
1167 LLVMContext &Context) {
1168 // If this could be contributing to a vector, analyze it.
1169 if (VecTy != Type::getVoidTy(Context)) { // either null or a vector type.
1171 // If the In type is a vector that is the same size as the alloca, see if it
1172 // matches the existing VecTy.
1173 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1174 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1175 // If we're storing/loading a vector of the right size, allow it as a
1176 // vector. If this the first vector we see, remember the type so that
1177 // we know the element size.
1182 } else if (In->isFloatTy() || In->isDoubleTy() ||
1183 (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1184 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1185 // If we're accessing something that could be an element of a vector, see
1186 // if the implied vector agrees with what we already have and if Offset is
1187 // compatible with it.
1188 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1189 if (Offset % EltSize == 0 &&
1190 AllocaSize % EltSize == 0 &&
1192 cast<VectorType>(VecTy)->getElementType()
1193 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1195 VecTy = VectorType::get(In, AllocaSize/EltSize);
1201 // Otherwise, we have a case that we can't handle with an optimized vector
1202 // form. We can still turn this into a large integer.
1203 VecTy = Type::getVoidTy(Context);
1206 /// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
1207 /// its accesses to a single vector type, return true and set VecTy to
1208 /// the new type. If we could convert the alloca into a single promotable
1209 /// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1210 /// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1211 /// is the current offset from the base of the alloca being analyzed.
1213 /// If we see at least one access to the value that is as a vector type, set the
1215 bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1216 bool &SawVec, uint64_t Offset,
1217 unsigned AllocaSize) {
1218 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1219 Instruction *User = cast<Instruction>(*UI);
1221 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1222 // Don't break volatile loads.
1223 if (LI->isVolatile())
1225 MergeInType(LI->getType(), Offset, VecTy,
1226 AllocaSize, *TD, V->getContext());
1227 SawVec |= isa<VectorType>(LI->getType());
1231 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1232 // Storing the pointer, not into the value?
1233 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
1234 MergeInType(SI->getOperand(0)->getType(), Offset,
1235 VecTy, AllocaSize, *TD, V->getContext());
1236 SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
1240 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
1241 if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1244 IsNotTrivial = true;
1248 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1249 // If this is a GEP with a variable indices, we can't handle it.
1250 if (!GEP->hasAllConstantIndices())
1253 // Compute the offset that this GEP adds to the pointer.
1254 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1255 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getPointerOperandType(),
1256 &Indices[0], Indices.size());
1257 // See if all uses can be converted.
1258 if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
1261 IsNotTrivial = true;
1265 // If this is a constant sized memset of a constant value (e.g. 0) we can
1267 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1268 // Store of constant value and constant size.
1269 if (isa<ConstantInt>(MSI->getValue()) &&
1270 isa<ConstantInt>(MSI->getLength())) {
1271 IsNotTrivial = true;
1276 // If this is a memcpy or memmove into or out of the whole allocation, we
1277 // can handle it like a load or store of the scalar type.
1278 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1279 if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
1280 if (Len->getZExtValue() == AllocaSize && Offset == 0) {
1281 IsNotTrivial = true;
1286 // Otherwise, we cannot handle this!
1293 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1294 /// directly. This happens when we are converting an "integer union" to a
1295 /// single integer scalar, or when we are converting a "vector union" to a
1296 /// vector with insert/extractelement instructions.
1298 /// Offset is an offset from the original alloca, in bits that need to be
1299 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1300 void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
1301 while (!Ptr->use_empty()) {
1302 Instruction *User = cast<Instruction>(Ptr->use_back());
1304 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1305 ConvertUsesToScalar(CI, NewAI, Offset);
1306 CI->eraseFromParent();
1310 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1311 // Compute the offset that this GEP adds to the pointer.
1312 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1313 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getPointerOperandType(),
1314 &Indices[0], Indices.size());
1315 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
1316 GEP->eraseFromParent();
1320 IRBuilder<> Builder(User->getParent(), User);
1322 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1323 // The load is a bit extract from NewAI shifted right by Offset bits.
1324 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1326 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1327 LI->replaceAllUsesWith(NewLoadVal);
1328 LI->eraseFromParent();
1332 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1333 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1334 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
1335 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1337 Builder.CreateStore(New, NewAI);
1338 SI->eraseFromParent();
1340 // If the load we just inserted is now dead, then the inserted store
1341 // overwrote the entire thing.
1342 if (Old->use_empty())
1343 Old->eraseFromParent();
1347 // If this is a constant sized memset of a constant value (e.g. 0) we can
1348 // transform it into a store of the expanded constant value.
1349 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1350 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1351 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
1352 if (NumBytes != 0) {
1353 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1355 // Compute the value replicated the right number of times.
1356 APInt APVal(NumBytes*8, Val);
1358 // Splat the value if non-zero.
1360 for (unsigned i = 1; i != NumBytes; ++i)
1361 APVal |= APVal << 8;
1363 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
1364 Value *New = ConvertScalar_InsertValue(
1365 ConstantInt::get(User->getContext(), APVal),
1366 Old, Offset, Builder);
1367 Builder.CreateStore(New, NewAI);
1369 // If the load we just inserted is now dead, then the memset overwrote
1370 // the entire thing.
1371 if (Old->use_empty())
1372 Old->eraseFromParent();
1374 MSI->eraseFromParent();
1378 // If this is a memcpy or memmove into or out of the whole allocation, we
1379 // can handle it like a load or store of the scalar type.
1380 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1381 assert(Offset == 0 && "must be store to start of alloca");
1383 // If the source and destination are both to the same alloca, then this is
1384 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
1386 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject(0));
1388 if (MTI->getSource()->getUnderlyingObject(0) != OrigAI) {
1389 // Dest must be OrigAI, change this to be a load from the original
1390 // pointer (bitcasted), then a store to our new alloca.
1391 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
1392 Value *SrcPtr = MTI->getSource();
1393 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
1395 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
1396 SrcVal->setAlignment(MTI->getAlignment());
1397 Builder.CreateStore(SrcVal, NewAI);
1398 } else if (MTI->getDest()->getUnderlyingObject(0) != OrigAI) {
1399 // Src must be OrigAI, change this to be a load from NewAI then a store
1400 // through the original dest pointer (bitcasted).
1401 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
1402 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
1404 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
1405 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
1406 NewStore->setAlignment(MTI->getAlignment());
1408 // Noop transfer. Src == Dst
1411 MTI->eraseFromParent();
1415 llvm_unreachable("Unsupported operation!");
1419 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1420 /// or vector value FromVal, extracting the bits from the offset specified by
1421 /// Offset. This returns the value, which is of type ToType.
1423 /// This happens when we are converting an "integer union" to a single
1424 /// integer scalar, or when we are converting a "vector union" to a vector with
1425 /// insert/extractelement instructions.
1427 /// Offset is an offset from the original alloca, in bits that need to be
1428 /// shifted to the right.
1429 Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1430 uint64_t Offset, IRBuilder<> &Builder) {
1431 // If the load is of the whole new alloca, no conversion is needed.
1432 if (FromVal->getType() == ToType && Offset == 0)
1435 // If the result alloca is a vector type, this is either an element
1436 // access or a bitcast to another vector type of the same size.
1437 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1438 if (isa<VectorType>(ToType))
1439 return Builder.CreateBitCast(FromVal, ToType, "tmp");
1441 // Otherwise it must be an element access.
1444 unsigned EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
1445 Elt = Offset/EltSize;
1446 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
1448 // Return the element extracted out of it.
1449 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
1450 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
1451 if (V->getType() != ToType)
1452 V = Builder.CreateBitCast(V, ToType, "tmp");
1456 // If ToType is a first class aggregate, extract out each of the pieces and
1457 // use insertvalue's to form the FCA.
1458 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1459 const StructLayout &Layout = *TD->getStructLayout(ST);
1460 Value *Res = UndefValue::get(ST);
1461 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1462 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
1463 Offset+Layout.getElementOffsetInBits(i),
1465 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1470 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
1471 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
1472 Value *Res = UndefValue::get(AT);
1473 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1474 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1475 Offset+i*EltSize, Builder);
1476 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1481 // Otherwise, this must be a union that was converted to an integer value.
1482 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
1484 // If this is a big-endian system and the load is narrower than the
1485 // full alloca type, we need to do a shift to get the right bits.
1487 if (TD->isBigEndian()) {
1488 // On big-endian machines, the lowest bit is stored at the bit offset
1489 // from the pointer given by getTypeStoreSizeInBits. This matters for
1490 // integers with a bitwidth that is not a multiple of 8.
1491 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
1492 TD->getTypeStoreSizeInBits(ToType) - Offset;
1497 // Note: we support negative bitwidths (with shl) which are not defined.
1498 // We do this to support (f.e.) loads off the end of a structure where
1499 // only some bits are used.
1500 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
1501 FromVal = Builder.CreateLShr(FromVal,
1502 ConstantInt::get(FromVal->getType(),
1504 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
1505 FromVal = Builder.CreateShl(FromVal,
1506 ConstantInt::get(FromVal->getType(),
1509 // Finally, unconditionally truncate the integer to the right width.
1510 unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
1511 if (LIBitWidth < NTy->getBitWidth())
1513 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
1514 LIBitWidth), "tmp");
1515 else if (LIBitWidth > NTy->getBitWidth())
1517 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
1518 LIBitWidth), "tmp");
1520 // If the result is an integer, this is a trunc or bitcast.
1521 if (isa<IntegerType>(ToType)) {
1523 } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
1524 // Just do a bitcast, we know the sizes match up.
1525 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
1527 // Otherwise must be a pointer.
1528 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
1530 assert(FromVal->getType() == ToType && "Didn't convert right?");
1534 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1535 /// or vector value "Old" at the offset specified by Offset.
1537 /// This happens when we are converting an "integer union" to a
1538 /// single integer scalar, or when we are converting a "vector union" to a
1539 /// vector with insert/extractelement instructions.
1541 /// Offset is an offset from the original alloca, in bits that need to be
1542 /// shifted to the right.
1543 Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
1544 uint64_t Offset, IRBuilder<> &Builder) {
1546 // Convert the stored type to the actual type, shift it left to insert
1547 // then 'or' into place.
1548 const Type *AllocaType = Old->getType();
1549 LLVMContext &Context = Old->getContext();
1551 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
1552 uint64_t VecSize = TD->getTypeAllocSizeInBits(VTy);
1553 uint64_t ValSize = TD->getTypeAllocSizeInBits(SV->getType());
1555 // Changing the whole vector with memset or with an access of a different
1557 if (ValSize == VecSize)
1558 return Builder.CreateBitCast(SV, AllocaType, "tmp");
1560 uint64_t EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
1562 // Must be an element insertion.
1563 unsigned Elt = Offset/EltSize;
1565 if (SV->getType() != VTy->getElementType())
1566 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1568 SV = Builder.CreateInsertElement(Old, SV,
1569 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
1574 // If SV is a first-class aggregate value, insert each value recursively.
1575 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1576 const StructLayout &Layout = *TD->getStructLayout(ST);
1577 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1578 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1579 Old = ConvertScalar_InsertValue(Elt, Old,
1580 Offset+Layout.getElementOffsetInBits(i),
1586 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
1587 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
1588 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1589 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1590 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
1595 // If SV is a float, convert it to the appropriate integer type.
1596 // If it is a pointer, do the same.
1597 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1598 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1599 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1600 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1601 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
1602 SV = Builder.CreateBitCast(SV,
1603 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
1604 else if (isa<PointerType>(SV->getType()))
1605 SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(SV->getContext()), "tmp");
1607 // Zero extend or truncate the value if needed.
1608 if (SV->getType() != AllocaType) {
1609 if (SV->getType()->getPrimitiveSizeInBits() <
1610 AllocaType->getPrimitiveSizeInBits())
1611 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
1613 // Truncation may be needed if storing more than the alloca can hold
1614 // (undefined behavior).
1615 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
1616 SrcWidth = DestWidth;
1617 SrcStoreWidth = DestStoreWidth;
1621 // If this is a big-endian system and the store is narrower than the
1622 // full alloca type, we need to do a shift to get the right bits.
1624 if (TD->isBigEndian()) {
1625 // On big-endian machines, the lowest bit is stored at the bit offset
1626 // from the pointer given by getTypeStoreSizeInBits. This matters for
1627 // integers with a bitwidth that is not a multiple of 8.
1628 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1633 // Note: we support negative bitwidths (with shr) which are not defined.
1634 // We do this to support (f.e.) stores off the end of a structure where
1635 // only some bits in the structure are set.
1636 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1637 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1638 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
1641 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1642 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
1644 Mask = Mask.lshr(-ShAmt);
1647 // Mask out the bits we are about to insert from the old value, and or
1649 if (SrcWidth != DestWidth) {
1650 assert(DestWidth > SrcWidth);
1651 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1652 SV = Builder.CreateOr(Old, SV, "ins");
1659 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1660 /// some part of a constant global variable. This intentionally only accepts
1661 /// constant expressions because we don't can't rewrite arbitrary instructions.
1662 static bool PointsToConstantGlobal(Value *V) {
1663 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1664 return GV->isConstant();
1665 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1666 if (CE->getOpcode() == Instruction::BitCast ||
1667 CE->getOpcode() == Instruction::GetElementPtr)
1668 return PointsToConstantGlobal(CE->getOperand(0));
1672 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1673 /// pointer to an alloca. Ignore any reads of the pointer, return false if we
1674 /// see any stores or other unknown uses. If we see pointer arithmetic, keep
1675 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
1676 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1677 /// the alloca, and if the source pointer is a pointer to a constant global, we
1678 /// can optimize this.
1679 static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1681 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1682 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1683 // Ignore non-volatile loads, they are always ok.
1684 if (!LI->isVolatile())
1687 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1688 // If uses of the bitcast are ok, we are ok.
1689 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1693 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1694 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1695 // doesn't, it does.
1696 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1697 isOffset || !GEP->hasAllZeroIndices()))
1702 // If this is isn't our memcpy/memmove, reject it as something we can't
1704 if (!isa<MemTransferInst>(*UI))
1707 // If we already have seen a copy, reject the second one.
1708 if (TheCopy) return false;
1710 // If the pointer has been offset from the start of the alloca, we can't
1711 // safely handle this.
1712 if (isOffset) return false;
1714 // If the memintrinsic isn't using the alloca as the dest, reject it.
1715 if (UI.getOperandNo() != 1) return false;
1717 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1719 // If the source of the memcpy/move is not a constant global, reject it.
1720 if (!PointsToConstantGlobal(MI->getOperand(2)))
1723 // Otherwise, the transform is safe. Remember the copy instruction.
1729 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1730 /// modified by a copy from a constant global. If we can prove this, we can
1731 /// replace any uses of the alloca with uses of the global directly.
1732 Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
1733 Instruction *TheCopy = 0;
1734 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))