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