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