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