stop using methods that take vectors.
[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/Pass.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Analysis/Dominators.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/GetElementPtrTypeIterator.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/ADT/StringExtras.h"
39 using namespace llvm;
40
41 STATISTIC(NumReplaced,  "Number of allocas broken up");
42 STATISTIC(NumPromoted,  "Number of allocas promoted");
43 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
44
45 namespace {
46   struct VISIBILITY_HIDDEN SROA : public FunctionPass {
47     bool runOnFunction(Function &F);
48
49     bool performScalarRepl(Function &F);
50     bool performPromotion(Function &F);
51
52     // getAnalysisUsage - This pass does not require any passes, but we know it
53     // will not alter the CFG, so say so.
54     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
55       AU.addRequired<DominatorTree>();
56       AU.addRequired<DominanceFrontier>();
57       AU.addRequired<TargetData>();
58       AU.setPreservesCFG();
59     }
60
61   private:
62     int isSafeElementUse(Value *Ptr);
63     int isSafeUseOfAllocation(Instruction *User);
64     int isSafeAllocaToScalarRepl(AllocationInst *AI);
65     void CanonicalizeAllocaUsers(AllocationInst *AI);
66     AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
67     
68     const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
69     void ConvertToScalar(AllocationInst *AI, const Type *Ty);
70     void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
71   };
72
73   RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
74 }
75
76 // Public interface to the ScalarReplAggregates pass
77 FunctionPass *llvm::createScalarReplAggregatesPass() { return new SROA(); }
78
79
80 bool SROA::runOnFunction(Function &F) {
81   bool Changed = performPromotion(F);
82   while (1) {
83     bool LocalChange = performScalarRepl(F);
84     if (!LocalChange) break;   // No need to repromote if no scalarrepl
85     Changed = true;
86     LocalChange = performPromotion(F);
87     if (!LocalChange) break;   // No need to re-scalarrepl if no promotion
88   }
89
90   return Changed;
91 }
92
93
94 bool SROA::performPromotion(Function &F) {
95   std::vector<AllocaInst*> Allocas;
96   const TargetData &TD = getAnalysis<TargetData>();
97   DominatorTree     &DT = getAnalysis<DominatorTree>();
98   DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
99
100   BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
101
102   bool Changed = false;
103
104   while (1) {
105     Allocas.clear();
106
107     // Find allocas that are safe to promote, by looking at all instructions in
108     // the entry node
109     for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
110       if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
111         if (isAllocaPromotable(AI, TD))
112           Allocas.push_back(AI);
113
114     if (Allocas.empty()) break;
115
116     PromoteMemToReg(Allocas, DT, DF, TD);
117     NumPromoted += Allocas.size();
118     Changed = true;
119   }
120
121   return Changed;
122 }
123
124 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
125 // which runs on all of the malloc/alloca instructions in the function, removing
126 // them if they are only used by getelementptr instructions.
127 //
128 bool SROA::performScalarRepl(Function &F) {
129   std::vector<AllocationInst*> WorkList;
130
131   // Scan the entry basic block, adding any alloca's and mallocs to the worklist
132   BasicBlock &BB = F.getEntryBlock();
133   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
134     if (AllocationInst *A = dyn_cast<AllocationInst>(I))
135       WorkList.push_back(A);
136
137   // Process the worklist
138   bool Changed = false;
139   while (!WorkList.empty()) {
140     AllocationInst *AI = WorkList.back();
141     WorkList.pop_back();
142     
143     // Handle dead allocas trivially.  These can be formed by SROA'ing arrays
144     // with unused elements.
145     if (AI->use_empty()) {
146       AI->eraseFromParent();
147       continue;
148     }
149     
150     // If we can turn this aggregate value (potentially with casts) into a
151     // simple scalar value that can be mem2reg'd into a register value.
152     bool IsNotTrivial = false;
153     if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
154       if (IsNotTrivial && ActualType != Type::VoidTy) {
155         ConvertToScalar(AI, ActualType);
156         Changed = true;
157         continue;
158       }
159
160     // We cannot transform the allocation instruction if it is an array
161     // allocation (allocations OF arrays are ok though), and an allocation of a
162     // scalar value cannot be decomposed at all.
163     //
164     if (AI->isArrayAllocation() ||
165         (!isa<StructType>(AI->getAllocatedType()) &&
166          !isa<ArrayType>(AI->getAllocatedType()))) continue;
167
168     // Check that all of the users of the allocation are capable of being
169     // transformed.
170     switch (isSafeAllocaToScalarRepl(AI)) {
171     default: assert(0 && "Unexpected value!");
172     case 0:  // Not safe to scalar replace.
173       continue;
174     case 1:  // Safe, but requires cleanup/canonicalizations first
175       CanonicalizeAllocaUsers(AI);
176     case 3:  // Safe to scalar replace.
177       break;
178     }
179
180     DOUT << "Found inst to xform: " << *AI;
181     Changed = true;
182
183     std::vector<AllocaInst*> ElementAllocas;
184     if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
185       ElementAllocas.reserve(ST->getNumContainedTypes());
186       for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
187         AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0, 
188                                         AI->getAlignment(),
189                                         AI->getName() + "." + utostr(i), AI);
190         ElementAllocas.push_back(NA);
191         WorkList.push_back(NA);  // Add to worklist for recursive processing
192       }
193     } else {
194       const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
195       ElementAllocas.reserve(AT->getNumElements());
196       const Type *ElTy = AT->getElementType();
197       for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
198         AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
199                                         AI->getName() + "." + utostr(i), AI);
200         ElementAllocas.push_back(NA);
201         WorkList.push_back(NA);  // Add to worklist for recursive processing
202       }
203     }
204
205     // Now that we have created the alloca instructions that we want to use,
206     // expand the getelementptr instructions to use them.
207     //
208     while (!AI->use_empty()) {
209       Instruction *User = cast<Instruction>(AI->use_back());
210       GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
211       // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
212       unsigned Idx =
213          (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
214
215       assert(Idx < ElementAllocas.size() && "Index out of range?");
216       AllocaInst *AllocaToUse = ElementAllocas[Idx];
217
218       Value *RepValue;
219       if (GEPI->getNumOperands() == 3) {
220         // Do not insert a new getelementptr instruction with zero indices, only
221         // to have it optimized out later.
222         RepValue = AllocaToUse;
223       } else {
224         // We are indexing deeply into the structure, so we still need a
225         // getelement ptr instruction to finish the indexing.  This may be
226         // expanded itself once the worklist is rerun.
227         //
228         SmallVector<Value*, 8> NewArgs;
229         NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
230         NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
231         RepValue = new GetElementPtrInst(AllocaToUse, &NewArgs[0],
232                                          NewArgs.size(), "", GEPI);
233         RepValue->takeName(GEPI);
234       }
235
236       // Move all of the users over to the new GEP.
237       GEPI->replaceAllUsesWith(RepValue);
238       // Delete the old GEP
239       GEPI->eraseFromParent();
240     }
241
242     // Finally, delete the Alloca instruction
243     AI->eraseFromParent();
244     NumReplaced++;
245   }
246
247   return Changed;
248 }
249
250
251 /// isSafeElementUse - Check to see if this use is an allowed use for a
252 /// getelementptr instruction of an array aggregate allocation.
253 ///
254 int SROA::isSafeElementUse(Value *Ptr) {
255   for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
256        I != E; ++I) {
257     Instruction *User = cast<Instruction>(*I);
258     switch (User->getOpcode()) {
259     case Instruction::Load:  break;
260     case Instruction::Store:
261       // Store is ok if storing INTO the pointer, not storing the pointer
262       if (User->getOperand(0) == Ptr) return 0;
263       break;
264     case Instruction::GetElementPtr: {
265       GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
266       if (GEP->getNumOperands() > 1) {
267         if (!isa<Constant>(GEP->getOperand(1)) ||
268             !cast<Constant>(GEP->getOperand(1))->isNullValue())
269           return 0;  // Using pointer arithmetic to navigate the array...
270       }
271       if (!isSafeElementUse(GEP)) return 0;
272       break;
273     }
274     default:
275       DOUT << "  Transformation preventing inst: " << *User;
276       return 0;
277     }
278   }
279   return 3;  // All users look ok :)
280 }
281
282 /// AllUsersAreLoads - Return true if all users of this value are loads.
283 static bool AllUsersAreLoads(Value *Ptr) {
284   for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
285        I != E; ++I)
286     if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
287       return false;
288   return true;
289 }
290
291 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
292 /// aggregate allocation.
293 ///
294 int SROA::isSafeUseOfAllocation(Instruction *User) {
295   if (!isa<GetElementPtrInst>(User)) return 0;
296
297   GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
298   gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
299
300   // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
301   if (I == E ||
302       I.getOperand() != Constant::getNullValue(I.getOperand()->getType()))
303     return 0;
304
305   ++I;
306   if (I == E) return 0;  // ran out of GEP indices??
307
308   // If this is a use of an array allocation, do a bit more checking for sanity.
309   if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
310     uint64_t NumElements = AT->getNumElements();
311
312     if (isa<ConstantInt>(I.getOperand())) {
313       // Check to make sure that index falls within the array.  If not,
314       // something funny is going on, so we won't do the optimization.
315       //
316       if (cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue() >= NumElements)
317         return 0;
318
319       // We cannot scalar repl this level of the array unless any array
320       // sub-indices are in-range constants.  In particular, consider:
321       // A[0][i].  We cannot know that the user isn't doing invalid things like
322       // allowing i to index an out-of-range subscript that accesses A[1].
323       //
324       // Scalar replacing *just* the outer index of the array is probably not
325       // going to be a win anyway, so just give up.
326       for (++I; I != E && (isa<ArrayType>(*I) || isa<PackedType>(*I)); ++I) {
327         uint64_t NumElements;
328         if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*I))
329           NumElements = SubArrayTy->getNumElements();
330         else
331           NumElements = cast<PackedType>(*I)->getNumElements();
332         
333         if (!isa<ConstantInt>(I.getOperand())) return 0;
334         if (cast<ConstantInt>(I.getOperand())->getZExtValue() >= NumElements)
335           return 0;
336       }
337       
338     } else {
339       // If this is an array index and the index is not constant, we cannot
340       // promote... that is unless the array has exactly one or two elements in
341       // it, in which case we CAN promote it, but we have to canonicalize this
342       // out if this is the only problem.
343       if ((NumElements == 1 || NumElements == 2) &&
344           AllUsersAreLoads(GEPI))
345         return 1;  // Canonicalization required!
346       return 0;
347     }
348   }
349
350   // If there are any non-simple uses of this getelementptr, make sure to reject
351   // them.
352   return isSafeElementUse(GEPI);
353 }
354
355 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
356 /// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
357 /// or 1 if safe after canonicalization has been performed.
358 ///
359 int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
360   // Loop over the use list of the alloca.  We can only transform it if all of
361   // the users are safe to transform.
362   //
363   int isSafe = 3;
364   for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
365        I != E; ++I) {
366     isSafe &= isSafeUseOfAllocation(cast<Instruction>(*I));
367     if (isSafe == 0) {
368       DOUT << "Cannot transform: " << *AI << "  due to user: " << **I;
369       return 0;
370     }
371   }
372   // If we require cleanup, isSafe is now 1, otherwise it is 3.
373   return isSafe;
374 }
375
376 /// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
377 /// allocation, but only if cleaned up, perform the cleanups required.
378 void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
379   // At this point, we know that the end result will be SROA'd and promoted, so
380   // we can insert ugly code if required so long as sroa+mem2reg will clean it
381   // up.
382   for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
383        UI != E; ) {
384     GetElementPtrInst *GEPI = cast<GetElementPtrInst>(*UI++);
385     gep_type_iterator I = gep_type_begin(GEPI);
386     ++I;
387
388     if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
389       uint64_t NumElements = AT->getNumElements();
390
391       if (!isa<ConstantInt>(I.getOperand())) {
392         if (NumElements == 1) {
393           GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
394         } else {
395           assert(NumElements == 2 && "Unhandled case!");
396           // All users of the GEP must be loads.  At each use of the GEP, insert
397           // two loads of the appropriate indexed GEP and select between them.
398           Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(), 
399                               Constant::getNullValue(I.getOperand()->getType()),
400              "isone", GEPI);
401           // Insert the new GEP instructions, which are properly indexed.
402           SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
403           Indices[1] = Constant::getNullValue(Type::Int32Ty);
404           Value *ZeroIdx = new GetElementPtrInst(GEPI->getOperand(0),
405                                                  &Indices[0], Indices.size(),
406                                                  GEPI->getName()+".0", GEPI);
407           Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
408           Value *OneIdx = new GetElementPtrInst(GEPI->getOperand(0),
409                                                 &Indices[0], Indices.size(),
410                                                 GEPI->getName()+".1", GEPI);
411           // Replace all loads of the variable index GEP with loads from both
412           // indexes and a select.
413           while (!GEPI->use_empty()) {
414             LoadInst *LI = cast<LoadInst>(GEPI->use_back());
415             Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
416             Value *One  = new LoadInst(OneIdx , LI->getName()+".1", LI);
417             Value *R = new SelectInst(IsOne, One, Zero, LI->getName(), LI);
418             LI->replaceAllUsesWith(R);
419             LI->eraseFromParent();
420           }
421           GEPI->eraseFromParent();
422         }
423       }
424     }
425   }
426 }
427
428 /// MergeInType - Add the 'In' type to the accumulated type so far.  If the
429 /// types are incompatible, return true, otherwise update Accum and return
430 /// false.
431 ///
432 /// There are three cases we handle here:
433 ///   1) An effectively-integer union, where the pieces are stored into as
434 ///      smaller integers (common with byte swap and other idioms).
435 ///   2) A union of vector types of the same size and potentially its elements.
436 ///      Here we turn element accesses into insert/extract element operations.
437 ///   3) A union of scalar types, such as int/float or int/pointer.  Here we
438 ///      merge together into integers, allowing the xform to work with #1 as
439 ///      well.
440 static bool MergeInType(const Type *In, const Type *&Accum,
441                         const TargetData &TD) {
442   // If this is our first type, just use it.
443   const PackedType *PTy;
444   if (Accum == Type::VoidTy || In == Accum) {
445     Accum = In;
446   } else if (In == Type::VoidTy) {
447     // Noop.
448   } else if (In->isInteger() && Accum->isInteger()) {   // integer union.
449     // Otherwise pick whichever type is larger.
450     if (cast<IntegerType>(In)->getBitWidth() > 
451         cast<IntegerType>(Accum)->getBitWidth())
452       Accum = In;
453   } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
454     // Pointer unions just stay as one of the pointers.
455   } else if (isa<PackedType>(In) || isa<PackedType>(Accum)) {
456     if ((PTy = dyn_cast<PackedType>(Accum)) && 
457         PTy->getElementType() == In) {
458       // Accum is a vector, and we are accessing an element: ok.
459     } else if ((PTy = dyn_cast<PackedType>(In)) && 
460                PTy->getElementType() == Accum) {
461       // In is a vector, and accum is an element: ok, remember In.
462       Accum = In;
463     } else if ((PTy = dyn_cast<PackedType>(In)) && isa<PackedType>(Accum) &&
464                PTy->getBitWidth() == cast<PackedType>(Accum)->getBitWidth()) {
465       // Two vectors of the same size: keep Accum.
466     } else {
467       // Cannot insert an short into a <4 x int> or handle
468       // <2 x int> -> <4 x int>
469       return true;
470     }
471   } else {
472     // Pointer/FP/Integer unions merge together as integers.
473     switch (Accum->getTypeID()) {
474     case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
475     case Type::FloatTyID:   Accum = Type::Int32Ty; break;
476     case Type::DoubleTyID:  Accum = Type::Int64Ty; break;
477     default:
478       assert(Accum->isInteger() && "Unknown FP type!");
479       break;
480     }
481     
482     switch (In->getTypeID()) {
483     case Type::PointerTyID: In = TD.getIntPtrType(); break;
484     case Type::FloatTyID:   In = Type::Int32Ty; break;
485     case Type::DoubleTyID:  In = Type::Int64Ty; break;
486     default:
487       assert(In->isInteger() && "Unknown FP type!");
488       break;
489     }
490     return MergeInType(In, Accum, TD);
491   }
492   return false;
493 }
494
495 /// getUIntAtLeastAsBitAs - Return an unsigned integer type that is at least
496 /// as big as the specified type.  If there is no suitable type, this returns
497 /// null.
498 const Type *getUIntAtLeastAsBitAs(unsigned NumBits) {
499   if (NumBits > 64) return 0;
500   if (NumBits > 32) return Type::Int64Ty;
501   if (NumBits > 16) return Type::Int32Ty;
502   if (NumBits > 8) return Type::Int16Ty;
503   return Type::Int8Ty;    
504 }
505
506 /// CanConvertToScalar - V is a pointer.  If we can convert the pointee to a
507 /// single scalar integer type, return that type.  Further, if the use is not
508 /// a completely trivial use that mem2reg could promote, set IsNotTrivial.  If
509 /// there are no uses of this pointer, return Type::VoidTy to differentiate from
510 /// failure.
511 ///
512 const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
513   const Type *UsedType = Type::VoidTy; // No uses, no forced type.
514   const TargetData &TD = getAnalysis<TargetData>();
515   const PointerType *PTy = cast<PointerType>(V->getType());
516
517   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
518     Instruction *User = cast<Instruction>(*UI);
519     
520     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
521       if (MergeInType(LI->getType(), UsedType, TD))
522         return 0;
523       
524     } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
525       // Storing the pointer, not into the value?
526       if (SI->getOperand(0) == V) return 0;
527       
528       // NOTE: We could handle storing of FP imms into integers here!
529       
530       if (MergeInType(SI->getOperand(0)->getType(), UsedType, TD))
531         return 0;
532     } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
533       IsNotTrivial = true;
534       const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
535       if (!SubTy || MergeInType(SubTy, UsedType, TD)) return 0;
536     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
537       // Check to see if this is stepping over an element: GEP Ptr, int C
538       if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
539         unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
540         unsigned ElSize = TD.getTypeSize(PTy->getElementType());
541         unsigned BitOffset = Idx*ElSize*8;
542         if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
543         
544         IsNotTrivial = true;
545         const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
546         if (SubElt == 0) return 0;
547         if (SubElt != Type::VoidTy && SubElt->isInteger()) {
548           const Type *NewTy = 
549             getUIntAtLeastAsBitAs(TD.getTypeSize(SubElt)*8+BitOffset);
550           if (NewTy == 0 || MergeInType(NewTy, UsedType, TD)) return 0;
551           continue;
552         }
553       } else if (GEP->getNumOperands() == 3 && 
554                  isa<ConstantInt>(GEP->getOperand(1)) &&
555                  isa<ConstantInt>(GEP->getOperand(2)) &&
556                  cast<Constant>(GEP->getOperand(1))->isNullValue()) {
557         // We are stepping into an element, e.g. a structure or an array:
558         // GEP Ptr, int 0, uint C
559         const Type *AggTy = PTy->getElementType();
560         unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
561         
562         if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
563           if (Idx >= ATy->getNumElements()) return 0;  // Out of range.
564         } else if (const PackedType *PackedTy = dyn_cast<PackedType>(AggTy)) {
565           // Getting an element of the packed vector.
566           if (Idx >= PackedTy->getNumElements()) return 0;  // Out of range.
567
568           // Merge in the packed type.
569           if (MergeInType(PackedTy, UsedType, TD)) return 0;
570           
571           const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
572           if (SubTy == 0) return 0;
573           
574           if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
575             return 0;
576
577           // We'll need to change this to an insert/extract element operation.
578           IsNotTrivial = true;
579           continue;    // Everything looks ok
580           
581         } else if (isa<StructType>(AggTy)) {
582           // Structs are always ok.
583         } else {
584           return 0;
585         }
586         const Type *NTy = getUIntAtLeastAsBitAs(TD.getTypeSize(AggTy)*8);
587         if (NTy == 0 || MergeInType(NTy, UsedType, TD)) return 0;
588         const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
589         if (SubTy == 0) return 0;
590         if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
591           return 0;
592         continue;    // Everything looks ok
593       }
594       return 0;
595     } else {
596       // Cannot handle this!
597       return 0;
598     }
599   }
600   
601   return UsedType;
602 }
603
604 /// ConvertToScalar - The specified alloca passes the CanConvertToScalar
605 /// predicate and is non-trivial.  Convert it to something that can be trivially
606 /// promoted into a register by mem2reg.
607 void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
608   DOUT << "CONVERT TO SCALAR: " << *AI << "  TYPE = "
609        << *ActualTy << "\n";
610   ++NumConverted;
611   
612   BasicBlock *EntryBlock = AI->getParent();
613   assert(EntryBlock == &EntryBlock->getParent()->front() &&
614          "Not in the entry block!");
615   EntryBlock->getInstList().remove(AI);  // Take the alloca out of the program.
616   
617   // Create and insert the alloca.
618   AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
619                                      EntryBlock->begin());
620   ConvertUsesToScalar(AI, NewAI, 0);
621   delete AI;
622 }
623
624
625 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
626 /// directly.  This happens when we are converting an "integer union" to a
627 /// single integer scalar, or when we are converting a "vector union" to a
628 /// vector with insert/extractelement instructions.
629 ///
630 /// Offset is an offset from the original alloca, in bits that need to be
631 /// shifted to the right.  By the end of this, there should be no uses of Ptr.
632 void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
633   bool isVectorInsert = isa<PackedType>(NewAI->getType()->getElementType());
634   const TargetData &TD = getAnalysis<TargetData>();
635   while (!Ptr->use_empty()) {
636     Instruction *User = cast<Instruction>(Ptr->use_back());
637     
638     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
639       // The load is a bit extract from NewAI shifted right by Offset bits.
640       Value *NV = new LoadInst(NewAI, LI->getName(), LI);
641       if (NV->getType() != LI->getType()) {
642         if (const PackedType *PTy = dyn_cast<PackedType>(NV->getType())) {
643           // If the result alloca is a packed type, this is either an element
644           // access or a bitcast to another packed type.
645           if (isa<PackedType>(LI->getType())) {
646             NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
647           } else {
648             // Must be an element access.
649             unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
650             NV = new ExtractElementInst(
651                            NV, ConstantInt::get(Type::Int32Ty, Elt), "tmp", LI);
652           }
653         } else if (isa<PointerType>(NV->getType())) {
654           assert(isa<PointerType>(LI->getType()));
655           // Must be ptr->ptr cast.  Anything else would result in NV being
656           // an integer.
657           NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
658         } else {
659           assert(NV->getType()->isInteger() && "Unknown promotion!");
660           if (Offset && Offset < TD.getTypeSize(NV->getType())*8) {
661             NV = BinaryOperator::createLShr(NV, 
662                                         ConstantInt::get(NV->getType(), Offset),
663                                         LI->getName(), LI);
664           }
665           
666           // If the result is an integer, this is a trunc or bitcast.
667           if (LI->getType()->isInteger()) {
668             NV = CastInst::createTruncOrBitCast(NV, LI->getType(),
669                                                 LI->getName(), LI);
670           } else if (LI->getType()->isFloatingPoint()) {
671             // If needed, truncate the integer to the appropriate size.
672             if (NV->getType()->getPrimitiveSizeInBits() > 
673                 LI->getType()->getPrimitiveSizeInBits()) {
674               switch (LI->getType()->getTypeID()) {
675               default: assert(0 && "Unknown FP type!");
676               case Type::FloatTyID:
677                 NV = new TruncInst(NV, Type::Int32Ty, LI->getName(), LI);
678                 break;
679               case Type::DoubleTyID:
680                 NV = new TruncInst(NV, Type::Int64Ty, LI->getName(), LI);
681                 break;
682               }
683             }
684             
685             // Then do a bitcast.
686             NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
687           } else {
688             // Otherwise must be a pointer.
689             NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
690           }
691         }
692       }
693       LI->replaceAllUsesWith(NV);
694       LI->eraseFromParent();
695     } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
696       assert(SI->getOperand(0) != Ptr && "Consistency error!");
697
698       // Convert the stored type to the actual type, shift it left to insert
699       // then 'or' into place.
700       Value *SV = SI->getOperand(0);
701       const Type *AllocaType = NewAI->getType()->getElementType();
702       if (SV->getType() != AllocaType) {
703         Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
704         
705         if (const PackedType *PTy = dyn_cast<PackedType>(AllocaType)) {
706           // If the result alloca is a packed type, this is either an element
707           // access or a bitcast to another packed type.
708           if (isa<PackedType>(SV->getType())) {
709             SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
710           } else {            
711             // Must be an element insertion.
712             unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
713             SV = new InsertElementInst(Old, SV,
714                                        ConstantInt::get(Type::Int32Ty, Elt),
715                                        "tmp", SI);
716           }
717         } else {
718           // If SV is a float, convert it to the appropriate integer type.
719           // If it is a pointer, do the same, and also handle ptr->ptr casts
720           // here.
721           switch (SV->getType()->getTypeID()) {
722           default:
723             assert(!SV->getType()->isFloatingPoint() && "Unknown FP type!");
724             break;
725           case Type::FloatTyID:
726             SV = new BitCastInst(SV, Type::Int32Ty, SV->getName(), SI);
727             break;
728           case Type::DoubleTyID:
729             SV = new BitCastInst(SV, Type::Int64Ty, SV->getName(), SI);
730             break;
731           case Type::PointerTyID:
732             if (isa<PointerType>(AllocaType))
733               SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
734             else
735               SV = new PtrToIntInst(SV, TD.getIntPtrType(), SV->getName(), SI);
736             break;
737           }
738
739           unsigned SrcSize = TD.getTypeSize(SV->getType())*8;
740
741           // Always zero extend the value if needed.
742           if (SV->getType() != AllocaType)
743             SV = CastInst::createZExtOrBitCast(SV, AllocaType,
744                                                SV->getName(), SI);
745           if (Offset && Offset < AllocaType->getPrimitiveSizeInBits())
746             SV = BinaryOperator::createShl(SV,
747                                         ConstantInt::get(SV->getType(), Offset),
748                                         SV->getName()+".adj", SI);
749           // Mask out the bits we are about to insert from the old value.
750           unsigned TotalBits = TD.getTypeSize(SV->getType())*8;
751           if (TotalBits != SrcSize) {
752             assert(TotalBits > SrcSize);
753             uint64_t Mask = ~(((1ULL << SrcSize)-1) << Offset);
754             Mask = Mask & cast<IntegerType>(SV->getType())->getBitMask();
755             Old = BinaryOperator::createAnd(Old,
756                                         ConstantInt::get(Old->getType(), Mask),
757                                             Old->getName()+".mask", SI);
758             SV = BinaryOperator::createOr(Old, SV, SV->getName()+".ins", SI);
759           }
760         }
761       }
762       new StoreInst(SV, NewAI, SI);
763       SI->eraseFromParent();
764       
765     } else if (CastInst *CI = dyn_cast<CastInst>(User)) {
766       unsigned NewOff = Offset;
767       const TargetData &TD = getAnalysis<TargetData>();
768       if (TD.isBigEndian() && !isVectorInsert) {
769         // Adjust the pointer.  For example, storing 16-bits into a 32-bit
770         // alloca with just a cast makes it modify the top 16-bits.
771         const Type *SrcTy = cast<PointerType>(Ptr->getType())->getElementType();
772         const Type *DstTy = cast<PointerType>(CI->getType())->getElementType();
773         int PtrDiffBits = TD.getTypeSize(SrcTy)*8-TD.getTypeSize(DstTy)*8;
774         NewOff += PtrDiffBits;
775       }
776       ConvertUsesToScalar(CI, NewAI, NewOff);
777       CI->eraseFromParent();
778     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
779       const PointerType *AggPtrTy = 
780         cast<PointerType>(GEP->getOperand(0)->getType());
781       const TargetData &TD = getAnalysis<TargetData>();
782       unsigned AggSizeInBits = TD.getTypeSize(AggPtrTy->getElementType())*8;
783       
784       // Check to see if this is stepping over an element: GEP Ptr, int C
785       unsigned NewOffset = Offset;
786       if (GEP->getNumOperands() == 2) {
787         unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
788         unsigned BitOffset = Idx*AggSizeInBits;
789         
790         if (TD.isLittleEndian() || isVectorInsert)
791           NewOffset += BitOffset;
792         else
793           NewOffset -= BitOffset;
794         
795       } else if (GEP->getNumOperands() == 3) {
796         // We know that operand #2 is zero.
797         unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
798         const Type *AggTy = AggPtrTy->getElementType();
799         if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
800           unsigned ElSizeBits = TD.getTypeSize(SeqTy->getElementType())*8;
801
802           if (TD.isLittleEndian() || isVectorInsert)
803             NewOffset += ElSizeBits*Idx;
804           else
805             NewOffset += AggSizeInBits-ElSizeBits*(Idx+1);
806         } else if (const StructType *STy = dyn_cast<StructType>(AggTy)) {
807           unsigned EltBitOffset =
808             TD.getStructLayout(STy)->getElementOffset(Idx)*8;
809           
810           if (TD.isLittleEndian() || isVectorInsert)
811             NewOffset += EltBitOffset;
812           else {
813             const PointerType *ElPtrTy = cast<PointerType>(GEP->getType());
814             unsigned ElSizeBits = TD.getTypeSize(ElPtrTy->getElementType())*8;
815             NewOffset += AggSizeInBits-(EltBitOffset+ElSizeBits);
816           }
817           
818         } else {
819           assert(0 && "Unsupported operation!");
820           abort();
821         }
822       } else {
823         assert(0 && "Unsupported operation!");
824         abort();
825       }
826       ConvertUsesToScalar(GEP, NewAI, NewOffset);
827       GEP->eraseFromParent();
828     } else {
829       assert(0 && "Unsupported operation!");
830       abort();
831     }
832   }
833 }