Fix 80-column violations.
[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       isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
507       if (Info.isUnsafe) return;
508       break;
509     }
510     case Instruction::BitCast:
511       if (isFirstElt) {
512         isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
513         if (Info.isUnsafe) return;
514         break;
515       }
516       DEBUG(errs() << "  Transformation preventing inst: " << *User << '\n');
517       return MarkUnsafe(Info);
518     case Instruction::Call:
519       if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
520         if (isFirstElt) {
521           isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
522           if (Info.isUnsafe) return;
523           break;
524         }
525       }
526       DEBUG(errs() << "  Transformation preventing inst: " << *User << '\n');
527       return MarkUnsafe(Info);
528     default:
529       DEBUG(errs() << "  Transformation preventing inst: " << *User << '\n');
530       return MarkUnsafe(Info);
531     }
532   }
533   return;  // All users look ok :)
534 }
535
536 /// AllUsersAreLoads - Return true if all users of this value are loads.
537 static bool AllUsersAreLoads(Value *Ptr) {
538   for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
539        I != E; ++I)
540     if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
541       return false;
542   return true;
543 }
544
545 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
546 /// aggregate allocation.
547 ///
548 void SROA::isSafeUseOfAllocation(Instruction *User, AllocaInst *AI,
549                                  AllocaInfo &Info) {
550   if (BitCastInst *C = dyn_cast<BitCastInst>(User))
551     return isSafeUseOfBitCastedAllocation(C, AI, Info);
552
553   if (LoadInst *LI = dyn_cast<LoadInst>(User))
554     if (!LI->isVolatile())
555       return;// Loads (returning a first class aggregrate) are always rewritable
556
557   if (StoreInst *SI = dyn_cast<StoreInst>(User))
558     if (!SI->isVolatile() && SI->getOperand(0) != AI)
559       return;// Store is ok if storing INTO the pointer, not storing the pointer
560  
561   GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
562   if (GEPI == 0)
563     return MarkUnsafe(Info);
564
565   gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
566
567   // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
568   if (I == E ||
569       I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
570     return MarkUnsafe(Info);
571   }
572
573   ++I;
574   if (I == E) return MarkUnsafe(Info);  // ran out of GEP indices??
575
576   bool IsAllZeroIndices = true;
577   
578   // If the first index is a non-constant index into an array, see if we can
579   // handle it as a special case.
580   if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
581     if (!isa<ConstantInt>(I.getOperand())) {
582       IsAllZeroIndices = 0;
583       uint64_t NumElements = AT->getNumElements();
584       
585       // If this is an array index and the index is not constant, we cannot
586       // promote... that is unless the array has exactly one or two elements in
587       // it, in which case we CAN promote it, but we have to canonicalize this
588       // out if this is the only problem.
589       if ((NumElements == 1 || NumElements == 2) &&
590           AllUsersAreLoads(GEPI)) {
591         Info.needsCleanup = true;
592         return;  // Canonicalization required!
593       }
594       return MarkUnsafe(Info);
595     }
596   }
597  
598   // Walk through the GEP type indices, checking the types that this indexes
599   // into.
600   for (; I != E; ++I) {
601     // Ignore struct elements, no extra checking needed for these.
602     if (isa<StructType>(*I))
603       continue;
604     
605     ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
606     if (!IdxVal) return MarkUnsafe(Info);
607
608     // Are all indices still zero?
609     IsAllZeroIndices &= IdxVal->isZero();
610     
611     if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
612       // This GEP indexes an array.  Verify that this is an in-range constant
613       // integer. Specifically, consider A[0][i]. We cannot know that the user
614       // isn't doing invalid things like allowing i to index an out-of-range
615       // subscript that accesses A[1].  Because of this, we have to reject SROA
616       // of any accesses into structs where any of the components are variables.
617       if (IdxVal->getZExtValue() >= AT->getNumElements())
618         return MarkUnsafe(Info);
619     } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
620       if (IdxVal->getZExtValue() >= VT->getNumElements())
621         return MarkUnsafe(Info);
622     }
623   }
624   
625   // If there are any non-simple uses of this getelementptr, make sure to reject
626   // them.
627   return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
628 }
629
630 /// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
631 /// intrinsic can be promoted by SROA.  At this point, we know that the operand
632 /// of the memintrinsic is a pointer to the beginning of the allocation.
633 void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocaInst *AI,
634                                           unsigned OpNo, AllocaInfo &Info) {
635   // If not constant length, give up.
636   ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
637   if (!Length) return MarkUnsafe(Info);
638   
639   // If not the whole aggregate, give up.
640   if (Length->getZExtValue() !=
641       TD->getTypeAllocSize(AI->getType()->getElementType()))
642     return MarkUnsafe(Info);
643   
644   // We only know about memcpy/memset/memmove.
645   if (!isa<MemIntrinsic>(MI))
646     return MarkUnsafe(Info);
647   
648   // Otherwise, we can transform it.  Determine whether this is a memcpy/set
649   // into or out of the aggregate.
650   if (OpNo == 1)
651     Info.isMemCpyDst = true;
652   else {
653     assert(OpNo == 2);
654     Info.isMemCpySrc = true;
655   }
656 }
657
658 /// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
659 /// are 
660 void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocaInst *AI,
661                                           AllocaInfo &Info) {
662   for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
663        UI != E; ++UI) {
664     if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
665       isSafeUseOfBitCastedAllocation(BCU, AI, Info);
666     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
667       isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
668     } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
669       if (SI->isVolatile())
670         return MarkUnsafe(Info);
671       
672       // If storing the entire alloca in one chunk through a bitcasted pointer
673       // to integer, we can transform it.  This happens (for example) when you
674       // cast a {i32,i32}* to i64* and store through it.  This is similar to the
675       // memcpy case and occurs in various "byval" cases and emulated memcpys.
676       if (isa<IntegerType>(SI->getOperand(0)->getType()) &&
677           TD->getTypeAllocSize(SI->getOperand(0)->getType()) ==
678           TD->getTypeAllocSize(AI->getType()->getElementType())) {
679         Info.isMemCpyDst = true;
680         continue;
681       }
682       return MarkUnsafe(Info);
683     } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
684       if (LI->isVolatile())
685         return MarkUnsafe(Info);
686
687       // If loading the entire alloca in one chunk through a bitcasted pointer
688       // to integer, we can transform it.  This happens (for example) when you
689       // cast a {i32,i32}* to i64* and load through it.  This is similar to the
690       // memcpy case and occurs in various "byval" cases and emulated memcpys.
691       if (isa<IntegerType>(LI->getType()) &&
692           TD->getTypeAllocSize(LI->getType()) ==
693           TD->getTypeAllocSize(AI->getType()->getElementType())) {
694         Info.isMemCpySrc = true;
695         continue;
696       }
697       return MarkUnsafe(Info);
698     } else if (isa<DbgInfoIntrinsic>(UI)) {
699       // If one user is DbgInfoIntrinsic then check if all users are
700       // DbgInfoIntrinsics.
701       if (OnlyUsedByDbgInfoIntrinsics(BC)) {
702         Info.needsCleanup = true;
703         return;
704       }
705       else
706         MarkUnsafe(Info);
707     }
708     else {
709       return MarkUnsafe(Info);
710     }
711     if (Info.isUnsafe) return;
712   }
713 }
714
715 /// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
716 /// to its first element.  Transform users of the cast to use the new values
717 /// instead.
718 void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocaInst *AI,
719                                       SmallVector<AllocaInst*, 32> &NewElts) {
720   Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
721   while (UI != UE) {
722     Instruction *User = cast<Instruction>(*UI++);
723     if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) {
724       RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
725       if (BCU->use_empty()) BCU->eraseFromParent();
726       continue;
727     }
728
729     if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
730       // This must be memcpy/memmove/memset of the entire aggregate.
731       // Split into one per element.
732       RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts);
733       continue;
734     }
735       
736     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
737       // If this is a store of the entire alloca from an integer, rewrite it.
738       RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
739       continue;
740     }
741
742     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
743       // If this is a load of the entire alloca to an integer, rewrite it.
744       RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
745       continue;
746     }
747     
748     // Otherwise it must be some other user of a gep of the first pointer.  Just
749     // leave these alone.
750     continue;
751   }
752 }
753
754 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
755 /// Rewrite it to copy or set the elements of the scalarized memory.
756 void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
757                                         AllocaInst *AI,
758                                         SmallVector<AllocaInst*, 32> &NewElts) {
759   
760   // If this is a memcpy/memmove, construct the other pointer as the
761   // appropriate type.  The "Other" pointer is the pointer that goes to memory
762   // that doesn't have anything to do with the alloca that we are promoting. For
763   // memset, this Value* stays null.
764   Value *OtherPtr = 0;
765   LLVMContext &Context = MI->getContext();
766   unsigned MemAlignment = MI->getAlignment();
767   if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
768     if (BCInst == MTI->getRawDest())
769       OtherPtr = MTI->getRawSource();
770     else {
771       assert(BCInst == MTI->getRawSource());
772       OtherPtr = MTI->getRawDest();
773     }
774   }
775   
776   // If there is an other pointer, we want to convert it to the same pointer
777   // type as AI has, so we can GEP through it safely.
778   if (OtherPtr) {
779     // It is likely that OtherPtr is a bitcast, if so, remove it.
780     if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
781       OtherPtr = BC->getOperand(0);
782     // All zero GEPs are effectively bitcasts.
783     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
784       if (GEP->hasAllZeroIndices())
785         OtherPtr = GEP->getOperand(0);
786     
787     if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
788       if (BCE->getOpcode() == Instruction::BitCast)
789         OtherPtr = BCE->getOperand(0);
790     
791     // If the pointer is not the right type, insert a bitcast to the right
792     // type.
793     if (OtherPtr->getType() != AI->getType())
794       OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
795                                  MI);
796   }
797   
798   // Process each element of the aggregate.
799   Value *TheFn = MI->getOperand(0);
800   const Type *BytePtrTy = MI->getRawDest()->getType();
801   bool SROADest = MI->getRawDest() == BCInst;
802   
803   Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
804
805   for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
806     // If this is a memcpy/memmove, emit a GEP of the other element address.
807     Value *OtherElt = 0;
808     unsigned OtherEltAlign = MemAlignment;
809     
810     if (OtherPtr) {
811       Value *Idx[2] = { Zero,
812                       ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
813       OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
814                                            OtherPtr->getNameStr()+"."+Twine(i),
815                                            MI);
816       uint64_t EltOffset;
817       const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
818       if (const StructType *ST =
819             dyn_cast<StructType>(OtherPtrTy->getElementType())) {
820         EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
821       } else {
822         const Type *EltTy =
823           cast<SequentialType>(OtherPtr->getType())->getElementType();
824         EltOffset = TD->getTypeAllocSize(EltTy)*i;
825       }
826       
827       // The alignment of the other pointer is the guaranteed alignment of the
828       // element, which is affected by both the known alignment of the whole
829       // mem intrinsic and the alignment of the element.  If the alignment of
830       // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
831       // known alignment is just 4 bytes.
832       OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
833     }
834     
835     Value *EltPtr = NewElts[i];
836     const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
837     
838     // If we got down to a scalar, insert a load or store as appropriate.
839     if (EltTy->isSingleValueType()) {
840       if (isa<MemTransferInst>(MI)) {
841         if (SROADest) {
842           // From Other to Alloca.
843           Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
844           new StoreInst(Elt, EltPtr, MI);
845         } else {
846           // From Alloca to Other.
847           Value *Elt = new LoadInst(EltPtr, "tmp", MI);
848           new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
849         }
850         continue;
851       }
852       assert(isa<MemSetInst>(MI));
853       
854       // If the stored element is zero (common case), just store a null
855       // constant.
856       Constant *StoreVal;
857       if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
858         if (CI->isZero()) {
859           StoreVal = Constant::getNullValue(EltTy);  // 0.0, null, 0, <0,0>
860         } else {
861           // If EltTy is a vector type, get the element type.
862           const Type *ValTy = EltTy->getScalarType();
863
864           // Construct an integer with the right value.
865           unsigned EltSize = TD->getTypeSizeInBits(ValTy);
866           APInt OneVal(EltSize, CI->getZExtValue());
867           APInt TotalVal(OneVal);
868           // Set each byte.
869           for (unsigned i = 0; 8*i < EltSize; ++i) {
870             TotalVal = TotalVal.shl(8);
871             TotalVal |= OneVal;
872           }
873           
874           // Convert the integer value to the appropriate type.
875           StoreVal = ConstantInt::get(Context, TotalVal);
876           if (isa<PointerType>(ValTy))
877             StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
878           else if (ValTy->isFloatingPoint())
879             StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
880           assert(StoreVal->getType() == ValTy && "Type mismatch!");
881           
882           // If the requested value was a vector constant, create it.
883           if (EltTy != ValTy) {
884             unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
885             SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
886             StoreVal = ConstantVector::get(&Elts[0], NumElts);
887           }
888         }
889         new StoreInst(StoreVal, EltPtr, MI);
890         continue;
891       }
892       // Otherwise, if we're storing a byte variable, use a memset call for
893       // this element.
894     }
895     
896     // Cast the element pointer to BytePtrTy.
897     if (EltPtr->getType() != BytePtrTy)
898       EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
899     
900     // Cast the other pointer (if we have one) to BytePtrTy. 
901     if (OtherElt && OtherElt->getType() != BytePtrTy)
902       OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
903                                  MI);
904     
905     unsigned EltSize = TD->getTypeAllocSize(EltTy);
906     
907     // Finally, insert the meminst for this element.
908     if (isa<MemTransferInst>(MI)) {
909       Value *Ops[] = {
910         SROADest ? EltPtr : OtherElt,  // Dest ptr
911         SROADest ? OtherElt : EltPtr,  // Src ptr
912         ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
913         // Align
914         ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign)
915       };
916       CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
917     } else {
918       assert(isa<MemSetInst>(MI));
919       Value *Ops[] = {
920         EltPtr, MI->getOperand(2),  // Dest, Value,
921         ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
922         Zero  // Align
923       };
924       CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
925     }
926   }
927   MI->eraseFromParent();
928 }
929
930 /// RewriteStoreUserOfWholeAlloca - We found an store of an integer that
931 /// overwrites the entire allocation.  Extract out the pieces of the stored
932 /// integer and store them individually.
933 void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
934                                          SmallVector<AllocaInst*, 32> &NewElts){
935   // Extract each element out of the integer according to its structure offset
936   // and store the element value to the individual alloca.
937   Value *SrcVal = SI->getOperand(0);
938   const Type *AllocaEltTy = AI->getType()->getElementType();
939   uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
940   
941   // If this isn't a store of an integer to the whole alloca, it may be a store
942   // to the first element.  Just ignore the store in this case and normal SROA
943   // will handle it.
944   if (!isa<IntegerType>(SrcVal->getType()) ||
945       TD->getTypeAllocSizeInBits(SrcVal->getType()) != AllocaSizeBits)
946     return;
947   // Handle tail padding by extending the operand
948   if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
949     SrcVal = new ZExtInst(SrcVal,
950                           IntegerType::get(SI->getContext(), AllocaSizeBits), 
951                           "", SI);
952
953   DEBUG(errs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
954                << '\n');
955
956   // There are two forms here: AI could be an array or struct.  Both cases
957   // have different ways to compute the element offset.
958   if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
959     const StructLayout *Layout = TD->getStructLayout(EltSTy);
960     
961     for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
962       // Get the number of bits to shift SrcVal to get the value.
963       const Type *FieldTy = EltSTy->getElementType(i);
964       uint64_t Shift = Layout->getElementOffsetInBits(i);
965       
966       if (TD->isBigEndian())
967         Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
968       
969       Value *EltVal = SrcVal;
970       if (Shift) {
971         Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
972         EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
973                                             "sroa.store.elt", SI);
974       }
975       
976       // Truncate down to an integer of the right size.
977       uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
978       
979       // Ignore zero sized fields like {}, they obviously contain no data.
980       if (FieldSizeBits == 0) continue;
981       
982       if (FieldSizeBits != AllocaSizeBits)
983         EltVal = new TruncInst(EltVal,
984                              IntegerType::get(SI->getContext(), FieldSizeBits),
985                               "", SI);
986       Value *DestField = NewElts[i];
987       if (EltVal->getType() == FieldTy) {
988         // Storing to an integer field of this size, just do it.
989       } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
990         // Bitcast to the right element type (for fp/vector values).
991         EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
992       } else {
993         // Otherwise, bitcast the dest pointer (for aggregates).
994         DestField = new BitCastInst(DestField,
995                               PointerType::getUnqual(EltVal->getType()),
996                                     "", SI);
997       }
998       new StoreInst(EltVal, DestField, SI);
999     }
1000     
1001   } else {
1002     const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1003     const Type *ArrayEltTy = ATy->getElementType();
1004     uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
1005     uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1006
1007     uint64_t Shift;
1008     
1009     if (TD->isBigEndian())
1010       Shift = AllocaSizeBits-ElementOffset;
1011     else 
1012       Shift = 0;
1013     
1014     for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1015       // Ignore zero sized fields like {}, they obviously contain no data.
1016       if (ElementSizeBits == 0) continue;
1017       
1018       Value *EltVal = SrcVal;
1019       if (Shift) {
1020         Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
1021         EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1022                                             "sroa.store.elt", SI);
1023       }
1024       
1025       // Truncate down to an integer of the right size.
1026       if (ElementSizeBits != AllocaSizeBits)
1027         EltVal = new TruncInst(EltVal, 
1028                                IntegerType::get(SI->getContext(), 
1029                                                 ElementSizeBits),"",SI);
1030       Value *DestField = NewElts[i];
1031       if (EltVal->getType() == ArrayEltTy) {
1032         // Storing to an integer field of this size, just do it.
1033       } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
1034         // Bitcast to the right element type (for fp/vector values).
1035         EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1036       } else {
1037         // Otherwise, bitcast the dest pointer (for aggregates).
1038         DestField = new BitCastInst(DestField,
1039                               PointerType::getUnqual(EltVal->getType()),
1040                                     "", SI);
1041       }
1042       new StoreInst(EltVal, DestField, SI);
1043       
1044       if (TD->isBigEndian())
1045         Shift -= ElementOffset;
1046       else 
1047         Shift += ElementOffset;
1048     }
1049   }
1050   
1051   SI->eraseFromParent();
1052 }
1053
1054 /// RewriteLoadUserOfWholeAlloca - We found an load of the entire allocation to
1055 /// an integer.  Load the individual pieces to form the aggregate value.
1056 void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
1057                                         SmallVector<AllocaInst*, 32> &NewElts) {
1058   // Extract each element out of the NewElts according to its structure offset
1059   // and form the result value.
1060   const Type *AllocaEltTy = AI->getType()->getElementType();
1061   uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
1062   
1063   // If this isn't a load of the whole alloca to an integer, it may be a load
1064   // of the first element.  Just ignore the load in this case and normal SROA
1065   // will handle it.
1066   if (!isa<IntegerType>(LI->getType()) ||
1067       TD->getTypeAllocSizeInBits(LI->getType()) != AllocaSizeBits)
1068     return;
1069   
1070   DEBUG(errs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
1071                << '\n');
1072   
1073   // There are two forms here: AI could be an array or struct.  Both cases
1074   // have different ways to compute the element offset.
1075   const StructLayout *Layout = 0;
1076   uint64_t ArrayEltBitOffset = 0;
1077   if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1078     Layout = TD->getStructLayout(EltSTy);
1079   } else {
1080     const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
1081     ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
1082   }    
1083   
1084   Value *ResultVal = 
1085     Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
1086   
1087   for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1088     // Load the value from the alloca.  If the NewElt is an aggregate, cast
1089     // the pointer to an integer of the same size before doing the load.
1090     Value *SrcField = NewElts[i];
1091     const Type *FieldTy =
1092       cast<PointerType>(SrcField->getType())->getElementType();
1093     uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1094     
1095     // Ignore zero sized fields like {}, they obviously contain no data.
1096     if (FieldSizeBits == 0) continue;
1097     
1098     const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(), 
1099                                                      FieldSizeBits);
1100     if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
1101         !isa<VectorType>(FieldTy))
1102       SrcField = new BitCastInst(SrcField,
1103                                  PointerType::getUnqual(FieldIntTy),
1104                                  "", LI);
1105     SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1106
1107     // If SrcField is a fp or vector of the right size but that isn't an
1108     // integer type, bitcast to an integer so we can shift it.
1109     if (SrcField->getType() != FieldIntTy)
1110       SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1111
1112     // Zero extend the field to be the same size as the final alloca so that
1113     // we can shift and insert it.
1114     if (SrcField->getType() != ResultVal->getType())
1115       SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1116     
1117     // Determine the number of bits to shift SrcField.
1118     uint64_t Shift;
1119     if (Layout) // Struct case.
1120       Shift = Layout->getElementOffsetInBits(i);
1121     else  // Array case.
1122       Shift = i*ArrayEltBitOffset;
1123     
1124     if (TD->isBigEndian())
1125       Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1126     
1127     if (Shift) {
1128       Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
1129       SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1130     }
1131
1132     ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1133   }
1134
1135   // Handle tail padding by truncating the result
1136   if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1137     ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1138
1139   LI->replaceAllUsesWith(ResultVal);
1140   LI->eraseFromParent();
1141 }
1142
1143
1144 /// HasPadding - Return true if the specified type has any structure or
1145 /// alignment padding, false otherwise.
1146 static bool HasPadding(const Type *Ty, const TargetData &TD) {
1147   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1148     const StructLayout *SL = TD.getStructLayout(STy);
1149     unsigned PrevFieldBitOffset = 0;
1150     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1151       unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1152
1153       // Padding in sub-elements?
1154       if (HasPadding(STy->getElementType(i), TD))
1155         return true;
1156
1157       // Check to see if there is any padding between this element and the
1158       // previous one.
1159       if (i) {
1160         unsigned PrevFieldEnd =
1161         PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1162         if (PrevFieldEnd < FieldBitOffset)
1163           return true;
1164       }
1165
1166       PrevFieldBitOffset = FieldBitOffset;
1167     }
1168
1169     //  Check for tail padding.
1170     if (unsigned EltCount = STy->getNumElements()) {
1171       unsigned PrevFieldEnd = PrevFieldBitOffset +
1172                    TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
1173       if (PrevFieldEnd < SL->getSizeInBits())
1174         return true;
1175     }
1176
1177   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1178     return HasPadding(ATy->getElementType(), TD);
1179   } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1180     return HasPadding(VTy->getElementType(), TD);
1181   }
1182   return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
1183 }
1184
1185 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1186 /// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
1187 /// or 1 if safe after canonicalization has been performed.
1188 ///
1189 int SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
1190   // Loop over the use list of the alloca.  We can only transform it if all of
1191   // the users are safe to transform.
1192   AllocaInfo Info;
1193   
1194   for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
1195        I != E; ++I) {
1196     isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
1197     if (Info.isUnsafe) {
1198       DEBUG(errs() << "Cannot transform: " << *AI << "\n  due to user: "
1199                    << **I << '\n');
1200       return 0;
1201     }
1202   }
1203   
1204   // Okay, we know all the users are promotable.  If the aggregate is a memcpy
1205   // source and destination, we have to be careful.  In particular, the memcpy
1206   // could be moving around elements that live in structure padding of the LLVM
1207   // types, but may actually be used.  In these cases, we refuse to promote the
1208   // struct.
1209   if (Info.isMemCpySrc && Info.isMemCpyDst &&
1210       HasPadding(AI->getType()->getElementType(), *TD))
1211     return 0;
1212
1213   // If we require cleanup, return 1, otherwise return 3.
1214   return Info.needsCleanup ? 1 : 3;
1215 }
1216
1217 /// CleanupGEP - GEP is used by an Alloca, which can be prompted after the GEP
1218 /// is canonicalized here.
1219 void SROA::CleanupGEP(GetElementPtrInst *GEPI) {
1220   gep_type_iterator I = gep_type_begin(GEPI);
1221   ++I;
1222   
1223   const ArrayType *AT = dyn_cast<ArrayType>(*I);
1224   if (!AT) 
1225     return;
1226
1227   uint64_t NumElements = AT->getNumElements();
1228   
1229   if (isa<ConstantInt>(I.getOperand()))
1230     return;
1231
1232   if (NumElements == 1) {
1233     GEPI->setOperand(2, 
1234                   Constant::getNullValue(Type::getInt32Ty(GEPI->getContext())));
1235     return;
1236   } 
1237     
1238   assert(NumElements == 2 && "Unhandled case!");
1239   // All users of the GEP must be loads.  At each use of the GEP, insert
1240   // two loads of the appropriate indexed GEP and select between them.
1241   Value *IsOne = new ICmpInst(GEPI, ICmpInst::ICMP_NE, I.getOperand(), 
1242                               Constant::getNullValue(I.getOperand()->getType()),
1243                               "isone");
1244   // Insert the new GEP instructions, which are properly indexed.
1245   SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
1246   Indices[1] = Constant::getNullValue(Type::getInt32Ty(GEPI->getContext()));
1247   Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1248                                              Indices.begin(),
1249                                              Indices.end(),
1250                                              GEPI->getName()+".0", GEPI);
1251   Indices[1] = ConstantInt::get(Type::getInt32Ty(GEPI->getContext()), 1);
1252   Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1253                                             Indices.begin(),
1254                                             Indices.end(),
1255                                             GEPI->getName()+".1", GEPI);
1256   // Replace all loads of the variable index GEP with loads from both
1257   // indexes and a select.
1258   while (!GEPI->use_empty()) {
1259     LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1260     Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1261     Value *One  = new LoadInst(OneIdx , LI->getName()+".1", LI);
1262     Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
1263     LI->replaceAllUsesWith(R);
1264     LI->eraseFromParent();
1265   }
1266   GEPI->eraseFromParent();
1267 }
1268
1269
1270 /// CleanupAllocaUsers - If SROA reported that it can promote the specified
1271 /// allocation, but only if cleaned up, perform the cleanups required.
1272 void SROA::CleanupAllocaUsers(AllocaInst *AI) {
1273   // At this point, we know that the end result will be SROA'd and promoted, so
1274   // we can insert ugly code if required so long as sroa+mem2reg will clean it
1275   // up.
1276   for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1277        UI != E; ) {
1278     User *U = *UI++;
1279     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U))
1280       CleanupGEP(GEPI);
1281     else {
1282       Instruction *I = cast<Instruction>(U);
1283       SmallVector<DbgInfoIntrinsic *, 2> DbgInUses;
1284       if (!isa<StoreInst>(I) && OnlyUsedByDbgInfoIntrinsics(I, &DbgInUses)) {
1285         // Safe to remove debug info uses.
1286         while (!DbgInUses.empty()) {
1287           DbgInfoIntrinsic *DI = DbgInUses.back(); DbgInUses.pop_back();
1288           DI->eraseFromParent();
1289         }
1290         I->eraseFromParent();
1291       }
1292     }
1293   }
1294 }
1295
1296 /// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1297 /// the offset specified by Offset (which is specified in bytes).
1298 ///
1299 /// There are two cases we handle here:
1300 ///   1) A union of vector types of the same size and potentially its elements.
1301 ///      Here we turn element accesses into insert/extract element operations.
1302 ///      This promotes a <4 x float> with a store of float to the third element
1303 ///      into a <4 x float> that uses insert element.
1304 ///   2) A fully general blob of memory, which we turn into some (potentially
1305 ///      large) integer type with extract and insert operations where the loads
1306 ///      and stores would mutate the memory.
1307 static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
1308                         unsigned AllocaSize, const TargetData &TD,
1309                         LLVMContext &Context) {
1310   // If this could be contributing to a vector, analyze it.
1311   if (VecTy != Type::getVoidTy(Context)) { // either null or a vector type.
1312
1313     // If the In type is a vector that is the same size as the alloca, see if it
1314     // matches the existing VecTy.
1315     if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1316       if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1317         // If we're storing/loading a vector of the right size, allow it as a
1318         // vector.  If this the first vector we see, remember the type so that
1319         // we know the element size.
1320         if (VecTy == 0)
1321           VecTy = VInTy;
1322         return;
1323       }
1324     } else if (In->isFloatTy() || In->isDoubleTy() ||
1325                (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1326                 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1327       // If we're accessing something that could be an element of a vector, see
1328       // if the implied vector agrees with what we already have and if Offset is
1329       // compatible with it.
1330       unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1331       if (Offset % EltSize == 0 &&
1332           AllocaSize % EltSize == 0 &&
1333           (VecTy == 0 || 
1334            cast<VectorType>(VecTy)->getElementType()
1335                  ->getPrimitiveSizeInBits()/8 == EltSize)) {
1336         if (VecTy == 0)
1337           VecTy = VectorType::get(In, AllocaSize/EltSize);
1338         return;
1339       }
1340     }
1341   }
1342   
1343   // Otherwise, we have a case that we can't handle with an optimized vector
1344   // form.  We can still turn this into a large integer.
1345   VecTy = Type::getVoidTy(Context);
1346 }
1347
1348 /// CanConvertToScalar - V is a pointer.  If we can convert the pointee and all
1349 /// its accesses to use a to single vector type, return true, and set VecTy to
1350 /// the new type.  If we could convert the alloca into a single promotable
1351 /// integer, return true but set VecTy to VoidTy.  Further, if the use is not a
1352 /// completely trivial use that mem2reg could promote, set IsNotTrivial.  Offset
1353 /// is the current offset from the base of the alloca being analyzed.
1354 ///
1355 /// If we see at least one access to the value that is as a vector type, set the
1356 /// SawVec flag.
1357 ///
1358 bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1359                               bool &SawVec, uint64_t Offset,
1360                               unsigned AllocaSize) {
1361   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1362     Instruction *User = cast<Instruction>(*UI);
1363     
1364     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1365       // Don't break volatile loads.
1366       if (LI->isVolatile())
1367         return false;
1368       MergeInType(LI->getType(), Offset, VecTy,
1369                   AllocaSize, *TD, V->getContext());
1370       SawVec |= isa<VectorType>(LI->getType());
1371       continue;
1372     }
1373     
1374     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1375       // Storing the pointer, not into the value?
1376       if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
1377       MergeInType(SI->getOperand(0)->getType(), Offset,
1378                   VecTy, AllocaSize, *TD, V->getContext());
1379       SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
1380       continue;
1381     }
1382     
1383     if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
1384       if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1385                               AllocaSize))
1386         return false;
1387       IsNotTrivial = true;
1388       continue;
1389     }
1390
1391     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1392       // If this is a GEP with a variable indices, we can't handle it.
1393       if (!GEP->hasAllConstantIndices())
1394         return false;
1395       
1396       // Compute the offset that this GEP adds to the pointer.
1397       SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1398       uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1399                                                 &Indices[0], Indices.size());
1400       // See if all uses can be converted.
1401       if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
1402                               AllocaSize))
1403         return false;
1404       IsNotTrivial = true;
1405       continue;
1406     }
1407
1408     // If this is a constant sized memset of a constant value (e.g. 0) we can
1409     // handle it.
1410     if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1411       // Store of constant value and constant size.
1412       if (isa<ConstantInt>(MSI->getValue()) &&
1413           isa<ConstantInt>(MSI->getLength())) {
1414         IsNotTrivial = true;
1415         continue;
1416       }
1417     }
1418
1419     // If this is a memcpy or memmove into or out of the whole allocation, we
1420     // can handle it like a load or store of the scalar type.
1421     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1422       if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
1423         if (Len->getZExtValue() == AllocaSize && Offset == 0) {
1424           IsNotTrivial = true;
1425           continue;
1426         }
1427     }
1428     
1429     // Ignore dbg intrinsic.
1430     if (isa<DbgInfoIntrinsic>(User))
1431       continue;
1432
1433     // Otherwise, we cannot handle this!
1434     return false;
1435   }
1436   
1437   return true;
1438 }
1439
1440
1441 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1442 /// directly.  This happens when we are converting an "integer union" to a
1443 /// single integer scalar, or when we are converting a "vector union" to a
1444 /// vector with insert/extractelement instructions.
1445 ///
1446 /// Offset is an offset from the original alloca, in bits that need to be
1447 /// shifted to the right.  By the end of this, there should be no uses of Ptr.
1448 void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
1449   while (!Ptr->use_empty()) {
1450     Instruction *User = cast<Instruction>(Ptr->use_back());
1451
1452     if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1453       ConvertUsesToScalar(CI, NewAI, Offset);
1454       CI->eraseFromParent();
1455       continue;
1456     }
1457
1458     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1459       // Compute the offset that this GEP adds to the pointer.
1460       SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1461       uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1462                                                 &Indices[0], Indices.size());
1463       ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
1464       GEP->eraseFromParent();
1465       continue;
1466     }
1467     
1468     IRBuilder<> Builder(User->getParent(), User);
1469     
1470     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1471       // The load is a bit extract from NewAI shifted right by Offset bits.
1472       Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1473       Value *NewLoadVal
1474         = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1475       LI->replaceAllUsesWith(NewLoadVal);
1476       LI->eraseFromParent();
1477       continue;
1478     }
1479     
1480     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1481       assert(SI->getOperand(0) != Ptr && "Consistency error!");
1482       // FIXME: Remove once builder has Twine API.
1483       Value *Old = Builder.CreateLoad(NewAI,
1484                                       (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,
1510                                         (NewAI->getName()+".in").str().c_str());
1511         Value *New = ConvertScalar_InsertValue(
1512                                     ConstantInt::get(User->getContext(), APVal),
1513                                                Old, Offset, Builder);
1514         Builder.CreateStore(New, NewAI);
1515       }
1516       MSI->eraseFromParent();
1517       continue;
1518     }
1519
1520     // If this is a memcpy or memmove into or out of the whole allocation, we
1521     // can handle it like a load or store of the scalar type.
1522     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1523       assert(Offset == 0 && "must be store to start of alloca");
1524       
1525       // If the source and destination are both to the same alloca, then this is
1526       // a noop copy-to-self, just delete it.  Otherwise, emit a load and store
1527       // as appropriate.
1528       AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject());
1529       
1530       if (MTI->getSource()->getUnderlyingObject() != OrigAI) {
1531         // Dest must be OrigAI, change this to be a load from the original
1532         // pointer (bitcasted), then a store to our new alloca.
1533         assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
1534         Value *SrcPtr = MTI->getSource();
1535         SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
1536         
1537         LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
1538         SrcVal->setAlignment(MTI->getAlignment());
1539         Builder.CreateStore(SrcVal, NewAI);
1540       } else if (MTI->getDest()->getUnderlyingObject() != OrigAI) {
1541         // Src must be OrigAI, change this to be a load from NewAI then a store
1542         // through the original dest pointer (bitcasted).
1543         assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
1544         LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
1545
1546         Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
1547         StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
1548         NewStore->setAlignment(MTI->getAlignment());
1549       } else {
1550         // Noop transfer. Src == Dst
1551       }
1552           
1553
1554       MTI->eraseFromParent();
1555       continue;
1556     }
1557     
1558     // If user is a dbg info intrinsic then it is safe to remove it.
1559     if (isa<DbgInfoIntrinsic>(User)) {
1560       User->eraseFromParent();
1561       continue;
1562     }
1563
1564     llvm_unreachable("Unsupported operation!");
1565   }
1566 }
1567
1568 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1569 /// or vector value FromVal, extracting the bits from the offset specified by
1570 /// Offset.  This returns the value, which is of type ToType.
1571 ///
1572 /// This happens when we are converting an "integer union" to a single
1573 /// integer scalar, or when we are converting a "vector union" to a vector with
1574 /// insert/extractelement instructions.
1575 ///
1576 /// Offset is an offset from the original alloca, in bits that need to be
1577 /// shifted to the right.
1578 Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1579                                         uint64_t Offset, IRBuilder<> &Builder) {
1580   // If the load is of the whole new alloca, no conversion is needed.
1581   if (FromVal->getType() == ToType && Offset == 0)
1582     return FromVal;
1583
1584   // If the result alloca is a vector type, this is either an element
1585   // access or a bitcast to another vector type of the same size.
1586   if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1587     if (isa<VectorType>(ToType))
1588       return Builder.CreateBitCast(FromVal, ToType, "tmp");
1589
1590     // Otherwise it must be an element access.
1591     unsigned Elt = 0;
1592     if (Offset) {
1593       unsigned EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
1594       Elt = Offset/EltSize;
1595       assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
1596     }
1597     // Return the element extracted out of it.
1598     Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
1599                     Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
1600     if (V->getType() != ToType)
1601       V = Builder.CreateBitCast(V, ToType, "tmp");
1602     return V;
1603   }
1604   
1605   // If ToType is a first class aggregate, extract out each of the pieces and
1606   // use insertvalue's to form the FCA.
1607   if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1608     const StructLayout &Layout = *TD->getStructLayout(ST);
1609     Value *Res = UndefValue::get(ST);
1610     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1611       Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
1612                                         Offset+Layout.getElementOffsetInBits(i),
1613                                               Builder);
1614       Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1615     }
1616     return Res;
1617   }
1618   
1619   if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
1620     uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
1621     Value *Res = UndefValue::get(AT);
1622     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1623       Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1624                                               Offset+i*EltSize, Builder);
1625       Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1626     }
1627     return Res;
1628   }
1629
1630   // Otherwise, this must be a union that was converted to an integer value.
1631   const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
1632
1633   // If this is a big-endian system and the load is narrower than the
1634   // full alloca type, we need to do a shift to get the right bits.
1635   int ShAmt = 0;
1636   if (TD->isBigEndian()) {
1637     // On big-endian machines, the lowest bit is stored at the bit offset
1638     // from the pointer given by getTypeStoreSizeInBits.  This matters for
1639     // integers with a bitwidth that is not a multiple of 8.
1640     ShAmt = TD->getTypeStoreSizeInBits(NTy) -
1641             TD->getTypeStoreSizeInBits(ToType) - Offset;
1642   } else {
1643     ShAmt = Offset;
1644   }
1645
1646   // Note: we support negative bitwidths (with shl) which are not defined.
1647   // We do this to support (f.e.) loads off the end of a structure where
1648   // only some bits are used.
1649   if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
1650     FromVal = Builder.CreateLShr(FromVal,
1651                                  ConstantInt::get(FromVal->getType(),
1652                                                            ShAmt), "tmp");
1653   else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
1654     FromVal = Builder.CreateShl(FromVal, 
1655                                 ConstantInt::get(FromVal->getType(),
1656                                                           -ShAmt), "tmp");
1657
1658   // Finally, unconditionally truncate the integer to the right width.
1659   unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
1660   if (LIBitWidth < NTy->getBitWidth())
1661     FromVal =
1662       Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(), 
1663                                                     LIBitWidth), "tmp");
1664   else if (LIBitWidth > NTy->getBitWidth())
1665     FromVal =
1666        Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(), 
1667                                                     LIBitWidth), "tmp");
1668
1669   // If the result is an integer, this is a trunc or bitcast.
1670   if (isa<IntegerType>(ToType)) {
1671     // Should be done.
1672   } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
1673     // Just do a bitcast, we know the sizes match up.
1674     FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
1675   } else {
1676     // Otherwise must be a pointer.
1677     FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
1678   }
1679   assert(FromVal->getType() == ToType && "Didn't convert right?");
1680   return FromVal;
1681 }
1682
1683
1684 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1685 /// or vector value "Old" at the offset specified by Offset.
1686 ///
1687 /// This happens when we are converting an "integer union" to a
1688 /// single integer scalar, or when we are converting a "vector union" to a
1689 /// vector with insert/extractelement instructions.
1690 ///
1691 /// Offset is an offset from the original alloca, in bits that need to be
1692 /// shifted to the right.
1693 Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
1694                                        uint64_t Offset, IRBuilder<> &Builder) {
1695
1696   // Convert the stored type to the actual type, shift it left to insert
1697   // then 'or' into place.
1698   const Type *AllocaType = Old->getType();
1699   LLVMContext &Context = Old->getContext();
1700
1701   if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
1702     uint64_t VecSize = TD->getTypeAllocSizeInBits(VTy);
1703     uint64_t ValSize = TD->getTypeAllocSizeInBits(SV->getType());
1704     
1705     // Changing the whole vector with memset or with an access of a different
1706     // vector type?
1707     if (ValSize == VecSize)
1708       return Builder.CreateBitCast(SV, AllocaType, "tmp");
1709
1710     uint64_t EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
1711
1712     // Must be an element insertion.
1713     unsigned Elt = Offset/EltSize;
1714     
1715     if (SV->getType() != VTy->getElementType())
1716       SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1717     
1718     SV = Builder.CreateInsertElement(Old, SV, 
1719                      ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
1720                                      "tmp");
1721     return SV;
1722   }
1723   
1724   // If SV is a first-class aggregate value, insert each value recursively.
1725   if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1726     const StructLayout &Layout = *TD->getStructLayout(ST);
1727     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1728       Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1729       Old = ConvertScalar_InsertValue(Elt, Old, 
1730                                       Offset+Layout.getElementOffsetInBits(i),
1731                                       Builder);
1732     }
1733     return Old;
1734   }
1735   
1736   if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
1737     uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
1738     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1739       Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1740       Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
1741     }
1742     return Old;
1743   }
1744
1745   // If SV is a float, convert it to the appropriate integer type.
1746   // If it is a pointer, do the same.
1747   unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1748   unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1749   unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1750   unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1751   if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
1752     SV = Builder.CreateBitCast(SV,
1753                             IntegerType::get(SV->getContext(),SrcWidth), "tmp");
1754   else if (isa<PointerType>(SV->getType()))
1755     SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(SV->getContext()), "tmp");
1756
1757   // Zero extend or truncate the value if needed.
1758   if (SV->getType() != AllocaType) {
1759     if (SV->getType()->getPrimitiveSizeInBits() <
1760              AllocaType->getPrimitiveSizeInBits())
1761       SV = Builder.CreateZExt(SV, AllocaType, "tmp");
1762     else {
1763       // Truncation may be needed if storing more than the alloca can hold
1764       // (undefined behavior).
1765       SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
1766       SrcWidth = DestWidth;
1767       SrcStoreWidth = DestStoreWidth;
1768     }
1769   }
1770
1771   // If this is a big-endian system and the store is narrower than the
1772   // full alloca type, we need to do a shift to get the right bits.
1773   int ShAmt = 0;
1774   if (TD->isBigEndian()) {
1775     // On big-endian machines, the lowest bit is stored at the bit offset
1776     // from the pointer given by getTypeStoreSizeInBits.  This matters for
1777     // integers with a bitwidth that is not a multiple of 8.
1778     ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1779   } else {
1780     ShAmt = Offset;
1781   }
1782
1783   // Note: we support negative bitwidths (with shr) which are not defined.
1784   // We do this to support (f.e.) stores off the end of a structure where
1785   // only some bits in the structure are set.
1786   APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1787   if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1788     SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
1789                            ShAmt), "tmp");
1790     Mask <<= ShAmt;
1791   } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1792     SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
1793                             -ShAmt), "tmp");
1794     Mask = Mask.lshr(-ShAmt);
1795   }
1796
1797   // Mask out the bits we are about to insert from the old value, and or
1798   // in the new bits.
1799   if (SrcWidth != DestWidth) {
1800     assert(DestWidth > SrcWidth);
1801     Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1802     SV = Builder.CreateOr(Old, SV, "ins");
1803   }
1804   return SV;
1805 }
1806
1807
1808
1809 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1810 /// some part of a constant global variable.  This intentionally only accepts
1811 /// constant expressions because we don't can't rewrite arbitrary instructions.
1812 static bool PointsToConstantGlobal(Value *V) {
1813   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1814     return GV->isConstant();
1815   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1816     if (CE->getOpcode() == Instruction::BitCast || 
1817         CE->getOpcode() == Instruction::GetElementPtr)
1818       return PointsToConstantGlobal(CE->getOperand(0));
1819   return false;
1820 }
1821
1822 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1823 /// pointer to an alloca.  Ignore any reads of the pointer, return false if we
1824 /// see any stores or other unknown uses.  If we see pointer arithmetic, keep
1825 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
1826 /// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
1827 /// the alloca, and if the source pointer is a pointer to a constant  global, we
1828 /// can optimize this.
1829 static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1830                                            bool isOffset) {
1831   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1832     if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1833       // Ignore non-volatile loads, they are always ok.
1834       if (!LI->isVolatile())
1835         continue;
1836     
1837     if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1838       // If uses of the bitcast are ok, we are ok.
1839       if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1840         return false;
1841       continue;
1842     }
1843     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1844       // If the GEP has all zero indices, it doesn't offset the pointer.  If it
1845       // doesn't, it does.
1846       if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1847                                          isOffset || !GEP->hasAllZeroIndices()))
1848         return false;
1849       continue;
1850     }
1851     
1852     // If this is isn't our memcpy/memmove, reject it as something we can't
1853     // handle.
1854     if (!isa<MemTransferInst>(*UI))
1855       return false;
1856
1857     // If we already have seen a copy, reject the second one.
1858     if (TheCopy) return false;
1859     
1860     // If the pointer has been offset from the start of the alloca, we can't
1861     // safely handle this.
1862     if (isOffset) return false;
1863
1864     // If the memintrinsic isn't using the alloca as the dest, reject it.
1865     if (UI.getOperandNo() != 1) return false;
1866     
1867     MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1868     
1869     // If the source of the memcpy/move is not a constant global, reject it.
1870     if (!PointsToConstantGlobal(MI->getOperand(2)))
1871       return false;
1872     
1873     // Otherwise, the transform is safe.  Remember the copy instruction.
1874     TheCopy = MI;
1875   }
1876   return true;
1877 }
1878
1879 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1880 /// modified by a copy from a constant global.  If we can prove this, we can
1881 /// replace any uses of the alloca with uses of the global directly.
1882 Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
1883   Instruction *TheCopy = 0;
1884   if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1885     return TheCopy;
1886   return 0;
1887 }