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