Implement full support for promoting allocas to registers using SSAUpdater
[oota-llvm.git] / lib / Transforms / Scalar / ScalarReplAggregates.cpp
1 //===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
15 //
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.
19 //
20 //===----------------------------------------------------------------------===//
21
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/Module.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Analysis/DominanceFrontier.h"
34 #include "llvm/Analysis/ValueTracking.h"
35 #include "llvm/Target/TargetData.h"
36 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
37 #include "llvm/Transforms/Utils/Local.h"
38 #include "llvm/Transforms/Utils/SSAUpdater.h"
39 #include "llvm/Support/CallSite.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/GetElementPtrTypeIterator.h"
43 #include "llvm/Support/IRBuilder.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/ADT/SmallVector.h"
47 #include "llvm/ADT/Statistic.h"
48 using namespace llvm;
49
50 STATISTIC(NumReplaced,  "Number of allocas broken up");
51 STATISTIC(NumPromoted,  "Number of allocas promoted");
52 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
53 STATISTIC(NumGlobals,   "Number of allocas copied from constant global");
54
55 enum {
56   UsePromoteMemToReg = 1
57 };
58
59 namespace {
60   struct SROA : public FunctionPass {
61     static char ID; // Pass identification, replacement for typeid
62     explicit SROA(signed T = -1) : FunctionPass(ID) {
63       initializeSROAPass(*PassRegistry::getPassRegistry());
64       if (T == -1)
65         SRThreshold = 128;
66       else
67         SRThreshold = T;
68     }
69
70     bool runOnFunction(Function &F);
71
72     bool performScalarRepl(Function &F);
73     bool performPromotion(Function &F);
74
75     // getAnalysisUsage - This pass does not require any passes, but we know it
76     // will not alter the CFG, so say so.
77     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
78       if (UsePromoteMemToReg) {
79         AU.addRequired<DominatorTree>();
80         AU.addRequired<DominanceFrontier>();
81       }
82       AU.setPreservesCFG();
83     }
84
85   private:
86     TargetData *TD;
87
88     /// DeadInsts - Keep track of instructions we have made dead, so that
89     /// we can remove them after we are done working.
90     SmallVector<Value*, 32> DeadInsts;
91
92     /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
93     /// information about the uses.  All these fields are initialized to false
94     /// and set to true when something is learned.
95     struct AllocaInfo {
96       /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
97       bool isUnsafe : 1;
98
99       /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
100       bool isMemCpySrc : 1;
101
102       /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
103       bool isMemCpyDst : 1;
104
105       AllocaInfo()
106         : isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false) {}
107     };
108
109     unsigned SRThreshold;
110
111     void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
112
113     bool isSafeAllocaToScalarRepl(AllocaInst *AI);
114
115     void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
116                              AllocaInfo &Info);
117     void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
118                    AllocaInfo &Info);
119     void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
120                          const Type *MemOpType, bool isStore, AllocaInfo &Info);
121     bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
122     uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
123                                   const Type *&IdxTy);
124
125     void DoScalarReplacement(AllocaInst *AI,
126                              std::vector<AllocaInst*> &WorkList);
127     void DeleteDeadInstructions();
128
129     void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
130                               SmallVector<AllocaInst*, 32> &NewElts);
131     void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
132                         SmallVector<AllocaInst*, 32> &NewElts);
133     void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
134                     SmallVector<AllocaInst*, 32> &NewElts);
135     void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
136                                       AllocaInst *AI,
137                                       SmallVector<AllocaInst*, 32> &NewElts);
138     void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
139                                        SmallVector<AllocaInst*, 32> &NewElts);
140     void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
141                                       SmallVector<AllocaInst*, 32> &NewElts);
142
143     static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
144   };
145 }
146
147 char SROA::ID = 0;
148 INITIALIZE_PASS_BEGIN(SROA, "scalarrepl",
149                 "Scalar Replacement of Aggregates", false, false)
150 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
151 INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
152 INITIALIZE_PASS_END(SROA, "scalarrepl",
153                 "Scalar Replacement of Aggregates", false, false)
154
155 // Public interface to the ScalarReplAggregates pass
156 FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
157   return new SROA(Threshold);
158 }
159
160
161 //===----------------------------------------------------------------------===//
162 // Convert To Scalar Optimization.
163 //===----------------------------------------------------------------------===//
164
165 namespace {
166 /// ConvertToScalarInfo - This class implements the "Convert To Scalar"
167 /// optimization, which scans the uses of an alloca and determines if it can
168 /// rewrite it in terms of a single new alloca that can be mem2reg'd.
169 class ConvertToScalarInfo {
170   /// AllocaSize - The size of the alloca being considered.
171   unsigned AllocaSize;
172   const TargetData &TD;
173
174   /// IsNotTrivial - This is set to true if there is some access to the object
175   /// which means that mem2reg can't promote it.
176   bool IsNotTrivial;
177
178   /// VectorTy - This tracks the type that we should promote the vector to if
179   /// it is possible to turn it into a vector.  This starts out null, and if it
180   /// isn't possible to turn into a vector type, it gets set to VoidTy.
181   const Type *VectorTy;
182
183   /// HadAVector - True if there is at least one vector access to the alloca.
184   /// We don't want to turn random arrays into vectors and use vector element
185   /// insert/extract, but if there are element accesses to something that is
186   /// also declared as a vector, we do want to promote to a vector.
187   bool HadAVector;
188
189 public:
190   explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
191     : AllocaSize(Size), TD(td) {
192     IsNotTrivial = false;
193     VectorTy = 0;
194     HadAVector = false;
195   }
196
197   AllocaInst *TryConvert(AllocaInst *AI);
198
199 private:
200   bool CanConvertToScalar(Value *V, uint64_t Offset);
201   void MergeInType(const Type *In, uint64_t Offset);
202   void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
203
204   Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
205                                     uint64_t Offset, IRBuilder<> &Builder);
206   Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
207                                    uint64_t Offset, IRBuilder<> &Builder);
208 };
209 } // end anonymous namespace.
210
211
212 /// IsVerbotenVectorType - Return true if this is a vector type ScalarRepl isn't
213 /// allowed to form.  We do this to avoid MMX types, which is a complete hack,
214 /// but is required until the backend is fixed.
215 static bool IsVerbotenVectorType(const VectorType *VTy, const Instruction *I) {
216   StringRef Triple(I->getParent()->getParent()->getParent()->getTargetTriple());
217   if (!Triple.startswith("i386") &&
218       !Triple.startswith("x86_64"))
219     return false;
220
221   // Reject all the MMX vector types.
222   switch (VTy->getNumElements()) {
223   default: return false;
224   case 1: return VTy->getElementType()->isIntegerTy(64);
225   case 2: return VTy->getElementType()->isIntegerTy(32);
226   case 4: return VTy->getElementType()->isIntegerTy(16);
227   case 8: return VTy->getElementType()->isIntegerTy(8);
228   }
229 }
230
231
232 /// TryConvert - Analyze the specified alloca, and if it is safe to do so,
233 /// rewrite it to be a new alloca which is mem2reg'able.  This returns the new
234 /// alloca if possible or null if not.
235 AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
236   // If we can't convert this scalar, or if mem2reg can trivially do it, bail
237   // out.
238   if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
239     return 0;
240
241   // If we were able to find a vector type that can handle this with
242   // insert/extract elements, and if there was at least one use that had
243   // a vector type, promote this to a vector.  We don't want to promote
244   // random stuff that doesn't use vectors (e.g. <9 x double>) because then
245   // we just get a lot of insert/extracts.  If at least one vector is
246   // involved, then we probably really do have a union of vector/array.
247   const Type *NewTy;
248   if (VectorTy && VectorTy->isVectorTy() && HadAVector &&
249       !IsVerbotenVectorType(cast<VectorType>(VectorTy), AI)) {
250     DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n  TYPE = "
251           << *VectorTy << '\n');
252     NewTy = VectorTy;  // Use the vector type.
253   } else {
254     DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
255     // Create and insert the integer alloca.
256     NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
257   }
258   AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
259   ConvertUsesToScalar(AI, NewAI, 0);
260   return NewAI;
261 }
262
263 /// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
264 /// so far at the offset specified by Offset (which is specified in bytes).
265 ///
266 /// There are two cases we handle here:
267 ///   1) A union of vector types of the same size and potentially its elements.
268 ///      Here we turn element accesses into insert/extract element operations.
269 ///      This promotes a <4 x float> with a store of float to the third element
270 ///      into a <4 x float> that uses insert element.
271 ///   2) A fully general blob of memory, which we turn into some (potentially
272 ///      large) integer type with extract and insert operations where the loads
273 ///      and stores would mutate the memory.  We mark this by setting VectorTy
274 ///      to VoidTy.
275 void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
276   // If we already decided to turn this into a blob of integer memory, there is
277   // nothing to be done.
278   if (VectorTy && VectorTy->isVoidTy())
279     return;
280
281   // If this could be contributing to a vector, analyze it.
282
283   // If the In type is a vector that is the same size as the alloca, see if it
284   // matches the existing VecTy.
285   if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
286     // Remember if we saw a vector type.
287     HadAVector = true;
288
289     if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
290       // If we're storing/loading a vector of the right size, allow it as a
291       // vector.  If this the first vector we see, remember the type so that
292       // we know the element size.  If this is a subsequent access, ignore it
293       // even if it is a differing type but the same size.  Worst case we can
294       // bitcast the resultant vectors.
295       if (VectorTy == 0)
296         VectorTy = VInTy;
297       return;
298     }
299   } else if (In->isFloatTy() || In->isDoubleTy() ||
300              (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
301               isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
302     // If we're accessing something that could be an element of a vector, see
303     // if the implied vector agrees with what we already have and if Offset is
304     // compatible with it.
305     unsigned EltSize = In->getPrimitiveSizeInBits()/8;
306     if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
307         (VectorTy == 0 ||
308          cast<VectorType>(VectorTy)->getElementType()
309                ->getPrimitiveSizeInBits()/8 == EltSize)) {
310       if (VectorTy == 0)
311         VectorTy = VectorType::get(In, AllocaSize/EltSize);
312       return;
313     }
314   }
315
316   // Otherwise, we have a case that we can't handle with an optimized vector
317   // form.  We can still turn this into a large integer.
318   VectorTy = Type::getVoidTy(In->getContext());
319 }
320
321 /// CanConvertToScalar - V is a pointer.  If we can convert the pointee and all
322 /// its accesses to a single vector type, return true and set VecTy to
323 /// the new type.  If we could convert the alloca into a single promotable
324 /// integer, return true but set VecTy to VoidTy.  Further, if the use is not a
325 /// completely trivial use that mem2reg could promote, set IsNotTrivial.  Offset
326 /// is the current offset from the base of the alloca being analyzed.
327 ///
328 /// If we see at least one access to the value that is as a vector type, set the
329 /// SawVec flag.
330 bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
331   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
332     Instruction *User = cast<Instruction>(*UI);
333
334     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
335       // Don't break volatile loads.
336       if (LI->isVolatile())
337         return false;
338       // Don't touch MMX operations.
339       if (LI->getType()->isX86_MMXTy())
340         return false;
341       MergeInType(LI->getType(), Offset);
342       continue;
343     }
344
345     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
346       // Storing the pointer, not into the value?
347       if (SI->getOperand(0) == V || SI->isVolatile()) return false;
348       // Don't touch MMX operations.
349       if (SI->getOperand(0)->getType()->isX86_MMXTy())
350         return false;
351       MergeInType(SI->getOperand(0)->getType(), Offset);
352       continue;
353     }
354
355     if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
356       IsNotTrivial = true;  // Can't be mem2reg'd.
357       if (!CanConvertToScalar(BCI, Offset))
358         return false;
359       continue;
360     }
361
362     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
363       // If this is a GEP with a variable indices, we can't handle it.
364       if (!GEP->hasAllConstantIndices())
365         return false;
366
367       // Compute the offset that this GEP adds to the pointer.
368       SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
369       uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
370                                                &Indices[0], Indices.size());
371       // See if all uses can be converted.
372       if (!CanConvertToScalar(GEP, Offset+GEPOffset))
373         return false;
374       IsNotTrivial = true;  // Can't be mem2reg'd.
375       continue;
376     }
377
378     // If this is a constant sized memset of a constant value (e.g. 0) we can
379     // handle it.
380     if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
381       // Store of constant value and constant size.
382       if (!isa<ConstantInt>(MSI->getValue()) ||
383           !isa<ConstantInt>(MSI->getLength()))
384         return false;
385       IsNotTrivial = true;  // Can't be mem2reg'd.
386       continue;
387     }
388
389     // If this is a memcpy or memmove into or out of the whole allocation, we
390     // can handle it like a load or store of the scalar type.
391     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
392       ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
393       if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
394         return false;
395
396       IsNotTrivial = true;  // Can't be mem2reg'd.
397       continue;
398     }
399
400     // Otherwise, we cannot handle this!
401     return false;
402   }
403
404   return true;
405 }
406
407 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
408 /// directly.  This happens when we are converting an "integer union" to a
409 /// single integer scalar, or when we are converting a "vector union" to a
410 /// vector with insert/extractelement instructions.
411 ///
412 /// Offset is an offset from the original alloca, in bits that need to be
413 /// shifted to the right.  By the end of this, there should be no uses of Ptr.
414 void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
415                                               uint64_t Offset) {
416   while (!Ptr->use_empty()) {
417     Instruction *User = cast<Instruction>(Ptr->use_back());
418
419     if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
420       ConvertUsesToScalar(CI, NewAI, Offset);
421       CI->eraseFromParent();
422       continue;
423     }
424
425     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
426       // Compute the offset that this GEP adds to the pointer.
427       SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
428       uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
429                                                &Indices[0], Indices.size());
430       ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
431       GEP->eraseFromParent();
432       continue;
433     }
434
435     IRBuilder<> Builder(User);
436
437     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
438       // The load is a bit extract from NewAI shifted right by Offset bits.
439       Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
440       Value *NewLoadVal
441         = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
442       LI->replaceAllUsesWith(NewLoadVal);
443       LI->eraseFromParent();
444       continue;
445     }
446
447     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
448       assert(SI->getOperand(0) != Ptr && "Consistency error!");
449       Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
450       Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
451                                              Builder);
452       Builder.CreateStore(New, NewAI);
453       SI->eraseFromParent();
454
455       // If the load we just inserted is now dead, then the inserted store
456       // overwrote the entire thing.
457       if (Old->use_empty())
458         Old->eraseFromParent();
459       continue;
460     }
461
462     // If this is a constant sized memset of a constant value (e.g. 0) we can
463     // transform it into a store of the expanded constant value.
464     if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
465       assert(MSI->getRawDest() == Ptr && "Consistency error!");
466       unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
467       if (NumBytes != 0) {
468         unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
469
470         // Compute the value replicated the right number of times.
471         APInt APVal(NumBytes*8, Val);
472
473         // Splat the value if non-zero.
474         if (Val)
475           for (unsigned i = 1; i != NumBytes; ++i)
476             APVal |= APVal << 8;
477
478         Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
479         Value *New = ConvertScalar_InsertValue(
480                                     ConstantInt::get(User->getContext(), APVal),
481                                                Old, Offset, Builder);
482         Builder.CreateStore(New, NewAI);
483
484         // If the load we just inserted is now dead, then the memset overwrote
485         // the entire thing.
486         if (Old->use_empty())
487           Old->eraseFromParent();
488       }
489       MSI->eraseFromParent();
490       continue;
491     }
492
493     // If this is a memcpy or memmove into or out of the whole allocation, we
494     // can handle it like a load or store of the scalar type.
495     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
496       assert(Offset == 0 && "must be store to start of alloca");
497
498       // If the source and destination are both to the same alloca, then this is
499       // a noop copy-to-self, just delete it.  Otherwise, emit a load and store
500       // as appropriate.
501       AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, 0));
502
503       if (GetUnderlyingObject(MTI->getSource(), 0) != OrigAI) {
504         // Dest must be OrigAI, change this to be a load from the original
505         // pointer (bitcasted), then a store to our new alloca.
506         assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
507         Value *SrcPtr = MTI->getSource();
508         const PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
509         const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
510         if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
511           AIPTy = PointerType::get(AIPTy->getElementType(),
512                                    SPTy->getAddressSpace());
513         }
514         SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
515
516         LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
517         SrcVal->setAlignment(MTI->getAlignment());
518         Builder.CreateStore(SrcVal, NewAI);
519       } else if (GetUnderlyingObject(MTI->getDest(), 0) != OrigAI) {
520         // Src must be OrigAI, change this to be a load from NewAI then a store
521         // through the original dest pointer (bitcasted).
522         assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
523         LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
524
525         const PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
526         const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
527         if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
528           AIPTy = PointerType::get(AIPTy->getElementType(),
529                                    DPTy->getAddressSpace());
530         }
531         Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
532
533         StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
534         NewStore->setAlignment(MTI->getAlignment());
535       } else {
536         // Noop transfer. Src == Dst
537       }
538
539       MTI->eraseFromParent();
540       continue;
541     }
542
543     llvm_unreachable("Unsupported operation!");
544   }
545 }
546
547 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
548 /// or vector value FromVal, extracting the bits from the offset specified by
549 /// Offset.  This returns the value, which is of type ToType.
550 ///
551 /// This happens when we are converting an "integer union" to a single
552 /// integer scalar, or when we are converting a "vector union" to a vector with
553 /// insert/extractelement instructions.
554 ///
555 /// Offset is an offset from the original alloca, in bits that need to be
556 /// shifted to the right.
557 Value *ConvertToScalarInfo::
558 ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
559                            uint64_t Offset, IRBuilder<> &Builder) {
560   // If the load is of the whole new alloca, no conversion is needed.
561   if (FromVal->getType() == ToType && Offset == 0)
562     return FromVal;
563
564   // If the result alloca is a vector type, this is either an element
565   // access or a bitcast to another vector type of the same size.
566   if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
567     if (ToType->isVectorTy())
568       return Builder.CreateBitCast(FromVal, ToType, "tmp");
569
570     // Otherwise it must be an element access.
571     unsigned Elt = 0;
572     if (Offset) {
573       unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
574       Elt = Offset/EltSize;
575       assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
576     }
577     // Return the element extracted out of it.
578     Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
579                     Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
580     if (V->getType() != ToType)
581       V = Builder.CreateBitCast(V, ToType, "tmp");
582     return V;
583   }
584
585   // If ToType is a first class aggregate, extract out each of the pieces and
586   // use insertvalue's to form the FCA.
587   if (const StructType *ST = dyn_cast<StructType>(ToType)) {
588     const StructLayout &Layout = *TD.getStructLayout(ST);
589     Value *Res = UndefValue::get(ST);
590     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
591       Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
592                                         Offset+Layout.getElementOffsetInBits(i),
593                                               Builder);
594       Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
595     }
596     return Res;
597   }
598
599   if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
600     uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
601     Value *Res = UndefValue::get(AT);
602     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
603       Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
604                                               Offset+i*EltSize, Builder);
605       Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
606     }
607     return Res;
608   }
609
610   // Otherwise, this must be a union that was converted to an integer value.
611   const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
612
613   // If this is a big-endian system and the load is narrower than the
614   // full alloca type, we need to do a shift to get the right bits.
615   int ShAmt = 0;
616   if (TD.isBigEndian()) {
617     // On big-endian machines, the lowest bit is stored at the bit offset
618     // from the pointer given by getTypeStoreSizeInBits.  This matters for
619     // integers with a bitwidth that is not a multiple of 8.
620     ShAmt = TD.getTypeStoreSizeInBits(NTy) -
621             TD.getTypeStoreSizeInBits(ToType) - Offset;
622   } else {
623     ShAmt = Offset;
624   }
625
626   // Note: we support negative bitwidths (with shl) which are not defined.
627   // We do this to support (f.e.) loads off the end of a structure where
628   // only some bits are used.
629   if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
630     FromVal = Builder.CreateLShr(FromVal,
631                                  ConstantInt::get(FromVal->getType(),
632                                                            ShAmt), "tmp");
633   else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
634     FromVal = Builder.CreateShl(FromVal,
635                                 ConstantInt::get(FromVal->getType(),
636                                                           -ShAmt), "tmp");
637
638   // Finally, unconditionally truncate the integer to the right width.
639   unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
640   if (LIBitWidth < NTy->getBitWidth())
641     FromVal =
642       Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
643                                                     LIBitWidth), "tmp");
644   else if (LIBitWidth > NTy->getBitWidth())
645     FromVal =
646        Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
647                                                     LIBitWidth), "tmp");
648
649   // If the result is an integer, this is a trunc or bitcast.
650   if (ToType->isIntegerTy()) {
651     // Should be done.
652   } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
653     // Just do a bitcast, we know the sizes match up.
654     FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
655   } else {
656     // Otherwise must be a pointer.
657     FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
658   }
659   assert(FromVal->getType() == ToType && "Didn't convert right?");
660   return FromVal;
661 }
662
663 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
664 /// or vector value "Old" at the offset specified by Offset.
665 ///
666 /// This happens when we are converting an "integer union" to a
667 /// single integer scalar, or when we are converting a "vector union" to a
668 /// vector with insert/extractelement instructions.
669 ///
670 /// Offset is an offset from the original alloca, in bits that need to be
671 /// shifted to the right.
672 Value *ConvertToScalarInfo::
673 ConvertScalar_InsertValue(Value *SV, Value *Old,
674                           uint64_t Offset, IRBuilder<> &Builder) {
675   // Convert the stored type to the actual type, shift it left to insert
676   // then 'or' into place.
677   const Type *AllocaType = Old->getType();
678   LLVMContext &Context = Old->getContext();
679
680   if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
681     uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
682     uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
683
684     // Changing the whole vector with memset or with an access of a different
685     // vector type?
686     if (ValSize == VecSize)
687       return Builder.CreateBitCast(SV, AllocaType, "tmp");
688
689     uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
690
691     // Must be an element insertion.
692     unsigned Elt = Offset/EltSize;
693
694     if (SV->getType() != VTy->getElementType())
695       SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
696
697     SV = Builder.CreateInsertElement(Old, SV,
698                      ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
699                                      "tmp");
700     return SV;
701   }
702
703   // If SV is a first-class aggregate value, insert each value recursively.
704   if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
705     const StructLayout &Layout = *TD.getStructLayout(ST);
706     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
707       Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
708       Old = ConvertScalar_InsertValue(Elt, Old,
709                                       Offset+Layout.getElementOffsetInBits(i),
710                                       Builder);
711     }
712     return Old;
713   }
714
715   if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
716     uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
717     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
718       Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
719       Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
720     }
721     return Old;
722   }
723
724   // If SV is a float, convert it to the appropriate integer type.
725   // If it is a pointer, do the same.
726   unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
727   unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
728   unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
729   unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
730   if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
731     SV = Builder.CreateBitCast(SV,
732                             IntegerType::get(SV->getContext(),SrcWidth), "tmp");
733   else if (SV->getType()->isPointerTy())
734     SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
735
736   // Zero extend or truncate the value if needed.
737   if (SV->getType() != AllocaType) {
738     if (SV->getType()->getPrimitiveSizeInBits() <
739              AllocaType->getPrimitiveSizeInBits())
740       SV = Builder.CreateZExt(SV, AllocaType, "tmp");
741     else {
742       // Truncation may be needed if storing more than the alloca can hold
743       // (undefined behavior).
744       SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
745       SrcWidth = DestWidth;
746       SrcStoreWidth = DestStoreWidth;
747     }
748   }
749
750   // If this is a big-endian system and the store is narrower than the
751   // full alloca type, we need to do a shift to get the right bits.
752   int ShAmt = 0;
753   if (TD.isBigEndian()) {
754     // On big-endian machines, the lowest bit is stored at the bit offset
755     // from the pointer given by getTypeStoreSizeInBits.  This matters for
756     // integers with a bitwidth that is not a multiple of 8.
757     ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
758   } else {
759     ShAmt = Offset;
760   }
761
762   // Note: we support negative bitwidths (with shr) which are not defined.
763   // We do this to support (f.e.) stores off the end of a structure where
764   // only some bits in the structure are set.
765   APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
766   if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
767     SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
768                            ShAmt), "tmp");
769     Mask <<= ShAmt;
770   } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
771     SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
772                             -ShAmt), "tmp");
773     Mask = Mask.lshr(-ShAmt);
774   }
775
776   // Mask out the bits we are about to insert from the old value, and or
777   // in the new bits.
778   if (SrcWidth != DestWidth) {
779     assert(DestWidth > SrcWidth);
780     Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
781     SV = Builder.CreateOr(Old, SV, "ins");
782   }
783   return SV;
784 }
785
786
787 //===----------------------------------------------------------------------===//
788 // SRoA Driver
789 //===----------------------------------------------------------------------===//
790
791
792 bool SROA::runOnFunction(Function &F) {
793   TD = getAnalysisIfAvailable<TargetData>();
794
795   bool Changed = performPromotion(F);
796
797   // FIXME: ScalarRepl currently depends on TargetData more than it
798   // theoretically needs to. It should be refactored in order to support
799   // target-independent IR. Until this is done, just skip the actual
800   // scalar-replacement portion of this pass.
801   if (!TD) return Changed;
802
803   while (1) {
804     bool LocalChange = performScalarRepl(F);
805     if (!LocalChange) break;   // No need to repromote if no scalarrepl
806     Changed = true;
807     LocalChange = performPromotion(F);
808     if (!LocalChange) break;   // No need to re-scalarrepl if no promotion
809   }
810
811   return Changed;
812 }
813
814 /// PromoteAlloca - Promote an alloca to registers, using SSAUpdater.
815 static void PromoteAlloca(AllocaInst *AI, SSAUpdater &SSA) {
816   SSA.Initialize(AI->getType()->getElementType(), AI->getName());
817
818   // First step: bucket up uses of the alloca by the block they occur in.
819   // This is important because we have to handle multiple defs/uses in a block
820   // ourselves: SSAUpdater is purely for cross-block references.
821   // FIXME: Want a TinyVector<Instruction*> since there is often 0/1 element.
822   DenseMap<BasicBlock*, std::vector<Instruction*> > UsesByBlock;
823   
824   for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
825        UI != E; ++UI) {
826     Instruction *User = cast<Instruction>(*UI);
827     UsesByBlock[User->getParent()].push_back(User);
828   }
829   
830   // Okay, now we can iterate over all the blocks in the function with uses,
831   // processing them.  Keep track of which loads are loading a live-in value.
832   // Walk the uses in the use-list order to be determinstic.
833   SmallVector<LoadInst*, 32> LiveInLoads;
834   DenseMap<Value*, Value*> ReplacedLoads;
835   
836   for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
837        UI != E; ++UI) {
838     Instruction *User = cast<Instruction>(*UI);
839     BasicBlock *BB = User->getParent();
840     std::vector<Instruction*> &BlockUses = UsesByBlock[BB];
841     
842     // If this block has already been processed, ignore this repeat use.
843     if (BlockUses.empty()) continue;
844     
845     // Okay, this is the first use in the block.  If this block just has a
846     // single user in it, we can rewrite it trivially.
847     if (BlockUses.size() == 1) {
848       // If it is a store, it is a trivial def of the value in the block.
849       if (StoreInst *SI = dyn_cast<StoreInst>(User))
850         SSA.AddAvailableValue(BB, SI->getOperand(0));
851       else 
852         // Otherwise it is a load, queue it to rewrite as a live-in load.
853         LiveInLoads.push_back(cast<LoadInst>(User));
854       BlockUses.clear();
855       continue;
856     }
857     
858     // Otherwise, check to see if this block is all loads.
859     bool HasStore = false;
860     for (unsigned i = 0, e = BlockUses.size(); i != e; ++i) {
861       if (isa<StoreInst>(BlockUses[i])) {
862         HasStore = true;
863         break;
864       }
865     }
866     
867     // If so, we can queue them all as live in loads.  We don't have an
868     // efficient way to tell which on is first in the block and don't want to
869     // scan large blocks, so just add all loads as live ins.
870     if (!HasStore) {
871       for (unsigned i = 0, e = BlockUses.size(); i != e; ++i)
872         LiveInLoads.push_back(cast<LoadInst>(BlockUses[i]));
873       BlockUses.clear();
874       continue;
875     }
876     
877     // Otherwise, we have mixed loads and stores (or just a bunch of stores).
878     // Since SSAUpdater is purely for cross-block values, we need to determine
879     // the order of these instructions in the block.  If the first use in the
880     // block is a load, then it uses the live in value.  The last store defines
881     // the live out value.  We handle this by doing a linear scan of the block.
882     Value *StoredValue = 0;
883     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
884       if (LoadInst *L = dyn_cast<LoadInst>(II)) {
885         // If this is a load from an unrelated pointer, ignore it.
886         if (L->getOperand(0) != AI) continue;
887         
888         // If we haven't seen a store yet, this is a live in use, otherwise
889         // use the stored value.
890         if (StoredValue) {
891           L->replaceAllUsesWith(StoredValue);
892           ReplacedLoads[L] = StoredValue;
893         } else {
894           LiveInLoads.push_back(L);
895         }
896         continue;
897       }
898       
899       if (StoreInst *S = dyn_cast<StoreInst>(II)) {
900         // If this is a store to an unrelated pointer, ignore it.
901         if (S->getPointerOperand() != AI) continue;
902         
903         // Remember that this is the active value in the block.
904         StoredValue = S->getOperand(0);
905       }
906     }
907     
908     // The last stored value that happened is the live-out for the block.
909     assert(StoredValue && "Already checked that there is a store in block");
910     SSA.AddAvailableValue(BB, StoredValue);
911     BlockUses.clear();
912   }
913   
914   // Okay, now we rewrite all loads that use live-in values in the loop,
915   // inserting PHI nodes as necessary.
916   for (unsigned i = 0, e = LiveInLoads.size(); i != e; ++i) {
917     LoadInst *ALoad = LiveInLoads[i];
918     Value *NewVal = SSA.GetValueInMiddleOfBlock(ALoad->getParent());
919     ALoad->replaceAllUsesWith(NewVal);
920     ReplacedLoads[ALoad] = NewVal;
921   }
922   
923   // Now that everything is rewritten, delete the old instructions from the
924   // function.  They should all be dead now.
925   for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E; ) {
926     Instruction *User = cast<Instruction>(*UI++);
927     
928     // If this is a load that still has uses, then the load must have been added
929     // as a live value in the SSAUpdate data structure for a block (e.g. because
930     // the loaded value was stored later).  In this case, we need to recursively
931     // propagate the updates until we get to the real value.
932     if (!User->use_empty()) {
933       Value *NewVal = ReplacedLoads[User];
934       assert(NewVal && "not a replaced load?");
935       
936       // Propagate down to the ultimate replacee.  The intermediately loads
937       // could theoretically already have been deleted, so we don't want to
938       // dereference the Value*'s.
939       DenseMap<Value*, Value*>::iterator RLI = ReplacedLoads.find(NewVal);
940       while (RLI != ReplacedLoads.end()) {
941         NewVal = RLI->second;
942         RLI = ReplacedLoads.find(NewVal);
943       }
944       
945       User->replaceAllUsesWith(NewVal);
946     }
947     
948     User->eraseFromParent();
949   }
950 }
951
952
953 bool SROA::performPromotion(Function &F) {
954   std::vector<AllocaInst*> Allocas;
955   DominatorTree *DT = 0;
956   DominanceFrontier *DF = 0;
957   if (UsePromoteMemToReg) {
958     DT = &getAnalysis<DominatorTree>();
959     DF = &getAnalysis<DominanceFrontier>();
960   }
961
962   BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
963
964   bool Changed = false;
965
966   while (1) {
967     Allocas.clear();
968
969     // Find allocas that are safe to promote, by looking at all instructions in
970     // the entry node
971     for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
972       if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
973         if (isAllocaPromotable(AI))
974           Allocas.push_back(AI);
975
976     if (Allocas.empty()) break;
977
978     if (UsePromoteMemToReg)
979       PromoteMemToReg(Allocas, *DT, *DF);
980     else {
981       SSAUpdater SSA;
982       for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
983         PromoteAlloca(Allocas[i], SSA);
984         Allocas[i]->eraseFromParent();
985       }
986     }
987     NumPromoted += Allocas.size();
988     Changed = true;
989   }
990
991   return Changed;
992 }
993
994
995 /// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
996 /// SROA.  It must be a struct or array type with a small number of elements.
997 static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
998   const Type *T = AI->getAllocatedType();
999   // Do not promote any struct into more than 32 separate vars.
1000   if (const StructType *ST = dyn_cast<StructType>(T))
1001     return ST->getNumElements() <= 32;
1002   // Arrays are much less likely to be safe for SROA; only consider
1003   // them if they are very small.
1004   if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1005     return AT->getNumElements() <= 8;
1006   return false;
1007 }
1008
1009
1010 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
1011 // which runs on all of the malloc/alloca instructions in the function, removing
1012 // them if they are only used by getelementptr instructions.
1013 //
1014 bool SROA::performScalarRepl(Function &F) {
1015   std::vector<AllocaInst*> WorkList;
1016
1017   // Scan the entry basic block, adding allocas to the worklist.
1018   BasicBlock &BB = F.getEntryBlock();
1019   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
1020     if (AllocaInst *A = dyn_cast<AllocaInst>(I))
1021       WorkList.push_back(A);
1022
1023   // Process the worklist
1024   bool Changed = false;
1025   while (!WorkList.empty()) {
1026     AllocaInst *AI = WorkList.back();
1027     WorkList.pop_back();
1028
1029     // Handle dead allocas trivially.  These can be formed by SROA'ing arrays
1030     // with unused elements.
1031     if (AI->use_empty()) {
1032       AI->eraseFromParent();
1033       Changed = true;
1034       continue;
1035     }
1036
1037     // If this alloca is impossible for us to promote, reject it early.
1038     if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1039       continue;
1040
1041     // Check to see if this allocation is only modified by a memcpy/memmove from
1042     // a constant global.  If this is the case, we can change all users to use
1043     // the constant global instead.  This is commonly produced by the CFE by
1044     // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
1045     // is only subsequently read.
1046     if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
1047       DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
1048       DEBUG(dbgs() << "  memcpy = " << *TheCopy << '\n');
1049       Constant *TheSrc = cast<Constant>(TheCopy->getSource());
1050       AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
1051       TheCopy->eraseFromParent();  // Don't mutate the global.
1052       AI->eraseFromParent();
1053       ++NumGlobals;
1054       Changed = true;
1055       continue;
1056     }
1057
1058     // Check to see if we can perform the core SROA transformation.  We cannot
1059     // transform the allocation instruction if it is an array allocation
1060     // (allocations OF arrays are ok though), and an allocation of a scalar
1061     // value cannot be decomposed at all.
1062     uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
1063
1064     // Do not promote [0 x %struct].
1065     if (AllocaSize == 0) continue;
1066
1067     // Do not promote any struct whose size is too big.
1068     if (AllocaSize > SRThreshold) continue;
1069
1070     // If the alloca looks like a good candidate for scalar replacement, and if
1071     // all its users can be transformed, then split up the aggregate into its
1072     // separate elements.
1073     if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1074       DoScalarReplacement(AI, WorkList);
1075       Changed = true;
1076       continue;
1077     }
1078
1079     // If we can turn this aggregate value (potentially with casts) into a
1080     // simple scalar value that can be mem2reg'd into a register value.
1081     // IsNotTrivial tracks whether this is something that mem2reg could have
1082     // promoted itself.  If so, we don't want to transform it needlessly.  Note
1083     // that we can't just check based on the type: the alloca may be of an i32
1084     // but that has pointer arithmetic to set byte 3 of it or something.
1085     if (AllocaInst *NewAI =
1086           ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
1087       NewAI->takeName(AI);
1088       AI->eraseFromParent();
1089       ++NumConverted;
1090       Changed = true;
1091       continue;
1092     }
1093
1094     // Otherwise, couldn't process this alloca.
1095   }
1096
1097   return Changed;
1098 }
1099
1100 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1101 /// predicate, do SROA now.
1102 void SROA::DoScalarReplacement(AllocaInst *AI,
1103                                std::vector<AllocaInst*> &WorkList) {
1104   DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
1105   SmallVector<AllocaInst*, 32> ElementAllocas;
1106   if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1107     ElementAllocas.reserve(ST->getNumContainedTypes());
1108     for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
1109       AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
1110                                       AI->getAlignment(),
1111                                       AI->getName() + "." + Twine(i), AI);
1112       ElementAllocas.push_back(NA);
1113       WorkList.push_back(NA);  // Add to worklist for recursive processing
1114     }
1115   } else {
1116     const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1117     ElementAllocas.reserve(AT->getNumElements());
1118     const Type *ElTy = AT->getElementType();
1119     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1120       AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
1121                                       AI->getName() + "." + Twine(i), AI);
1122       ElementAllocas.push_back(NA);
1123       WorkList.push_back(NA);  // Add to worklist for recursive processing
1124     }
1125   }
1126
1127   // Now that we have created the new alloca instructions, rewrite all the
1128   // uses of the old alloca.
1129   RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
1130
1131   // Now erase any instructions that were made dead while rewriting the alloca.
1132   DeleteDeadInstructions();
1133   AI->eraseFromParent();
1134
1135   ++NumReplaced;
1136 }
1137
1138 /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1139 /// recursively including all their operands that become trivially dead.
1140 void SROA::DeleteDeadInstructions() {
1141   while (!DeadInsts.empty()) {
1142     Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
1143
1144     for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1145       if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1146         // Zero out the operand and see if it becomes trivially dead.
1147         // (But, don't add allocas to the dead instruction list -- they are
1148         // already on the worklist and will be deleted separately.)
1149         *OI = 0;
1150         if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1151           DeadInsts.push_back(U);
1152       }
1153
1154     I->eraseFromParent();
1155   }
1156 }
1157
1158 /// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1159 /// performing scalar replacement of alloca AI.  The results are flagged in
1160 /// the Info parameter.  Offset indicates the position within AI that is
1161 /// referenced by this instruction.
1162 void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1163                                AllocaInfo &Info) {
1164   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1165     Instruction *User = cast<Instruction>(*UI);
1166
1167     if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1168       isSafeForScalarRepl(BC, AI, Offset, Info);
1169     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1170       uint64_t GEPOffset = Offset;
1171       isSafeGEP(GEPI, AI, GEPOffset, Info);
1172       if (!Info.isUnsafe)
1173         isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
1174     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1175       ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1176       if (Length)
1177         isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
1178                         UI.getOperandNo() == 0, Info);
1179       else
1180         MarkUnsafe(Info);
1181     } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1182       if (!LI->isVolatile()) {
1183         const Type *LIType = LI->getType();
1184         isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
1185                         LIType, false, Info);
1186       } else
1187         MarkUnsafe(Info);
1188     } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1189       // Store is ok if storing INTO the pointer, not storing the pointer
1190       if (!SI->isVolatile() && SI->getOperand(0) != I) {
1191         const Type *SIType = SI->getOperand(0)->getType();
1192         isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
1193                         SIType, true, Info);
1194       } else
1195         MarkUnsafe(Info);
1196     } else {
1197       DEBUG(errs() << "  Transformation preventing inst: " << *User << '\n');
1198       MarkUnsafe(Info);
1199     }
1200     if (Info.isUnsafe) return;
1201   }
1202 }
1203
1204 /// isSafeGEP - Check if a GEP instruction can be handled for scalar
1205 /// replacement.  It is safe when all the indices are constant, in-bounds
1206 /// references, and when the resulting offset corresponds to an element within
1207 /// the alloca type.  The results are flagged in the Info parameter.  Upon
1208 /// return, Offset is adjusted as specified by the GEP indices.
1209 void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
1210                      uint64_t &Offset, AllocaInfo &Info) {
1211   gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1212   if (GEPIt == E)
1213     return;
1214
1215   // Walk through the GEP type indices, checking the types that this indexes
1216   // into.
1217   for (; GEPIt != E; ++GEPIt) {
1218     // Ignore struct elements, no extra checking needed for these.
1219     if ((*GEPIt)->isStructTy())
1220       continue;
1221
1222     ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1223     if (!IdxVal)
1224       return MarkUnsafe(Info);
1225   }
1226
1227   // Compute the offset due to this GEP and check if the alloca has a
1228   // component element at that offset.
1229   SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1230   Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1231                                  &Indices[0], Indices.size());
1232   if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
1233     MarkUnsafe(Info);
1234 }
1235
1236 /// isHomogeneousAggregate - Check if type T is a struct or array containing
1237 /// elements of the same type (which is always true for arrays).  If so,
1238 /// return true with NumElts and EltTy set to the number of elements and the
1239 /// element type, respectively.
1240 static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts,
1241                                    const Type *&EltTy) {
1242   if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1243     NumElts = AT->getNumElements();
1244     EltTy = (NumElts == 0 ? 0 : AT->getElementType());
1245     return true;
1246   }
1247   if (const StructType *ST = dyn_cast<StructType>(T)) {
1248     NumElts = ST->getNumContainedTypes();
1249     EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
1250     for (unsigned n = 1; n < NumElts; ++n) {
1251       if (ST->getContainedType(n) != EltTy)
1252         return false;
1253     }
1254     return true;
1255   }
1256   return false;
1257 }
1258
1259 /// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1260 /// "homogeneous" aggregates with the same element type and number of elements.
1261 static bool isCompatibleAggregate(const Type *T1, const Type *T2) {
1262   if (T1 == T2)
1263     return true;
1264
1265   unsigned NumElts1, NumElts2;
1266   const Type *EltTy1, *EltTy2;
1267   if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1268       isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1269       NumElts1 == NumElts2 &&
1270       EltTy1 == EltTy2)
1271     return true;
1272
1273   return false;
1274 }
1275
1276 /// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1277 /// alloca or has an offset and size that corresponds to a component element
1278 /// within it.  The offset checked here may have been formed from a GEP with a
1279 /// pointer bitcasted to a different type.
1280 void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
1281                            const Type *MemOpType, bool isStore,
1282                            AllocaInfo &Info) {
1283   // Check if this is a load/store of the entire alloca.
1284   if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
1285     // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1286     // loads/stores (which are essentially the same as the MemIntrinsics with
1287     // regard to copying padding between elements).  But, if an alloca is
1288     // flagged as both a source and destination of such operations, we'll need
1289     // to check later for padding between elements.
1290     if (!MemOpType || MemOpType->isIntegerTy()) {
1291       if (isStore)
1292         Info.isMemCpyDst = true;
1293       else
1294         Info.isMemCpySrc = true;
1295       return;
1296     }
1297     // This is also safe for references using a type that is compatible with
1298     // the type of the alloca, so that loads/stores can be rewritten using
1299     // insertvalue/extractvalue.
1300     if (isCompatibleAggregate(MemOpType, AI->getAllocatedType()))
1301       return;
1302   }
1303   // Check if the offset/size correspond to a component within the alloca type.
1304   const Type *T = AI->getAllocatedType();
1305   if (TypeHasComponent(T, Offset, MemSize))
1306     return;
1307
1308   return MarkUnsafe(Info);
1309 }
1310
1311 /// TypeHasComponent - Return true if T has a component type with the
1312 /// specified offset and size.  If Size is zero, do not check the size.
1313 bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1314   const Type *EltTy;
1315   uint64_t EltSize;
1316   if (const StructType *ST = dyn_cast<StructType>(T)) {
1317     const StructLayout *Layout = TD->getStructLayout(ST);
1318     unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1319     EltTy = ST->getContainedType(EltIdx);
1320     EltSize = TD->getTypeAllocSize(EltTy);
1321     Offset -= Layout->getElementOffset(EltIdx);
1322   } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1323     EltTy = AT->getElementType();
1324     EltSize = TD->getTypeAllocSize(EltTy);
1325     if (Offset >= AT->getNumElements() * EltSize)
1326       return false;
1327     Offset %= EltSize;
1328   } else {
1329     return false;
1330   }
1331   if (Offset == 0 && (Size == 0 || EltSize == Size))
1332     return true;
1333   // Check if the component spans multiple elements.
1334   if (Offset + Size > EltSize)
1335     return false;
1336   return TypeHasComponent(EltTy, Offset, Size);
1337 }
1338
1339 /// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1340 /// the instruction I, which references it, to use the separate elements.
1341 /// Offset indicates the position within AI that is referenced by this
1342 /// instruction.
1343 void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1344                                 SmallVector<AllocaInst*, 32> &NewElts) {
1345   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1346     Instruction *User = cast<Instruction>(*UI);
1347
1348     if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1349       RewriteBitCast(BC, AI, Offset, NewElts);
1350     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1351       RewriteGEP(GEPI, AI, Offset, NewElts);
1352     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1353       ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1354       uint64_t MemSize = Length->getZExtValue();
1355       if (Offset == 0 &&
1356           MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1357         RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
1358       // Otherwise the intrinsic can only touch a single element and the
1359       // address operand will be updated, so nothing else needs to be done.
1360     } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1361       const Type *LIType = LI->getType();
1362       if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
1363         // Replace:
1364         //   %res = load { i32, i32 }* %alloc
1365         // with:
1366         //   %load.0 = load i32* %alloc.0
1367         //   %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1368         //   %load.1 = load i32* %alloc.1
1369         //   %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1370         // (Also works for arrays instead of structs)
1371         Value *Insert = UndefValue::get(LIType);
1372         for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1373           Value *Load = new LoadInst(NewElts[i], "load", LI);
1374           Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1375         }
1376         LI->replaceAllUsesWith(Insert);
1377         DeadInsts.push_back(LI);
1378       } else if (LIType->isIntegerTy() &&
1379                  TD->getTypeAllocSize(LIType) ==
1380                  TD->getTypeAllocSize(AI->getAllocatedType())) {
1381         // If this is a load of the entire alloca to an integer, rewrite it.
1382         RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1383       }
1384     } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1385       Value *Val = SI->getOperand(0);
1386       const Type *SIType = Val->getType();
1387       if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
1388         // Replace:
1389         //   store { i32, i32 } %val, { i32, i32 }* %alloc
1390         // with:
1391         //   %val.0 = extractvalue { i32, i32 } %val, 0
1392         //   store i32 %val.0, i32* %alloc.0
1393         //   %val.1 = extractvalue { i32, i32 } %val, 1
1394         //   store i32 %val.1, i32* %alloc.1
1395         // (Also works for arrays instead of structs)
1396         for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1397           Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1398           new StoreInst(Extract, NewElts[i], SI);
1399         }
1400         DeadInsts.push_back(SI);
1401       } else if (SIType->isIntegerTy() &&
1402                  TD->getTypeAllocSize(SIType) ==
1403                  TD->getTypeAllocSize(AI->getAllocatedType())) {
1404         // If this is a store of the entire alloca from an integer, rewrite it.
1405         RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1406       }
1407     }
1408   }
1409 }
1410
1411 /// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1412 /// and recursively continue updating all of its uses.
1413 void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1414                           SmallVector<AllocaInst*, 32> &NewElts) {
1415   RewriteForScalarRepl(BC, AI, Offset, NewElts);
1416   if (BC->getOperand(0) != AI)
1417     return;
1418
1419   // The bitcast references the original alloca.  Replace its uses with
1420   // references to the first new element alloca.
1421   Instruction *Val = NewElts[0];
1422   if (Val->getType() != BC->getDestTy()) {
1423     Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1424     Val->takeName(BC);
1425   }
1426   BC->replaceAllUsesWith(Val);
1427   DeadInsts.push_back(BC);
1428 }
1429
1430 /// FindElementAndOffset - Return the index of the element containing Offset
1431 /// within the specified type, which must be either a struct or an array.
1432 /// Sets T to the type of the element and Offset to the offset within that
1433 /// element.  IdxTy is set to the type of the index result to be used in a
1434 /// GEP instruction.
1435 uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1436                                     const Type *&IdxTy) {
1437   uint64_t Idx = 0;
1438   if (const StructType *ST = dyn_cast<StructType>(T)) {
1439     const StructLayout *Layout = TD->getStructLayout(ST);
1440     Idx = Layout->getElementContainingOffset(Offset);
1441     T = ST->getContainedType(Idx);
1442     Offset -= Layout->getElementOffset(Idx);
1443     IdxTy = Type::getInt32Ty(T->getContext());
1444     return Idx;
1445   }
1446   const ArrayType *AT = cast<ArrayType>(T);
1447   T = AT->getElementType();
1448   uint64_t EltSize = TD->getTypeAllocSize(T);
1449   Idx = Offset / EltSize;
1450   Offset -= Idx * EltSize;
1451   IdxTy = Type::getInt64Ty(T->getContext());
1452   return Idx;
1453 }
1454
1455 /// RewriteGEP - Check if this GEP instruction moves the pointer across
1456 /// elements of the alloca that are being split apart, and if so, rewrite
1457 /// the GEP to be relative to the new element.
1458 void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1459                       SmallVector<AllocaInst*, 32> &NewElts) {
1460   uint64_t OldOffset = Offset;
1461   SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1462   Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1463                                  &Indices[0], Indices.size());
1464
1465   RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1466
1467   const Type *T = AI->getAllocatedType();
1468   const Type *IdxTy;
1469   uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
1470   if (GEPI->getOperand(0) == AI)
1471     OldIdx = ~0ULL; // Force the GEP to be rewritten.
1472
1473   T = AI->getAllocatedType();
1474   uint64_t EltOffset = Offset;
1475   uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
1476
1477   // If this GEP does not move the pointer across elements of the alloca
1478   // being split, then it does not needs to be rewritten.
1479   if (Idx == OldIdx)
1480     return;
1481
1482   const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1483   SmallVector<Value*, 8> NewArgs;
1484   NewArgs.push_back(Constant::getNullValue(i32Ty));
1485   while (EltOffset != 0) {
1486     uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1487     NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
1488   }
1489   Instruction *Val = NewElts[Idx];
1490   if (NewArgs.size() > 1) {
1491     Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1492                                             NewArgs.end(), "", GEPI);
1493     Val->takeName(GEPI);
1494   }
1495   if (Val->getType() != GEPI->getType())
1496     Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
1497   GEPI->replaceAllUsesWith(Val);
1498   DeadInsts.push_back(GEPI);
1499 }
1500
1501 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1502 /// Rewrite it to copy or set the elements of the scalarized memory.
1503 void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
1504                                         AllocaInst *AI,
1505                                         SmallVector<AllocaInst*, 32> &NewElts) {
1506   // If this is a memcpy/memmove, construct the other pointer as the
1507   // appropriate type.  The "Other" pointer is the pointer that goes to memory
1508   // that doesn't have anything to do with the alloca that we are promoting. For
1509   // memset, this Value* stays null.
1510   Value *OtherPtr = 0;
1511   unsigned MemAlignment = MI->getAlignment();
1512   if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
1513     if (Inst == MTI->getRawDest())
1514       OtherPtr = MTI->getRawSource();
1515     else {
1516       assert(Inst == MTI->getRawSource());
1517       OtherPtr = MTI->getRawDest();
1518     }
1519   }
1520
1521   // If there is an other pointer, we want to convert it to the same pointer
1522   // type as AI has, so we can GEP through it safely.
1523   if (OtherPtr) {
1524     unsigned AddrSpace =
1525       cast<PointerType>(OtherPtr->getType())->getAddressSpace();
1526
1527     // Remove bitcasts and all-zero GEPs from OtherPtr.  This is an
1528     // optimization, but it's also required to detect the corner case where
1529     // both pointer operands are referencing the same memory, and where
1530     // OtherPtr may be a bitcast or GEP that currently being rewritten.  (This
1531     // function is only called for mem intrinsics that access the whole
1532     // aggregate, so non-zero GEPs are not an issue here.)
1533     OtherPtr = OtherPtr->stripPointerCasts();
1534
1535     // Copying the alloca to itself is a no-op: just delete it.
1536     if (OtherPtr == AI || OtherPtr == NewElts[0]) {
1537       // This code will run twice for a no-op memcpy -- once for each operand.
1538       // Put only one reference to MI on the DeadInsts list.
1539       for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
1540              E = DeadInsts.end(); I != E; ++I)
1541         if (*I == MI) return;
1542       DeadInsts.push_back(MI);
1543       return;
1544     }
1545
1546     // If the pointer is not the right type, insert a bitcast to the right
1547     // type.
1548     const Type *NewTy =
1549       PointerType::get(AI->getType()->getElementType(), AddrSpace);
1550
1551     if (OtherPtr->getType() != NewTy)
1552       OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
1553   }
1554
1555   // Process each element of the aggregate.
1556   bool SROADest = MI->getRawDest() == Inst;
1557
1558   Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
1559
1560   for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1561     // If this is a memcpy/memmove, emit a GEP of the other element address.
1562     Value *OtherElt = 0;
1563     unsigned OtherEltAlign = MemAlignment;
1564
1565     if (OtherPtr) {
1566       Value *Idx[2] = { Zero,
1567                       ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
1568       OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
1569                                               OtherPtr->getName()+"."+Twine(i),
1570                                                    MI);
1571       uint64_t EltOffset;
1572       const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
1573       const Type *OtherTy = OtherPtrTy->getElementType();
1574       if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
1575         EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
1576       } else {
1577         const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
1578         EltOffset = TD->getTypeAllocSize(EltTy)*i;
1579       }
1580
1581       // The alignment of the other pointer is the guaranteed alignment of the
1582       // element, which is affected by both the known alignment of the whole
1583       // mem intrinsic and the alignment of the element.  If the alignment of
1584       // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
1585       // known alignment is just 4 bytes.
1586       OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
1587     }
1588
1589     Value *EltPtr = NewElts[i];
1590     const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
1591
1592     // If we got down to a scalar, insert a load or store as appropriate.
1593     if (EltTy->isSingleValueType()) {
1594       if (isa<MemTransferInst>(MI)) {
1595         if (SROADest) {
1596           // From Other to Alloca.
1597           Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
1598           new StoreInst(Elt, EltPtr, MI);
1599         } else {
1600           // From Alloca to Other.
1601           Value *Elt = new LoadInst(EltPtr, "tmp", MI);
1602           new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
1603         }
1604         continue;
1605       }
1606       assert(isa<MemSetInst>(MI));
1607
1608       // If the stored element is zero (common case), just store a null
1609       // constant.
1610       Constant *StoreVal;
1611       if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
1612         if (CI->isZero()) {
1613           StoreVal = Constant::getNullValue(EltTy);  // 0.0, null, 0, <0,0>
1614         } else {
1615           // If EltTy is a vector type, get the element type.
1616           const Type *ValTy = EltTy->getScalarType();
1617
1618           // Construct an integer with the right value.
1619           unsigned EltSize = TD->getTypeSizeInBits(ValTy);
1620           APInt OneVal(EltSize, CI->getZExtValue());
1621           APInt TotalVal(OneVal);
1622           // Set each byte.
1623           for (unsigned i = 0; 8*i < EltSize; ++i) {
1624             TotalVal = TotalVal.shl(8);
1625             TotalVal |= OneVal;
1626           }
1627
1628           // Convert the integer value to the appropriate type.
1629           StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
1630           if (ValTy->isPointerTy())
1631             StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
1632           else if (ValTy->isFloatingPointTy())
1633             StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
1634           assert(StoreVal->getType() == ValTy && "Type mismatch!");
1635
1636           // If the requested value was a vector constant, create it.
1637           if (EltTy != ValTy) {
1638             unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
1639             SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
1640             StoreVal = ConstantVector::get(&Elts[0], NumElts);
1641           }
1642         }
1643         new StoreInst(StoreVal, EltPtr, MI);
1644         continue;
1645       }
1646       // Otherwise, if we're storing a byte variable, use a memset call for
1647       // this element.
1648     }
1649
1650     unsigned EltSize = TD->getTypeAllocSize(EltTy);
1651
1652     IRBuilder<> Builder(MI);
1653
1654     // Finally, insert the meminst for this element.
1655     if (isa<MemSetInst>(MI)) {
1656       Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
1657                            MI->isVolatile());
1658     } else {
1659       assert(isa<MemTransferInst>(MI));
1660       Value *Dst = SROADest ? EltPtr : OtherElt;  // Dest ptr
1661       Value *Src = SROADest ? OtherElt : EltPtr;  // Src ptr
1662
1663       if (isa<MemCpyInst>(MI))
1664         Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
1665       else
1666         Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
1667     }
1668   }
1669   DeadInsts.push_back(MI);
1670 }
1671
1672 /// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
1673 /// overwrites the entire allocation.  Extract out the pieces of the stored
1674 /// integer and store them individually.
1675 void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
1676                                          SmallVector<AllocaInst*, 32> &NewElts){
1677   // Extract each element out of the integer according to its structure offset
1678   // and store the element value to the individual alloca.
1679   Value *SrcVal = SI->getOperand(0);
1680   const Type *AllocaEltTy = AI->getAllocatedType();
1681   uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
1682
1683   // Handle tail padding by extending the operand
1684   if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
1685     SrcVal = new ZExtInst(SrcVal,
1686                           IntegerType::get(SI->getContext(), AllocaSizeBits),
1687                           "", SI);
1688
1689   DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
1690                << '\n');
1691
1692   // There are two forms here: AI could be an array or struct.  Both cases
1693   // have different ways to compute the element offset.
1694   if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1695     const StructLayout *Layout = TD->getStructLayout(EltSTy);
1696
1697     for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1698       // Get the number of bits to shift SrcVal to get the value.
1699       const Type *FieldTy = EltSTy->getElementType(i);
1700       uint64_t Shift = Layout->getElementOffsetInBits(i);
1701
1702       if (TD->isBigEndian())
1703         Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
1704
1705       Value *EltVal = SrcVal;
1706       if (Shift) {
1707         Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
1708         EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1709                                             "sroa.store.elt", SI);
1710       }
1711
1712       // Truncate down to an integer of the right size.
1713       uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1714
1715       // Ignore zero sized fields like {}, they obviously contain no data.
1716       if (FieldSizeBits == 0) continue;
1717
1718       if (FieldSizeBits != AllocaSizeBits)
1719         EltVal = new TruncInst(EltVal,
1720                              IntegerType::get(SI->getContext(), FieldSizeBits),
1721                               "", SI);
1722       Value *DestField = NewElts[i];
1723       if (EltVal->getType() == FieldTy) {
1724         // Storing to an integer field of this size, just do it.
1725       } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
1726         // Bitcast to the right element type (for fp/vector values).
1727         EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
1728       } else {
1729         // Otherwise, bitcast the dest pointer (for aggregates).
1730         DestField = new BitCastInst(DestField,
1731                               PointerType::getUnqual(EltVal->getType()),
1732                                     "", SI);
1733       }
1734       new StoreInst(EltVal, DestField, SI);
1735     }
1736
1737   } else {
1738     const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1739     const Type *ArrayEltTy = ATy->getElementType();
1740     uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
1741     uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1742
1743     uint64_t Shift;
1744
1745     if (TD->isBigEndian())
1746       Shift = AllocaSizeBits-ElementOffset;
1747     else
1748       Shift = 0;
1749
1750     for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1751       // Ignore zero sized fields like {}, they obviously contain no data.
1752       if (ElementSizeBits == 0) continue;
1753
1754       Value *EltVal = SrcVal;
1755       if (Shift) {
1756         Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
1757         EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1758                                             "sroa.store.elt", SI);
1759       }
1760
1761       // Truncate down to an integer of the right size.
1762       if (ElementSizeBits != AllocaSizeBits)
1763         EltVal = new TruncInst(EltVal,
1764                                IntegerType::get(SI->getContext(),
1765                                                 ElementSizeBits), "", SI);
1766       Value *DestField = NewElts[i];
1767       if (EltVal->getType() == ArrayEltTy) {
1768         // Storing to an integer field of this size, just do it.
1769       } else if (ArrayEltTy->isFloatingPointTy() ||
1770                  ArrayEltTy->isVectorTy()) {
1771         // Bitcast to the right element type (for fp/vector values).
1772         EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1773       } else {
1774         // Otherwise, bitcast the dest pointer (for aggregates).
1775         DestField = new BitCastInst(DestField,
1776                               PointerType::getUnqual(EltVal->getType()),
1777                                     "", SI);
1778       }
1779       new StoreInst(EltVal, DestField, SI);
1780
1781       if (TD->isBigEndian())
1782         Shift -= ElementOffset;
1783       else
1784         Shift += ElementOffset;
1785     }
1786   }
1787
1788   DeadInsts.push_back(SI);
1789 }
1790
1791 /// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
1792 /// an integer.  Load the individual pieces to form the aggregate value.
1793 void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
1794                                         SmallVector<AllocaInst*, 32> &NewElts) {
1795   // Extract each element out of the NewElts according to its structure offset
1796   // and form the result value.
1797   const Type *AllocaEltTy = AI->getAllocatedType();
1798   uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
1799
1800   DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
1801                << '\n');
1802
1803   // There are two forms here: AI could be an array or struct.  Both cases
1804   // have different ways to compute the element offset.
1805   const StructLayout *Layout = 0;
1806   uint64_t ArrayEltBitOffset = 0;
1807   if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1808     Layout = TD->getStructLayout(EltSTy);
1809   } else {
1810     const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
1811     ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
1812   }
1813
1814   Value *ResultVal =
1815     Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
1816
1817   for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1818     // Load the value from the alloca.  If the NewElt is an aggregate, cast
1819     // the pointer to an integer of the same size before doing the load.
1820     Value *SrcField = NewElts[i];
1821     const Type *FieldTy =
1822       cast<PointerType>(SrcField->getType())->getElementType();
1823     uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1824
1825     // Ignore zero sized fields like {}, they obviously contain no data.
1826     if (FieldSizeBits == 0) continue;
1827
1828     const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1829                                                      FieldSizeBits);
1830     if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
1831         !FieldTy->isVectorTy())
1832       SrcField = new BitCastInst(SrcField,
1833                                  PointerType::getUnqual(FieldIntTy),
1834                                  "", LI);
1835     SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1836
1837     // If SrcField is a fp or vector of the right size but that isn't an
1838     // integer type, bitcast to an integer so we can shift it.
1839     if (SrcField->getType() != FieldIntTy)
1840       SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1841
1842     // Zero extend the field to be the same size as the final alloca so that
1843     // we can shift and insert it.
1844     if (SrcField->getType() != ResultVal->getType())
1845       SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1846
1847     // Determine the number of bits to shift SrcField.
1848     uint64_t Shift;
1849     if (Layout) // Struct case.
1850       Shift = Layout->getElementOffsetInBits(i);
1851     else  // Array case.
1852       Shift = i*ArrayEltBitOffset;
1853
1854     if (TD->isBigEndian())
1855       Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1856
1857     if (Shift) {
1858       Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
1859       SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1860     }
1861
1862     // Don't create an 'or x, 0' on the first iteration.
1863     if (!isa<Constant>(ResultVal) ||
1864         !cast<Constant>(ResultVal)->isNullValue())
1865       ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1866     else
1867       ResultVal = SrcField;
1868   }
1869
1870   // Handle tail padding by truncating the result
1871   if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1872     ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1873
1874   LI->replaceAllUsesWith(ResultVal);
1875   DeadInsts.push_back(LI);
1876 }
1877
1878 /// HasPadding - Return true if the specified type has any structure or
1879 /// alignment padding in between the elements that would be split apart
1880 /// by SROA; return false otherwise.
1881 static bool HasPadding(const Type *Ty, const TargetData &TD) {
1882   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1883     Ty = ATy->getElementType();
1884     return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
1885   }
1886
1887   // SROA currently handles only Arrays and Structs.
1888   const StructType *STy = cast<StructType>(Ty);
1889   const StructLayout *SL = TD.getStructLayout(STy);
1890   unsigned PrevFieldBitOffset = 0;
1891   for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1892     unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1893
1894     // Check to see if there is any padding between this element and the
1895     // previous one.
1896     if (i) {
1897       unsigned PrevFieldEnd =
1898         PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1899       if (PrevFieldEnd < FieldBitOffset)
1900         return true;
1901     }
1902     PrevFieldBitOffset = FieldBitOffset;
1903   }
1904   // Check for tail padding.
1905   if (unsigned EltCount = STy->getNumElements()) {
1906     unsigned PrevFieldEnd = PrevFieldBitOffset +
1907       TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
1908     if (PrevFieldEnd < SL->getSizeInBits())
1909       return true;
1910   }
1911   return false;
1912 }
1913
1914 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1915 /// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
1916 /// or 1 if safe after canonicalization has been performed.
1917 bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
1918   // Loop over the use list of the alloca.  We can only transform it if all of
1919   // the users are safe to transform.
1920   AllocaInfo Info;
1921
1922   isSafeForScalarRepl(AI, AI, 0, Info);
1923   if (Info.isUnsafe) {
1924     DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
1925     return false;
1926   }
1927
1928   // Okay, we know all the users are promotable.  If the aggregate is a memcpy
1929   // source and destination, we have to be careful.  In particular, the memcpy
1930   // could be moving around elements that live in structure padding of the LLVM
1931   // types, but may actually be used.  In these cases, we refuse to promote the
1932   // struct.
1933   if (Info.isMemCpySrc && Info.isMemCpyDst &&
1934       HasPadding(AI->getAllocatedType(), *TD))
1935     return false;
1936
1937   return true;
1938 }
1939
1940
1941
1942 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1943 /// some part of a constant global variable.  This intentionally only accepts
1944 /// constant expressions because we don't can't rewrite arbitrary instructions.
1945 static bool PointsToConstantGlobal(Value *V) {
1946   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1947     return GV->isConstant();
1948   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1949     if (CE->getOpcode() == Instruction::BitCast ||
1950         CE->getOpcode() == Instruction::GetElementPtr)
1951       return PointsToConstantGlobal(CE->getOperand(0));
1952   return false;
1953 }
1954
1955 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1956 /// pointer to an alloca.  Ignore any reads of the pointer, return false if we
1957 /// see any stores or other unknown uses.  If we see pointer arithmetic, keep
1958 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
1959 /// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
1960 /// the alloca, and if the source pointer is a pointer to a constant global, we
1961 /// can optimize this.
1962 static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
1963                                            bool isOffset) {
1964   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1965     User *U = cast<Instruction>(*UI);
1966
1967     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1968       // Ignore non-volatile loads, they are always ok.
1969       if (LI->isVolatile()) return false;
1970       continue;
1971     }
1972
1973     if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1974       // If uses of the bitcast are ok, we are ok.
1975       if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1976         return false;
1977       continue;
1978     }
1979     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
1980       // If the GEP has all zero indices, it doesn't offset the pointer.  If it
1981       // doesn't, it does.
1982       if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1983                                          isOffset || !GEP->hasAllZeroIndices()))
1984         return false;
1985       continue;
1986     }
1987
1988     if (CallSite CS = U) {
1989       // If this is a readonly/readnone call site, then we know it is just a
1990       // load and we can ignore it.
1991       if (CS.onlyReadsMemory())
1992         continue;
1993
1994       // If this is the function being called then we treat it like a load and
1995       // ignore it.
1996       if (CS.isCallee(UI))
1997         continue;
1998
1999       // If this is being passed as a byval argument, the caller is making a
2000       // copy, so it is only a read of the alloca.
2001       unsigned ArgNo = CS.getArgumentNo(UI);
2002       if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
2003         continue;
2004     }
2005
2006     // If this is isn't our memcpy/memmove, reject it as something we can't
2007     // handle.
2008     MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2009     if (MI == 0)
2010       return false;
2011
2012     // If the transfer is using the alloca as a source of the transfer, then
2013     // ignore it since it is a load (unless the transfer is volatile).
2014     if (UI.getOperandNo() == 1) {
2015       if (MI->isVolatile()) return false;
2016       continue;
2017     }
2018
2019     // If we already have seen a copy, reject the second one.
2020     if (TheCopy) return false;
2021
2022     // If the pointer has been offset from the start of the alloca, we can't
2023     // safely handle this.
2024     if (isOffset) return false;
2025
2026     // If the memintrinsic isn't using the alloca as the dest, reject it.
2027     if (UI.getOperandNo() != 0) return false;
2028
2029     // If the source of the memcpy/move is not a constant global, reject it.
2030     if (!PointsToConstantGlobal(MI->getSource()))
2031       return false;
2032
2033     // Otherwise, the transform is safe.  Remember the copy instruction.
2034     TheCopy = MI;
2035   }
2036   return true;
2037 }
2038
2039 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2040 /// modified by a copy from a constant global.  If we can prove this, we can
2041 /// replace any uses of the alloca with uses of the global directly.
2042 MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
2043   MemTransferInst *TheCopy = 0;
2044   if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
2045     return TheCopy;
2046   return 0;
2047 }