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