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