GlobalOpt.cpp revision 4200f2c815159e939351d5d447f7f68fb557e600
1//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
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 pass transforms simple global variables that never have their address
11// taken.  If obviously true, it marks read/write globals as constant, deletes
12// variables only stored to, etc.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "globalopt"
17#include "llvm/Transforms/IPO.h"
18#include "llvm/CallingConv.h"
19#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Instructions.h"
22#include "llvm/IntrinsicInst.h"
23#include "llvm/LLVMContext.h"
24#include "llvm/Module.h"
25#include "llvm/Pass.h"
26#include "llvm/Analysis/ConstantFolding.h"
27#include "llvm/Analysis/MemoryBuiltins.h"
28#include "llvm/Target/TargetData.h"
29#include "llvm/Support/CallSite.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/GetElementPtrTypeIterator.h"
33#include "llvm/Support/MathExtras.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/ADT/DenseMap.h"
36#include "llvm/ADT/SmallPtrSet.h"
37#include "llvm/ADT/SmallVector.h"
38#include "llvm/ADT/Statistic.h"
39#include "llvm/ADT/STLExtras.h"
40#include <algorithm>
41using namespace llvm;
42
43STATISTIC(NumMarked    , "Number of globals marked constant");
44STATISTIC(NumSRA       , "Number of aggregate globals broken into scalars");
45STATISTIC(NumHeapSRA   , "Number of heap objects SRA'd");
46STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
47STATISTIC(NumDeleted   , "Number of globals deleted");
48STATISTIC(NumFnDeleted , "Number of functions deleted");
49STATISTIC(NumGlobUses  , "Number of global uses devirtualized");
50STATISTIC(NumLocalized , "Number of globals localized");
51STATISTIC(NumShrunkToBool  , "Number of global vars shrunk to booleans");
52STATISTIC(NumFastCallFns   , "Number of functions converted to fastcc");
53STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
54STATISTIC(NumNestRemoved   , "Number of nest attributes removed");
55STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
56STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
57
58namespace {
59  struct GlobalOpt : public ModulePass {
60    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
61    }
62    static char ID; // Pass identification, replacement for typeid
63    GlobalOpt() : ModulePass(&ID) {}
64
65    bool runOnModule(Module &M);
66
67  private:
68    GlobalVariable *FindGlobalCtors(Module &M);
69    bool OptimizeFunctions(Module &M);
70    bool OptimizeGlobalVars(Module &M);
71    bool OptimizeGlobalAliases(Module &M);
72    bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
73    bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
74  };
75}
76
77char GlobalOpt::ID = 0;
78static RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
79
80ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
81
82namespace {
83
84/// GlobalStatus - As we analyze each global, keep track of some information
85/// about it.  If we find out that the address of the global is taken, none of
86/// this info will be accurate.
87struct GlobalStatus {
88  /// isLoaded - True if the global is ever loaded.  If the global isn't ever
89  /// loaded it can be deleted.
90  bool isLoaded;
91
92  /// StoredType - Keep track of what stores to the global look like.
93  ///
94  enum StoredType {
95    /// NotStored - There is no store to this global.  It can thus be marked
96    /// constant.
97    NotStored,
98
99    /// isInitializerStored - This global is stored to, but the only thing
100    /// stored is the constant it was initialized with.  This is only tracked
101    /// for scalar globals.
102    isInitializerStored,
103
104    /// isStoredOnce - This global is stored to, but only its initializer and
105    /// one other value is ever stored to it.  If this global isStoredOnce, we
106    /// track the value stored to it in StoredOnceValue below.  This is only
107    /// tracked for scalar globals.
108    isStoredOnce,
109
110    /// isStored - This global is stored to by multiple values or something else
111    /// that we cannot track.
112    isStored
113  } StoredType;
114
115  /// StoredOnceValue - If only one value (besides the initializer constant) is
116  /// ever stored to this global, keep track of what value it is.
117  Value *StoredOnceValue;
118
119  /// AccessingFunction/HasMultipleAccessingFunctions - These start out
120  /// null/false.  When the first accessing function is noticed, it is recorded.
121  /// When a second different accessing function is noticed,
122  /// HasMultipleAccessingFunctions is set to true.
123  Function *AccessingFunction;
124  bool HasMultipleAccessingFunctions;
125
126  /// HasNonInstructionUser - Set to true if this global has a user that is not
127  /// an instruction (e.g. a constant expr or GV initializer).
128  bool HasNonInstructionUser;
129
130  /// HasPHIUser - Set to true if this global has a user that is a PHI node.
131  bool HasPHIUser;
132
133  GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
134                   AccessingFunction(0), HasMultipleAccessingFunctions(false),
135                   HasNonInstructionUser(false), HasPHIUser(false) {}
136};
137
138}
139
140// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
141// by constants itself.  Note that constants cannot be cyclic, so this test is
142// pretty easy to implement recursively.
143//
144static bool SafeToDestroyConstant(Constant *C) {
145  if (isa<GlobalValue>(C)) return false;
146
147  for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
148    if (Constant *CU = dyn_cast<Constant>(*UI)) {
149      if (!SafeToDestroyConstant(CU)) return false;
150    } else
151      return false;
152  return true;
153}
154
155
156/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
157/// structure.  If the global has its address taken, return true to indicate we
158/// can't do anything with it.
159///
160static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
161                          SmallPtrSet<PHINode*, 16> &PHIUsers) {
162  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
163    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
164      GS.HasNonInstructionUser = true;
165
166      if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
167
168    } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
169      if (!GS.HasMultipleAccessingFunctions) {
170        Function *F = I->getParent()->getParent();
171        if (GS.AccessingFunction == 0)
172          GS.AccessingFunction = F;
173        else if (GS.AccessingFunction != F)
174          GS.HasMultipleAccessingFunctions = true;
175      }
176      if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
177        GS.isLoaded = true;
178        if (LI->isVolatile()) return true;  // Don't hack on volatile loads.
179      } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
180        // Don't allow a store OF the address, only stores TO the address.
181        if (SI->getOperand(0) == V) return true;
182
183        if (SI->isVolatile()) return true;  // Don't hack on volatile stores.
184
185        // If this is a direct store to the global (i.e., the global is a scalar
186        // value, not an aggregate), keep more specific information about
187        // stores.
188        if (GS.StoredType != GlobalStatus::isStored) {
189          if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
190            Value *StoredVal = SI->getOperand(0);
191            if (StoredVal == GV->getInitializer()) {
192              if (GS.StoredType < GlobalStatus::isInitializerStored)
193                GS.StoredType = GlobalStatus::isInitializerStored;
194            } else if (isa<LoadInst>(StoredVal) &&
195                       cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
196              // G = G
197              if (GS.StoredType < GlobalStatus::isInitializerStored)
198                GS.StoredType = GlobalStatus::isInitializerStored;
199            } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
200              GS.StoredType = GlobalStatus::isStoredOnce;
201              GS.StoredOnceValue = StoredVal;
202            } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
203                       GS.StoredOnceValue == StoredVal) {
204              // noop.
205            } else {
206              GS.StoredType = GlobalStatus::isStored;
207            }
208          } else {
209            GS.StoredType = GlobalStatus::isStored;
210          }
211        }
212      } else if (isa<GetElementPtrInst>(I)) {
213        if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
214      } else if (isa<SelectInst>(I)) {
215        if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
216      } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
217        // PHI nodes we can check just like select or GEP instructions, but we
218        // have to be careful about infinite recursion.
219        if (PHIUsers.insert(PN))  // Not already visited.
220          if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
221        GS.HasPHIUser = true;
222      } else if (isa<CmpInst>(I)) {
223      } else if (isa<MemTransferInst>(I)) {
224        if (I->getOperand(1) == V)
225          GS.StoredType = GlobalStatus::isStored;
226        if (I->getOperand(2) == V)
227          GS.isLoaded = true;
228      } else if (isa<MemSetInst>(I)) {
229        assert(I->getOperand(1) == V && "Memset only takes one pointer!");
230        GS.StoredType = GlobalStatus::isStored;
231      } else {
232        return true;  // Any other non-load instruction might take address!
233      }
234    } else if (Constant *C = dyn_cast<Constant>(*UI)) {
235      GS.HasNonInstructionUser = true;
236      // We might have a dead and dangling constant hanging off of here.
237      if (!SafeToDestroyConstant(C))
238        return true;
239    } else {
240      GS.HasNonInstructionUser = true;
241      // Otherwise must be some other user.
242      return true;
243    }
244
245  return false;
246}
247
248static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx,
249                                             LLVMContext &Context) {
250  ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
251  if (!CI) return 0;
252  unsigned IdxV = CI->getZExtValue();
253
254  if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
255    if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
256  } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
257    if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
258  } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
259    if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
260  } else if (isa<ConstantAggregateZero>(Agg)) {
261    if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
262      if (IdxV < STy->getNumElements())
263        return Constant::getNullValue(STy->getElementType(IdxV));
264    } else if (const SequentialType *STy =
265               dyn_cast<SequentialType>(Agg->getType())) {
266      return Constant::getNullValue(STy->getElementType());
267    }
268  } else if (isa<UndefValue>(Agg)) {
269    if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
270      if (IdxV < STy->getNumElements())
271        return UndefValue::get(STy->getElementType(IdxV));
272    } else if (const SequentialType *STy =
273               dyn_cast<SequentialType>(Agg->getType())) {
274      return UndefValue::get(STy->getElementType());
275    }
276  }
277  return 0;
278}
279
280
281/// CleanupConstantGlobalUsers - We just marked GV constant.  Loop over all
282/// users of the global, cleaning up the obvious ones.  This is largely just a
283/// quick scan over the use list to clean up the easy and obvious cruft.  This
284/// returns true if it made a change.
285static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
286                                       LLVMContext &Context) {
287  bool Changed = false;
288  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
289    User *U = *UI++;
290
291    if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
292      if (Init) {
293        // Replace the load with the initializer.
294        LI->replaceAllUsesWith(Init);
295        LI->eraseFromParent();
296        Changed = true;
297      }
298    } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
299      // Store must be unreachable or storing Init into the global.
300      SI->eraseFromParent();
301      Changed = true;
302    } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
303      if (CE->getOpcode() == Instruction::GetElementPtr) {
304        Constant *SubInit = 0;
305        if (Init)
306          SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
307        Changed |= CleanupConstantGlobalUsers(CE, SubInit, Context);
308      } else if (CE->getOpcode() == Instruction::BitCast &&
309                 isa<PointerType>(CE->getType())) {
310        // Pointer cast, delete any stores and memsets to the global.
311        Changed |= CleanupConstantGlobalUsers(CE, 0, Context);
312      }
313
314      if (CE->use_empty()) {
315        CE->destroyConstant();
316        Changed = true;
317      }
318    } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
319      // Do not transform "gepinst (gep constexpr (GV))" here, because forming
320      // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
321      // and will invalidate our notion of what Init is.
322      Constant *SubInit = 0;
323      if (!isa<ConstantExpr>(GEP->getOperand(0))) {
324        ConstantExpr *CE =
325          dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, Context));
326        if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
327          SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
328      }
329      Changed |= CleanupConstantGlobalUsers(GEP, SubInit, Context);
330
331      if (GEP->use_empty()) {
332        GEP->eraseFromParent();
333        Changed = true;
334      }
335    } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
336      if (MI->getRawDest() == V) {
337        MI->eraseFromParent();
338        Changed = true;
339      }
340
341    } else if (Constant *C = dyn_cast<Constant>(U)) {
342      // If we have a chain of dead constantexprs or other things dangling from
343      // us, and if they are all dead, nuke them without remorse.
344      if (SafeToDestroyConstant(C)) {
345        C->destroyConstant();
346        // This could have invalidated UI, start over from scratch.
347        CleanupConstantGlobalUsers(V, Init, Context);
348        return true;
349      }
350    }
351  }
352  return Changed;
353}
354
355/// isSafeSROAElementUse - Return true if the specified instruction is a safe
356/// user of a derived expression from a global that we want to SROA.
357static bool isSafeSROAElementUse(Value *V) {
358  // We might have a dead and dangling constant hanging off of here.
359  if (Constant *C = dyn_cast<Constant>(V))
360    return SafeToDestroyConstant(C);
361
362  Instruction *I = dyn_cast<Instruction>(V);
363  if (!I) return false;
364
365  // Loads are ok.
366  if (isa<LoadInst>(I)) return true;
367
368  // Stores *to* the pointer are ok.
369  if (StoreInst *SI = dyn_cast<StoreInst>(I))
370    return SI->getOperand(0) != V;
371
372  // Otherwise, it must be a GEP.
373  GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
374  if (GEPI == 0) return false;
375
376  if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
377      !cast<Constant>(GEPI->getOperand(1))->isNullValue())
378    return false;
379
380  for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
381       I != E; ++I)
382    if (!isSafeSROAElementUse(*I))
383      return false;
384  return true;
385}
386
387
388/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
389/// Look at it and its uses and decide whether it is safe to SROA this global.
390///
391static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
392  // The user of the global must be a GEP Inst or a ConstantExpr GEP.
393  if (!isa<GetElementPtrInst>(U) &&
394      (!isa<ConstantExpr>(U) ||
395       cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
396    return false;
397
398  // Check to see if this ConstantExpr GEP is SRA'able.  In particular, we
399  // don't like < 3 operand CE's, and we don't like non-constant integer
400  // indices.  This enforces that all uses are 'gep GV, 0, C, ...' for some
401  // value of C.
402  if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
403      !cast<Constant>(U->getOperand(1))->isNullValue() ||
404      !isa<ConstantInt>(U->getOperand(2)))
405    return false;
406
407  gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
408  ++GEPI;  // Skip over the pointer index.
409
410  // If this is a use of an array allocation, do a bit more checking for sanity.
411  if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
412    uint64_t NumElements = AT->getNumElements();
413    ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
414
415    // Check to make sure that index falls within the array.  If not,
416    // something funny is going on, so we won't do the optimization.
417    //
418    if (Idx->getZExtValue() >= NumElements)
419      return false;
420
421    // We cannot scalar repl this level of the array unless any array
422    // sub-indices are in-range constants.  In particular, consider:
423    // A[0][i].  We cannot know that the user isn't doing invalid things like
424    // allowing i to index an out-of-range subscript that accesses A[1].
425    //
426    // Scalar replacing *just* the outer index of the array is probably not
427    // going to be a win anyway, so just give up.
428    for (++GEPI; // Skip array index.
429         GEPI != E;
430         ++GEPI) {
431      uint64_t NumElements;
432      if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
433        NumElements = SubArrayTy->getNumElements();
434      else if (const VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
435        NumElements = SubVectorTy->getNumElements();
436      else {
437        assert(isa<StructType>(*GEPI) &&
438               "Indexed GEP type is not array, vector, or struct!");
439        continue;
440      }
441
442      ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
443      if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
444        return false;
445    }
446  }
447
448  for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
449    if (!isSafeSROAElementUse(*I))
450      return false;
451  return true;
452}
453
454/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
455/// is safe for us to perform this transformation.
456///
457static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
458  for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
459       UI != E; ++UI) {
460    if (!IsUserOfGlobalSafeForSRA(*UI, GV))
461      return false;
462  }
463  return true;
464}
465
466
467/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
468/// variable.  This opens the door for other optimizations by exposing the
469/// behavior of the program in a more fine-grained way.  We have determined that
470/// this transformation is safe already.  We return the first global variable we
471/// insert so that the caller can reprocess it.
472static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD,
473                                 LLVMContext &Context) {
474  // Make sure this global only has simple uses that we can SRA.
475  if (!GlobalUsersSafeToSRA(GV))
476    return 0;
477
478  assert(GV->hasLocalLinkage() && !GV->isConstant());
479  Constant *Init = GV->getInitializer();
480  const Type *Ty = Init->getType();
481
482  std::vector<GlobalVariable*> NewGlobals;
483  Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
484
485  // Get the alignment of the global, either explicit or target-specific.
486  unsigned StartAlignment = GV->getAlignment();
487  if (StartAlignment == 0)
488    StartAlignment = TD.getABITypeAlignment(GV->getType());
489
490  if (const StructType *STy = dyn_cast<StructType>(Ty)) {
491    NewGlobals.reserve(STy->getNumElements());
492    const StructLayout &Layout = *TD.getStructLayout(STy);
493    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
494      Constant *In = getAggregateConstantElement(Init,
495                                ConstantInt::get(Type::getInt32Ty(Context), i),
496                                    Context);
497      assert(In && "Couldn't get element of initializer?");
498      GlobalVariable *NGV = new GlobalVariable(Context,
499                                               STy->getElementType(i), false,
500                                               GlobalVariable::InternalLinkage,
501                                               In, GV->getName()+"."+Twine(i),
502                                               GV->isThreadLocal(),
503                                              GV->getType()->getAddressSpace());
504      Globals.insert(GV, NGV);
505      NewGlobals.push_back(NGV);
506
507      // Calculate the known alignment of the field.  If the original aggregate
508      // had 256 byte alignment for example, something might depend on that:
509      // propagate info to each field.
510      uint64_t FieldOffset = Layout.getElementOffset(i);
511      unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
512      if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
513        NGV->setAlignment(NewAlign);
514    }
515  } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
516    unsigned NumElements = 0;
517    if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
518      NumElements = ATy->getNumElements();
519    else
520      NumElements = cast<VectorType>(STy)->getNumElements();
521
522    if (NumElements > 16 && GV->hasNUsesOrMore(16))
523      return 0; // It's not worth it.
524    NewGlobals.reserve(NumElements);
525
526    uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
527    unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
528    for (unsigned i = 0, e = NumElements; i != e; ++i) {
529      Constant *In = getAggregateConstantElement(Init,
530                                ConstantInt::get(Type::getInt32Ty(Context), i),
531                                    Context);
532      assert(In && "Couldn't get element of initializer?");
533
534      GlobalVariable *NGV = new GlobalVariable(Context,
535                                               STy->getElementType(), false,
536                                               GlobalVariable::InternalLinkage,
537                                               In, GV->getName()+"."+Twine(i),
538                                               GV->isThreadLocal(),
539                                              GV->getType()->getAddressSpace());
540      Globals.insert(GV, NGV);
541      NewGlobals.push_back(NGV);
542
543      // Calculate the known alignment of the field.  If the original aggregate
544      // had 256 byte alignment for example, something might depend on that:
545      // propagate info to each field.
546      unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
547      if (NewAlign > EltAlign)
548        NGV->setAlignment(NewAlign);
549    }
550  }
551
552  if (NewGlobals.empty())
553    return 0;
554
555  DEBUG(errs() << "PERFORMING GLOBAL SRA ON: " << *GV);
556
557  Constant *NullInt = Constant::getNullValue(Type::getInt32Ty(Context));
558
559  // Loop over all of the uses of the global, replacing the constantexpr geps,
560  // with smaller constantexpr geps or direct references.
561  while (!GV->use_empty()) {
562    User *GEP = GV->use_back();
563    assert(((isa<ConstantExpr>(GEP) &&
564             cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
565            isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
566
567    // Ignore the 1th operand, which has to be zero or else the program is quite
568    // broken (undefined).  Get the 2nd operand, which is the structure or array
569    // index.
570    unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
571    if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
572
573    Value *NewPtr = NewGlobals[Val];
574
575    // Form a shorter GEP if needed.
576    if (GEP->getNumOperands() > 3) {
577      if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
578        SmallVector<Constant*, 8> Idxs;
579        Idxs.push_back(NullInt);
580        for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
581          Idxs.push_back(CE->getOperand(i));
582        NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
583                                                &Idxs[0], Idxs.size());
584      } else {
585        GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
586        SmallVector<Value*, 8> Idxs;
587        Idxs.push_back(NullInt);
588        for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
589          Idxs.push_back(GEPI->getOperand(i));
590        NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
591                                           GEPI->getName()+"."+Twine(Val),GEPI);
592      }
593    }
594    GEP->replaceAllUsesWith(NewPtr);
595
596    if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
597      GEPI->eraseFromParent();
598    else
599      cast<ConstantExpr>(GEP)->destroyConstant();
600  }
601
602  // Delete the old global, now that it is dead.
603  Globals.erase(GV);
604  ++NumSRA;
605
606  // Loop over the new globals array deleting any globals that are obviously
607  // dead.  This can arise due to scalarization of a structure or an array that
608  // has elements that are dead.
609  unsigned FirstGlobal = 0;
610  for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
611    if (NewGlobals[i]->use_empty()) {
612      Globals.erase(NewGlobals[i]);
613      if (FirstGlobal == i) ++FirstGlobal;
614    }
615
616  return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
617}
618
619/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
620/// value will trap if the value is dynamically null.  PHIs keeps track of any
621/// phi nodes we've seen to avoid reprocessing them.
622static bool AllUsesOfValueWillTrapIfNull(Value *V,
623                                         SmallPtrSet<PHINode*, 8> &PHIs) {
624  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
625    if (isa<LoadInst>(*UI)) {
626      // Will trap.
627    } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
628      if (SI->getOperand(0) == V) {
629        //cerr << "NONTRAPPING USE: " << **UI;
630        return false;  // Storing the value.
631      }
632    } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
633      if (CI->getOperand(0) != V) {
634        //cerr << "NONTRAPPING USE: " << **UI;
635        return false;  // Not calling the ptr
636      }
637    } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
638      if (II->getOperand(0) != V) {
639        //cerr << "NONTRAPPING USE: " << **UI;
640        return false;  // Not calling the ptr
641      }
642    } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
643      if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
644    } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
645      if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
646    } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
647      // If we've already seen this phi node, ignore it, it has already been
648      // checked.
649      if (PHIs.insert(PN))
650        return AllUsesOfValueWillTrapIfNull(PN, PHIs);
651    } else if (isa<ICmpInst>(*UI) &&
652               isa<ConstantPointerNull>(UI->getOperand(1))) {
653      // Ignore setcc X, null
654    } else {
655      //cerr << "NONTRAPPING USE: " << **UI;
656      return false;
657    }
658  return true;
659}
660
661/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
662/// from GV will trap if the loaded value is null.  Note that this also permits
663/// comparisons of the loaded value against null, as a special case.
664static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
665  for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
666    if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
667      SmallPtrSet<PHINode*, 8> PHIs;
668      if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
669        return false;
670    } else if (isa<StoreInst>(*UI)) {
671      // Ignore stores to the global.
672    } else {
673      // We don't know or understand this user, bail out.
674      //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
675      return false;
676    }
677
678  return true;
679}
680
681static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV,
682                                           LLVMContext &Context) {
683  bool Changed = false;
684  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
685    Instruction *I = cast<Instruction>(*UI++);
686    if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
687      LI->setOperand(0, NewV);
688      Changed = true;
689    } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
690      if (SI->getOperand(1) == V) {
691        SI->setOperand(1, NewV);
692        Changed = true;
693      }
694    } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
695      if (I->getOperand(0) == V) {
696        // Calling through the pointer!  Turn into a direct call, but be careful
697        // that the pointer is not also being passed as an argument.
698        I->setOperand(0, NewV);
699        Changed = true;
700        bool PassedAsArg = false;
701        for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
702          if (I->getOperand(i) == V) {
703            PassedAsArg = true;
704            I->setOperand(i, NewV);
705          }
706
707        if (PassedAsArg) {
708          // Being passed as an argument also.  Be careful to not invalidate UI!
709          UI = V->use_begin();
710        }
711      }
712    } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
713      Changed |= OptimizeAwayTrappingUsesOfValue(CI,
714                                ConstantExpr::getCast(CI->getOpcode(),
715                                                NewV, CI->getType()), Context);
716      if (CI->use_empty()) {
717        Changed = true;
718        CI->eraseFromParent();
719      }
720    } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
721      // Should handle GEP here.
722      SmallVector<Constant*, 8> Idxs;
723      Idxs.reserve(GEPI->getNumOperands()-1);
724      for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
725           i != e; ++i)
726        if (Constant *C = dyn_cast<Constant>(*i))
727          Idxs.push_back(C);
728        else
729          break;
730      if (Idxs.size() == GEPI->getNumOperands()-1)
731        Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
732                          ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
733                                                        Idxs.size()), Context);
734      if (GEPI->use_empty()) {
735        Changed = true;
736        GEPI->eraseFromParent();
737      }
738    }
739  }
740
741  return Changed;
742}
743
744
745/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
746/// value stored into it.  If there are uses of the loaded value that would trap
747/// if the loaded value is dynamically null, then we know that they cannot be
748/// reachable with a null optimize away the load.
749static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
750                                            LLVMContext &Context) {
751  bool Changed = false;
752
753  // Keep track of whether we are able to remove all the uses of the global
754  // other than the store that defines it.
755  bool AllNonStoreUsesGone = true;
756
757  // Replace all uses of loads with uses of uses of the stored value.
758  for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
759    User *GlobalUser = *GUI++;
760    if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
761      Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV, Context);
762      // If we were able to delete all uses of the loads
763      if (LI->use_empty()) {
764        LI->eraseFromParent();
765        Changed = true;
766      } else {
767        AllNonStoreUsesGone = false;
768      }
769    } else if (isa<StoreInst>(GlobalUser)) {
770      // Ignore the store that stores "LV" to the global.
771      assert(GlobalUser->getOperand(1) == GV &&
772             "Must be storing *to* the global");
773    } else {
774      AllNonStoreUsesGone = false;
775
776      // If we get here we could have other crazy uses that are transitively
777      // loaded.
778      assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
779              isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
780    }
781  }
782
783  if (Changed) {
784    DEBUG(errs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
785    ++NumGlobUses;
786  }
787
788  // If we nuked all of the loads, then none of the stores are needed either,
789  // nor is the global.
790  if (AllNonStoreUsesGone) {
791    DEBUG(errs() << "  *** GLOBAL NOW DEAD!\n");
792    CleanupConstantGlobalUsers(GV, 0, Context);
793    if (GV->use_empty()) {
794      GV->eraseFromParent();
795      ++NumDeleted;
796    }
797    Changed = true;
798  }
799  return Changed;
800}
801
802/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
803/// instructions that are foldable.
804static void ConstantPropUsersOf(Value *V, LLVMContext &Context) {
805  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
806    if (Instruction *I = dyn_cast<Instruction>(*UI++))
807      if (Constant *NewC = ConstantFoldInstruction(I, Context)) {
808        I->replaceAllUsesWith(NewC);
809
810        // Advance UI to the next non-I use to avoid invalidating it!
811        // Instructions could multiply use V.
812        while (UI != E && *UI == I)
813          ++UI;
814        I->eraseFromParent();
815      }
816}
817
818/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
819/// variable, and transforms the program as if it always contained the result of
820/// the specified malloc.  Because it is always the result of the specified
821/// malloc, there is no reason to actually DO the malloc.  Instead, turn the
822/// malloc into a global, and any loads of GV as uses of the new global.
823static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
824                                                     CallInst *CI,
825                                                     BitCastInst *BCI,
826                                                     Value* NElems,
827                                                     LLVMContext &Context,
828                                                     TargetData* TD) {
829  DEBUG(errs() << "PROMOTING MALLOC GLOBAL: " << *GV
830               << "  CALL = " << *CI << "  BCI = " << *BCI << '\n');
831
832  const Type *IntPtrTy = TD->getIntPtrType(Context);
833
834  ConstantInt *NElements = cast<ConstantInt>(NElems);
835  if (NElements->getZExtValue() != 1) {
836    // If we have an array allocation, transform it to a single element
837    // allocation to make the code below simpler.
838    Type *NewTy = ArrayType::get(getMallocAllocatedType(CI),
839                                 NElements->getZExtValue());
840    Value* NewM = CallInst::CreateMalloc(CI, IntPtrTy, NewTy);
841    Instruction* NewMI = cast<Instruction>(NewM);
842    Value* Indices[2];
843    Indices[0] = Indices[1] = Constant::getNullValue(IntPtrTy);
844    Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
845                                              NewMI->getName()+".el0", CI);
846    BCI->replaceAllUsesWith(NewGEP);
847    BCI->eraseFromParent();
848    CI->eraseFromParent();
849    BCI = cast<BitCastInst>(NewMI);
850    CI = extractMallocCallFromBitCast(NewMI);
851  }
852
853  // Create the new global variable.  The contents of the malloc'd memory is
854  // undefined, so initialize with an undef value.
855  const Type *MAT = getMallocAllocatedType(CI);
856  Constant *Init = UndefValue::get(MAT);
857  GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
858                                             MAT, false,
859                                             GlobalValue::InternalLinkage, Init,
860                                             GV->getName()+".body",
861                                             GV,
862                                             GV->isThreadLocal());
863
864  // Anything that used the malloc now uses the global directly.
865  BCI->replaceAllUsesWith(NewGV);
866
867  Constant *RepValue = NewGV;
868  if (NewGV->getType() != GV->getType()->getElementType())
869    RepValue = ConstantExpr::getBitCast(RepValue,
870                                        GV->getType()->getElementType());
871
872  // If there is a comparison against null, we will insert a global bool to
873  // keep track of whether the global was initialized yet or not.
874  GlobalVariable *InitBool =
875    new GlobalVariable(Context, Type::getInt1Ty(Context), false,
876                       GlobalValue::InternalLinkage,
877                       ConstantInt::getFalse(Context), GV->getName()+".init",
878                       GV->isThreadLocal());
879  bool InitBoolUsed = false;
880
881  // Loop over all uses of GV, processing them in turn.
882  std::vector<StoreInst*> Stores;
883  while (!GV->use_empty())
884    if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
885      while (!LI->use_empty()) {
886        Use &LoadUse = LI->use_begin().getUse();
887        if (!isa<ICmpInst>(LoadUse.getUser()))
888          LoadUse = RepValue;
889        else {
890          ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
891          // Replace the cmp X, 0 with a use of the bool value.
892          Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI);
893          InitBoolUsed = true;
894          switch (ICI->getPredicate()) {
895          default: llvm_unreachable("Unknown ICmp Predicate!");
896          case ICmpInst::ICMP_ULT:
897          case ICmpInst::ICMP_SLT:
898            LV = ConstantInt::getFalse(Context);   // X < null -> always false
899            break;
900          case ICmpInst::ICMP_ULE:
901          case ICmpInst::ICMP_SLE:
902          case ICmpInst::ICMP_EQ:
903            LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
904            break;
905          case ICmpInst::ICMP_NE:
906          case ICmpInst::ICMP_UGE:
907          case ICmpInst::ICMP_SGE:
908          case ICmpInst::ICMP_UGT:
909          case ICmpInst::ICMP_SGT:
910            break;  // no change.
911          }
912          ICI->replaceAllUsesWith(LV);
913          ICI->eraseFromParent();
914        }
915      }
916      LI->eraseFromParent();
917    } else {
918      StoreInst *SI = cast<StoreInst>(GV->use_back());
919      // The global is initialized when the store to it occurs.
920      new StoreInst(ConstantInt::getTrue(Context), InitBool, SI);
921      SI->eraseFromParent();
922    }
923
924  // If the initialization boolean was used, insert it, otherwise delete it.
925  if (!InitBoolUsed) {
926    while (!InitBool->use_empty())  // Delete initializations
927      cast<Instruction>(InitBool->use_back())->eraseFromParent();
928    delete InitBool;
929  } else
930    GV->getParent()->getGlobalList().insert(GV, InitBool);
931
932
933  // Now the GV is dead, nuke it and the malloc.
934  GV->eraseFromParent();
935  BCI->eraseFromParent();
936  CI->eraseFromParent();
937
938  // To further other optimizations, loop over all users of NewGV and try to
939  // constant prop them.  This will promote GEP instructions with constant
940  // indices into GEP constant-exprs, which will allow global-opt to hack on it.
941  ConstantPropUsersOf(NewGV, Context);
942  if (RepValue != NewGV)
943    ConstantPropUsersOf(RepValue, Context);
944
945  return NewGV;
946}
947
948/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
949/// to make sure that there are no complex uses of V.  We permit simple things
950/// like dereferencing the pointer, but not storing through the address, unless
951/// it is to the specified global.
952static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
953                                                      GlobalVariable *GV,
954                                              SmallPtrSet<PHINode*, 8> &PHIs) {
955  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
956    Instruction *Inst = cast<Instruction>(*UI);
957
958    if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
959      continue; // Fine, ignore.
960    }
961
962    if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
963      if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
964        return false;  // Storing the pointer itself... bad.
965      continue; // Otherwise, storing through it, or storing into GV... fine.
966    }
967
968    if (isa<GetElementPtrInst>(Inst)) {
969      if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
970        return false;
971      continue;
972    }
973
974    if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
975      // PHIs are ok if all uses are ok.  Don't infinitely recurse through PHI
976      // cycles.
977      if (PHIs.insert(PN))
978        if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
979          return false;
980      continue;
981    }
982
983    if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
984      if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
985        return false;
986      continue;
987    }
988
989    return false;
990  }
991  return true;
992}
993
994/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
995/// somewhere.  Transform all uses of the allocation into loads from the
996/// global and uses of the resultant pointer.  Further, delete the store into
997/// GV.  This assumes that these value pass the
998/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
999static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
1000                                          GlobalVariable *GV) {
1001  while (!Alloc->use_empty()) {
1002    Instruction *U = cast<Instruction>(*Alloc->use_begin());
1003    Instruction *InsertPt = U;
1004    if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1005      // If this is the store of the allocation into the global, remove it.
1006      if (SI->getOperand(1) == GV) {
1007        SI->eraseFromParent();
1008        continue;
1009      }
1010    } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1011      // Insert the load in the corresponding predecessor, not right before the
1012      // PHI.
1013      InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
1014    } else if (isa<BitCastInst>(U)) {
1015      // Must be bitcast between the malloc and store to initialize the global.
1016      ReplaceUsesOfMallocWithGlobal(U, GV);
1017      U->eraseFromParent();
1018      continue;
1019    } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1020      // If this is a "GEP bitcast" and the user is a store to the global, then
1021      // just process it as a bitcast.
1022      if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1023        if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1024          if (SI->getOperand(1) == GV) {
1025            // Must be bitcast GEP between the malloc and store to initialize
1026            // the global.
1027            ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1028            GEPI->eraseFromParent();
1029            continue;
1030          }
1031    }
1032
1033    // Insert a load from the global, and use it instead of the malloc.
1034    Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
1035    U->replaceUsesOfWith(Alloc, NL);
1036  }
1037}
1038
1039/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1040/// of a load) are simple enough to perform heap SRA on.  This permits GEP's
1041/// that index through the array and struct field, icmps of null, and PHIs.
1042static bool LoadUsesSimpleEnoughForHeapSRA(Value *V,
1043                              SmallPtrSet<PHINode*, 32> &LoadUsingPHIs,
1044                              SmallPtrSet<PHINode*, 32> &LoadUsingPHIsPerLoad) {
1045  // We permit two users of the load: setcc comparing against the null
1046  // pointer, and a getelementptr of a specific form.
1047  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1048    Instruction *User = cast<Instruction>(*UI);
1049
1050    // Comparison against null is ok.
1051    if (ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1052      if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1053        return false;
1054      continue;
1055    }
1056
1057    // getelementptr is also ok, but only a simple form.
1058    if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1059      // Must index into the array and into the struct.
1060      if (GEPI->getNumOperands() < 3)
1061        return false;
1062
1063      // Otherwise the GEP is ok.
1064      continue;
1065    }
1066
1067    if (PHINode *PN = dyn_cast<PHINode>(User)) {
1068      if (!LoadUsingPHIsPerLoad.insert(PN))
1069        // This means some phi nodes are dependent on each other.
1070        // Avoid infinite looping!
1071        return false;
1072      if (!LoadUsingPHIs.insert(PN))
1073        // If we have already analyzed this PHI, then it is safe.
1074        continue;
1075
1076      // Make sure all uses of the PHI are simple enough to transform.
1077      if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1078                                          LoadUsingPHIs, LoadUsingPHIsPerLoad))
1079        return false;
1080
1081      continue;
1082    }
1083
1084    // Otherwise we don't know what this is, not ok.
1085    return false;
1086  }
1087
1088  return true;
1089}
1090
1091
1092/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1093/// GV are simple enough to perform HeapSRA, return true.
1094static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
1095                                                    Instruction *StoredVal) {
1096  SmallPtrSet<PHINode*, 32> LoadUsingPHIs;
1097  SmallPtrSet<PHINode*, 32> LoadUsingPHIsPerLoad;
1098  for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
1099       ++UI)
1100    if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1101      if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1102                                          LoadUsingPHIsPerLoad))
1103        return false;
1104      LoadUsingPHIsPerLoad.clear();
1105    }
1106
1107  // If we reach here, we know that all uses of the loads and transitive uses
1108  // (through PHI nodes) are simple enough to transform.  However, we don't know
1109  // that all inputs the to the PHI nodes are in the same equivalence sets.
1110  // Check to verify that all operands of the PHIs are either PHIS that can be
1111  // transformed, loads from GV, or MI itself.
1112  for (SmallPtrSet<PHINode*, 32>::iterator I = LoadUsingPHIs.begin(),
1113       E = LoadUsingPHIs.end(); I != E; ++I) {
1114    PHINode *PN = *I;
1115    for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1116      Value *InVal = PN->getIncomingValue(op);
1117
1118      // PHI of the stored value itself is ok.
1119      if (InVal == StoredVal) continue;
1120
1121      if (PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1122        // One of the PHIs in our set is (optimistically) ok.
1123        if (LoadUsingPHIs.count(InPN))
1124          continue;
1125        return false;
1126      }
1127
1128      // Load from GV is ok.
1129      if (LoadInst *LI = dyn_cast<LoadInst>(InVal))
1130        if (LI->getOperand(0) == GV)
1131          continue;
1132
1133      // UNDEF? NULL?
1134
1135      // Anything else is rejected.
1136      return false;
1137    }
1138  }
1139
1140  return true;
1141}
1142
1143static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1144               DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1145                   std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
1146                   LLVMContext &Context) {
1147  std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1148
1149  if (FieldNo >= FieldVals.size())
1150    FieldVals.resize(FieldNo+1);
1151
1152  // If we already have this value, just reuse the previously scalarized
1153  // version.
1154  if (Value *FieldVal = FieldVals[FieldNo])
1155    return FieldVal;
1156
1157  // Depending on what instruction this is, we have several cases.
1158  Value *Result;
1159  if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1160    // This is a scalarized version of the load from the global.  Just create
1161    // a new Load of the scalarized global.
1162    Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1163                                           InsertedScalarizedValues,
1164                                           PHIsToRewrite, Context),
1165                          LI->getName()+".f"+Twine(FieldNo), LI);
1166  } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1167    // PN's type is pointer to struct.  Make a new PHI of pointer to struct
1168    // field.
1169    const StructType *ST =
1170      cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1171
1172    Result =
1173     PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
1174                     PN->getName()+".f"+Twine(FieldNo), PN);
1175    PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1176  } else {
1177    llvm_unreachable("Unknown usable value");
1178    Result = 0;
1179  }
1180
1181  return FieldVals[FieldNo] = Result;
1182}
1183
1184/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1185/// the load, rewrite the derived value to use the HeapSRoA'd load.
1186static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1187             DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1188                   std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
1189                   LLVMContext &Context) {
1190  // If this is a comparison against null, handle it.
1191  if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1192    assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1193    // If we have a setcc of the loaded pointer, we can use a setcc of any
1194    // field.
1195    Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
1196                                   InsertedScalarizedValues, PHIsToRewrite,
1197                                   Context);
1198
1199    Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
1200                              Constant::getNullValue(NPtr->getType()),
1201                              SCI->getName());
1202    SCI->replaceAllUsesWith(New);
1203    SCI->eraseFromParent();
1204    return;
1205  }
1206
1207  // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
1208  if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1209    assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1210           && "Unexpected GEPI!");
1211
1212    // Load the pointer for this field.
1213    unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1214    Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
1215                                     InsertedScalarizedValues, PHIsToRewrite,
1216                                     Context);
1217
1218    // Create the new GEP idx vector.
1219    SmallVector<Value*, 8> GEPIdx;
1220    GEPIdx.push_back(GEPI->getOperand(1));
1221    GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1222
1223    Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1224                                             GEPIdx.begin(), GEPIdx.end(),
1225                                             GEPI->getName(), GEPI);
1226    GEPI->replaceAllUsesWith(NGEPI);
1227    GEPI->eraseFromParent();
1228    return;
1229  }
1230
1231  // Recursively transform the users of PHI nodes.  This will lazily create the
1232  // PHIs that are needed for individual elements.  Keep track of what PHIs we
1233  // see in InsertedScalarizedValues so that we don't get infinite loops (very
1234  // antisocial).  If the PHI is already in InsertedScalarizedValues, it has
1235  // already been seen first by another load, so its uses have already been
1236  // processed.
1237  PHINode *PN = cast<PHINode>(LoadUser);
1238  bool Inserted;
1239  DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1240  tie(InsertPos, Inserted) =
1241    InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1242  if (!Inserted) return;
1243
1244  // If this is the first time we've seen this PHI, recursively process all
1245  // users.
1246  for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1247    Instruction *User = cast<Instruction>(*UI++);
1248    RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1249                            Context);
1250  }
1251}
1252
1253/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global.  Ptr
1254/// is a value loaded from the global.  Eliminate all uses of Ptr, making them
1255/// use FieldGlobals instead.  All uses of loaded values satisfy
1256/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
1257static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
1258               DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1259                   std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
1260                   LLVMContext &Context) {
1261  for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
1262       UI != E; ) {
1263    Instruction *User = cast<Instruction>(*UI++);
1264    RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1265                            Context);
1266  }
1267
1268  if (Load->use_empty()) {
1269    Load->eraseFromParent();
1270    InsertedScalarizedValues.erase(Load);
1271  }
1272}
1273
1274/// PerformHeapAllocSRoA - CI is an allocation of an array of structures.  Break
1275/// it up into multiple allocations of arrays of the fields.
1276static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV,
1277                                            CallInst *CI, BitCastInst* BCI,
1278                                            Value* NElems,
1279                                            LLVMContext &Context,
1280                                            TargetData *TD) {
1281  DEBUG(errs() << "SROA HEAP ALLOC: " << *GV << "  MALLOC CALL = " << *CI
1282               << " BITCAST = " << *BCI << '\n');
1283  const Type* MAT = getMallocAllocatedType(CI);
1284  const StructType *STy = cast<StructType>(MAT);
1285
1286  // There is guaranteed to be at least one use of the malloc (storing
1287  // it into GV).  If there are other uses, change them to be uses of
1288  // the global to simplify later code.  This also deletes the store
1289  // into GV.
1290  ReplaceUsesOfMallocWithGlobal(BCI, GV);
1291
1292  // Okay, at this point, there are no users of the malloc.  Insert N
1293  // new mallocs at the same place as CI, and N globals.
1294  std::vector<Value*> FieldGlobals;
1295  std::vector<Value*> FieldMallocs;
1296
1297  for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1298    const Type *FieldTy = STy->getElementType(FieldNo);
1299    const PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
1300
1301    GlobalVariable *NGV =
1302      new GlobalVariable(*GV->getParent(),
1303                         PFieldTy, false, GlobalValue::InternalLinkage,
1304                         Constant::getNullValue(PFieldTy),
1305                         GV->getName() + ".f" + Twine(FieldNo), GV,
1306                         GV->isThreadLocal());
1307    FieldGlobals.push_back(NGV);
1308
1309    Value *NMI = CallInst::CreateMalloc(CI, TD->getIntPtrType(Context),
1310                                        FieldTy, NElems,
1311                                        BCI->getName() + ".f" + Twine(FieldNo));
1312    FieldMallocs.push_back(NMI);
1313    new StoreInst(NMI, NGV, BCI);
1314  }
1315
1316  // The tricky aspect of this transformation is handling the case when malloc
1317  // fails.  In the original code, malloc failing would set the result pointer
1318  // of malloc to null.  In this case, some mallocs could succeed and others
1319  // could fail.  As such, we emit code that looks like this:
1320  //    F0 = malloc(field0)
1321  //    F1 = malloc(field1)
1322  //    F2 = malloc(field2)
1323  //    if (F0 == 0 || F1 == 0 || F2 == 0) {
1324  //      if (F0) { free(F0); F0 = 0; }
1325  //      if (F1) { free(F1); F1 = 0; }
1326  //      if (F2) { free(F2); F2 = 0; }
1327  //    }
1328  Value *RunningOr = 0;
1329  for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1330    Value *Cond = new ICmpInst(BCI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1331                              Constant::getNullValue(FieldMallocs[i]->getType()),
1332                                  "isnull");
1333    if (!RunningOr)
1334      RunningOr = Cond;   // First seteq
1335    else
1336      RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", BCI);
1337  }
1338
1339  // Split the basic block at the old malloc.
1340  BasicBlock *OrigBB = BCI->getParent();
1341  BasicBlock *ContBB = OrigBB->splitBasicBlock(BCI, "malloc_cont");
1342
1343  // Create the block to check the first condition.  Put all these blocks at the
1344  // end of the function as they are unlikely to be executed.
1345  BasicBlock *NullPtrBlock = BasicBlock::Create(Context, "malloc_ret_null",
1346                                                OrigBB->getParent());
1347
1348  // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1349  // branch on RunningOr.
1350  OrigBB->getTerminator()->eraseFromParent();
1351  BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
1352
1353  // Within the NullPtrBlock, we need to emit a comparison and branch for each
1354  // pointer, because some may be null while others are not.
1355  for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1356    Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1357    Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
1358                              Constant::getNullValue(GVVal->getType()),
1359                              "tmp");
1360    BasicBlock *FreeBlock = BasicBlock::Create(Context, "free_it",
1361                                               OrigBB->getParent());
1362    BasicBlock *NextBlock = BasicBlock::Create(Context, "next",
1363                                               OrigBB->getParent());
1364    Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1365                                         Cmp, NullPtrBlock);
1366
1367    // Fill in FreeBlock.
1368    CallInst::CreateFree(GVVal, BI);
1369    new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1370                  FreeBlock);
1371    BranchInst::Create(NextBlock, FreeBlock);
1372
1373    NullPtrBlock = NextBlock;
1374  }
1375
1376  BranchInst::Create(ContBB, NullPtrBlock);
1377
1378  // CI and BCI are no longer needed, remove them.
1379  BCI->eraseFromParent();
1380  CI->eraseFromParent();
1381
1382  /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1383  /// update all uses of the load, keep track of what scalarized loads are
1384  /// inserted for a given load.
1385  DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1386  InsertedScalarizedValues[GV] = FieldGlobals;
1387
1388  std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1389
1390  // Okay, the malloc site is completely handled.  All of the uses of GV are now
1391  // loads, and all uses of those loads are simple.  Rewrite them to use loads
1392  // of the per-field globals instead.
1393  for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1394    Instruction *User = cast<Instruction>(*UI++);
1395
1396    if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1397      RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite,
1398                                   Context);
1399      continue;
1400    }
1401
1402    // Must be a store of null.
1403    StoreInst *SI = cast<StoreInst>(User);
1404    assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1405           "Unexpected heap-sra user!");
1406
1407    // Insert a store of null into each global.
1408    for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1409      const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1410      Constant *Null = Constant::getNullValue(PT->getElementType());
1411      new StoreInst(Null, FieldGlobals[i], SI);
1412    }
1413    // Erase the original store.
1414    SI->eraseFromParent();
1415  }
1416
1417  // While we have PHIs that are interesting to rewrite, do it.
1418  while (!PHIsToRewrite.empty()) {
1419    PHINode *PN = PHIsToRewrite.back().first;
1420    unsigned FieldNo = PHIsToRewrite.back().second;
1421    PHIsToRewrite.pop_back();
1422    PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1423    assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1424
1425    // Add all the incoming values.  This can materialize more phis.
1426    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1427      Value *InVal = PN->getIncomingValue(i);
1428      InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
1429                               PHIsToRewrite, Context);
1430      FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1431    }
1432  }
1433
1434  // Drop all inter-phi links and any loads that made it this far.
1435  for (DenseMap<Value*, std::vector<Value*> >::iterator
1436       I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1437       I != E; ++I) {
1438    if (PHINode *PN = dyn_cast<PHINode>(I->first))
1439      PN->dropAllReferences();
1440    else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1441      LI->dropAllReferences();
1442  }
1443
1444  // Delete all the phis and loads now that inter-references are dead.
1445  for (DenseMap<Value*, std::vector<Value*> >::iterator
1446       I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1447       I != E; ++I) {
1448    if (PHINode *PN = dyn_cast<PHINode>(I->first))
1449      PN->eraseFromParent();
1450    else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1451      LI->eraseFromParent();
1452  }
1453
1454  // The old global is now dead, remove it.
1455  GV->eraseFromParent();
1456
1457  ++NumHeapSRA;
1458  return cast<GlobalVariable>(FieldGlobals[0]);
1459}
1460
1461/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1462/// pointer global variable with a single value stored it that is a malloc or
1463/// cast of malloc.
1464static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1465                                               CallInst *CI,
1466                                               BitCastInst *BCI,
1467                                               Module::global_iterator &GVI,
1468                                               TargetData *TD,
1469                                               LLVMContext &Context) {
1470  // If we can't figure out the type being malloced, then we can't optimize.
1471  const Type *AllocTy = getMallocAllocatedType(CI);
1472  assert(AllocTy);
1473
1474  // If this is a malloc of an abstract type, don't touch it.
1475  if (!AllocTy->isSized())
1476    return false;
1477
1478  // We can't optimize this global unless all uses of it are *known* to be
1479  // of the malloc value, not of the null initializer value (consider a use
1480  // that compares the global's value against zero to see if the malloc has
1481  // been reached).  To do this, we check to see if all uses of the global
1482  // would trap if the global were null: this proves that they must all
1483  // happen after the malloc.
1484  if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1485    return false;
1486
1487  // We can't optimize this if the malloc itself is used in a complex way,
1488  // for example, being stored into multiple globals.  This allows the
1489  // malloc to be stored into the specified global, loaded setcc'd, and
1490  // GEP'd.  These are all things we could transform to using the global
1491  // for.
1492  {
1493    SmallPtrSet<PHINode*, 8> PHIs;
1494    if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1495      return false;
1496  }
1497
1498  // If we have a global that is only initialized with a fixed size malloc,
1499  // transform the program to use global memory instead of malloc'd memory.
1500  // This eliminates dynamic allocation, avoids an indirection accessing the
1501  // data, and exposes the resultant global to further GlobalOpt.
1502  Value *NElems = getMallocArraySize(CI, Context, TD);
1503  // We cannot optimize the malloc if we cannot determine malloc array size.
1504  if (NElems) {
1505    if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1506      // Restrict this transformation to only working on small allocations
1507      // (2048 bytes currently), as we don't want to introduce a 16M global or
1508      // something.
1509      if (TD &&
1510          NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1511        GVI = OptimizeGlobalAddressOfMalloc(GV, CI, BCI, NElems, Context, TD);
1512        return true;
1513      }
1514
1515    // If the allocation is an array of structures, consider transforming this
1516    // into multiple malloc'd arrays, one for each field.  This is basically
1517    // SRoA for malloc'd memory.
1518
1519    // If this is an allocation of a fixed size array of structs, analyze as a
1520    // variable size array.  malloc [100 x struct],1 -> malloc struct, 100
1521    if (NElems == ConstantInt::get(CI->getOperand(1)->getType(), 1))
1522      if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1523        AllocTy = AT->getElementType();
1524
1525    if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
1526      // This the structure has an unreasonable number of fields, leave it
1527      // alone.
1528      if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1529          AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, BCI)) {
1530
1531        // If this is a fixed size array, transform the Malloc to be an alloc of
1532        // structs.  malloc [100 x struct],1 -> malloc struct, 100
1533        if (const ArrayType *AT =
1534                              dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1535          Value* NumElements = ConstantInt::get(Type::getInt32Ty(Context),
1536                                                AT->getNumElements());
1537          Value* NewMI = CallInst::CreateMalloc(CI, TD->getIntPtrType(Context),
1538                                                AllocSTy, NumElements,
1539                                                BCI->getName());
1540          Value *Cast = new BitCastInst(NewMI, getMallocType(CI), "tmp", CI);
1541          BCI->replaceAllUsesWith(Cast);
1542          BCI->eraseFromParent();
1543          CI->eraseFromParent();
1544          BCI = cast<BitCastInst>(NewMI);
1545          CI = extractMallocCallFromBitCast(NewMI);
1546        }
1547
1548        GVI = PerformHeapAllocSRoA(GV, CI, BCI, NElems, Context, TD);
1549        return true;
1550      }
1551    }
1552  }
1553
1554  return false;
1555}
1556
1557// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1558// that only one value (besides its initializer) is ever stored to the global.
1559static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1560                                     Module::global_iterator &GVI,
1561                                     TargetData *TD, LLVMContext &Context) {
1562  // Ignore no-op GEPs and bitcasts.
1563  StoredOnceVal = StoredOnceVal->stripPointerCasts();
1564
1565  // If we are dealing with a pointer global that is initialized to null and
1566  // only has one (non-null) value stored into it, then we can optimize any
1567  // users of the loaded value (often calls and loads) that would trap if the
1568  // value was null.
1569  if (isa<PointerType>(GV->getInitializer()->getType()) &&
1570      GV->getInitializer()->isNullValue()) {
1571    if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1572      if (GV->getInitializer()->getType() != SOVC->getType())
1573        SOVC =
1574         ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
1575
1576      // Optimize away any trapping uses of the loaded value.
1577      if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, Context))
1578        return true;
1579    } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
1580      if (getMallocAllocatedType(CI)) {
1581        BitCastInst* BCI = NULL;
1582        for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
1583             UI != E; )
1584          BCI = dyn_cast<BitCastInst>(cast<Instruction>(*UI++));
1585        if (BCI &&
1586            TryToOptimizeStoreOfMallocToGlobal(GV, CI, BCI, GVI, TD, Context))
1587          return true;
1588      }
1589    }
1590  }
1591
1592  return false;
1593}
1594
1595/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1596/// two values ever stored into GV are its initializer and OtherVal.  See if we
1597/// can shrink the global into a boolean and select between the two values
1598/// whenever it is used.  This exposes the values to other scalar optimizations.
1599static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal,
1600                                       LLVMContext &Context) {
1601  const Type *GVElType = GV->getType()->getElementType();
1602
1603  // If GVElType is already i1, it is already shrunk.  If the type of the GV is
1604  // an FP value, pointer or vector, don't do this optimization because a select
1605  // between them is very expensive and unlikely to lead to later
1606  // simplification.  In these cases, we typically end up with "cond ? v1 : v2"
1607  // where v1 and v2 both require constant pool loads, a big loss.
1608  if (GVElType == Type::getInt1Ty(Context) || GVElType->isFloatingPoint() ||
1609      isa<PointerType>(GVElType) || isa<VectorType>(GVElType))
1610    return false;
1611
1612  // Walk the use list of the global seeing if all the uses are load or store.
1613  // If there is anything else, bail out.
1614  for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
1615    if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
1616      return false;
1617
1618  DEBUG(errs() << "   *** SHRINKING TO BOOL: " << *GV);
1619
1620  // Create the new global, initializing it to false.
1621  GlobalVariable *NewGV = new GlobalVariable(Context,
1622                                             Type::getInt1Ty(Context), false,
1623         GlobalValue::InternalLinkage, ConstantInt::getFalse(Context),
1624                                             GV->getName()+".b",
1625                                             GV->isThreadLocal());
1626  GV->getParent()->getGlobalList().insert(GV, NewGV);
1627
1628  Constant *InitVal = GV->getInitializer();
1629  assert(InitVal->getType() != Type::getInt1Ty(Context) &&
1630         "No reason to shrink to bool!");
1631
1632  // If initialized to zero and storing one into the global, we can use a cast
1633  // instead of a select to synthesize the desired value.
1634  bool IsOneZero = false;
1635  if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1636    IsOneZero = InitVal->isNullValue() && CI->isOne();
1637
1638  while (!GV->use_empty()) {
1639    Instruction *UI = cast<Instruction>(GV->use_back());
1640    if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1641      // Change the store into a boolean store.
1642      bool StoringOther = SI->getOperand(0) == OtherVal;
1643      // Only do this if we weren't storing a loaded value.
1644      Value *StoreVal;
1645      if (StoringOther || SI->getOperand(0) == InitVal)
1646        StoreVal = ConstantInt::get(Type::getInt1Ty(Context), StoringOther);
1647      else {
1648        // Otherwise, we are storing a previously loaded copy.  To do this,
1649        // change the copy from copying the original value to just copying the
1650        // bool.
1651        Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1652
1653        // If we're already replaced the input, StoredVal will be a cast or
1654        // select instruction.  If not, it will be a load of the original
1655        // global.
1656        if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1657          assert(LI->getOperand(0) == GV && "Not a copy!");
1658          // Insert a new load, to preserve the saved value.
1659          StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1660        } else {
1661          assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1662                 "This is not a form that we understand!");
1663          StoreVal = StoredVal->getOperand(0);
1664          assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1665        }
1666      }
1667      new StoreInst(StoreVal, NewGV, SI);
1668    } else {
1669      // Change the load into a load of bool then a select.
1670      LoadInst *LI = cast<LoadInst>(UI);
1671      LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
1672      Value *NSI;
1673      if (IsOneZero)
1674        NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1675      else
1676        NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
1677      NSI->takeName(LI);
1678      LI->replaceAllUsesWith(NSI);
1679    }
1680    UI->eraseFromParent();
1681  }
1682
1683  GV->eraseFromParent();
1684  return true;
1685}
1686
1687
1688/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1689/// it if possible.  If we make a change, return true.
1690bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1691                                      Module::global_iterator &GVI) {
1692  SmallPtrSet<PHINode*, 16> PHIUsers;
1693  GlobalStatus GS;
1694  GV->removeDeadConstantUsers();
1695
1696  if (GV->use_empty()) {
1697    DEBUG(errs() << "GLOBAL DEAD: " << *GV);
1698    GV->eraseFromParent();
1699    ++NumDeleted;
1700    return true;
1701  }
1702
1703  if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
1704#if 0
1705    cerr << "Global: " << *GV;
1706    cerr << "  isLoaded = " << GS.isLoaded << "\n";
1707    cerr << "  StoredType = ";
1708    switch (GS.StoredType) {
1709    case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1710    case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1711    case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1712    case GlobalStatus::isStored: cerr << "stored\n"; break;
1713    }
1714    if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
1715      cerr << "  StoredOnceValue = " << *GS.StoredOnceValue << "\n";
1716    if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
1717      cerr << "  AccessingFunction = " << GS.AccessingFunction->getName()
1718                << "\n";
1719    cerr << "  HasMultipleAccessingFunctions =  "
1720              << GS.HasMultipleAccessingFunctions << "\n";
1721    cerr << "  HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
1722    cerr << "\n";
1723#endif
1724
1725    // If this is a first class global and has only one accessing function
1726    // and this function is main (which we know is not recursive we can make
1727    // this global a local variable) we replace the global with a local alloca
1728    // in this function.
1729    //
1730    // NOTE: It doesn't make sense to promote non single-value types since we
1731    // are just replacing static memory to stack memory.
1732    //
1733    // If the global is in different address space, don't bring it to stack.
1734    if (!GS.HasMultipleAccessingFunctions &&
1735        GS.AccessingFunction && !GS.HasNonInstructionUser &&
1736        GV->getType()->getElementType()->isSingleValueType() &&
1737        GS.AccessingFunction->getName() == "main" &&
1738        GS.AccessingFunction->hasExternalLinkage() &&
1739        GV->getType()->getAddressSpace() == 0) {
1740      DEBUG(errs() << "LOCALIZING GLOBAL: " << *GV);
1741      Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1742      const Type* ElemTy = GV->getType()->getElementType();
1743      // FIXME: Pass Global's alignment when globals have alignment
1744      AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1745      if (!isa<UndefValue>(GV->getInitializer()))
1746        new StoreInst(GV->getInitializer(), Alloca, FirstI);
1747
1748      GV->replaceAllUsesWith(Alloca);
1749      GV->eraseFromParent();
1750      ++NumLocalized;
1751      return true;
1752    }
1753
1754    // If the global is never loaded (but may be stored to), it is dead.
1755    // Delete it now.
1756    if (!GS.isLoaded) {
1757      DEBUG(errs() << "GLOBAL NEVER LOADED: " << *GV);
1758
1759      // Delete any stores we can find to the global.  We may not be able to
1760      // make it completely dead though.
1761      bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(),
1762                                                GV->getContext());
1763
1764      // If the global is dead now, delete it.
1765      if (GV->use_empty()) {
1766        GV->eraseFromParent();
1767        ++NumDeleted;
1768        Changed = true;
1769      }
1770      return Changed;
1771
1772    } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1773      DEBUG(errs() << "MARKING CONSTANT: " << *GV);
1774      GV->setConstant(true);
1775
1776      // Clean up any obviously simplifiable users now.
1777      CleanupConstantGlobalUsers(GV, GV->getInitializer(), GV->getContext());
1778
1779      // If the global is dead now, just nuke it.
1780      if (GV->use_empty()) {
1781        DEBUG(errs() << "   *** Marking constant allowed us to simplify "
1782                     << "all users and delete global!\n");
1783        GV->eraseFromParent();
1784        ++NumDeleted;
1785      }
1786
1787      ++NumMarked;
1788      return true;
1789    } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1790      if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1791        if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD,
1792                                                   GV->getContext())) {
1793          GVI = FirstNewGV;  // Don't skip the newly produced globals!
1794          return true;
1795        }
1796    } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1797      // If the initial value for the global was an undef value, and if only
1798      // one other value was stored into it, we can just change the
1799      // initializer to be the stored value, then delete all stores to the
1800      // global.  This allows us to mark it constant.
1801      if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1802        if (isa<UndefValue>(GV->getInitializer())) {
1803          // Change the initial value here.
1804          GV->setInitializer(SOVConstant);
1805
1806          // Clean up any obviously simplifiable users now.
1807          CleanupConstantGlobalUsers(GV, GV->getInitializer(),
1808                                     GV->getContext());
1809
1810          if (GV->use_empty()) {
1811            DEBUG(errs() << "   *** Substituting initializer allowed us to "
1812                         << "simplify all users and delete global!\n");
1813            GV->eraseFromParent();
1814            ++NumDeleted;
1815          } else {
1816            GVI = GV;
1817          }
1818          ++NumSubstitute;
1819          return true;
1820        }
1821
1822      // Try to optimize globals based on the knowledge that only one value
1823      // (besides its initializer) is ever stored to the global.
1824      if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1825                                   getAnalysisIfAvailable<TargetData>(),
1826                                   GV->getContext()))
1827        return true;
1828
1829      // Otherwise, if the global was not a boolean, we can shrink it to be a
1830      // boolean.
1831      if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1832        if (TryToShrinkGlobalToBoolean(GV, SOVConstant, GV->getContext())) {
1833          ++NumShrunkToBool;
1834          return true;
1835        }
1836    }
1837  }
1838  return false;
1839}
1840
1841/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1842/// function, changing them to FastCC.
1843static void ChangeCalleesToFastCall(Function *F) {
1844  for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1845    CallSite User(cast<Instruction>(*UI));
1846    User.setCallingConv(CallingConv::Fast);
1847  }
1848}
1849
1850static AttrListPtr StripNest(const AttrListPtr &Attrs) {
1851  for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1852    if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
1853      continue;
1854
1855    // There can be only one.
1856    return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
1857  }
1858
1859  return Attrs;
1860}
1861
1862static void RemoveNestAttribute(Function *F) {
1863  F->setAttributes(StripNest(F->getAttributes()));
1864  for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1865    CallSite User(cast<Instruction>(*UI));
1866    User.setAttributes(StripNest(User.getAttributes()));
1867  }
1868}
1869
1870bool GlobalOpt::OptimizeFunctions(Module &M) {
1871  bool Changed = false;
1872  // Optimize functions.
1873  for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1874    Function *F = FI++;
1875    // Functions without names cannot be referenced outside this module.
1876    if (!F->hasName() && !F->isDeclaration())
1877      F->setLinkage(GlobalValue::InternalLinkage);
1878    F->removeDeadConstantUsers();
1879    if (F->use_empty() && (F->hasLocalLinkage() ||
1880                           F->hasLinkOnceLinkage())) {
1881      M.getFunctionList().erase(F);
1882      Changed = true;
1883      ++NumFnDeleted;
1884    } else if (F->hasLocalLinkage()) {
1885      if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1886          !F->hasAddressTaken()) {
1887        // If this function has C calling conventions, is not a varargs
1888        // function, and is only called directly, promote it to use the Fast
1889        // calling convention.
1890        F->setCallingConv(CallingConv::Fast);
1891        ChangeCalleesToFastCall(F);
1892        ++NumFastCallFns;
1893        Changed = true;
1894      }
1895
1896      if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
1897          !F->hasAddressTaken()) {
1898        // The function is not used by a trampoline intrinsic, so it is safe
1899        // to remove the 'nest' attribute.
1900        RemoveNestAttribute(F);
1901        ++NumNestRemoved;
1902        Changed = true;
1903      }
1904    }
1905  }
1906  return Changed;
1907}
1908
1909bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1910  bool Changed = false;
1911  for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1912       GVI != E; ) {
1913    GlobalVariable *GV = GVI++;
1914    // Global variables without names cannot be referenced outside this module.
1915    if (!GV->hasName() && !GV->isDeclaration())
1916      GV->setLinkage(GlobalValue::InternalLinkage);
1917    if (!GV->isConstant() && GV->hasLocalLinkage() &&
1918        GV->hasInitializer())
1919      Changed |= ProcessInternalGlobal(GV, GVI);
1920  }
1921  return Changed;
1922}
1923
1924/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1925/// initializers have an init priority of 65535.
1926GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1927  for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1928       I != E; ++I)
1929    if (I->getName() == "llvm.global_ctors") {
1930      // Found it, verify it's an array of { int, void()* }.
1931      const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1932      if (!ATy) return 0;
1933      const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1934      if (!STy || STy->getNumElements() != 2 ||
1935          STy->getElementType(0) != Type::getInt32Ty(M.getContext())) return 0;
1936      const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1937      if (!PFTy) return 0;
1938      const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1939      if (!FTy || FTy->getReturnType() != Type::getVoidTy(M.getContext()) ||
1940          FTy->isVarArg() || FTy->getNumParams() != 0)
1941        return 0;
1942
1943      // Verify that the initializer is simple enough for us to handle.
1944      if (!I->hasDefinitiveInitializer()) return 0;
1945      ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1946      if (!CA) return 0;
1947      for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1948        if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
1949          if (isa<ConstantPointerNull>(CS->getOperand(1)))
1950            continue;
1951
1952          // Must have a function or null ptr.
1953          if (!isa<Function>(CS->getOperand(1)))
1954            return 0;
1955
1956          // Init priority must be standard.
1957          ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1958          if (!CI || CI->getZExtValue() != 65535)
1959            return 0;
1960        } else {
1961          return 0;
1962        }
1963
1964      return I;
1965    }
1966  return 0;
1967}
1968
1969/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1970/// return a list of the functions and null terminator as a vector.
1971static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1972  ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1973  std::vector<Function*> Result;
1974  Result.reserve(CA->getNumOperands());
1975  for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1976    ConstantStruct *CS = cast<ConstantStruct>(*i);
1977    Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1978  }
1979  return Result;
1980}
1981
1982/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1983/// specified array, returning the new global to use.
1984static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1985                                          const std::vector<Function*> &Ctors,
1986                                          LLVMContext &Context) {
1987  // If we made a change, reassemble the initializer list.
1988  std::vector<Constant*> CSVals;
1989  CSVals.push_back(ConstantInt::get(Type::getInt32Ty(Context), 65535));
1990  CSVals.push_back(0);
1991
1992  // Create the new init list.
1993  std::vector<Constant*> CAList;
1994  for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
1995    if (Ctors[i]) {
1996      CSVals[1] = Ctors[i];
1997    } else {
1998      const Type *FTy = FunctionType::get(Type::getVoidTy(Context), false);
1999      const PointerType *PFTy = PointerType::getUnqual(FTy);
2000      CSVals[1] = Constant::getNullValue(PFTy);
2001      CSVals[0] = ConstantInt::get(Type::getInt32Ty(Context), 2147483647);
2002    }
2003    CAList.push_back(ConstantStruct::get(Context, CSVals, false));
2004  }
2005
2006  // Create the array initializer.
2007  const Type *StructTy =
2008      cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
2009  Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
2010                                                   CAList.size()), CAList);
2011
2012  // If we didn't change the number of elements, don't create a new GV.
2013  if (CA->getType() == GCL->getInitializer()->getType()) {
2014    GCL->setInitializer(CA);
2015    return GCL;
2016  }
2017
2018  // Create the new global and insert it next to the existing list.
2019  GlobalVariable *NGV = new GlobalVariable(Context, CA->getType(),
2020                                           GCL->isConstant(),
2021                                           GCL->getLinkage(), CA, "",
2022                                           GCL->isThreadLocal());
2023  GCL->getParent()->getGlobalList().insert(GCL, NGV);
2024  NGV->takeName(GCL);
2025
2026  // Nuke the old list, replacing any uses with the new one.
2027  if (!GCL->use_empty()) {
2028    Constant *V = NGV;
2029    if (V->getType() != GCL->getType())
2030      V = ConstantExpr::getBitCast(V, GCL->getType());
2031    GCL->replaceAllUsesWith(V);
2032  }
2033  GCL->eraseFromParent();
2034
2035  if (Ctors.size())
2036    return NGV;
2037  else
2038    return 0;
2039}
2040
2041
2042static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
2043                        Value *V) {
2044  if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2045  Constant *R = ComputedValues[V];
2046  assert(R && "Reference to an uncomputed value!");
2047  return R;
2048}
2049
2050/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2051/// enough for us to understand.  In particular, if it is a cast of something,
2052/// we punt.  We basically just support direct accesses to globals and GEP's of
2053/// globals.  This should be kept up to date with CommitValueTo.
2054static bool isSimpleEnoughPointerToCommit(Constant *C, LLVMContext &Context) {
2055  // Conservatively, avoid aggregate types. This is because we don't
2056  // want to worry about them partially overlapping other stores.
2057  if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2058    return false;
2059
2060  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2061    // Do not allow weak/linkonce/dllimport/dllexport linkage or
2062    // external globals.
2063    return GV->hasDefinitiveInitializer();
2064
2065  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2066    // Handle a constantexpr gep.
2067    if (CE->getOpcode() == Instruction::GetElementPtr &&
2068        isa<GlobalVariable>(CE->getOperand(0)) &&
2069        cast<GEPOperator>(CE)->isInBounds()) {
2070      GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2071      // Do not allow weak/linkonce/dllimport/dllexport linkage or
2072      // external globals.
2073      if (!GV->hasDefinitiveInitializer())
2074        return false;
2075
2076      // The first index must be zero.
2077      ConstantInt *CI = dyn_cast<ConstantInt>(*next(CE->op_begin()));
2078      if (!CI || !CI->isZero()) return false;
2079
2080      // The remaining indices must be compile-time known integers within the
2081      // notional bounds of the corresponding static array types.
2082      if (!CE->isGEPWithNoNotionalOverIndexing())
2083        return false;
2084
2085      return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2086    }
2087  return false;
2088}
2089
2090/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2091/// initializer.  This returns 'Init' modified to reflect 'Val' stored into it.
2092/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2093static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
2094                                   ConstantExpr *Addr, unsigned OpNo,
2095                                   LLVMContext &Context) {
2096  // Base case of the recursion.
2097  if (OpNo == Addr->getNumOperands()) {
2098    assert(Val->getType() == Init->getType() && "Type mismatch!");
2099    return Val;
2100  }
2101
2102  if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2103    std::vector<Constant*> Elts;
2104
2105    // Break up the constant into its elements.
2106    if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2107      for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2108        Elts.push_back(cast<Constant>(*i));
2109    } else if (isa<ConstantAggregateZero>(Init)) {
2110      for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2111        Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
2112    } else if (isa<UndefValue>(Init)) {
2113      for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2114        Elts.push_back(UndefValue::get(STy->getElementType(i)));
2115    } else {
2116      llvm_unreachable("This code is out of sync with "
2117             " ConstantFoldLoadThroughGEPConstantExpr");
2118    }
2119
2120    // Replace the element that we are supposed to.
2121    ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2122    unsigned Idx = CU->getZExtValue();
2123    assert(Idx < STy->getNumElements() && "Struct index out of range!");
2124    Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1, Context);
2125
2126    // Return the modified struct.
2127    return ConstantStruct::get(Context, &Elts[0], Elts.size(), STy->isPacked());
2128  } else {
2129    ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2130    const ArrayType *ATy = cast<ArrayType>(Init->getType());
2131
2132    // Break up the array into elements.
2133    std::vector<Constant*> Elts;
2134    if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2135      for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2136        Elts.push_back(cast<Constant>(*i));
2137    } else if (isa<ConstantAggregateZero>(Init)) {
2138      Constant *Elt = Constant::getNullValue(ATy->getElementType());
2139      Elts.assign(ATy->getNumElements(), Elt);
2140    } else if (isa<UndefValue>(Init)) {
2141      Constant *Elt = UndefValue::get(ATy->getElementType());
2142      Elts.assign(ATy->getNumElements(), Elt);
2143    } else {
2144      llvm_unreachable("This code is out of sync with "
2145             " ConstantFoldLoadThroughGEPConstantExpr");
2146    }
2147
2148    assert(CI->getZExtValue() < ATy->getNumElements());
2149    Elts[CI->getZExtValue()] =
2150      EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1, Context);
2151    return ConstantArray::get(ATy, Elts);
2152  }
2153}
2154
2155/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2156/// isSimpleEnoughPointerToCommit) should get Val as its value.  Make it happen.
2157static void CommitValueTo(Constant *Val, Constant *Addr,
2158                          LLVMContext &Context) {
2159  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2160    assert(GV->hasInitializer());
2161    GV->setInitializer(Val);
2162    return;
2163  }
2164
2165  ConstantExpr *CE = cast<ConstantExpr>(Addr);
2166  GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2167
2168  Constant *Init = GV->getInitializer();
2169  Init = EvaluateStoreInto(Init, Val, CE, 2, Context);
2170  GV->setInitializer(Init);
2171}
2172
2173/// ComputeLoadResult - Return the value that would be computed by a load from
2174/// P after the stores reflected by 'memory' have been performed.  If we can't
2175/// decide, return null.
2176static Constant *ComputeLoadResult(Constant *P,
2177                                const DenseMap<Constant*, Constant*> &Memory,
2178                                LLVMContext &Context) {
2179  // If this memory location has been recently stored, use the stored value: it
2180  // is the most up-to-date.
2181  DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
2182  if (I != Memory.end()) return I->second;
2183
2184  // Access it.
2185  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2186    if (GV->hasDefinitiveInitializer())
2187      return GV->getInitializer();
2188    return 0;
2189  }
2190
2191  // Handle a constantexpr getelementptr.
2192  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2193    if (CE->getOpcode() == Instruction::GetElementPtr &&
2194        isa<GlobalVariable>(CE->getOperand(0))) {
2195      GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2196      if (GV->hasDefinitiveInitializer())
2197        return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2198    }
2199
2200  return 0;  // don't know how to evaluate.
2201}
2202
2203/// EvaluateFunction - Evaluate a call to function F, returning true if
2204/// successful, false if we can't evaluate it.  ActualArgs contains the formal
2205/// arguments for the function.
2206static bool EvaluateFunction(Function *F, Constant *&RetVal,
2207                             const SmallVectorImpl<Constant*> &ActualArgs,
2208                             std::vector<Function*> &CallStack,
2209                             DenseMap<Constant*, Constant*> &MutatedMemory,
2210                             std::vector<GlobalVariable*> &AllocaTmps) {
2211  // Check to see if this function is already executing (recursion).  If so,
2212  // bail out.  TODO: we might want to accept limited recursion.
2213  if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2214    return false;
2215
2216  LLVMContext &Context = F->getContext();
2217
2218  CallStack.push_back(F);
2219
2220  /// Values - As we compute SSA register values, we store their contents here.
2221  DenseMap<Value*, Constant*> Values;
2222
2223  // Initialize arguments to the incoming values specified.
2224  unsigned ArgNo = 0;
2225  for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2226       ++AI, ++ArgNo)
2227    Values[AI] = ActualArgs[ArgNo];
2228
2229  /// ExecutedBlocks - We only handle non-looping, non-recursive code.  As such,
2230  /// we can only evaluate any one basic block at most once.  This set keeps
2231  /// track of what we have executed so we can detect recursive cases etc.
2232  SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2233
2234  // CurInst - The current instruction we're evaluating.
2235  BasicBlock::iterator CurInst = F->begin()->begin();
2236
2237  // This is the main evaluation loop.
2238  while (1) {
2239    Constant *InstResult = 0;
2240
2241    if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
2242      if (SI->isVolatile()) return false;  // no volatile accesses.
2243      Constant *Ptr = getVal(Values, SI->getOperand(1));
2244      if (!isSimpleEnoughPointerToCommit(Ptr, Context))
2245        // If this is too complex for us to commit, reject it.
2246        return false;
2247      Constant *Val = getVal(Values, SI->getOperand(0));
2248      MutatedMemory[Ptr] = Val;
2249    } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
2250      InstResult = ConstantExpr::get(BO->getOpcode(),
2251                                     getVal(Values, BO->getOperand(0)),
2252                                     getVal(Values, BO->getOperand(1)));
2253    } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
2254      InstResult = ConstantExpr::getCompare(CI->getPredicate(),
2255                                            getVal(Values, CI->getOperand(0)),
2256                                            getVal(Values, CI->getOperand(1)));
2257    } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
2258      InstResult = ConstantExpr::getCast(CI->getOpcode(),
2259                                         getVal(Values, CI->getOperand(0)),
2260                                         CI->getType());
2261    } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
2262      InstResult =
2263            ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
2264                                           getVal(Values, SI->getOperand(1)),
2265                                           getVal(Values, SI->getOperand(2)));
2266    } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2267      Constant *P = getVal(Values, GEP->getOperand(0));
2268      SmallVector<Constant*, 8> GEPOps;
2269      for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2270           i != e; ++i)
2271        GEPOps.push_back(getVal(Values, *i));
2272      InstResult = cast<GEPOperator>(GEP)->isInBounds() ?
2273          ConstantExpr::getInBoundsGetElementPtr(P, &GEPOps[0], GEPOps.size()) :
2274          ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
2275    } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
2276      if (LI->isVolatile()) return false;  // no volatile accesses.
2277      InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
2278                                     MutatedMemory, Context);
2279      if (InstResult == 0) return false; // Could not evaluate load.
2280    } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
2281      if (AI->isArrayAllocation()) return false;  // Cannot handle array allocs.
2282      const Type *Ty = AI->getType()->getElementType();
2283      AllocaTmps.push_back(new GlobalVariable(Context, Ty, false,
2284                                              GlobalValue::InternalLinkage,
2285                                              UndefValue::get(Ty),
2286                                              AI->getName()));
2287      InstResult = AllocaTmps.back();
2288    } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
2289
2290      // Debug info can safely be ignored here.
2291      if (isa<DbgInfoIntrinsic>(CI)) {
2292        ++CurInst;
2293        continue;
2294      }
2295
2296      // Cannot handle inline asm.
2297      if (isa<InlineAsm>(CI->getOperand(0))) return false;
2298
2299      // Resolve function pointers.
2300      Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2301      if (!Callee) return false;  // Cannot resolve.
2302
2303      SmallVector<Constant*, 8> Formals;
2304      for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2305           i != e; ++i)
2306        Formals.push_back(getVal(Values, *i));
2307
2308      if (Callee->isDeclaration()) {
2309        // If this is a function we can constant fold, do it.
2310        if (Constant *C = ConstantFoldCall(Callee, Formals.data(),
2311                                           Formals.size())) {
2312          InstResult = C;
2313        } else {
2314          return false;
2315        }
2316      } else {
2317        if (Callee->getFunctionType()->isVarArg())
2318          return false;
2319
2320        Constant *RetVal;
2321        // Execute the call, if successful, use the return value.
2322        if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2323                              MutatedMemory, AllocaTmps))
2324          return false;
2325        InstResult = RetVal;
2326      }
2327    } else if (isa<TerminatorInst>(CurInst)) {
2328      BasicBlock *NewBB = 0;
2329      if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2330        if (BI->isUnconditional()) {
2331          NewBB = BI->getSuccessor(0);
2332        } else {
2333          ConstantInt *Cond =
2334            dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
2335          if (!Cond) return false;  // Cannot determine.
2336
2337          NewBB = BI->getSuccessor(!Cond->getZExtValue());
2338        }
2339      } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2340        ConstantInt *Val =
2341          dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
2342        if (!Val) return false;  // Cannot determine.
2343        NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2344      } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2345        Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts();
2346        if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2347          NewBB = BA->getBasicBlock();
2348        if (NewBB == 0) return false;  // Cannot determine.
2349      } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
2350        if (RI->getNumOperands())
2351          RetVal = getVal(Values, RI->getOperand(0));
2352
2353        CallStack.pop_back();  // return from fn.
2354        return true;  // We succeeded at evaluating this ctor!
2355      } else {
2356        // invoke, unwind, unreachable.
2357        return false;  // Cannot handle this terminator.
2358      }
2359
2360      // Okay, we succeeded in evaluating this control flow.  See if we have
2361      // executed the new block before.  If so, we have a looping function,
2362      // which we cannot evaluate in reasonable time.
2363      if (!ExecutedBlocks.insert(NewBB))
2364        return false;  // looped!
2365
2366      // Okay, we have never been in this block before.  Check to see if there
2367      // are any PHI nodes.  If so, evaluate them with information about where
2368      // we came from.
2369      BasicBlock *OldBB = CurInst->getParent();
2370      CurInst = NewBB->begin();
2371      PHINode *PN;
2372      for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2373        Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2374
2375      // Do NOT increment CurInst.  We know that the terminator had no value.
2376      continue;
2377    } else {
2378      // Did not know how to evaluate this!
2379      return false;
2380    }
2381
2382    if (!CurInst->use_empty())
2383      Values[CurInst] = InstResult;
2384
2385    // Advance program counter.
2386    ++CurInst;
2387  }
2388}
2389
2390/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2391/// we can.  Return true if we can, false otherwise.
2392static bool EvaluateStaticConstructor(Function *F) {
2393  /// MutatedMemory - For each store we execute, we update this map.  Loads
2394  /// check this to get the most up-to-date value.  If evaluation is successful,
2395  /// this state is committed to the process.
2396  DenseMap<Constant*, Constant*> MutatedMemory;
2397
2398  /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2399  /// to represent its body.  This vector is needed so we can delete the
2400  /// temporary globals when we are done.
2401  std::vector<GlobalVariable*> AllocaTmps;
2402
2403  /// CallStack - This is used to detect recursion.  In pathological situations
2404  /// we could hit exponential behavior, but at least there is nothing
2405  /// unbounded.
2406  std::vector<Function*> CallStack;
2407
2408  // Call the function.
2409  Constant *RetValDummy;
2410  bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2411                                      SmallVector<Constant*, 0>(), CallStack,
2412                                      MutatedMemory, AllocaTmps);
2413  if (EvalSuccess) {
2414    // We succeeded at evaluation: commit the result.
2415    DEBUG(errs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2416          << F->getName() << "' to " << MutatedMemory.size()
2417          << " stores.\n");
2418    for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
2419         E = MutatedMemory.end(); I != E; ++I)
2420      CommitValueTo(I->second, I->first, F->getContext());
2421  }
2422
2423  // At this point, we are done interpreting.  If we created any 'alloca'
2424  // temporaries, release them now.
2425  while (!AllocaTmps.empty()) {
2426    GlobalVariable *Tmp = AllocaTmps.back();
2427    AllocaTmps.pop_back();
2428
2429    // If there are still users of the alloca, the program is doing something
2430    // silly, e.g. storing the address of the alloca somewhere and using it
2431    // later.  Since this is undefined, we'll just make it be null.
2432    if (!Tmp->use_empty())
2433      Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2434    delete Tmp;
2435  }
2436
2437  return EvalSuccess;
2438}
2439
2440
2441
2442/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2443/// Return true if anything changed.
2444bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2445  std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2446  bool MadeChange = false;
2447  if (Ctors.empty()) return false;
2448
2449  // Loop over global ctors, optimizing them when we can.
2450  for (unsigned i = 0; i != Ctors.size(); ++i) {
2451    Function *F = Ctors[i];
2452    // Found a null terminator in the middle of the list, prune off the rest of
2453    // the list.
2454    if (F == 0) {
2455      if (i != Ctors.size()-1) {
2456        Ctors.resize(i+1);
2457        MadeChange = true;
2458      }
2459      break;
2460    }
2461
2462    // We cannot simplify external ctor functions.
2463    if (F->empty()) continue;
2464
2465    // If we can evaluate the ctor at compile time, do.
2466    if (EvaluateStaticConstructor(F)) {
2467      Ctors.erase(Ctors.begin()+i);
2468      MadeChange = true;
2469      --i;
2470      ++NumCtorsEvaluated;
2471      continue;
2472    }
2473  }
2474
2475  if (!MadeChange) return false;
2476
2477  GCL = InstallGlobalCtors(GCL, Ctors, GCL->getContext());
2478  return true;
2479}
2480
2481bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
2482  bool Changed = false;
2483
2484  for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
2485       I != E;) {
2486    Module::alias_iterator J = I++;
2487    // Aliases without names cannot be referenced outside this module.
2488    if (!J->hasName() && !J->isDeclaration())
2489      J->setLinkage(GlobalValue::InternalLinkage);
2490    // If the aliasee may change at link time, nothing can be done - bail out.
2491    if (J->mayBeOverridden())
2492      continue;
2493
2494    Constant *Aliasee = J->getAliasee();
2495    GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2496    Target->removeDeadConstantUsers();
2497    bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2498
2499    // Make all users of the alias use the aliasee instead.
2500    if (!J->use_empty()) {
2501      J->replaceAllUsesWith(Aliasee);
2502      ++NumAliasesResolved;
2503      Changed = true;
2504    }
2505
2506    // If the aliasee has internal linkage, give it the name and linkage
2507    // of the alias, and delete the alias.  This turns:
2508    //   define internal ... @f(...)
2509    //   @a = alias ... @f
2510    // into:
2511    //   define ... @a(...)
2512    if (!Target->hasLocalLinkage())
2513      continue;
2514
2515    // The transform is only useful if the alias does not have internal linkage.
2516    if (J->hasLocalLinkage())
2517      continue;
2518
2519    // Do not perform the transform if multiple aliases potentially target the
2520    // aliasee.  This check also ensures that it is safe to replace the section
2521    // and other attributes of the aliasee with those of the alias.
2522    if (!hasOneUse)
2523      continue;
2524
2525    // Give the aliasee the name, linkage and other attributes of the alias.
2526    Target->takeName(J);
2527    Target->setLinkage(J->getLinkage());
2528    Target->GlobalValue::copyAttributesFrom(J);
2529
2530    // Delete the alias.
2531    M.getAliasList().erase(J);
2532    ++NumAliasesRemoved;
2533    Changed = true;
2534  }
2535
2536  return Changed;
2537}
2538
2539bool GlobalOpt::runOnModule(Module &M) {
2540  bool Changed = false;
2541
2542  // Try to find the llvm.globalctors list.
2543  GlobalVariable *GlobalCtors = FindGlobalCtors(M);
2544
2545  bool LocalChange = true;
2546  while (LocalChange) {
2547    LocalChange = false;
2548
2549    // Delete functions that are trivially dead, ccc -> fastcc
2550    LocalChange |= OptimizeFunctions(M);
2551
2552    // Optimize global_ctors list.
2553    if (GlobalCtors)
2554      LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2555
2556    // Optimize non-address-taken globals.
2557    LocalChange |= OptimizeGlobalVars(M);
2558
2559    // Resolve aliases, when possible.
2560    LocalChange |= OptimizeGlobalAliases(M);
2561    Changed |= LocalChange;
2562  }
2563
2564  // TODO: Move all global ctors functions to the end of the module for code
2565  // layout.
2566
2567  return Changed;
2568}
2569