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