refactor the SROA code out into its own method, no functionality change.
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Instructions.h"
28 #include "llvm/IntrinsicInst.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Analysis/Dominators.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/GetElementPtrTypeIterator.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/ADT/Statistic.h"
39 #include "llvm/ADT/StringExtras.h"
40 using namespace llvm;
41
42 STATISTIC(NumReplaced,  "Number of allocas broken up");
43 STATISTIC(NumPromoted,  "Number of allocas promoted");
44 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
45
46 namespace {
47   struct VISIBILITY_HIDDEN SROA : public FunctionPass {
48     bool runOnFunction(Function &F);
49
50     bool performScalarRepl(Function &F);
51     bool performPromotion(Function &F);
52
53     // getAnalysisUsage - This pass does not require any passes, but we know it
54     // will not alter the CFG, so say so.
55     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56       AU.addRequired<ETForest>();
57       AU.addRequired<DominanceFrontier>();
58       AU.addRequired<TargetData>();
59       AU.setPreservesCFG();
60     }
61
62   private:
63     int isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI);
64     int isSafeUseOfAllocation(Instruction *User, AllocationInst *AI);
65     bool isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI);
66     bool isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI);
67     int isSafeAllocaToScalarRepl(AllocationInst *AI);
68     void DoScalarReplacement(AllocationInst *AI, 
69                              std::vector<AllocationInst*> &WorkList);
70     void CanonicalizeAllocaUsers(AllocationInst *AI);
71     AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
72     
73     void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
74                                     SmallVector<AllocaInst*, 32> &NewElts);
75     
76     const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
77     void ConvertToScalar(AllocationInst *AI, const Type *Ty);
78     void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
79   };
80
81   RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
82 }
83
84 // Public interface to the ScalarReplAggregates pass
85 FunctionPass *llvm::createScalarReplAggregatesPass() { return new SROA(); }
86
87
88 bool SROA::runOnFunction(Function &F) {
89   bool Changed = performPromotion(F);
90   while (1) {
91     bool LocalChange = performScalarRepl(F);
92     if (!LocalChange) break;   // No need to repromote if no scalarrepl
93     Changed = true;
94     LocalChange = performPromotion(F);
95     if (!LocalChange) break;   // No need to re-scalarrepl if no promotion
96   }
97
98   return Changed;
99 }
100
101
102 bool SROA::performPromotion(Function &F) {
103   std::vector<AllocaInst*> Allocas;
104   const TargetData &TD = getAnalysis<TargetData>();
105   ETForest         &ET = getAnalysis<ETForest>();
106   DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
107
108   BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
109
110   bool Changed = false;
111
112   while (1) {
113     Allocas.clear();
114
115     // Find allocas that are safe to promote, by looking at all instructions in
116     // the entry node
117     for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
118       if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
119         if (isAllocaPromotable(AI, TD))
120           Allocas.push_back(AI);
121
122     if (Allocas.empty()) break;
123
124     PromoteMemToReg(Allocas, ET, DF, TD);
125     NumPromoted += Allocas.size();
126     Changed = true;
127   }
128
129   return Changed;
130 }
131
132 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
133 // which runs on all of the malloc/alloca instructions in the function, removing
134 // them if they are only used by getelementptr instructions.
135 //
136 bool SROA::performScalarRepl(Function &F) {
137   std::vector<AllocationInst*> WorkList;
138
139   // Scan the entry basic block, adding any alloca's and mallocs to the worklist
140   BasicBlock &BB = F.getEntryBlock();
141   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
142     if (AllocationInst *A = dyn_cast<AllocationInst>(I))
143       WorkList.push_back(A);
144
145   // Process the worklist
146   bool Changed = false;
147   while (!WorkList.empty()) {
148     AllocationInst *AI = WorkList.back();
149     WorkList.pop_back();
150     
151     // Handle dead allocas trivially.  These can be formed by SROA'ing arrays
152     // with unused elements.
153     if (AI->use_empty()) {
154       AI->eraseFromParent();
155       continue;
156     }
157     
158     // If we can turn this aggregate value (potentially with casts) into a
159     // simple scalar value that can be mem2reg'd into a register value.
160     bool IsNotTrivial = false;
161     if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
162       if (IsNotTrivial && ActualType != Type::VoidTy) {
163         ConvertToScalar(AI, ActualType);
164         Changed = true;
165         continue;
166       }
167
168     // We cannot transform the allocation instruction if it is an array
169     // allocation (allocations OF arrays are ok though), and an allocation of a
170     // scalar value cannot be decomposed at all.
171     if (!AI->isArrayAllocation() &&
172         (isa<StructType>(AI->getAllocatedType()) ||
173          isa<ArrayType>(AI->getAllocatedType()))) {
174       // Check that all of the users of the allocation are capable of being
175       // transformed.
176       switch (isSafeAllocaToScalarRepl(AI)) {
177       default: assert(0 && "Unexpected value!");
178       case 0:  // Not safe to scalar replace.
179         break;
180       case 1:  // Safe, but requires cleanup/canonicalizations first
181         CanonicalizeAllocaUsers(AI);
182         // FALL THROUGH.
183       case 3:  // Safe to scalar replace.
184         DoScalarReplacement(AI, WorkList);
185         Changed = true;
186         continue;
187       }
188     }
189         
190     // Otherwise, couldn't process this.
191   }
192
193   return Changed;
194 }
195
196 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
197 /// predicate, do SROA now.
198 void SROA::DoScalarReplacement(AllocationInst *AI, 
199                                std::vector<AllocationInst*> &WorkList) {
200   DOUT << "Found inst to xform: " << *AI;
201   SmallVector<AllocaInst*, 32> ElementAllocas;
202   if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
203     ElementAllocas.reserve(ST->getNumContainedTypes());
204     for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
205       AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0, 
206                                       AI->getAlignment(),
207                                       AI->getName() + "." + utostr(i), AI);
208       ElementAllocas.push_back(NA);
209       WorkList.push_back(NA);  // Add to worklist for recursive processing
210     }
211   } else {
212     const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
213     ElementAllocas.reserve(AT->getNumElements());
214     const Type *ElTy = AT->getElementType();
215     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
216       AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
217                                       AI->getName() + "." + utostr(i), AI);
218       ElementAllocas.push_back(NA);
219       WorkList.push_back(NA);  // Add to worklist for recursive processing
220     }
221   }
222
223   // Now that we have created the alloca instructions that we want to use,
224   // expand the getelementptr instructions to use them.
225   //
226   while (!AI->use_empty()) {
227     Instruction *User = cast<Instruction>(AI->use_back());
228     if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
229       RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
230       BCInst->eraseFromParent();
231       continue;
232     }
233     
234     GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
235     // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
236     unsigned Idx =
237        (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
238
239     assert(Idx < ElementAllocas.size() && "Index out of range?");
240     AllocaInst *AllocaToUse = ElementAllocas[Idx];
241
242     Value *RepValue;
243     if (GEPI->getNumOperands() == 3) {
244       // Do not insert a new getelementptr instruction with zero indices, only
245       // to have it optimized out later.
246       RepValue = AllocaToUse;
247     } else {
248       // We are indexing deeply into the structure, so we still need a
249       // getelement ptr instruction to finish the indexing.  This may be
250       // expanded itself once the worklist is rerun.
251       //
252       SmallVector<Value*, 8> NewArgs;
253       NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
254       NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
255       RepValue = new GetElementPtrInst(AllocaToUse, &NewArgs[0],
256                                        NewArgs.size(), "", GEPI);
257       RepValue->takeName(GEPI);
258     }
259     
260     // If this GEP is to the start of the aggregate, check for memcpys.
261     if (Idx == 0) {
262       bool IsStartOfAggregateGEP = true;
263       for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i) {
264         if (!isa<ConstantInt>(GEPI->getOperand(i))) {
265           IsStartOfAggregateGEP = false;
266           break;
267         }
268         if (!cast<ConstantInt>(GEPI->getOperand(i))->isZero()) {
269           IsStartOfAggregateGEP = false;
270           break;
271         }
272       }
273       
274       if (IsStartOfAggregateGEP)
275         RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
276     }
277     
278
279     // Move all of the users over to the new GEP.
280     GEPI->replaceAllUsesWith(RepValue);
281     // Delete the old GEP
282     GEPI->eraseFromParent();
283   }
284
285   // Finally, delete the Alloca instruction
286   AI->eraseFromParent();
287   NumReplaced++;
288 }
289
290
291 /// isSafeElementUse - Check to see if this use is an allowed use for a
292 /// getelementptr instruction of an array aggregate allocation.  isFirstElt
293 /// indicates whether Ptr is known to the start of the aggregate.
294 ///
295 int SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI) {
296   for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
297        I != E; ++I) {
298     Instruction *User = cast<Instruction>(*I);
299     switch (User->getOpcode()) {
300     case Instruction::Load:  break;
301     case Instruction::Store:
302       // Store is ok if storing INTO the pointer, not storing the pointer
303       if (User->getOperand(0) == Ptr) return 0;
304       break;
305     case Instruction::GetElementPtr: {
306       GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
307       bool AreAllZeroIndices = isFirstElt;
308       if (GEP->getNumOperands() > 1) {
309         if (!isa<ConstantInt>(GEP->getOperand(1)) ||
310             !cast<ConstantInt>(GEP->getOperand(1))->isZero())
311           return 0;  // Using pointer arithmetic to navigate the array.
312        
313         if (AreAllZeroIndices) {
314           for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
315             if (!isa<ConstantInt>(GEP->getOperand(i)) ||    
316                 !cast<ConstantInt>(GEP->getOperand(i))->isZero()) {
317               AreAllZeroIndices = false;
318               break;
319             }
320           }
321         }
322       }
323       if (!isSafeElementUse(GEP, AreAllZeroIndices, AI)) return 0;
324       break;
325     }
326     case Instruction::BitCast:
327       if (isFirstElt &&
328           isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI)) 
329         break;
330       DOUT << "  Transformation preventing inst: " << *User;
331       return 0;
332     case Instruction::Call:
333       if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
334         if (isFirstElt && isSafeMemIntrinsicOnAllocation(MI, AI))
335           break;
336       }
337       DOUT << "  Transformation preventing inst: " << *User;
338       return 0;
339     default:
340       DOUT << "  Transformation preventing inst: " << *User;
341       return 0;
342     }
343   }
344   return 3;  // All users look ok :)
345 }
346
347 /// AllUsersAreLoads - Return true if all users of this value are loads.
348 static bool AllUsersAreLoads(Value *Ptr) {
349   for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
350        I != E; ++I)
351     if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
352       return false;
353   return true;
354 }
355
356 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
357 /// aggregate allocation.
358 ///
359 int SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI) {
360   if (BitCastInst *C = dyn_cast<BitCastInst>(User))
361     return isSafeUseOfBitCastedAllocation(C, AI) ? 3 : 0;
362   if (!isa<GetElementPtrInst>(User)) return 0;
363
364   GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
365   gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
366
367   // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
368   if (I == E ||
369       I.getOperand() != Constant::getNullValue(I.getOperand()->getType()))
370     return 0;
371
372   ++I;
373   if (I == E) return 0;  // ran out of GEP indices??
374
375   bool IsAllZeroIndices = true;
376   
377   // If this is a use of an array allocation, do a bit more checking for sanity.
378   if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
379     uint64_t NumElements = AT->getNumElements();
380
381     if (ConstantInt *Idx = dyn_cast<ConstantInt>(I.getOperand())) {
382       IsAllZeroIndices &= Idx->isZero();
383       
384       // Check to make sure that index falls within the array.  If not,
385       // something funny is going on, so we won't do the optimization.
386       //
387       if (Idx->getZExtValue() >= NumElements)
388         return 0;
389
390       // We cannot scalar repl this level of the array unless any array
391       // sub-indices are in-range constants.  In particular, consider:
392       // A[0][i].  We cannot know that the user isn't doing invalid things like
393       // allowing i to index an out-of-range subscript that accesses A[1].
394       //
395       // Scalar replacing *just* the outer index of the array is probably not
396       // going to be a win anyway, so just give up.
397       for (++I; I != E && (isa<ArrayType>(*I) || isa<VectorType>(*I)); ++I) {
398         uint64_t NumElements;
399         if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*I))
400           NumElements = SubArrayTy->getNumElements();
401         else
402           NumElements = cast<VectorType>(*I)->getNumElements();
403         
404         ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
405         if (!IdxVal) return 0;
406         if (IdxVal->getZExtValue() >= NumElements)
407           return 0;
408         IsAllZeroIndices &= IdxVal->isZero();
409       }
410       
411     } else {
412       IsAllZeroIndices = 0;
413       
414       // If this is an array index and the index is not constant, we cannot
415       // promote... that is unless the array has exactly one or two elements in
416       // it, in which case we CAN promote it, but we have to canonicalize this
417       // out if this is the only problem.
418       if ((NumElements == 1 || NumElements == 2) &&
419           AllUsersAreLoads(GEPI))
420         return 1;  // Canonicalization required!
421       return 0;
422     }
423   }
424
425   // If there are any non-simple uses of this getelementptr, make sure to reject
426   // them.
427   return isSafeElementUse(GEPI, IsAllZeroIndices, AI);
428 }
429
430 /// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
431 /// intrinsic can be promoted by SROA.  At this point, we know that the operand
432 /// of the memintrinsic is a pointer to the beginning of the allocation.
433 bool SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI){
434   // If not constant length, give up.
435   ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
436   if (!Length) return false;
437   
438   // If not the whole aggregate, give up.
439   const TargetData &TD = getAnalysis<TargetData>();
440   if (Length->getZExtValue() != TD.getTypeSize(AI->getType()->getElementType()))
441     return false;
442   
443   // We only know about memcpy/memset/memmove.
444   if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
445     return false;
446   // Otherwise, we can transform it.
447   return true;
448 }
449
450 /// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
451 /// are 
452 bool SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI) {
453   for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
454        UI != E; ++UI) {
455     if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
456       if (!isSafeUseOfBitCastedAllocation(BCU, AI)) 
457         return false;
458     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
459       if (!isSafeMemIntrinsicOnAllocation(MI, AI))
460         return false;
461     } else {
462       return false;
463     }
464   }
465   return true;
466 }
467
468 /// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
469 /// to its first element.  Transform users of the cast to use the new values
470 /// instead.
471 void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
472                                       SmallVector<AllocaInst*, 32> &NewElts) {
473   Constant *Zero = Constant::getNullValue(Type::Int32Ty);
474   const TargetData &TD = getAnalysis<TargetData>();
475   
476   Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
477   while (UI != UE) {
478     if (BitCastInst *BCU = dyn_cast<BitCastInst>(*UI)) {
479       RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
480       ++UI;
481       BCU->eraseFromParent();
482       continue;
483     }
484
485     // Otherwise, must be memcpy/memmove/memset of the entire aggregate.  Split
486     // into one per element.
487     MemIntrinsic *MI = dyn_cast<MemIntrinsic>(*UI);
488     
489     // If it's not a mem intrinsic, it must be some other user of a gep of the
490     // first pointer.  Just leave these alone.
491     if (!MI) {
492       ++UI;
493       continue;
494     }
495     
496     // If this is a memcpy/memmove, construct the other pointer as the
497     // appropriate type.
498     Value *OtherPtr = 0;
499     if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
500       if (BCInst == MCI->getRawDest())
501         OtherPtr = MCI->getRawSource();
502       else {
503         assert(BCInst == MCI->getRawSource());
504         OtherPtr = MCI->getRawDest();
505       }
506     } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
507       if (BCInst == MMI->getRawDest())
508         OtherPtr = MMI->getRawSource();
509       else {
510         assert(BCInst == MMI->getRawSource());
511         OtherPtr = MMI->getRawDest();
512       }
513     }
514     
515     // If there is an other pointer, we want to convert it to the same pointer
516     // type as AI has, so we can GEP through it.
517     if (OtherPtr) {
518       // It is likely that OtherPtr is a bitcast, if so, remove it.
519       if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
520         OtherPtr = BC->getOperand(0);
521       if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
522         if (BCE->getOpcode() == Instruction::BitCast)
523           OtherPtr = BCE->getOperand(0);
524       
525       // If the pointer is not the right type, insert a bitcast to the right
526       // type.
527       if (OtherPtr->getType() != AI->getType())
528         OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
529                                    MI);
530     }
531
532     // Process each element of the aggregate.
533     Value *TheFn = MI->getOperand(0);
534     const Type *BytePtrTy = MI->getRawDest()->getType();
535     bool SROADest = MI->getRawDest() == BCInst;
536
537     for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
538       // If this is a memcpy/memmove, emit a GEP of the other element address.
539       Value *OtherElt = 0;
540       if (OtherPtr) {
541         OtherElt = new GetElementPtrInst(OtherPtr, Zero,
542                                          ConstantInt::get(Type::Int32Ty, i),
543                                          OtherPtr->getNameStr()+"."+utostr(i),
544                                          MI);
545       }
546
547       Value *EltPtr = NewElts[i];
548       const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
549       
550       // If we got down to a scalar, insert a load or store as appropriate.
551       if (EltTy->isFirstClassType()) {
552         if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
553           Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
554                                     MI);
555           new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
556           continue;
557         } else {
558           assert(isa<MemSetInst>(MI));
559
560           // If the stored element is zero (common case), just store a null
561           // constant.
562           Constant *StoreVal;
563           if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
564             if (CI->isZero()) {
565               StoreVal = Constant::getNullValue(EltTy);  // 0.0, null, 0, <0,0>
566             } else {
567               // If EltTy is a packed type, get the element type.
568               const Type *ValTy = EltTy;
569               if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
570                 ValTy = VTy->getElementType();
571               
572               // Construct an integer with the right value.
573               unsigned EltSize = TD.getTypeSize(ValTy);
574               APInt OneVal(EltSize*8, CI->getZExtValue());
575               APInt TotalVal(OneVal);
576               // Set each byte.
577               for (unsigned i = 0; i != EltSize-1; ++i) {
578                 TotalVal = TotalVal.shl(8);
579                 TotalVal |= OneVal;
580               }
581               
582               // Convert the integer value to the appropriate type.
583               StoreVal = ConstantInt::get(TotalVal);
584               if (isa<PointerType>(ValTy))
585                 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
586               else if (ValTy->isFloatingPoint())
587                 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
588               assert(StoreVal->getType() == ValTy && "Type mismatch!");
589               
590               // If the requested value was a vector constant, create it.
591               if (EltTy != ValTy) {
592                 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
593                 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
594                 StoreVal = ConstantVector::get(&Elts[0], NumElts);
595               }
596             }
597             new StoreInst(StoreVal, EltPtr, MI);
598             continue;
599           }
600           // Otherwise, if we're storing a byte variable, use a memset call for
601           // this element.
602         }
603       }
604       
605       // Cast the element pointer to BytePtrTy.
606       if (EltPtr->getType() != BytePtrTy)
607         EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
608     
609       // Cast the other pointer (if we have one) to BytePtrTy. 
610       if (OtherElt && OtherElt->getType() != BytePtrTy)
611         OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
612                                    MI);
613     
614       unsigned EltSize = TD.getTypeSize(EltTy);
615
616       // Finally, insert the meminst for this element.
617       if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
618         Value *Ops[] = {
619           SROADest ? EltPtr : OtherElt,  // Dest ptr
620           SROADest ? OtherElt : EltPtr,  // Src ptr
621           ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
622           Zero  // Align
623         };
624         new CallInst(TheFn, Ops, 4, "", MI);
625       } else {
626         assert(isa<MemSetInst>(MI));
627         Value *Ops[] = {
628           EltPtr, MI->getOperand(2),  // Dest, Value,
629           ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
630           Zero  // Align
631         };
632         new CallInst(TheFn, Ops, 4, "", MI);
633       }
634     }
635
636     // Finally, MI is now dead, as we've modified its actions to occur on all of
637     // the elements of the aggregate.
638     ++UI;
639     MI->eraseFromParent();
640   }
641 }
642
643
644 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
645 /// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
646 /// or 1 if safe after canonicalization has been performed.
647 ///
648 int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
649   // Loop over the use list of the alloca.  We can only transform it if all of
650   // the users are safe to transform.
651   //
652   int isSafe = 3;
653   for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
654        I != E; ++I) {
655     isSafe &= isSafeUseOfAllocation(cast<Instruction>(*I), AI);
656     if (isSafe == 0) {
657       DOUT << "Cannot transform: " << *AI << "  due to user: " << **I;
658       return 0;
659     }
660   }
661   // If we require cleanup, isSafe is now 1, otherwise it is 3.
662   return isSafe;
663 }
664
665 /// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
666 /// allocation, but only if cleaned up, perform the cleanups required.
667 void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
668   // At this point, we know that the end result will be SROA'd and promoted, so
669   // we can insert ugly code if required so long as sroa+mem2reg will clean it
670   // up.
671   for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
672        UI != E; ) {
673     GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI++);
674     if (!GEPI) continue;
675     gep_type_iterator I = gep_type_begin(GEPI);
676     ++I;
677
678     if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
679       uint64_t NumElements = AT->getNumElements();
680
681       if (!isa<ConstantInt>(I.getOperand())) {
682         if (NumElements == 1) {
683           GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
684         } else {
685           assert(NumElements == 2 && "Unhandled case!");
686           // All users of the GEP must be loads.  At each use of the GEP, insert
687           // two loads of the appropriate indexed GEP and select between them.
688           Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(), 
689                               Constant::getNullValue(I.getOperand()->getType()),
690              "isone", GEPI);
691           // Insert the new GEP instructions, which are properly indexed.
692           SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
693           Indices[1] = Constant::getNullValue(Type::Int32Ty);
694           Value *ZeroIdx = new GetElementPtrInst(GEPI->getOperand(0),
695                                                  &Indices[0], Indices.size(),
696                                                  GEPI->getName()+".0", GEPI);
697           Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
698           Value *OneIdx = new GetElementPtrInst(GEPI->getOperand(0),
699                                                 &Indices[0], Indices.size(),
700                                                 GEPI->getName()+".1", GEPI);
701           // Replace all loads of the variable index GEP with loads from both
702           // indexes and a select.
703           while (!GEPI->use_empty()) {
704             LoadInst *LI = cast<LoadInst>(GEPI->use_back());
705             Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
706             Value *One  = new LoadInst(OneIdx , LI->getName()+".1", LI);
707             Value *R = new SelectInst(IsOne, One, Zero, LI->getName(), LI);
708             LI->replaceAllUsesWith(R);
709             LI->eraseFromParent();
710           }
711           GEPI->eraseFromParent();
712         }
713       }
714     }
715   }
716 }
717
718 /// MergeInType - Add the 'In' type to the accumulated type so far.  If the
719 /// types are incompatible, return true, otherwise update Accum and return
720 /// false.
721 ///
722 /// There are three cases we handle here:
723 ///   1) An effectively-integer union, where the pieces are stored into as
724 ///      smaller integers (common with byte swap and other idioms).
725 ///   2) A union of vector types of the same size and potentially its elements.
726 ///      Here we turn element accesses into insert/extract element operations.
727 ///   3) A union of scalar types, such as int/float or int/pointer.  Here we
728 ///      merge together into integers, allowing the xform to work with #1 as
729 ///      well.
730 static bool MergeInType(const Type *In, const Type *&Accum,
731                         const TargetData &TD) {
732   // If this is our first type, just use it.
733   const VectorType *PTy;
734   if (Accum == Type::VoidTy || In == Accum) {
735     Accum = In;
736   } else if (In == Type::VoidTy) {
737     // Noop.
738   } else if (In->isInteger() && Accum->isInteger()) {   // integer union.
739     // Otherwise pick whichever type is larger.
740     if (cast<IntegerType>(In)->getBitWidth() > 
741         cast<IntegerType>(Accum)->getBitWidth())
742       Accum = In;
743   } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
744     // Pointer unions just stay as one of the pointers.
745   } else if (isa<VectorType>(In) || isa<VectorType>(Accum)) {
746     if ((PTy = dyn_cast<VectorType>(Accum)) && 
747         PTy->getElementType() == In) {
748       // Accum is a vector, and we are accessing an element: ok.
749     } else if ((PTy = dyn_cast<VectorType>(In)) && 
750                PTy->getElementType() == Accum) {
751       // In is a vector, and accum is an element: ok, remember In.
752       Accum = In;
753     } else if ((PTy = dyn_cast<VectorType>(In)) && isa<VectorType>(Accum) &&
754                PTy->getBitWidth() == cast<VectorType>(Accum)->getBitWidth()) {
755       // Two vectors of the same size: keep Accum.
756     } else {
757       // Cannot insert an short into a <4 x int> or handle
758       // <2 x int> -> <4 x int>
759       return true;
760     }
761   } else {
762     // Pointer/FP/Integer unions merge together as integers.
763     switch (Accum->getTypeID()) {
764     case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
765     case Type::FloatTyID:   Accum = Type::Int32Ty; break;
766     case Type::DoubleTyID:  Accum = Type::Int64Ty; break;
767     default:
768       assert(Accum->isInteger() && "Unknown FP type!");
769       break;
770     }
771     
772     switch (In->getTypeID()) {
773     case Type::PointerTyID: In = TD.getIntPtrType(); break;
774     case Type::FloatTyID:   In = Type::Int32Ty; break;
775     case Type::DoubleTyID:  In = Type::Int64Ty; break;
776     default:
777       assert(In->isInteger() && "Unknown FP type!");
778       break;
779     }
780     return MergeInType(In, Accum, TD);
781   }
782   return false;
783 }
784
785 /// getUIntAtLeastAsBitAs - Return an unsigned integer type that is at least
786 /// as big as the specified type.  If there is no suitable type, this returns
787 /// null.
788 const Type *getUIntAtLeastAsBitAs(unsigned NumBits) {
789   if (NumBits > 64) return 0;
790   if (NumBits > 32) return Type::Int64Ty;
791   if (NumBits > 16) return Type::Int32Ty;
792   if (NumBits > 8) return Type::Int16Ty;
793   return Type::Int8Ty;    
794 }
795
796 /// CanConvertToScalar - V is a pointer.  If we can convert the pointee to a
797 /// single scalar integer type, return that type.  Further, if the use is not
798 /// a completely trivial use that mem2reg could promote, set IsNotTrivial.  If
799 /// there are no uses of this pointer, return Type::VoidTy to differentiate from
800 /// failure.
801 ///
802 const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
803   const Type *UsedType = Type::VoidTy; // No uses, no forced type.
804   const TargetData &TD = getAnalysis<TargetData>();
805   const PointerType *PTy = cast<PointerType>(V->getType());
806
807   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
808     Instruction *User = cast<Instruction>(*UI);
809     
810     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
811       if (MergeInType(LI->getType(), UsedType, TD))
812         return 0;
813       
814     } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
815       // Storing the pointer, not into the value?
816       if (SI->getOperand(0) == V) return 0;
817       
818       // NOTE: We could handle storing of FP imms into integers here!
819       
820       if (MergeInType(SI->getOperand(0)->getType(), UsedType, TD))
821         return 0;
822     } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
823       IsNotTrivial = true;
824       const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
825       if (!SubTy || MergeInType(SubTy, UsedType, TD)) return 0;
826     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
827       // Check to see if this is stepping over an element: GEP Ptr, int C
828       if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
829         unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
830         unsigned ElSize = TD.getTypeSize(PTy->getElementType());
831         unsigned BitOffset = Idx*ElSize*8;
832         if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
833         
834         IsNotTrivial = true;
835         const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
836         if (SubElt == 0) return 0;
837         if (SubElt != Type::VoidTy && SubElt->isInteger()) {
838           const Type *NewTy = 
839             getUIntAtLeastAsBitAs(TD.getTypeSize(SubElt)*8+BitOffset);
840           if (NewTy == 0 || MergeInType(NewTy, UsedType, TD)) return 0;
841           continue;
842         }
843       } else if (GEP->getNumOperands() == 3 && 
844                  isa<ConstantInt>(GEP->getOperand(1)) &&
845                  isa<ConstantInt>(GEP->getOperand(2)) &&
846                  cast<ConstantInt>(GEP->getOperand(1))->isZero()) {
847         // We are stepping into an element, e.g. a structure or an array:
848         // GEP Ptr, int 0, uint C
849         const Type *AggTy = PTy->getElementType();
850         unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
851         
852         if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
853           if (Idx >= ATy->getNumElements()) return 0;  // Out of range.
854         } else if (const VectorType *VectorTy = dyn_cast<VectorType>(AggTy)) {
855           // Getting an element of the packed vector.
856           if (Idx >= VectorTy->getNumElements()) return 0;  // Out of range.
857
858           // Merge in the vector type.
859           if (MergeInType(VectorTy, UsedType, TD)) return 0;
860           
861           const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
862           if (SubTy == 0) return 0;
863           
864           if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
865             return 0;
866
867           // We'll need to change this to an insert/extract element operation.
868           IsNotTrivial = true;
869           continue;    // Everything looks ok
870           
871         } else if (isa<StructType>(AggTy)) {
872           // Structs are always ok.
873         } else {
874           return 0;
875         }
876         const Type *NTy = getUIntAtLeastAsBitAs(TD.getTypeSize(AggTy)*8);
877         if (NTy == 0 || MergeInType(NTy, UsedType, TD)) return 0;
878         const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
879         if (SubTy == 0) return 0;
880         if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
881           return 0;
882         continue;    // Everything looks ok
883       }
884       return 0;
885     } else {
886       // Cannot handle this!
887       return 0;
888     }
889   }
890   
891   return UsedType;
892 }
893
894 /// ConvertToScalar - The specified alloca passes the CanConvertToScalar
895 /// predicate and is non-trivial.  Convert it to something that can be trivially
896 /// promoted into a register by mem2reg.
897 void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
898   DOUT << "CONVERT TO SCALAR: " << *AI << "  TYPE = "
899        << *ActualTy << "\n";
900   ++NumConverted;
901   
902   BasicBlock *EntryBlock = AI->getParent();
903   assert(EntryBlock == &EntryBlock->getParent()->getEntryBlock() &&
904          "Not in the entry block!");
905   EntryBlock->getInstList().remove(AI);  // Take the alloca out of the program.
906   
907   // Create and insert the alloca.
908   AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
909                                      EntryBlock->begin());
910   ConvertUsesToScalar(AI, NewAI, 0);
911   delete AI;
912 }
913
914
915 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
916 /// directly.  This happens when we are converting an "integer union" to a
917 /// single integer scalar, or when we are converting a "vector union" to a
918 /// vector with insert/extractelement instructions.
919 ///
920 /// Offset is an offset from the original alloca, in bits that need to be
921 /// shifted to the right.  By the end of this, there should be no uses of Ptr.
922 void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
923   const TargetData &TD = getAnalysis<TargetData>();
924   while (!Ptr->use_empty()) {
925     Instruction *User = cast<Instruction>(Ptr->use_back());
926     
927     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
928       // The load is a bit extract from NewAI shifted right by Offset bits.
929       Value *NV = new LoadInst(NewAI, LI->getName(), LI);
930       if (NV->getType() == LI->getType()) {
931         // We win, no conversion needed.
932       } else if (const VectorType *PTy = dyn_cast<VectorType>(NV->getType())) {
933         // If the result alloca is a vector type, this is either an element
934         // access or a bitcast to another vector type.
935         if (isa<VectorType>(LI->getType())) {
936           NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
937         } else {
938           // Must be an element access.
939           unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
940           NV = new ExtractElementInst(
941                          NV, ConstantInt::get(Type::Int32Ty, Elt), "tmp", LI);
942         }
943       } else if (isa<PointerType>(NV->getType())) {
944         assert(isa<PointerType>(LI->getType()));
945         // Must be ptr->ptr cast.  Anything else would result in NV being
946         // an integer.
947         NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
948       } else {
949         const IntegerType *NTy = cast<IntegerType>(NV->getType());
950         unsigned LIBitWidth = TD.getTypeSizeInBits(LI->getType());
951         
952         // If this is a big-endian system and the load is narrower than the
953         // full alloca type, we need to do a shift to get the right bits.
954         int ShAmt = 0;
955         if (TD.isBigEndian()) {
956           ShAmt = NTy->getBitWidth()-LIBitWidth-Offset;
957         } else {
958           ShAmt = Offset;
959         }
960         
961         // Note: we support negative bitwidths (with shl) which are not defined.
962         // We do this to support (f.e.) loads off the end of a structure where
963         // only some bits are used.
964         if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
965           NV = BinaryOperator::createLShr(NV, 
966                                           ConstantInt::get(NV->getType(),ShAmt),
967                                           LI->getName(), LI);
968         else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
969           NV = BinaryOperator::createShl(NV, 
970                                          ConstantInt::get(NV->getType(),-ShAmt),
971                                          LI->getName(), LI);
972         
973         // Finally, unconditionally truncate the integer to the right width.
974         if (LIBitWidth < NTy->getBitWidth())
975           NV = new TruncInst(NV, IntegerType::get(LIBitWidth),
976                              LI->getName(), LI);
977         
978         // If the result is an integer, this is a trunc or bitcast.
979         if (isa<IntegerType>(LI->getType())) {
980           assert(NV->getType() == LI->getType() && "Truncate wasn't enough?");
981         } else if (LI->getType()->isFloatingPoint()) {
982           // Just do a bitcast, we know the sizes match up.
983           NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
984         } else {
985           // Otherwise must be a pointer.
986           NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
987         }
988       }
989       LI->replaceAllUsesWith(NV);
990       LI->eraseFromParent();
991     } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
992       assert(SI->getOperand(0) != Ptr && "Consistency error!");
993
994       // Convert the stored type to the actual type, shift it left to insert
995       // then 'or' into place.
996       Value *SV = SI->getOperand(0);
997       const Type *AllocaType = NewAI->getType()->getElementType();
998       if (SV->getType() == AllocaType) {
999         // All is well.
1000       } else if (const VectorType *PTy = dyn_cast<VectorType>(AllocaType)) {
1001         Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1002
1003         // If the result alloca is a vector type, this is either an element
1004         // access or a bitcast to another vector type.
1005         if (isa<VectorType>(SV->getType())) {
1006           SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1007         } else {            
1008           // Must be an element insertion.
1009           unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
1010           SV = new InsertElementInst(Old, SV,
1011                                      ConstantInt::get(Type::Int32Ty, Elt),
1012                                      "tmp", SI);
1013         }
1014       } else if (isa<PointerType>(AllocaType)) {
1015         // If the alloca type is a pointer, then all the elements must be
1016         // pointers.
1017         if (SV->getType() != AllocaType)
1018           SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1019       } else {
1020         Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1021
1022         // If SV is a float, convert it to the appropriate integer type.
1023         // If it is a pointer, do the same, and also handle ptr->ptr casts
1024         // here.
1025         unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
1026         unsigned DestWidth = AllocaType->getPrimitiveSizeInBits();
1027         if (SV->getType()->isFloatingPoint())
1028           SV = new BitCastInst(SV, IntegerType::get(SrcWidth),
1029                                SV->getName(), SI);
1030         else if (isa<PointerType>(SV->getType()))
1031           SV = new PtrToIntInst(SV, TD.getIntPtrType(), SV->getName(), SI);
1032                  
1033         // Always zero extend the value if needed.
1034         if (SV->getType() != AllocaType)
1035           SV = new ZExtInst(SV, AllocaType, SV->getName(), SI);
1036         
1037         // If this is a big-endian system and the store is narrower than the
1038         // full alloca type, we need to do a shift to get the right bits.
1039         int ShAmt = 0;
1040         if (TD.isBigEndian()) {
1041           ShAmt = DestWidth-SrcWidth-Offset;
1042         } else {
1043           ShAmt = Offset;
1044         }
1045         
1046         // Note: we support negative bitwidths (with shr) which are not defined.
1047         // We do this to support (f.e.) stores off the end of a structure where
1048         // only some bits in the structure are set.
1049         APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1050         if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1051           SV = BinaryOperator::createShl(SV, 
1052                                          ConstantInt::get(SV->getType(), ShAmt),
1053                                          SV->getName(), SI);
1054           Mask <<= ShAmt;
1055         } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1056           SV = BinaryOperator::createLShr(SV,
1057                                          ConstantInt::get(SV->getType(),-ShAmt),
1058                                           SV->getName(), SI);
1059           Mask = Mask.lshr(ShAmt);
1060         }
1061         
1062         // Mask out the bits we are about to insert from the old value, and or
1063         // in the new bits.
1064         if (SrcWidth != DestWidth) {
1065           assert(DestWidth > SrcWidth);
1066           Old = BinaryOperator::createAnd(Old, ConstantInt::get(~Mask),
1067                                           Old->getName()+".mask", SI);
1068           SV = BinaryOperator::createOr(Old, SV, SV->getName()+".ins", SI);
1069         }
1070       }
1071       new StoreInst(SV, NewAI, SI);
1072       SI->eraseFromParent();
1073       
1074     } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1075        ConvertUsesToScalar(CI, NewAI, Offset);
1076       CI->eraseFromParent();
1077     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1078       const PointerType *AggPtrTy = 
1079         cast<PointerType>(GEP->getOperand(0)->getType());
1080       const TargetData &TD = getAnalysis<TargetData>();
1081       unsigned AggSizeInBits = TD.getTypeSize(AggPtrTy->getElementType())*8;
1082       
1083       // Check to see if this is stepping over an element: GEP Ptr, int C
1084       unsigned NewOffset = Offset;
1085       if (GEP->getNumOperands() == 2) {
1086         unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
1087         unsigned BitOffset = Idx*AggSizeInBits;
1088         
1089         NewOffset += BitOffset;
1090       } else if (GEP->getNumOperands() == 3) {
1091         // We know that operand #2 is zero.
1092         unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1093         const Type *AggTy = AggPtrTy->getElementType();
1094         if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
1095           unsigned ElSizeBits = TD.getTypeSize(SeqTy->getElementType())*8;
1096
1097           NewOffset += ElSizeBits*Idx;
1098         } else if (const StructType *STy = dyn_cast<StructType>(AggTy)) {
1099           unsigned EltBitOffset =
1100             TD.getStructLayout(STy)->getElementOffset(Idx)*8;
1101           
1102           NewOffset += EltBitOffset;
1103         } else {
1104           assert(0 && "Unsupported operation!");
1105           abort();
1106         }
1107       } else {
1108         assert(0 && "Unsupported operation!");
1109         abort();
1110       }
1111       ConvertUsesToScalar(GEP, NewAI, NewOffset);
1112       GEP->eraseFromParent();
1113     } else {
1114       assert(0 && "Unsupported operation!");
1115       abort();
1116     }
1117   }
1118 }