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