5f8ab517df9927552c1c59a232eac5fca609949a
[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/Dominators.h"
34 #include "llvm/Analysis/Loads.h"
35 #include "llvm/Analysis/ValueTracking.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 #include "llvm/Transforms/Utils/SSAUpdater.h"
40 #include "llvm/Support/CallSite.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/GetElementPtrTypeIterator.h"
44 #include "llvm/Support/IRBuilder.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/ADT/SetVector.h"
48 #include "llvm/ADT/SmallVector.h"
49 #include "llvm/ADT/Statistic.h"
50 using namespace llvm;
51
52 STATISTIC(NumReplaced,  "Number of allocas broken up");
53 STATISTIC(NumPromoted,  "Number of allocas promoted");
54 STATISTIC(NumAdjusted,  "Number of scalar allocas adjusted to allow promotion");
55 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
56 STATISTIC(NumGlobals,   "Number of allocas copied from constant global");
57
58 namespace {
59   struct SROA : public FunctionPass {
60     SROA(int T, bool hasDT, char &ID)
61       : FunctionPass(ID), HasDomTree(hasDT) {
62       if (T == -1)
63         SRThreshold = 128;
64       else
65         SRThreshold = T;
66     }
67
68     bool runOnFunction(Function &F);
69
70     bool performScalarRepl(Function &F);
71     bool performPromotion(Function &F);
72
73   private:
74     bool HasDomTree;
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       /// The alloca to promote.
86       AllocaInst *AI;
87       
88       /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
89       /// looping and avoid redundant work.
90       SmallPtrSet<PHINode*, 8> CheckedPHIs;
91       
92       /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
93       bool isUnsafe : 1;
94
95       /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
96       bool isMemCpySrc : 1;
97
98       /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
99       bool isMemCpyDst : 1;
100
101       /// hasSubelementAccess - This is true if a subelement of the alloca is
102       /// ever accessed, or false if the alloca is only accessed with mem
103       /// intrinsics or load/store that only access the entire alloca at once.
104       bool hasSubelementAccess : 1;
105       
106       /// hasALoadOrStore - This is true if there are any loads or stores to it.
107       /// The alloca may just be accessed with memcpy, for example, which would
108       /// not set this.
109       bool hasALoadOrStore : 1;
110       
111       explicit AllocaInfo(AllocaInst *ai)
112         : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
113           hasSubelementAccess(false), hasALoadOrStore(false) {}
114     };
115
116     unsigned SRThreshold;
117
118     void MarkUnsafe(AllocaInfo &I, Instruction *User) {
119       I.isUnsafe = true;
120       DEBUG(dbgs() << "  Transformation preventing inst: " << *User << '\n');
121     }
122
123     bool isSafeAllocaToScalarRepl(AllocaInst *AI);
124
125     void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
126     void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
127                                          AllocaInfo &Info);
128     void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
129     void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
130                          const Type *MemOpType, bool isStore, AllocaInfo &Info,
131                          Instruction *TheAccess, bool AllowWholeAccess);
132     bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
133     uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
134                                   const Type *&IdxTy);
135
136     void DoScalarReplacement(AllocaInst *AI,
137                              std::vector<AllocaInst*> &WorkList);
138     void DeleteDeadInstructions();
139
140     void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
141                               SmallVector<AllocaInst*, 32> &NewElts);
142     void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
143                         SmallVector<AllocaInst*, 32> &NewElts);
144     void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
145                     SmallVector<AllocaInst*, 32> &NewElts);
146     void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
147                                       AllocaInst *AI,
148                                       SmallVector<AllocaInst*, 32> &NewElts);
149     void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
150                                        SmallVector<AllocaInst*, 32> &NewElts);
151     void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
152                                       SmallVector<AllocaInst*, 32> &NewElts);
153
154     static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
155   };
156   
157   // SROA_DT - SROA that uses DominatorTree.
158   struct SROA_DT : public SROA {
159     static char ID;
160   public:
161     SROA_DT(int T = -1) : SROA(T, true, ID) {
162       initializeSROA_DTPass(*PassRegistry::getPassRegistry());
163     }
164     
165     // getAnalysisUsage - This pass does not require any passes, but we know it
166     // will not alter the CFG, so say so.
167     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
168       AU.addRequired<DominatorTree>();
169       AU.setPreservesCFG();
170     }
171   };
172   
173   // SROA_SSAUp - SROA that uses SSAUpdater.
174   struct SROA_SSAUp : public SROA {
175     static char ID;
176   public:
177     SROA_SSAUp(int T = -1) : SROA(T, false, ID) {
178       initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
179     }
180     
181     // getAnalysisUsage - This pass does not require any passes, but we know it
182     // will not alter the CFG, so say so.
183     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
184       AU.setPreservesCFG();
185     }
186   };
187   
188 }
189
190 char SROA_DT::ID = 0;
191 char SROA_SSAUp::ID = 0;
192
193 INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
194                 "Scalar Replacement of Aggregates (DT)", false, false)
195 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
196 INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
197                 "Scalar Replacement of Aggregates (DT)", false, false)
198
199 INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
200                       "Scalar Replacement of Aggregates (SSAUp)", false, false)
201 INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
202                     "Scalar Replacement of Aggregates (SSAUp)", false, false)
203
204 // Public interface to the ScalarReplAggregates pass
205 FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
206                                                    bool UseDomTree) {
207   if (UseDomTree)
208     return new SROA_DT(Threshold);
209   return new SROA_SSAUp(Threshold);
210 }
211
212
213 //===----------------------------------------------------------------------===//
214 // Convert To Scalar Optimization.
215 //===----------------------------------------------------------------------===//
216
217 namespace {
218 /// ConvertToScalarInfo - This class implements the "Convert To Scalar"
219 /// optimization, which scans the uses of an alloca and determines if it can
220 /// rewrite it in terms of a single new alloca that can be mem2reg'd.
221 class ConvertToScalarInfo {
222   /// AllocaSize - The size of the alloca being considered in bytes.
223   unsigned AllocaSize;
224   const TargetData &TD;
225
226   /// IsNotTrivial - This is set to true if there is some access to the object
227   /// which means that mem2reg can't promote it.
228   bool IsNotTrivial;
229
230   /// VectorTy - This tracks the type that we should promote the vector to if
231   /// it is possible to turn it into a vector.  This starts out null, and if it
232   /// isn't possible to turn into a vector type, it gets set to VoidTy.
233   const Type *VectorTy;
234
235   /// HadAVector - True if there is at least one vector access to the alloca.
236   /// We don't want to turn random arrays into vectors and use vector element
237   /// insert/extract, but if there are element accesses to something that is
238   /// also declared as a vector, we do want to promote to a vector.
239   bool HadAVector;
240
241   /// HadNonMemTransferAccess - True if there is at least one access to the 
242   /// alloca that is not a MemTransferInst.  We don't want to turn structs into
243   /// large integers unless there is some potential for optimization.
244   bool HadNonMemTransferAccess;
245
246 public:
247   explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
248     : AllocaSize(Size), TD(td), IsNotTrivial(false), VectorTy(0),
249       HadAVector(false), HadNonMemTransferAccess(false) { }
250
251   AllocaInst *TryConvert(AllocaInst *AI);
252
253 private:
254   bool CanConvertToScalar(Value *V, uint64_t Offset);
255   void MergeInType(const Type *In, uint64_t Offset, bool IsLoadOrStore);
256   bool MergeInVectorType(const VectorType *VInTy, uint64_t Offset);
257   void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
258
259   Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
260                                     uint64_t Offset, IRBuilder<> &Builder);
261   Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
262                                    uint64_t Offset, IRBuilder<> &Builder);
263 };
264 } // end anonymous namespace.
265
266
267 /// TryConvert - Analyze the specified alloca, and if it is safe to do so,
268 /// rewrite it to be a new alloca which is mem2reg'able.  This returns the new
269 /// alloca if possible or null if not.
270 AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
271   // If we can't convert this scalar, or if mem2reg can trivially do it, bail
272   // out.
273   if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
274     return 0;
275
276   // If we were able to find a vector type that can handle this with
277   // insert/extract elements, and if there was at least one use that had
278   // a vector type, promote this to a vector.  We don't want to promote
279   // random stuff that doesn't use vectors (e.g. <9 x double>) because then
280   // we just get a lot of insert/extracts.  If at least one vector is
281   // involved, then we probably really do have a union of vector/array.
282   const Type *NewTy;
283   if (VectorTy && VectorTy->isVectorTy() && HadAVector) {
284     DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n  TYPE = "
285           << *VectorTy << '\n');
286     NewTy = VectorTy;  // Use the vector type.
287   } else {
288     unsigned BitWidth = AllocaSize * 8;
289     if (!HadAVector && !HadNonMemTransferAccess &&
290         !TD.fitsInLegalInteger(BitWidth))
291       return 0;
292
293     DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
294     // Create and insert the integer alloca.
295     NewTy = IntegerType::get(AI->getContext(), BitWidth);
296   }
297   AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
298   ConvertUsesToScalar(AI, NewAI, 0);
299   return NewAI;
300 }
301
302 /// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
303 /// so far at the offset specified by Offset (which is specified in bytes).
304 ///
305 /// There are three cases we handle here:
306 ///   1) A union of vector types of the same size and potentially its elements.
307 ///      Here we turn element accesses into insert/extract element operations.
308 ///      This promotes a <4 x float> with a store of float to the third element
309 ///      into a <4 x float> that uses insert element.
310 ///   2) A union of vector types with power-of-2 size differences, e.g. a float,
311 ///      <2 x float> and <4 x float>.  Here we turn element accesses into insert
312 ///      and extract element operations, and <2 x float> accesses into a cast to
313 ///      <2 x double>, an extract, and a cast back to <2 x float>.
314 ///   3) A fully general blob of memory, which we turn into some (potentially
315 ///      large) integer type with extract and insert operations where the loads
316 ///      and stores would mutate the memory.  We mark this by setting VectorTy
317 ///      to VoidTy.
318 void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset,
319                                       bool IsLoadOrStore) {
320   // If we already decided to turn this into a blob of integer memory, there is
321   // nothing to be done.
322   if (VectorTy && VectorTy->isVoidTy())
323     return;
324
325   // If this could be contributing to a vector, analyze it.
326
327   // If the In type is a vector that is the same size as the alloca, see if it
328   // matches the existing VecTy.
329   if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
330     if (MergeInVectorType(VInTy, Offset))
331       return;
332   } else if (In->isFloatTy() || In->isDoubleTy() ||
333              (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
334               isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
335     // Full width accesses can be ignored, because they can always be turned
336     // into bitcasts.
337     unsigned EltSize = In->getPrimitiveSizeInBits()/8;
338     if (IsLoadOrStore && EltSize == AllocaSize)
339       return;
340
341     // If we're accessing something that could be an element of a vector, see
342     // if the implied vector agrees with what we already have and if Offset is
343     // compatible with it.
344     if (Offset % EltSize == 0 && AllocaSize % EltSize == 0) {
345       if (!VectorTy) {
346         VectorTy = VectorType::get(In, AllocaSize/EltSize);
347         return;
348       }
349
350       unsigned CurrentEltSize = cast<VectorType>(VectorTy)->getElementType()
351                                 ->getPrimitiveSizeInBits()/8;
352       if (EltSize == CurrentEltSize)
353         return;
354
355       if (In->isIntegerTy() && isPowerOf2_32(AllocaSize / EltSize))
356         return;
357     }
358   }
359
360   // Otherwise, we have a case that we can't handle with an optimized vector
361   // form.  We can still turn this into a large integer.
362   VectorTy = Type::getVoidTy(In->getContext());
363 }
364
365 /// MergeInVectorType - Handles the vector case of MergeInType, returning true
366 /// if the type was successfully merged and false otherwise.
367 bool ConvertToScalarInfo::MergeInVectorType(const VectorType *VInTy,
368                                             uint64_t Offset) {
369   // Remember if we saw a vector type.
370   HadAVector = true;
371
372   // TODO: Support nonzero offsets?
373   if (Offset != 0)
374     return false;
375
376   // Only allow vectors that are a power-of-2 away from the size of the alloca.
377   if (!isPowerOf2_64(AllocaSize / (VInTy->getBitWidth() / 8)))
378     return false;
379
380   // If this the first vector we see, remember the type so that we know the
381   // element size.
382   if (!VectorTy) {
383     VectorTy = VInTy;
384     return true;
385   }
386
387   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
388   unsigned InBitWidth = VInTy->getBitWidth();
389
390   // Vectors of the same size can be converted using a simple bitcast.
391   if (InBitWidth == BitWidth && AllocaSize == (InBitWidth / 8))
392     return true;
393
394   const Type *ElementTy = cast<VectorType>(VectorTy)->getElementType();
395   const Type *InElementTy = cast<VectorType>(VInTy)->getElementType();
396
397   // Do not allow mixed integer and floating-point accesses from vectors of
398   // different sizes.
399   if (ElementTy->isFloatingPointTy() != InElementTy->isFloatingPointTy())
400     return false;
401
402   if (ElementTy->isFloatingPointTy()) {
403     // Only allow floating-point vectors of different sizes if they have the
404     // same element type.
405     // TODO: This could be loosened a bit, but would anything benefit?
406     if (ElementTy != InElementTy)
407       return false;
408
409     // There are no arbitrary-precision floating-point types, which limits the
410     // number of legal vector types with larger element types that we can form
411     // to bitcast and extract a subvector.
412     // TODO: We could support some more cases with mixed fp128 and double here.
413     if (!(BitWidth == 64 || BitWidth == 128) ||
414         !(InBitWidth == 64 || InBitWidth == 128))
415       return false;
416   } else {
417     assert(ElementTy->isIntegerTy() && "Vector elements must be either integer "
418                                        "or floating-point.");
419     unsigned BitWidth = ElementTy->getPrimitiveSizeInBits();
420     unsigned InBitWidth = InElementTy->getPrimitiveSizeInBits();
421
422     // Do not allow integer types smaller than a byte or types whose widths are
423     // not a multiple of a byte.
424     if (BitWidth < 8 || InBitWidth < 8 ||
425         BitWidth % 8 != 0 || InBitWidth % 8 != 0)
426       return false;
427   }
428
429   // Pick the largest of the two vector types.
430   if (InBitWidth > BitWidth)
431     VectorTy = VInTy;
432
433   return true;
434 }
435
436 /// CanConvertToScalar - V is a pointer.  If we can convert the pointee and all
437 /// its accesses to a single vector type, return true and set VecTy to
438 /// the new type.  If we could convert the alloca into a single promotable
439 /// integer, return true but set VecTy to VoidTy.  Further, if the use is not a
440 /// completely trivial use that mem2reg could promote, set IsNotTrivial.  Offset
441 /// is the current offset from the base of the alloca being analyzed.
442 ///
443 /// If we see at least one access to the value that is as a vector type, set the
444 /// SawVec flag.
445 bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
446   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
447     Instruction *User = cast<Instruction>(*UI);
448
449     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
450       // Don't break volatile loads.
451       if (LI->isVolatile())
452         return false;
453       // Don't touch MMX operations.
454       if (LI->getType()->isX86_MMXTy())
455         return false;
456       HadNonMemTransferAccess = true;
457       MergeInType(LI->getType(), Offset, true);
458       continue;
459     }
460
461     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
462       // Storing the pointer, not into the value?
463       if (SI->getOperand(0) == V || SI->isVolatile()) return false;
464       // Don't touch MMX operations.
465       if (SI->getOperand(0)->getType()->isX86_MMXTy())
466         return false;
467       HadNonMemTransferAccess = true;
468       MergeInType(SI->getOperand(0)->getType(), Offset, true);
469       continue;
470     }
471
472     if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
473       IsNotTrivial = true;  // Can't be mem2reg'd.
474       if (!CanConvertToScalar(BCI, Offset))
475         return false;
476       continue;
477     }
478
479     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
480       // If this is a GEP with a variable indices, we can't handle it.
481       if (!GEP->hasAllConstantIndices())
482         return false;
483
484       // Compute the offset that this GEP adds to the pointer.
485       SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
486       uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
487                                                &Indices[0], Indices.size());
488       // See if all uses can be converted.
489       if (!CanConvertToScalar(GEP, Offset+GEPOffset))
490         return false;
491       IsNotTrivial = true;  // Can't be mem2reg'd.
492       HadNonMemTransferAccess = true;
493       continue;
494     }
495
496     // If this is a constant sized memset of a constant value (e.g. 0) we can
497     // handle it.
498     if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
499       // Store of constant value and constant size.
500       if (!isa<ConstantInt>(MSI->getValue()) ||
501           !isa<ConstantInt>(MSI->getLength()))
502         return false;
503       IsNotTrivial = true;  // Can't be mem2reg'd.
504       HadNonMemTransferAccess = true;
505       continue;
506     }
507
508     // If this is a memcpy or memmove into or out of the whole allocation, we
509     // can handle it like a load or store of the scalar type.
510     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
511       ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
512       if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
513         return false;
514
515       IsNotTrivial = true;  // Can't be mem2reg'd.
516       continue;
517     }
518
519     // Otherwise, we cannot handle this!
520     return false;
521   }
522
523   return true;
524 }
525
526 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
527 /// directly.  This happens when we are converting an "integer union" to a
528 /// single integer scalar, or when we are converting a "vector union" to a
529 /// vector with insert/extractelement instructions.
530 ///
531 /// Offset is an offset from the original alloca, in bits that need to be
532 /// shifted to the right.  By the end of this, there should be no uses of Ptr.
533 void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
534                                               uint64_t Offset) {
535   while (!Ptr->use_empty()) {
536     Instruction *User = cast<Instruction>(Ptr->use_back());
537
538     if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
539       ConvertUsesToScalar(CI, NewAI, Offset);
540       CI->eraseFromParent();
541       continue;
542     }
543
544     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
545       // Compute the offset that this GEP adds to the pointer.
546       SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
547       uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
548                                                &Indices[0], Indices.size());
549       ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
550       GEP->eraseFromParent();
551       continue;
552     }
553
554     IRBuilder<> Builder(User);
555
556     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
557       // The load is a bit extract from NewAI shifted right by Offset bits.
558       Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
559       Value *NewLoadVal
560         = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
561       LI->replaceAllUsesWith(NewLoadVal);
562       LI->eraseFromParent();
563       continue;
564     }
565
566     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
567       assert(SI->getOperand(0) != Ptr && "Consistency error!");
568       Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
569       Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
570                                              Builder);
571       Builder.CreateStore(New, NewAI);
572       SI->eraseFromParent();
573
574       // If the load we just inserted is now dead, then the inserted store
575       // overwrote the entire thing.
576       if (Old->use_empty())
577         Old->eraseFromParent();
578       continue;
579     }
580
581     // If this is a constant sized memset of a constant value (e.g. 0) we can
582     // transform it into a store of the expanded constant value.
583     if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
584       assert(MSI->getRawDest() == Ptr && "Consistency error!");
585       unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
586       if (NumBytes != 0) {
587         unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
588
589         // Compute the value replicated the right number of times.
590         APInt APVal(NumBytes*8, Val);
591
592         // Splat the value if non-zero.
593         if (Val)
594           for (unsigned i = 1; i != NumBytes; ++i)
595             APVal |= APVal << 8;
596
597         Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
598         Value *New = ConvertScalar_InsertValue(
599                                     ConstantInt::get(User->getContext(), APVal),
600                                                Old, Offset, Builder);
601         Builder.CreateStore(New, NewAI);
602
603         // If the load we just inserted is now dead, then the memset overwrote
604         // the entire thing.
605         if (Old->use_empty())
606           Old->eraseFromParent();
607       }
608       MSI->eraseFromParent();
609       continue;
610     }
611
612     // If this is a memcpy or memmove into or out of the whole allocation, we
613     // can handle it like a load or store of the scalar type.
614     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
615       assert(Offset == 0 && "must be store to start of alloca");
616
617       // If the source and destination are both to the same alloca, then this is
618       // a noop copy-to-self, just delete it.  Otherwise, emit a load and store
619       // as appropriate.
620       AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0));
621
622       if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) {
623         // Dest must be OrigAI, change this to be a load from the original
624         // pointer (bitcasted), then a store to our new alloca.
625         assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
626         Value *SrcPtr = MTI->getSource();
627         const PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
628         const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
629         if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
630           AIPTy = PointerType::get(AIPTy->getElementType(),
631                                    SPTy->getAddressSpace());
632         }
633         SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
634
635         LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
636         SrcVal->setAlignment(MTI->getAlignment());
637         Builder.CreateStore(SrcVal, NewAI);
638       } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) {
639         // Src must be OrigAI, change this to be a load from NewAI then a store
640         // through the original dest pointer (bitcasted).
641         assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
642         LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
643
644         const PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
645         const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
646         if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
647           AIPTy = PointerType::get(AIPTy->getElementType(),
648                                    DPTy->getAddressSpace());
649         }
650         Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
651
652         StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
653         NewStore->setAlignment(MTI->getAlignment());
654       } else {
655         // Noop transfer. Src == Dst
656       }
657
658       MTI->eraseFromParent();
659       continue;
660     }
661
662     llvm_unreachable("Unsupported operation!");
663   }
664 }
665
666 /// getScaledElementType - Gets a scaled element type for a partial vector
667 /// access of an alloca. The input types must be integer or floating-point
668 /// scalar or vector types, and the resulting type is an integer, float or
669 /// double.
670 static const Type *getScaledElementType(const Type *Ty1, const Type *Ty2,
671                                         unsigned NewBitWidth) {
672   bool IsFP1 = Ty1->isFloatingPointTy() ||
673                (Ty1->isVectorTy() &&
674                 cast<VectorType>(Ty1)->getElementType()->isFloatingPointTy());
675   bool IsFP2 = Ty2->isFloatingPointTy() ||
676                (Ty2->isVectorTy() &&
677                 cast<VectorType>(Ty2)->getElementType()->isFloatingPointTy());
678
679   LLVMContext &Context = Ty1->getContext();
680
681   // Prefer floating-point types over integer types, as integer types may have
682   // been created by earlier scalar replacement.
683   if (IsFP1 || IsFP2) {
684     if (NewBitWidth == 32)
685       return Type::getFloatTy(Context);
686     if (NewBitWidth == 64)
687       return Type::getDoubleTy(Context);
688   }
689
690   return Type::getIntNTy(Context, NewBitWidth);
691 }
692
693 /// CreateShuffleVectorCast - Creates a shuffle vector to convert one vector
694 /// to another vector of the same element type which has the same allocation
695 /// size but different primitive sizes (e.g. <3 x i32> and <4 x i32>).
696 static Value *CreateShuffleVectorCast(Value *FromVal, const Type *ToType,
697                                       IRBuilder<> &Builder) {
698   const Type *FromType = FromVal->getType();
699   const VectorType *FromVTy = cast<VectorType>(FromType);
700   const VectorType *ToVTy = cast<VectorType>(ToType);
701   assert((ToVTy->getElementType() == FromVTy->getElementType()) &&
702          "Vectors must have the same element type");
703    Value *UnV = UndefValue::get(FromType);
704    unsigned numEltsFrom = FromVTy->getNumElements();
705    unsigned numEltsTo = ToVTy->getNumElements();
706
707    SmallVector<Constant*, 3> Args;
708    const Type* Int32Ty = Builder.getInt32Ty();
709    unsigned minNumElts = std::min(numEltsFrom, numEltsTo);
710    unsigned i;
711    for (i=0; i != minNumElts; ++i)
712      Args.push_back(ConstantInt::get(Int32Ty, i));
713
714    if (i < numEltsTo) {
715      Constant* UnC = UndefValue::get(Int32Ty);
716      for (; i != numEltsTo; ++i)
717        Args.push_back(UnC);
718    }
719    Constant *Mask = ConstantVector::get(Args);
720    return Builder.CreateShuffleVector(FromVal, UnV, Mask, "tmpV");
721 }
722
723 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
724 /// or vector value FromVal, extracting the bits from the offset specified by
725 /// Offset.  This returns the value, which is of type ToType.
726 ///
727 /// This happens when we are converting an "integer union" to a single
728 /// integer scalar, or when we are converting a "vector union" to a vector with
729 /// insert/extractelement instructions.
730 ///
731 /// Offset is an offset from the original alloca, in bits that need to be
732 /// shifted to the right.
733 Value *ConvertToScalarInfo::
734 ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
735                            uint64_t Offset, IRBuilder<> &Builder) {
736   // If the load is of the whole new alloca, no conversion is needed.
737   const Type *FromType = FromVal->getType();
738   if (FromType == ToType && Offset == 0)
739     return FromVal;
740
741   // If the result alloca is a vector type, this is either an element
742   // access or a bitcast to another vector type of the same size.
743   if (const VectorType *VTy = dyn_cast<VectorType>(FromType)) {
744     unsigned ToTypeSize = TD.getTypeAllocSize(ToType);
745     if (ToTypeSize == AllocaSize) {
746       // If the two types have the same primitive size, use a bit cast.
747       // Otherwise, it is two vectors with the same element type that has
748       // the same allocation size but different number of elements so use
749       // a shuffle vector.
750       if (FromType->getPrimitiveSizeInBits() ==
751           ToType->getPrimitiveSizeInBits())
752         return Builder.CreateBitCast(FromVal, ToType, "tmp");
753       else
754         return CreateShuffleVectorCast(FromVal, ToType, Builder);
755     }
756
757     if (isPowerOf2_64(AllocaSize / ToTypeSize)) {
758       assert(!(ToType->isVectorTy() && Offset != 0) && "Can't extract a value "
759              "of a smaller vector type at a nonzero offset.");
760
761       const Type *CastElementTy = getScaledElementType(FromType, ToType,
762                                                        ToTypeSize * 8);
763       unsigned NumCastVectorElements = AllocaSize / ToTypeSize;
764
765       LLVMContext &Context = FromVal->getContext();
766       const Type *CastTy = VectorType::get(CastElementTy,
767                                            NumCastVectorElements);
768       Value *Cast = Builder.CreateBitCast(FromVal, CastTy, "tmp");
769
770       unsigned EltSize = TD.getTypeAllocSizeInBits(CastElementTy);
771       unsigned Elt = Offset/EltSize;
772       assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
773       Value *Extract = Builder.CreateExtractElement(Cast, ConstantInt::get(
774                                         Type::getInt32Ty(Context), Elt), "tmp");
775       return Builder.CreateBitCast(Extract, ToType, "tmp");
776     }
777
778     // Otherwise it must be an element access.
779     unsigned Elt = 0;
780     if (Offset) {
781       unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
782       Elt = Offset/EltSize;
783       assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
784     }
785     // Return the element extracted out of it.
786     Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
787                     Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
788     if (V->getType() != ToType)
789       V = Builder.CreateBitCast(V, ToType, "tmp");
790     return V;
791   }
792
793   // If ToType is a first class aggregate, extract out each of the pieces and
794   // use insertvalue's to form the FCA.
795   if (const StructType *ST = dyn_cast<StructType>(ToType)) {
796     const StructLayout &Layout = *TD.getStructLayout(ST);
797     Value *Res = UndefValue::get(ST);
798     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
799       Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
800                                         Offset+Layout.getElementOffsetInBits(i),
801                                               Builder);
802       Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
803     }
804     return Res;
805   }
806
807   if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
808     uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
809     Value *Res = UndefValue::get(AT);
810     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
811       Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
812                                               Offset+i*EltSize, Builder);
813       Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
814     }
815     return Res;
816   }
817
818   // Otherwise, this must be a union that was converted to an integer value.
819   const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
820
821   // If this is a big-endian system and the load is narrower than the
822   // full alloca type, we need to do a shift to get the right bits.
823   int ShAmt = 0;
824   if (TD.isBigEndian()) {
825     // On big-endian machines, the lowest bit is stored at the bit offset
826     // from the pointer given by getTypeStoreSizeInBits.  This matters for
827     // integers with a bitwidth that is not a multiple of 8.
828     ShAmt = TD.getTypeStoreSizeInBits(NTy) -
829             TD.getTypeStoreSizeInBits(ToType) - Offset;
830   } else {
831     ShAmt = Offset;
832   }
833
834   // Note: we support negative bitwidths (with shl) which are not defined.
835   // We do this to support (f.e.) loads off the end of a structure where
836   // only some bits are used.
837   if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
838     FromVal = Builder.CreateLShr(FromVal,
839                                  ConstantInt::get(FromVal->getType(),
840                                                            ShAmt), "tmp");
841   else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
842     FromVal = Builder.CreateShl(FromVal,
843                                 ConstantInt::get(FromVal->getType(),
844                                                           -ShAmt), "tmp");
845
846   // Finally, unconditionally truncate the integer to the right width.
847   unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
848   if (LIBitWidth < NTy->getBitWidth())
849     FromVal =
850       Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
851                                                     LIBitWidth), "tmp");
852   else if (LIBitWidth > NTy->getBitWidth())
853     FromVal =
854        Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
855                                                     LIBitWidth), "tmp");
856
857   // If the result is an integer, this is a trunc or bitcast.
858   if (ToType->isIntegerTy()) {
859     // Should be done.
860   } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
861     // Just do a bitcast, we know the sizes match up.
862     FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
863   } else {
864     // Otherwise must be a pointer.
865     FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
866   }
867   assert(FromVal->getType() == ToType && "Didn't convert right?");
868   return FromVal;
869 }
870
871 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
872 /// or vector value "Old" at the offset specified by Offset.
873 ///
874 /// This happens when we are converting an "integer union" to a
875 /// single integer scalar, or when we are converting a "vector union" to a
876 /// vector with insert/extractelement instructions.
877 ///
878 /// Offset is an offset from the original alloca, in bits that need to be
879 /// shifted to the right.
880 Value *ConvertToScalarInfo::
881 ConvertScalar_InsertValue(Value *SV, Value *Old,
882                           uint64_t Offset, IRBuilder<> &Builder) {
883   // Convert the stored type to the actual type, shift it left to insert
884   // then 'or' into place.
885   const Type *AllocaType = Old->getType();
886   LLVMContext &Context = Old->getContext();
887
888   if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
889     uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
890     uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
891
892     // Changing the whole vector with memset or with an access of a different
893     // vector type?
894     if (ValSize == VecSize) {
895       // If the two types have the same primitive size, use a bit cast.
896       // Otherwise, it is two vectors with the same element type that has
897       // the same allocation size but different number of elements so use
898       // a shuffle vector.
899       if (VTy->getPrimitiveSizeInBits() ==
900           SV->getType()->getPrimitiveSizeInBits())
901         return Builder.CreateBitCast(SV, AllocaType, "tmp");
902       else
903         return CreateShuffleVectorCast(SV, VTy, Builder);
904     }
905
906     if (isPowerOf2_64(VecSize / ValSize)) {
907       assert(!(SV->getType()->isVectorTy() && Offset != 0) && "Can't insert a "
908              "value of a smaller vector type at a nonzero offset.");
909
910       const Type *CastElementTy = getScaledElementType(VTy, SV->getType(),
911                                                        ValSize);
912       unsigned NumCastVectorElements = VecSize / ValSize;
913
914       LLVMContext &Context = SV->getContext();
915       const Type *OldCastTy = VectorType::get(CastElementTy,
916                                               NumCastVectorElements);
917       Value *OldCast = Builder.CreateBitCast(Old, OldCastTy, "tmp");
918
919       Value *SVCast = Builder.CreateBitCast(SV, CastElementTy, "tmp");
920
921       unsigned EltSize = TD.getTypeAllocSizeInBits(CastElementTy);
922       unsigned Elt = Offset/EltSize;
923       assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
924       Value *Insert =
925         Builder.CreateInsertElement(OldCast, SVCast, ConstantInt::get(
926                                         Type::getInt32Ty(Context), Elt), "tmp");
927       return Builder.CreateBitCast(Insert, AllocaType, "tmp");
928     }
929
930     // Must be an element insertion.
931     assert(SV->getType() == VTy->getElementType());
932     uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
933     unsigned Elt = Offset/EltSize;
934     return Builder.CreateInsertElement(Old, SV,
935                      ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
936                                      "tmp");
937   }
938
939   // If SV is a first-class aggregate value, insert each value recursively.
940   if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
941     const StructLayout &Layout = *TD.getStructLayout(ST);
942     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
943       Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
944       Old = ConvertScalar_InsertValue(Elt, Old,
945                                       Offset+Layout.getElementOffsetInBits(i),
946                                       Builder);
947     }
948     return Old;
949   }
950
951   if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
952     uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
953     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
954       Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
955       Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
956     }
957     return Old;
958   }
959
960   // If SV is a float, convert it to the appropriate integer type.
961   // If it is a pointer, do the same.
962   unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
963   unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
964   unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
965   unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
966   if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
967     SV = Builder.CreateBitCast(SV,
968                             IntegerType::get(SV->getContext(),SrcWidth), "tmp");
969   else if (SV->getType()->isPointerTy())
970     SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
971
972   // Zero extend or truncate the value if needed.
973   if (SV->getType() != AllocaType) {
974     if (SV->getType()->getPrimitiveSizeInBits() <
975              AllocaType->getPrimitiveSizeInBits())
976       SV = Builder.CreateZExt(SV, AllocaType, "tmp");
977     else {
978       // Truncation may be needed if storing more than the alloca can hold
979       // (undefined behavior).
980       SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
981       SrcWidth = DestWidth;
982       SrcStoreWidth = DestStoreWidth;
983     }
984   }
985
986   // If this is a big-endian system and the store is narrower than the
987   // full alloca type, we need to do a shift to get the right bits.
988   int ShAmt = 0;
989   if (TD.isBigEndian()) {
990     // On big-endian machines, the lowest bit is stored at the bit offset
991     // from the pointer given by getTypeStoreSizeInBits.  This matters for
992     // integers with a bitwidth that is not a multiple of 8.
993     ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
994   } else {
995     ShAmt = Offset;
996   }
997
998   // Note: we support negative bitwidths (with shr) which are not defined.
999   // We do this to support (f.e.) stores off the end of a structure where
1000   // only some bits in the structure are set.
1001   APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1002   if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1003     SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
1004                            ShAmt), "tmp");
1005     Mask <<= ShAmt;
1006   } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1007     SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
1008                             -ShAmt), "tmp");
1009     Mask = Mask.lshr(-ShAmt);
1010   }
1011
1012   // Mask out the bits we are about to insert from the old value, and or
1013   // in the new bits.
1014   if (SrcWidth != DestWidth) {
1015     assert(DestWidth > SrcWidth);
1016     Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1017     SV = Builder.CreateOr(Old, SV, "ins");
1018   }
1019   return SV;
1020 }
1021
1022
1023 //===----------------------------------------------------------------------===//
1024 // SRoA Driver
1025 //===----------------------------------------------------------------------===//
1026
1027
1028 bool SROA::runOnFunction(Function &F) {
1029   TD = getAnalysisIfAvailable<TargetData>();
1030
1031   bool Changed = performPromotion(F);
1032
1033   // FIXME: ScalarRepl currently depends on TargetData more than it
1034   // theoretically needs to. It should be refactored in order to support
1035   // target-independent IR. Until this is done, just skip the actual
1036   // scalar-replacement portion of this pass.
1037   if (!TD) return Changed;
1038
1039   while (1) {
1040     bool LocalChange = performScalarRepl(F);
1041     if (!LocalChange) break;   // No need to repromote if no scalarrepl
1042     Changed = true;
1043     LocalChange = performPromotion(F);
1044     if (!LocalChange) break;   // No need to re-scalarrepl if no promotion
1045   }
1046
1047   return Changed;
1048 }
1049
1050 namespace {
1051 class AllocaPromoter : public LoadAndStorePromoter {
1052   AllocaInst *AI;
1053 public:
1054   AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S)
1055     : LoadAndStorePromoter(Insts, S), AI(0) {}
1056   
1057   void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
1058     // Remember which alloca we're promoting (for isInstInList).
1059     this->AI = AI;
1060     LoadAndStorePromoter::run(Insts);
1061     AI->eraseFromParent();
1062   }
1063   
1064   virtual bool isInstInList(Instruction *I,
1065                             const SmallVectorImpl<Instruction*> &Insts) const {
1066     if (LoadInst *LI = dyn_cast<LoadInst>(I))
1067       return LI->getOperand(0) == AI;
1068     return cast<StoreInst>(I)->getPointerOperand() == AI;
1069   }
1070 };
1071 } // end anon namespace
1072
1073 /// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1074 /// subsequently loaded can be rewritten to load both input pointers and then
1075 /// select between the result, allowing the load of the alloca to be promoted.
1076 /// From this:
1077 ///   %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1078 ///   %V = load i32* %P2
1079 /// to:
1080 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
1081 ///   %V2 = load i32* %Other
1082 ///   %V = select i1 %cond, i32 %V1, i32 %V2
1083 ///
1084 /// We can do this to a select if its only uses are loads and if the operand to
1085 /// the select can be loaded unconditionally.
1086 static bool isSafeSelectToSpeculate(SelectInst *SI, const TargetData *TD) {
1087   bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
1088   bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
1089   
1090   for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
1091        UI != UE; ++UI) {
1092     LoadInst *LI = dyn_cast<LoadInst>(*UI);
1093     if (LI == 0 || LI->isVolatile()) return false;
1094     
1095     // Both operands to the select need to be dereferencable, either absolutely
1096     // (e.g. allocas) or at this point because we can see other accesses to it.
1097     if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1098                                                     LI->getAlignment(), TD))
1099       return false;
1100     if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1101                                                     LI->getAlignment(), TD))
1102       return false;
1103   }
1104   
1105   return true;
1106 }
1107
1108 /// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1109 /// subsequently loaded can be rewritten to load both input pointers in the pred
1110 /// blocks and then PHI the results, allowing the load of the alloca to be
1111 /// promoted.
1112 /// From this:
1113 ///   %P2 = phi [i32* %Alloca, i32* %Other]
1114 ///   %V = load i32* %P2
1115 /// to:
1116 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
1117 ///   ...
1118 ///   %V2 = load i32* %Other
1119 ///   ...
1120 ///   %V = phi [i32 %V1, i32 %V2]
1121 ///
1122 /// We can do this to a select if its only uses are loads and if the operand to
1123 /// the select can be loaded unconditionally.
1124 static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) {
1125   // For now, we can only do this promotion if the load is in the same block as
1126   // the PHI, and if there are no stores between the phi and load.
1127   // TODO: Allow recursive phi users.
1128   // TODO: Allow stores.
1129   BasicBlock *BB = PN->getParent();
1130   unsigned MaxAlign = 0;
1131   for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1132        UI != UE; ++UI) {
1133     LoadInst *LI = dyn_cast<LoadInst>(*UI);
1134     if (LI == 0 || LI->isVolatile()) return false;
1135     
1136     // For now we only allow loads in the same block as the PHI.  This is a
1137     // common case that happens when instcombine merges two loads through a PHI.
1138     if (LI->getParent() != BB) return false;
1139     
1140     // Ensure that there are no instructions between the PHI and the load that
1141     // could store.
1142     for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1143       if (BBI->mayWriteToMemory())
1144         return false;
1145     
1146     MaxAlign = std::max(MaxAlign, LI->getAlignment());
1147   }
1148   
1149   // Okay, we know that we have one or more loads in the same block as the PHI.
1150   // We can transform this if it is safe to push the loads into the predecessor
1151   // blocks.  The only thing to watch out for is that we can't put a possibly
1152   // trapping load in the predecessor if it is a critical edge.
1153   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1154     BasicBlock *Pred = PN->getIncomingBlock(i);
1155
1156     // If the predecessor has a single successor, then the edge isn't critical.
1157     if (Pred->getTerminator()->getNumSuccessors() == 1)
1158       continue;
1159     
1160     Value *InVal = PN->getIncomingValue(i);
1161     
1162     // If the InVal is an invoke in the pred, we can't put a load on the edge.
1163     if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
1164       if (II->getParent() == Pred)
1165         return false;
1166
1167     // If this pointer is always safe to load, or if we can prove that there is
1168     // already a load in the block, then we can move the load to the pred block.
1169     if (InVal->isDereferenceablePointer() ||
1170         isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD))
1171       continue;
1172     
1173     return false;
1174   }
1175     
1176   return true;
1177 }
1178
1179
1180 /// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1181 /// direct (non-volatile) loads and stores to it.  If the alloca is close but
1182 /// not quite there, this will transform the code to allow promotion.  As such,
1183 /// it is a non-pure predicate.
1184 static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) {
1185   SetVector<Instruction*, SmallVector<Instruction*, 4>,
1186             SmallPtrSet<Instruction*, 4> > InstsToRewrite;
1187   
1188   for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
1189        UI != UE; ++UI) {
1190     User *U = *UI;
1191     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1192       if (LI->isVolatile())
1193         return false;
1194       continue;
1195     }
1196     
1197     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1198       if (SI->getOperand(0) == AI || SI->isVolatile())
1199         return false;   // Don't allow a store OF the AI, only INTO the AI.
1200       continue;
1201     }
1202
1203     if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1204       // If the condition being selected on is a constant, fold the select, yes
1205       // this does (rarely) happen early on.
1206       if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1207         Value *Result = SI->getOperand(1+CI->isZero());
1208         SI->replaceAllUsesWith(Result);
1209         SI->eraseFromParent();
1210         
1211         // This is very rare and we just scrambled the use list of AI, start
1212         // over completely.
1213         return tryToMakeAllocaBePromotable(AI, TD);
1214       }
1215
1216       // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1217       // loads, then we can transform this by rewriting the select.
1218       if (!isSafeSelectToSpeculate(SI, TD))
1219         return false;
1220       
1221       InstsToRewrite.insert(SI);
1222       continue;
1223     }
1224     
1225     if (PHINode *PN = dyn_cast<PHINode>(U)) {
1226       if (PN->use_empty()) {  // Dead PHIs can be stripped.
1227         InstsToRewrite.insert(PN);
1228         continue;
1229       }
1230       
1231       // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1232       // in the pred blocks, then we can transform this by rewriting the PHI.
1233       if (!isSafePHIToSpeculate(PN, TD))
1234         return false;
1235       
1236       InstsToRewrite.insert(PN);
1237       continue;
1238     }
1239     
1240     return false;
1241   }
1242
1243   // If there are no instructions to rewrite, then all uses are load/stores and
1244   // we're done!
1245   if (InstsToRewrite.empty())
1246     return true;
1247   
1248   // If we have instructions that need to be rewritten for this to be promotable
1249   // take care of it now.
1250   for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
1251     if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1252       // Selects in InstsToRewrite only have load uses.  Rewrite each as two
1253       // loads with a new select.
1254       while (!SI->use_empty()) {
1255         LoadInst *LI = cast<LoadInst>(SI->use_back());
1256       
1257         IRBuilder<> Builder(LI);
1258         LoadInst *TrueLoad = 
1259           Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1260         LoadInst *FalseLoad = 
1261           Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".t");
1262         
1263         // Transfer alignment and TBAA info if present.
1264         TrueLoad->setAlignment(LI->getAlignment());
1265         FalseLoad->setAlignment(LI->getAlignment());
1266         if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1267           TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1268           FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1269         }
1270         
1271         Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1272         V->takeName(LI);
1273         LI->replaceAllUsesWith(V);
1274         LI->eraseFromParent();
1275       }
1276     
1277       // Now that all the loads are gone, the select is gone too.
1278       SI->eraseFromParent();
1279       continue;
1280     }
1281     
1282     // Otherwise, we have a PHI node which allows us to push the loads into the
1283     // predecessors.
1284     PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1285     if (PN->use_empty()) {
1286       PN->eraseFromParent();
1287       continue;
1288     }
1289     
1290     const Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
1291     PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1292                                      PN->getName()+".ld", PN);
1293
1294     // Get the TBAA tag and alignment to use from one of the loads.  It doesn't
1295     // matter which one we get and if any differ, it doesn't matter.
1296     LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
1297     MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1298     unsigned Align = SomeLoad->getAlignment();
1299     
1300     // Rewrite all loads of the PN to use the new PHI.
1301     while (!PN->use_empty()) {
1302       LoadInst *LI = cast<LoadInst>(PN->use_back());
1303       LI->replaceAllUsesWith(NewPN);
1304       LI->eraseFromParent();
1305     }
1306     
1307     // Inject loads into all of the pred blocks.  Keep track of which blocks we
1308     // insert them into in case we have multiple edges from the same block.
1309     DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1310     
1311     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1312       BasicBlock *Pred = PN->getIncomingBlock(i);
1313       LoadInst *&Load = InsertedLoads[Pred];
1314       if (Load == 0) {
1315         Load = new LoadInst(PN->getIncomingValue(i),
1316                             PN->getName() + "." + Pred->getName(),
1317                             Pred->getTerminator());
1318         Load->setAlignment(Align);
1319         if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1320       }
1321       
1322       NewPN->addIncoming(Load, Pred);
1323     }
1324     
1325     PN->eraseFromParent();
1326   }
1327     
1328   ++NumAdjusted;
1329   return true;
1330 }
1331
1332
1333 bool SROA::performPromotion(Function &F) {
1334   std::vector<AllocaInst*> Allocas;
1335   DominatorTree *DT = 0;
1336   if (HasDomTree)
1337     DT = &getAnalysis<DominatorTree>();
1338
1339   BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
1340
1341   bool Changed = false;
1342   SmallVector<Instruction*, 64> Insts;
1343   while (1) {
1344     Allocas.clear();
1345
1346     // Find allocas that are safe to promote, by looking at all instructions in
1347     // the entry node
1348     for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1349       if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
1350         if (tryToMakeAllocaBePromotable(AI, TD))
1351           Allocas.push_back(AI);
1352
1353     if (Allocas.empty()) break;
1354
1355     if (HasDomTree)
1356       PromoteMemToReg(Allocas, *DT);
1357     else {
1358       SSAUpdater SSA;
1359       for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1360         AllocaInst *AI = Allocas[i];
1361         
1362         // Build list of instructions to promote.
1363         for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1364              UI != E; ++UI)
1365           Insts.push_back(cast<Instruction>(*UI));
1366         
1367         AllocaPromoter(Insts, SSA).run(AI, Insts);
1368         Insts.clear();
1369       }
1370     }
1371     NumPromoted += Allocas.size();
1372     Changed = true;
1373   }
1374
1375   return Changed;
1376 }
1377
1378
1379 /// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1380 /// SROA.  It must be a struct or array type with a small number of elements.
1381 static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
1382   const Type *T = AI->getAllocatedType();
1383   // Do not promote any struct into more than 32 separate vars.
1384   if (const StructType *ST = dyn_cast<StructType>(T))
1385     return ST->getNumElements() <= 32;
1386   // Arrays are much less likely to be safe for SROA; only consider
1387   // them if they are very small.
1388   if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1389     return AT->getNumElements() <= 8;
1390   return false;
1391 }
1392
1393
1394 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
1395 // which runs on all of the malloc/alloca instructions in the function, removing
1396 // them if they are only used by getelementptr instructions.
1397 //
1398 bool SROA::performScalarRepl(Function &F) {
1399   std::vector<AllocaInst*> WorkList;
1400
1401   // Scan the entry basic block, adding allocas to the worklist.
1402   BasicBlock &BB = F.getEntryBlock();
1403   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
1404     if (AllocaInst *A = dyn_cast<AllocaInst>(I))
1405       WorkList.push_back(A);
1406
1407   // Process the worklist
1408   bool Changed = false;
1409   while (!WorkList.empty()) {
1410     AllocaInst *AI = WorkList.back();
1411     WorkList.pop_back();
1412
1413     // Handle dead allocas trivially.  These can be formed by SROA'ing arrays
1414     // with unused elements.
1415     if (AI->use_empty()) {
1416       AI->eraseFromParent();
1417       Changed = true;
1418       continue;
1419     }
1420
1421     // If this alloca is impossible for us to promote, reject it early.
1422     if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1423       continue;
1424
1425     // Check to see if this allocation is only modified by a memcpy/memmove from
1426     // a constant global.  If this is the case, we can change all users to use
1427     // the constant global instead.  This is commonly produced by the CFE by
1428     // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
1429     // is only subsequently read.
1430     if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
1431       DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
1432       DEBUG(dbgs() << "  memcpy = " << *TheCopy << '\n');
1433       Constant *TheSrc = cast<Constant>(TheCopy->getSource());
1434       AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
1435       TheCopy->eraseFromParent();  // Don't mutate the global.
1436       AI->eraseFromParent();
1437       ++NumGlobals;
1438       Changed = true;
1439       continue;
1440     }
1441
1442     // Check to see if we can perform the core SROA transformation.  We cannot
1443     // transform the allocation instruction if it is an array allocation
1444     // (allocations OF arrays are ok though), and an allocation of a scalar
1445     // value cannot be decomposed at all.
1446     uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
1447
1448     // Do not promote [0 x %struct].
1449     if (AllocaSize == 0) continue;
1450
1451     // Do not promote any struct whose size is too big.
1452     if (AllocaSize > SRThreshold) continue;
1453
1454     // If the alloca looks like a good candidate for scalar replacement, and if
1455     // all its users can be transformed, then split up the aggregate into its
1456     // separate elements.
1457     if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1458       DoScalarReplacement(AI, WorkList);
1459       Changed = true;
1460       continue;
1461     }
1462
1463     // If we can turn this aggregate value (potentially with casts) into a
1464     // simple scalar value that can be mem2reg'd into a register value.
1465     // IsNotTrivial tracks whether this is something that mem2reg could have
1466     // promoted itself.  If so, we don't want to transform it needlessly.  Note
1467     // that we can't just check based on the type: the alloca may be of an i32
1468     // but that has pointer arithmetic to set byte 3 of it or something.
1469     if (AllocaInst *NewAI =
1470           ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
1471       NewAI->takeName(AI);
1472       AI->eraseFromParent();
1473       ++NumConverted;
1474       Changed = true;
1475       continue;
1476     }
1477
1478     // Otherwise, couldn't process this alloca.
1479   }
1480
1481   return Changed;
1482 }
1483
1484 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1485 /// predicate, do SROA now.
1486 void SROA::DoScalarReplacement(AllocaInst *AI,
1487                                std::vector<AllocaInst*> &WorkList) {
1488   DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
1489   SmallVector<AllocaInst*, 32> ElementAllocas;
1490   if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1491     ElementAllocas.reserve(ST->getNumContainedTypes());
1492     for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
1493       AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
1494                                       AI->getAlignment(),
1495                                       AI->getName() + "." + Twine(i), AI);
1496       ElementAllocas.push_back(NA);
1497       WorkList.push_back(NA);  // Add to worklist for recursive processing
1498     }
1499   } else {
1500     const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1501     ElementAllocas.reserve(AT->getNumElements());
1502     const Type *ElTy = AT->getElementType();
1503     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1504       AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
1505                                       AI->getName() + "." + Twine(i), AI);
1506       ElementAllocas.push_back(NA);
1507       WorkList.push_back(NA);  // Add to worklist for recursive processing
1508     }
1509   }
1510
1511   // Now that we have created the new alloca instructions, rewrite all the
1512   // uses of the old alloca.
1513   RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
1514
1515   // Now erase any instructions that were made dead while rewriting the alloca.
1516   DeleteDeadInstructions();
1517   AI->eraseFromParent();
1518
1519   ++NumReplaced;
1520 }
1521
1522 /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1523 /// recursively including all their operands that become trivially dead.
1524 void SROA::DeleteDeadInstructions() {
1525   while (!DeadInsts.empty()) {
1526     Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
1527
1528     for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1529       if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1530         // Zero out the operand and see if it becomes trivially dead.
1531         // (But, don't add allocas to the dead instruction list -- they are
1532         // already on the worklist and will be deleted separately.)
1533         *OI = 0;
1534         if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1535           DeadInsts.push_back(U);
1536       }
1537
1538     I->eraseFromParent();
1539   }
1540 }
1541
1542 /// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1543 /// performing scalar replacement of alloca AI.  The results are flagged in
1544 /// the Info parameter.  Offset indicates the position within AI that is
1545 /// referenced by this instruction.
1546 void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
1547                                AllocaInfo &Info) {
1548   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1549     Instruction *User = cast<Instruction>(*UI);
1550
1551     if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1552       isSafeForScalarRepl(BC, Offset, Info);
1553     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1554       uint64_t GEPOffset = Offset;
1555       isSafeGEP(GEPI, GEPOffset, Info);
1556       if (!Info.isUnsafe)
1557         isSafeForScalarRepl(GEPI, GEPOffset, Info);
1558     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1559       ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1560       if (Length == 0)
1561         return MarkUnsafe(Info, User);
1562       isSafeMemAccess(Offset, Length->getZExtValue(), 0,
1563                       UI.getOperandNo() == 0, Info, MI,
1564                       true /*AllowWholeAccess*/);
1565     } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1566       if (LI->isVolatile())
1567         return MarkUnsafe(Info, User);
1568       const Type *LIType = LI->getType();
1569       isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1570                       LIType, false, Info, LI, true /*AllowWholeAccess*/);
1571       Info.hasALoadOrStore = true;
1572         
1573     } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1574       // Store is ok if storing INTO the pointer, not storing the pointer
1575       if (SI->isVolatile() || SI->getOperand(0) == I)
1576         return MarkUnsafe(Info, User);
1577         
1578       const Type *SIType = SI->getOperand(0)->getType();
1579       isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1580                       SIType, true, Info, SI, true /*AllowWholeAccess*/);
1581       Info.hasALoadOrStore = true;
1582     } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1583       isSafePHISelectUseForScalarRepl(User, Offset, Info);
1584     } else {
1585       return MarkUnsafe(Info, User);
1586     }
1587     if (Info.isUnsafe) return;
1588   }
1589 }
1590  
1591
1592 /// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1593 /// derived from the alloca, we can often still split the alloca into elements.
1594 /// This is useful if we have a large alloca where one element is phi'd
1595 /// together somewhere: we can SRoA and promote all the other elements even if
1596 /// we end up not being able to promote this one.
1597 ///
1598 /// All we require is that the uses of the PHI do not index into other parts of
1599 /// the alloca.  The most important use case for this is single load and stores
1600 /// that are PHI'd together, which can happen due to code sinking.
1601 void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1602                                            AllocaInfo &Info) {
1603   // If we've already checked this PHI, don't do it again.
1604   if (PHINode *PN = dyn_cast<PHINode>(I))
1605     if (!Info.CheckedPHIs.insert(PN))
1606       return;
1607   
1608   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1609     Instruction *User = cast<Instruction>(*UI);
1610     
1611     if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1612       isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1613     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1614       // Only allow "bitcast" GEPs for simplicity.  We could generalize this,
1615       // but would have to prove that we're staying inside of an element being
1616       // promoted.
1617       if (!GEPI->hasAllZeroIndices())
1618         return MarkUnsafe(Info, User);
1619       isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1620     } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1621       if (LI->isVolatile())
1622         return MarkUnsafe(Info, User);
1623       const Type *LIType = LI->getType();
1624       isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1625                       LIType, false, Info, LI, false /*AllowWholeAccess*/);
1626       Info.hasALoadOrStore = true;
1627       
1628     } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1629       // Store is ok if storing INTO the pointer, not storing the pointer
1630       if (SI->isVolatile() || SI->getOperand(0) == I)
1631         return MarkUnsafe(Info, User);
1632       
1633       const Type *SIType = SI->getOperand(0)->getType();
1634       isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1635                       SIType, true, Info, SI, false /*AllowWholeAccess*/);
1636       Info.hasALoadOrStore = true;
1637     } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1638       isSafePHISelectUseForScalarRepl(User, Offset, Info);
1639     } else {
1640       return MarkUnsafe(Info, User);
1641     }
1642     if (Info.isUnsafe) return;
1643   }
1644 }
1645
1646 /// isSafeGEP - Check if a GEP instruction can be handled for scalar
1647 /// replacement.  It is safe when all the indices are constant, in-bounds
1648 /// references, and when the resulting offset corresponds to an element within
1649 /// the alloca type.  The results are flagged in the Info parameter.  Upon
1650 /// return, Offset is adjusted as specified by the GEP indices.
1651 void SROA::isSafeGEP(GetElementPtrInst *GEPI,
1652                      uint64_t &Offset, AllocaInfo &Info) {
1653   gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1654   if (GEPIt == E)
1655     return;
1656
1657   // Walk through the GEP type indices, checking the types that this indexes
1658   // into.
1659   for (; GEPIt != E; ++GEPIt) {
1660     // Ignore struct elements, no extra checking needed for these.
1661     if ((*GEPIt)->isStructTy())
1662       continue;
1663
1664     ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1665     if (!IdxVal)
1666       return MarkUnsafe(Info, GEPI);
1667   }
1668
1669   // Compute the offset due to this GEP and check if the alloca has a
1670   // component element at that offset.
1671   SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1672   Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1673                                  &Indices[0], Indices.size());
1674   if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 0))
1675     MarkUnsafe(Info, GEPI);
1676 }
1677
1678 /// isHomogeneousAggregate - Check if type T is a struct or array containing
1679 /// elements of the same type (which is always true for arrays).  If so,
1680 /// return true with NumElts and EltTy set to the number of elements and the
1681 /// element type, respectively.
1682 static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts,
1683                                    const Type *&EltTy) {
1684   if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1685     NumElts = AT->getNumElements();
1686     EltTy = (NumElts == 0 ? 0 : AT->getElementType());
1687     return true;
1688   }
1689   if (const StructType *ST = dyn_cast<StructType>(T)) {
1690     NumElts = ST->getNumContainedTypes();
1691     EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
1692     for (unsigned n = 1; n < NumElts; ++n) {
1693       if (ST->getContainedType(n) != EltTy)
1694         return false;
1695     }
1696     return true;
1697   }
1698   return false;
1699 }
1700
1701 /// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1702 /// "homogeneous" aggregates with the same element type and number of elements.
1703 static bool isCompatibleAggregate(const Type *T1, const Type *T2) {
1704   if (T1 == T2)
1705     return true;
1706
1707   unsigned NumElts1, NumElts2;
1708   const Type *EltTy1, *EltTy2;
1709   if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1710       isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1711       NumElts1 == NumElts2 &&
1712       EltTy1 == EltTy2)
1713     return true;
1714
1715   return false;
1716 }
1717
1718 /// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1719 /// alloca or has an offset and size that corresponds to a component element
1720 /// within it.  The offset checked here may have been formed from a GEP with a
1721 /// pointer bitcasted to a different type.
1722 ///
1723 /// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1724 /// unit.  If false, it only allows accesses known to be in a single element.
1725 void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
1726                            const Type *MemOpType, bool isStore,
1727                            AllocaInfo &Info, Instruction *TheAccess,
1728                            bool AllowWholeAccess) {
1729   // Check if this is a load/store of the entire alloca.
1730   if (Offset == 0 && AllowWholeAccess &&
1731       MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
1732     // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1733     // loads/stores (which are essentially the same as the MemIntrinsics with
1734     // regard to copying padding between elements).  But, if an alloca is
1735     // flagged as both a source and destination of such operations, we'll need
1736     // to check later for padding between elements.
1737     if (!MemOpType || MemOpType->isIntegerTy()) {
1738       if (isStore)
1739         Info.isMemCpyDst = true;
1740       else
1741         Info.isMemCpySrc = true;
1742       return;
1743     }
1744     // This is also safe for references using a type that is compatible with
1745     // the type of the alloca, so that loads/stores can be rewritten using
1746     // insertvalue/extractvalue.
1747     if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
1748       Info.hasSubelementAccess = true;
1749       return;
1750     }
1751   }
1752   // Check if the offset/size correspond to a component within the alloca type.
1753   const Type *T = Info.AI->getAllocatedType();
1754   if (TypeHasComponent(T, Offset, MemSize)) {
1755     Info.hasSubelementAccess = true;
1756     return;
1757   }
1758
1759   return MarkUnsafe(Info, TheAccess);
1760 }
1761
1762 /// TypeHasComponent - Return true if T has a component type with the
1763 /// specified offset and size.  If Size is zero, do not check the size.
1764 bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1765   const Type *EltTy;
1766   uint64_t EltSize;
1767   if (const StructType *ST = dyn_cast<StructType>(T)) {
1768     const StructLayout *Layout = TD->getStructLayout(ST);
1769     unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1770     EltTy = ST->getContainedType(EltIdx);
1771     EltSize = TD->getTypeAllocSize(EltTy);
1772     Offset -= Layout->getElementOffset(EltIdx);
1773   } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1774     EltTy = AT->getElementType();
1775     EltSize = TD->getTypeAllocSize(EltTy);
1776     if (Offset >= AT->getNumElements() * EltSize)
1777       return false;
1778     Offset %= EltSize;
1779   } else {
1780     return false;
1781   }
1782   if (Offset == 0 && (Size == 0 || EltSize == Size))
1783     return true;
1784   // Check if the component spans multiple elements.
1785   if (Offset + Size > EltSize)
1786     return false;
1787   return TypeHasComponent(EltTy, Offset, Size);
1788 }
1789
1790 /// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1791 /// the instruction I, which references it, to use the separate elements.
1792 /// Offset indicates the position within AI that is referenced by this
1793 /// instruction.
1794 void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1795                                 SmallVector<AllocaInst*, 32> &NewElts) {
1796   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1797     Use &TheUse = UI.getUse();
1798     Instruction *User = cast<Instruction>(*UI++);
1799
1800     if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1801       RewriteBitCast(BC, AI, Offset, NewElts);
1802       continue;
1803     }
1804     
1805     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1806       RewriteGEP(GEPI, AI, Offset, NewElts);
1807       continue;
1808     }
1809     
1810     if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1811       ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1812       uint64_t MemSize = Length->getZExtValue();
1813       if (Offset == 0 &&
1814           MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1815         RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
1816       // Otherwise the intrinsic can only touch a single element and the
1817       // address operand will be updated, so nothing else needs to be done.
1818       continue;
1819     }
1820     
1821     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1822       const Type *LIType = LI->getType();
1823       
1824       if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
1825         // Replace:
1826         //   %res = load { i32, i32 }* %alloc
1827         // with:
1828         //   %load.0 = load i32* %alloc.0
1829         //   %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1830         //   %load.1 = load i32* %alloc.1
1831         //   %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1832         // (Also works for arrays instead of structs)
1833         Value *Insert = UndefValue::get(LIType);
1834         for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1835           Value *Load = new LoadInst(NewElts[i], "load", LI);
1836           Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1837         }
1838         LI->replaceAllUsesWith(Insert);
1839         DeadInsts.push_back(LI);
1840       } else if (LIType->isIntegerTy() &&
1841                  TD->getTypeAllocSize(LIType) ==
1842                  TD->getTypeAllocSize(AI->getAllocatedType())) {
1843         // If this is a load of the entire alloca to an integer, rewrite it.
1844         RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1845       }
1846       continue;
1847     }
1848     
1849     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1850       Value *Val = SI->getOperand(0);
1851       const Type *SIType = Val->getType();
1852       if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
1853         // Replace:
1854         //   store { i32, i32 } %val, { i32, i32 }* %alloc
1855         // with:
1856         //   %val.0 = extractvalue { i32, i32 } %val, 0
1857         //   store i32 %val.0, i32* %alloc.0
1858         //   %val.1 = extractvalue { i32, i32 } %val, 1
1859         //   store i32 %val.1, i32* %alloc.1
1860         // (Also works for arrays instead of structs)
1861         for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1862           Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1863           new StoreInst(Extract, NewElts[i], SI);
1864         }
1865         DeadInsts.push_back(SI);
1866       } else if (SIType->isIntegerTy() &&
1867                  TD->getTypeAllocSize(SIType) ==
1868                  TD->getTypeAllocSize(AI->getAllocatedType())) {
1869         // If this is a store of the entire alloca from an integer, rewrite it.
1870         RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1871       }
1872       continue;
1873     }
1874     
1875     if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1876       // If we have a PHI user of the alloca itself (as opposed to a GEP or 
1877       // bitcast) we have to rewrite it.  GEP and bitcast uses will be RAUW'd to
1878       // the new pointer.
1879       if (!isa<AllocaInst>(I)) continue;
1880       
1881       assert(Offset == 0 && NewElts[0] &&
1882              "Direct alloca use should have a zero offset");
1883       
1884       // If we have a use of the alloca, we know the derived uses will be
1885       // utilizing just the first element of the scalarized result.  Insert a
1886       // bitcast of the first alloca before the user as required.
1887       AllocaInst *NewAI = NewElts[0];
1888       BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1889       NewAI->moveBefore(BCI);
1890       TheUse = BCI;
1891       continue;
1892     }
1893   }
1894 }
1895
1896 /// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1897 /// and recursively continue updating all of its uses.
1898 void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1899                           SmallVector<AllocaInst*, 32> &NewElts) {
1900   RewriteForScalarRepl(BC, AI, Offset, NewElts);
1901   if (BC->getOperand(0) != AI)
1902     return;
1903
1904   // The bitcast references the original alloca.  Replace its uses with
1905   // references to the first new element alloca.
1906   Instruction *Val = NewElts[0];
1907   if (Val->getType() != BC->getDestTy()) {
1908     Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1909     Val->takeName(BC);
1910   }
1911   BC->replaceAllUsesWith(Val);
1912   DeadInsts.push_back(BC);
1913 }
1914
1915 /// FindElementAndOffset - Return the index of the element containing Offset
1916 /// within the specified type, which must be either a struct or an array.
1917 /// Sets T to the type of the element and Offset to the offset within that
1918 /// element.  IdxTy is set to the type of the index result to be used in a
1919 /// GEP instruction.
1920 uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1921                                     const Type *&IdxTy) {
1922   uint64_t Idx = 0;
1923   if (const StructType *ST = dyn_cast<StructType>(T)) {
1924     const StructLayout *Layout = TD->getStructLayout(ST);
1925     Idx = Layout->getElementContainingOffset(Offset);
1926     T = ST->getContainedType(Idx);
1927     Offset -= Layout->getElementOffset(Idx);
1928     IdxTy = Type::getInt32Ty(T->getContext());
1929     return Idx;
1930   }
1931   const ArrayType *AT = cast<ArrayType>(T);
1932   T = AT->getElementType();
1933   uint64_t EltSize = TD->getTypeAllocSize(T);
1934   Idx = Offset / EltSize;
1935   Offset -= Idx * EltSize;
1936   IdxTy = Type::getInt64Ty(T->getContext());
1937   return Idx;
1938 }
1939
1940 /// RewriteGEP - Check if this GEP instruction moves the pointer across
1941 /// elements of the alloca that are being split apart, and if so, rewrite
1942 /// the GEP to be relative to the new element.
1943 void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1944                       SmallVector<AllocaInst*, 32> &NewElts) {
1945   uint64_t OldOffset = Offset;
1946   SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1947   Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1948                                  &Indices[0], Indices.size());
1949
1950   RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1951
1952   const Type *T = AI->getAllocatedType();
1953   const Type *IdxTy;
1954   uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
1955   if (GEPI->getOperand(0) == AI)
1956     OldIdx = ~0ULL; // Force the GEP to be rewritten.
1957
1958   T = AI->getAllocatedType();
1959   uint64_t EltOffset = Offset;
1960   uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
1961
1962   // If this GEP does not move the pointer across elements of the alloca
1963   // being split, then it does not needs to be rewritten.
1964   if (Idx == OldIdx)
1965     return;
1966
1967   const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1968   SmallVector<Value*, 8> NewArgs;
1969   NewArgs.push_back(Constant::getNullValue(i32Ty));
1970   while (EltOffset != 0) {
1971     uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1972     NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
1973   }
1974   Instruction *Val = NewElts[Idx];
1975   if (NewArgs.size() > 1) {
1976     Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1977                                             NewArgs.end(), "", GEPI);
1978     Val->takeName(GEPI);
1979   }
1980   if (Val->getType() != GEPI->getType())
1981     Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
1982   GEPI->replaceAllUsesWith(Val);
1983   DeadInsts.push_back(GEPI);
1984 }
1985
1986 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1987 /// Rewrite it to copy or set the elements of the scalarized memory.
1988 void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
1989                                         AllocaInst *AI,
1990                                         SmallVector<AllocaInst*, 32> &NewElts) {
1991   // If this is a memcpy/memmove, construct the other pointer as the
1992   // appropriate type.  The "Other" pointer is the pointer that goes to memory
1993   // that doesn't have anything to do with the alloca that we are promoting. For
1994   // memset, this Value* stays null.
1995   Value *OtherPtr = 0;
1996   unsigned MemAlignment = MI->getAlignment();
1997   if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
1998     if (Inst == MTI->getRawDest())
1999       OtherPtr = MTI->getRawSource();
2000     else {
2001       assert(Inst == MTI->getRawSource());
2002       OtherPtr = MTI->getRawDest();
2003     }
2004   }
2005
2006   // If there is an other pointer, we want to convert it to the same pointer
2007   // type as AI has, so we can GEP through it safely.
2008   if (OtherPtr) {
2009     unsigned AddrSpace =
2010       cast<PointerType>(OtherPtr->getType())->getAddressSpace();
2011
2012     // Remove bitcasts and all-zero GEPs from OtherPtr.  This is an
2013     // optimization, but it's also required to detect the corner case where
2014     // both pointer operands are referencing the same memory, and where
2015     // OtherPtr may be a bitcast or GEP that currently being rewritten.  (This
2016     // function is only called for mem intrinsics that access the whole
2017     // aggregate, so non-zero GEPs are not an issue here.)
2018     OtherPtr = OtherPtr->stripPointerCasts();
2019
2020     // Copying the alloca to itself is a no-op: just delete it.
2021     if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2022       // This code will run twice for a no-op memcpy -- once for each operand.
2023       // Put only one reference to MI on the DeadInsts list.
2024       for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
2025              E = DeadInsts.end(); I != E; ++I)
2026         if (*I == MI) return;
2027       DeadInsts.push_back(MI);
2028       return;
2029     }
2030
2031     // If the pointer is not the right type, insert a bitcast to the right
2032     // type.
2033     const Type *NewTy =
2034       PointerType::get(AI->getType()->getElementType(), AddrSpace);
2035
2036     if (OtherPtr->getType() != NewTy)
2037       OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
2038   }
2039
2040   // Process each element of the aggregate.
2041   bool SROADest = MI->getRawDest() == Inst;
2042
2043   Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
2044
2045   for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2046     // If this is a memcpy/memmove, emit a GEP of the other element address.
2047     Value *OtherElt = 0;
2048     unsigned OtherEltAlign = MemAlignment;
2049
2050     if (OtherPtr) {
2051       Value *Idx[2] = { Zero,
2052                       ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
2053       OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
2054                                               OtherPtr->getName()+"."+Twine(i),
2055                                                    MI);
2056       uint64_t EltOffset;
2057       const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
2058       const Type *OtherTy = OtherPtrTy->getElementType();
2059       if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
2060         EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
2061       } else {
2062         const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
2063         EltOffset = TD->getTypeAllocSize(EltTy)*i;
2064       }
2065
2066       // The alignment of the other pointer is the guaranteed alignment of the
2067       // element, which is affected by both the known alignment of the whole
2068       // mem intrinsic and the alignment of the element.  If the alignment of
2069       // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2070       // known alignment is just 4 bytes.
2071       OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
2072     }
2073
2074     Value *EltPtr = NewElts[i];
2075     const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
2076
2077     // If we got down to a scalar, insert a load or store as appropriate.
2078     if (EltTy->isSingleValueType()) {
2079       if (isa<MemTransferInst>(MI)) {
2080         if (SROADest) {
2081           // From Other to Alloca.
2082           Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2083           new StoreInst(Elt, EltPtr, MI);
2084         } else {
2085           // From Alloca to Other.
2086           Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2087           new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2088         }
2089         continue;
2090       }
2091       assert(isa<MemSetInst>(MI));
2092
2093       // If the stored element is zero (common case), just store a null
2094       // constant.
2095       Constant *StoreVal;
2096       if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
2097         if (CI->isZero()) {
2098           StoreVal = Constant::getNullValue(EltTy);  // 0.0, null, 0, <0,0>
2099         } else {
2100           // If EltTy is a vector type, get the element type.
2101           const Type *ValTy = EltTy->getScalarType();
2102
2103           // Construct an integer with the right value.
2104           unsigned EltSize = TD->getTypeSizeInBits(ValTy);
2105           APInt OneVal(EltSize, CI->getZExtValue());
2106           APInt TotalVal(OneVal);
2107           // Set each byte.
2108           for (unsigned i = 0; 8*i < EltSize; ++i) {
2109             TotalVal = TotalVal.shl(8);
2110             TotalVal |= OneVal;
2111           }
2112
2113           // Convert the integer value to the appropriate type.
2114           StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
2115           if (ValTy->isPointerTy())
2116             StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
2117           else if (ValTy->isFloatingPointTy())
2118             StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
2119           assert(StoreVal->getType() == ValTy && "Type mismatch!");
2120
2121           // If the requested value was a vector constant, create it.
2122           if (EltTy != ValTy) {
2123             unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
2124             SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
2125             StoreVal = ConstantVector::get(Elts);
2126           }
2127         }
2128         new StoreInst(StoreVal, EltPtr, MI);
2129         continue;
2130       }
2131       // Otherwise, if we're storing a byte variable, use a memset call for
2132       // this element.
2133     }
2134
2135     unsigned EltSize = TD->getTypeAllocSize(EltTy);
2136
2137     IRBuilder<> Builder(MI);
2138
2139     // Finally, insert the meminst for this element.
2140     if (isa<MemSetInst>(MI)) {
2141       Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2142                            MI->isVolatile());
2143     } else {
2144       assert(isa<MemTransferInst>(MI));
2145       Value *Dst = SROADest ? EltPtr : OtherElt;  // Dest ptr
2146       Value *Src = SROADest ? OtherElt : EltPtr;  // Src ptr
2147
2148       if (isa<MemCpyInst>(MI))
2149         Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2150       else
2151         Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
2152     }
2153   }
2154   DeadInsts.push_back(MI);
2155 }
2156
2157 /// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
2158 /// overwrites the entire allocation.  Extract out the pieces of the stored
2159 /// integer and store them individually.
2160 void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
2161                                          SmallVector<AllocaInst*, 32> &NewElts){
2162   // Extract each element out of the integer according to its structure offset
2163   // and store the element value to the individual alloca.
2164   Value *SrcVal = SI->getOperand(0);
2165   const Type *AllocaEltTy = AI->getAllocatedType();
2166   uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
2167
2168   IRBuilder<> Builder(SI);
2169   
2170   // Handle tail padding by extending the operand
2171   if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
2172     SrcVal = Builder.CreateZExt(SrcVal,
2173                             IntegerType::get(SI->getContext(), AllocaSizeBits));
2174
2175   DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
2176                << '\n');
2177
2178   // There are two forms here: AI could be an array or struct.  Both cases
2179   // have different ways to compute the element offset.
2180   if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2181     const StructLayout *Layout = TD->getStructLayout(EltSTy);
2182
2183     for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2184       // Get the number of bits to shift SrcVal to get the value.
2185       const Type *FieldTy = EltSTy->getElementType(i);
2186       uint64_t Shift = Layout->getElementOffsetInBits(i);
2187
2188       if (TD->isBigEndian())
2189         Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
2190
2191       Value *EltVal = SrcVal;
2192       if (Shift) {
2193         Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2194         EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2195       }
2196
2197       // Truncate down to an integer of the right size.
2198       uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
2199
2200       // Ignore zero sized fields like {}, they obviously contain no data.
2201       if (FieldSizeBits == 0) continue;
2202
2203       if (FieldSizeBits != AllocaSizeBits)
2204         EltVal = Builder.CreateTrunc(EltVal,
2205                              IntegerType::get(SI->getContext(), FieldSizeBits));
2206       Value *DestField = NewElts[i];
2207       if (EltVal->getType() == FieldTy) {
2208         // Storing to an integer field of this size, just do it.
2209       } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
2210         // Bitcast to the right element type (for fp/vector values).
2211         EltVal = Builder.CreateBitCast(EltVal, FieldTy);
2212       } else {
2213         // Otherwise, bitcast the dest pointer (for aggregates).
2214         DestField = Builder.CreateBitCast(DestField,
2215                                      PointerType::getUnqual(EltVal->getType()));
2216       }
2217       new StoreInst(EltVal, DestField, SI);
2218     }
2219
2220   } else {
2221     const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2222     const Type *ArrayEltTy = ATy->getElementType();
2223     uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
2224     uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
2225
2226     uint64_t Shift;
2227
2228     if (TD->isBigEndian())
2229       Shift = AllocaSizeBits-ElementOffset;
2230     else
2231       Shift = 0;
2232
2233     for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2234       // Ignore zero sized fields like {}, they obviously contain no data.
2235       if (ElementSizeBits == 0) continue;
2236
2237       Value *EltVal = SrcVal;
2238       if (Shift) {
2239         Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2240         EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2241       }
2242
2243       // Truncate down to an integer of the right size.
2244       if (ElementSizeBits != AllocaSizeBits)
2245         EltVal = Builder.CreateTrunc(EltVal,
2246                                      IntegerType::get(SI->getContext(),
2247                                                       ElementSizeBits));
2248       Value *DestField = NewElts[i];
2249       if (EltVal->getType() == ArrayEltTy) {
2250         // Storing to an integer field of this size, just do it.
2251       } else if (ArrayEltTy->isFloatingPointTy() ||
2252                  ArrayEltTy->isVectorTy()) {
2253         // Bitcast to the right element type (for fp/vector values).
2254         EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
2255       } else {
2256         // Otherwise, bitcast the dest pointer (for aggregates).
2257         DestField = Builder.CreateBitCast(DestField,
2258                                      PointerType::getUnqual(EltVal->getType()));
2259       }
2260       new StoreInst(EltVal, DestField, SI);
2261
2262       if (TD->isBigEndian())
2263         Shift -= ElementOffset;
2264       else
2265         Shift += ElementOffset;
2266     }
2267   }
2268
2269   DeadInsts.push_back(SI);
2270 }
2271
2272 /// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
2273 /// an integer.  Load the individual pieces to form the aggregate value.
2274 void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
2275                                         SmallVector<AllocaInst*, 32> &NewElts) {
2276   // Extract each element out of the NewElts according to its structure offset
2277   // and form the result value.
2278   const Type *AllocaEltTy = AI->getAllocatedType();
2279   uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
2280
2281   DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
2282                << '\n');
2283
2284   // There are two forms here: AI could be an array or struct.  Both cases
2285   // have different ways to compute the element offset.
2286   const StructLayout *Layout = 0;
2287   uint64_t ArrayEltBitOffset = 0;
2288   if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2289     Layout = TD->getStructLayout(EltSTy);
2290   } else {
2291     const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
2292     ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
2293   }
2294
2295   Value *ResultVal =
2296     Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
2297
2298   for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2299     // Load the value from the alloca.  If the NewElt is an aggregate, cast
2300     // the pointer to an integer of the same size before doing the load.
2301     Value *SrcField = NewElts[i];
2302     const Type *FieldTy =
2303       cast<PointerType>(SrcField->getType())->getElementType();
2304     uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
2305
2306     // Ignore zero sized fields like {}, they obviously contain no data.
2307     if (FieldSizeBits == 0) continue;
2308
2309     const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
2310                                                      FieldSizeBits);
2311     if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2312         !FieldTy->isVectorTy())
2313       SrcField = new BitCastInst(SrcField,
2314                                  PointerType::getUnqual(FieldIntTy),
2315                                  "", LI);
2316     SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2317
2318     // If SrcField is a fp or vector of the right size but that isn't an
2319     // integer type, bitcast to an integer so we can shift it.
2320     if (SrcField->getType() != FieldIntTy)
2321       SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2322
2323     // Zero extend the field to be the same size as the final alloca so that
2324     // we can shift and insert it.
2325     if (SrcField->getType() != ResultVal->getType())
2326       SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
2327
2328     // Determine the number of bits to shift SrcField.
2329     uint64_t Shift;
2330     if (Layout) // Struct case.
2331       Shift = Layout->getElementOffsetInBits(i);
2332     else  // Array case.
2333       Shift = i*ArrayEltBitOffset;
2334
2335     if (TD->isBigEndian())
2336       Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
2337
2338     if (Shift) {
2339       Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
2340       SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2341     }
2342
2343     // Don't create an 'or x, 0' on the first iteration.
2344     if (!isa<Constant>(ResultVal) ||
2345         !cast<Constant>(ResultVal)->isNullValue())
2346       ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2347     else
2348       ResultVal = SrcField;
2349   }
2350
2351   // Handle tail padding by truncating the result
2352   if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2353     ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2354
2355   LI->replaceAllUsesWith(ResultVal);
2356   DeadInsts.push_back(LI);
2357 }
2358
2359 /// HasPadding - Return true if the specified type has any structure or
2360 /// alignment padding in between the elements that would be split apart
2361 /// by SROA; return false otherwise.
2362 static bool HasPadding(const Type *Ty, const TargetData &TD) {
2363   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2364     Ty = ATy->getElementType();
2365     return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
2366   }
2367
2368   // SROA currently handles only Arrays and Structs.
2369   const StructType *STy = cast<StructType>(Ty);
2370   const StructLayout *SL = TD.getStructLayout(STy);
2371   unsigned PrevFieldBitOffset = 0;
2372   for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2373     unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2374
2375     // Check to see if there is any padding between this element and the
2376     // previous one.
2377     if (i) {
2378       unsigned PrevFieldEnd =
2379         PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
2380       if (PrevFieldEnd < FieldBitOffset)
2381         return true;
2382     }
2383     PrevFieldBitOffset = FieldBitOffset;
2384   }
2385   // Check for tail padding.
2386   if (unsigned EltCount = STy->getNumElements()) {
2387     unsigned PrevFieldEnd = PrevFieldBitOffset +
2388       TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
2389     if (PrevFieldEnd < SL->getSizeInBits())
2390       return true;
2391   }
2392   return false;
2393 }
2394
2395 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2396 /// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
2397 /// or 1 if safe after canonicalization has been performed.
2398 bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
2399   // Loop over the use list of the alloca.  We can only transform it if all of
2400   // the users are safe to transform.
2401   AllocaInfo Info(AI);
2402
2403   isSafeForScalarRepl(AI, 0, Info);
2404   if (Info.isUnsafe) {
2405     DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
2406     return false;
2407   }
2408
2409   // Okay, we know all the users are promotable.  If the aggregate is a memcpy
2410   // source and destination, we have to be careful.  In particular, the memcpy
2411   // could be moving around elements that live in structure padding of the LLVM
2412   // types, but may actually be used.  In these cases, we refuse to promote the
2413   // struct.
2414   if (Info.isMemCpySrc && Info.isMemCpyDst &&
2415       HasPadding(AI->getAllocatedType(), *TD))
2416     return false;
2417
2418   // If the alloca never has an access to just *part* of it, but is accessed
2419   // via loads and stores, then we should use ConvertToScalarInfo to promote
2420   // the alloca instead of promoting each piece at a time and inserting fission
2421   // and fusion code.
2422   if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2423     // If the struct/array just has one element, use basic SRoA.
2424     if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
2425       if (ST->getNumElements() > 1) return false;
2426     } else {
2427       if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2428         return false;
2429     }
2430   }
2431   
2432   return true;
2433 }
2434
2435
2436
2437 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
2438 /// some part of a constant global variable.  This intentionally only accepts
2439 /// constant expressions because we don't can't rewrite arbitrary instructions.
2440 static bool PointsToConstantGlobal(Value *V) {
2441   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2442     return GV->isConstant();
2443   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2444     if (CE->getOpcode() == Instruction::BitCast ||
2445         CE->getOpcode() == Instruction::GetElementPtr)
2446       return PointsToConstantGlobal(CE->getOperand(0));
2447   return false;
2448 }
2449
2450 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
2451 /// pointer to an alloca.  Ignore any reads of the pointer, return false if we
2452 /// see any stores or other unknown uses.  If we see pointer arithmetic, keep
2453 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
2454 /// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
2455 /// the alloca, and if the source pointer is a pointer to a constant global, we
2456 /// can optimize this.
2457 static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
2458                                            bool isOffset) {
2459   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
2460     User *U = cast<Instruction>(*UI);
2461
2462     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
2463       // Ignore non-volatile loads, they are always ok.
2464       if (LI->isVolatile()) return false;
2465       continue;
2466     }
2467
2468     if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
2469       // If uses of the bitcast are ok, we are ok.
2470       if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
2471         return false;
2472       continue;
2473     }
2474     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
2475       // If the GEP has all zero indices, it doesn't offset the pointer.  If it
2476       // doesn't, it does.
2477       if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
2478                                          isOffset || !GEP->hasAllZeroIndices()))
2479         return false;
2480       continue;
2481     }
2482
2483     if (CallSite CS = U) {
2484       // If this is the function being called then we treat it like a load and
2485       // ignore it.
2486       if (CS.isCallee(UI))
2487         continue;
2488
2489       // If this is a readonly/readnone call site, then we know it is just a
2490       // load (but one that potentially returns the value itself), so we can
2491       // ignore it if we know that the value isn't captured.
2492       unsigned ArgNo = CS.getArgumentNo(UI);
2493       if (CS.onlyReadsMemory() &&
2494           (CS.getInstruction()->use_empty() ||
2495            CS.paramHasAttr(ArgNo+1, Attribute::NoCapture)))
2496         continue;
2497
2498       // If this is being passed as a byval argument, the caller is making a
2499       // copy, so it is only a read of the alloca.
2500       if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
2501         continue;
2502     }
2503
2504     // If this is isn't our memcpy/memmove, reject it as something we can't
2505     // handle.
2506     MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2507     if (MI == 0)
2508       return false;
2509
2510     // If the transfer is using the alloca as a source of the transfer, then
2511     // ignore it since it is a load (unless the transfer is volatile).
2512     if (UI.getOperandNo() == 1) {
2513       if (MI->isVolatile()) return false;
2514       continue;
2515     }
2516
2517     // If we already have seen a copy, reject the second one.
2518     if (TheCopy) return false;
2519
2520     // If the pointer has been offset from the start of the alloca, we can't
2521     // safely handle this.
2522     if (isOffset) return false;
2523
2524     // If the memintrinsic isn't using the alloca as the dest, reject it.
2525     if (UI.getOperandNo() != 0) return false;
2526
2527     // If the source of the memcpy/move is not a constant global, reject it.
2528     if (!PointsToConstantGlobal(MI->getSource()))
2529       return false;
2530
2531     // Otherwise, the transform is safe.  Remember the copy instruction.
2532     TheCopy = MI;
2533   }
2534   return true;
2535 }
2536
2537 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2538 /// modified by a copy from a constant global.  If we can prove this, we can
2539 /// replace any uses of the alloca with uses of the global directly.
2540 MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
2541   MemTransferInst *TheCopy = 0;
2542   if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
2543     return TheCopy;
2544   return 0;
2545 }