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