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