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