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