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