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