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