simplify name juggling through the use of Value::takeName.
[oota-llvm.git] / lib / Transforms / IPO / GlobalOpt.cpp
1 //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Compiler.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include <algorithm>
33 #include <set>
34 using namespace llvm;
35
36 STATISTIC(NumMarked    , "Number of globals marked constant");
37 STATISTIC(NumSRA       , "Number of aggregate globals broken into scalars");
38 STATISTIC(NumHeapSRA   , "Number of heap objects SRA'd");
39 STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
40 STATISTIC(NumDeleted   , "Number of globals deleted");
41 STATISTIC(NumFnDeleted , "Number of functions deleted");
42 STATISTIC(NumGlobUses  , "Number of global uses devirtualized");
43 STATISTIC(NumLocalized , "Number of globals localized");
44 STATISTIC(NumShrunkToBool  , "Number of global vars shrunk to booleans");
45 STATISTIC(NumFastCallFns   , "Number of functions converted to fastcc");
46 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
47
48 namespace {
49   struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
50     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51       AU.addRequired<TargetData>();
52     }
53
54     bool runOnModule(Module &M);
55
56   private:
57     GlobalVariable *FindGlobalCtors(Module &M);
58     bool OptimizeFunctions(Module &M);
59     bool OptimizeGlobalVars(Module &M);
60     bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
61     bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
62   };
63
64   RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
65 }
66
67 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
68
69 /// GlobalStatus - As we analyze each global, keep track of some information
70 /// about it.  If we find out that the address of the global is taken, none of
71 /// this info will be accurate.
72 struct VISIBILITY_HIDDEN GlobalStatus {
73   /// isLoaded - True if the global is ever loaded.  If the global isn't ever
74   /// loaded it can be deleted.
75   bool isLoaded;
76
77   /// StoredType - Keep track of what stores to the global look like.
78   ///
79   enum StoredType {
80     /// NotStored - There is no store to this global.  It can thus be marked
81     /// constant.
82     NotStored,
83
84     /// isInitializerStored - This global is stored to, but the only thing
85     /// stored is the constant it was initialized with.  This is only tracked
86     /// for scalar globals.
87     isInitializerStored,
88
89     /// isStoredOnce - This global is stored to, but only its initializer and
90     /// one other value is ever stored to it.  If this global isStoredOnce, we
91     /// track the value stored to it in StoredOnceValue below.  This is only
92     /// tracked for scalar globals.
93     isStoredOnce,
94
95     /// isStored - This global is stored to by multiple values or something else
96     /// that we cannot track.
97     isStored
98   } StoredType;
99
100   /// StoredOnceValue - If only one value (besides the initializer constant) is
101   /// ever stored to this global, keep track of what value it is.
102   Value *StoredOnceValue;
103
104   /// AccessingFunction/HasMultipleAccessingFunctions - These start out
105   /// null/false.  When the first accessing function is noticed, it is recorded.
106   /// When a second different accessing function is noticed,
107   /// HasMultipleAccessingFunctions is set to true.
108   Function *AccessingFunction;
109   bool HasMultipleAccessingFunctions;
110
111   /// HasNonInstructionUser - Set to true if this global has a user that is not
112   /// an instruction (e.g. a constant expr or GV initializer).
113   bool HasNonInstructionUser;
114
115   /// HasPHIUser - Set to true if this global has a user that is a PHI node.
116   bool HasPHIUser;
117   
118   /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
119   /// the global exist.  Such users include GEP instruction with variable
120   /// indexes, and non-gep/load/store users like constant expr casts.
121   bool isNotSuitableForSRA;
122
123   GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
124                    AccessingFunction(0), HasMultipleAccessingFunctions(false),
125                    HasNonInstructionUser(false), HasPHIUser(false),
126                    isNotSuitableForSRA(false) {}
127 };
128
129
130
131 /// ConstantIsDead - Return true if the specified constant is (transitively)
132 /// dead.  The constant may be used by other constants (e.g. constant arrays and
133 /// constant exprs) as long as they are dead, but it cannot be used by anything
134 /// else.
135 static bool ConstantIsDead(Constant *C) {
136   if (isa<GlobalValue>(C)) return false;
137
138   for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
139     if (Constant *CU = dyn_cast<Constant>(*UI)) {
140       if (!ConstantIsDead(CU)) return false;
141     } else
142       return false;
143   return true;
144 }
145
146
147 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
148 /// structure.  If the global has its address taken, return true to indicate we
149 /// can't do anything with it.
150 ///
151 static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
152                           std::set<PHINode*> &PHIUsers) {
153   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
154     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
155       GS.HasNonInstructionUser = true;
156
157       if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
158       if (CE->getOpcode() != Instruction::GetElementPtr)
159         GS.isNotSuitableForSRA = true;
160       else if (!GS.isNotSuitableForSRA) {
161         // Check to see if this ConstantExpr GEP is SRA'able.  In particular, we
162         // don't like < 3 operand CE's, and we don't like non-constant integer
163         // indices.
164         if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
165           GS.isNotSuitableForSRA = true;
166         else {
167           for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
168             if (!isa<ConstantInt>(CE->getOperand(i))) {
169               GS.isNotSuitableForSRA = true;
170               break;
171             }
172         }
173       }
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 (isa<LoadInst>(I)) {
184         GS.isLoaded = true;
185       } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
186         // Don't allow a store OF the address, only stores TO the address.
187         if (SI->getOperand(0) == V) return true;
188
189         // If this is a direct store to the global (i.e., the global is a scalar
190         // value, not an aggregate), keep more specific information about
191         // stores.
192         if (GS.StoredType != GlobalStatus::isStored)
193           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
194             Value *StoredVal = SI->getOperand(0);
195             if (StoredVal == GV->getInitializer()) {
196               if (GS.StoredType < GlobalStatus::isInitializerStored)
197                 GS.StoredType = GlobalStatus::isInitializerStored;
198             } else if (isa<LoadInst>(StoredVal) &&
199                        cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
200               // G = G
201               if (GS.StoredType < GlobalStatus::isInitializerStored)
202                 GS.StoredType = GlobalStatus::isInitializerStored;
203             } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
204               GS.StoredType = GlobalStatus::isStoredOnce;
205               GS.StoredOnceValue = StoredVal;
206             } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
207                        GS.StoredOnceValue == StoredVal) {
208               // noop.
209             } else {
210               GS.StoredType = GlobalStatus::isStored;
211             }
212           } else {
213             GS.StoredType = GlobalStatus::isStored;
214           }
215       } else if (isa<GetElementPtrInst>(I)) {
216         if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
217
218         // If the first two indices are constants, this can be SRA'd.
219         if (isa<GlobalVariable>(I->getOperand(0))) {
220           if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
221               !cast<Constant>(I->getOperand(1))->isNullValue() ||
222               !isa<ConstantInt>(I->getOperand(2)))
223             GS.isNotSuitableForSRA = true;
224         } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
225           if (CE->getOpcode() != Instruction::GetElementPtr ||
226               CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
227               !isa<Constant>(I->getOperand(0)) ||
228               !cast<Constant>(I->getOperand(0))->isNullValue())
229             GS.isNotSuitableForSRA = true;
230         } else {
231           GS.isNotSuitableForSRA = true;
232         }
233       } else if (isa<SelectInst>(I)) {
234         if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
235         GS.isNotSuitableForSRA = true;
236       } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
237         // PHI nodes we can check just like select or GEP instructions, but we
238         // have to be careful about infinite recursion.
239         if (PHIUsers.insert(PN).second)  // Not already visited.
240           if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
241         GS.isNotSuitableForSRA = true;
242         GS.HasPHIUser = true;
243       } else if (isa<CmpInst>(I)) {
244         GS.isNotSuitableForSRA = true;
245       } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
246         if (I->getOperand(1) == V)
247           GS.StoredType = GlobalStatus::isStored;
248         if (I->getOperand(2) == V)
249           GS.isLoaded = true;
250         GS.isNotSuitableForSRA = true;
251       } else if (isa<MemSetInst>(I)) {
252         assert(I->getOperand(1) == V && "Memset only takes one pointer!");
253         GS.StoredType = GlobalStatus::isStored;
254         GS.isNotSuitableForSRA = true;
255       } else {
256         return true;  // Any other non-load instruction might take address!
257       }
258     } else if (Constant *C = dyn_cast<Constant>(*UI)) {
259       GS.HasNonInstructionUser = true;
260       // We might have a dead and dangling constant hanging off of here.
261       if (!ConstantIsDead(C))
262         return true;
263     } else {
264       GS.HasNonInstructionUser = true;
265       // Otherwise must be some other user.
266       return true;
267     }
268
269   return false;
270 }
271
272 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
273   ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
274   if (!CI) return 0;
275   unsigned IdxV = CI->getZExtValue();
276
277   if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
278     if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
279   } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
280     if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
281   } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
282     if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
283   } else if (isa<ConstantAggregateZero>(Agg)) {
284     if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
285       if (IdxV < STy->getNumElements())
286         return Constant::getNullValue(STy->getElementType(IdxV));
287     } else if (const SequentialType *STy =
288                dyn_cast<SequentialType>(Agg->getType())) {
289       return Constant::getNullValue(STy->getElementType());
290     }
291   } else if (isa<UndefValue>(Agg)) {
292     if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
293       if (IdxV < STy->getNumElements())
294         return UndefValue::get(STy->getElementType(IdxV));
295     } else if (const SequentialType *STy =
296                dyn_cast<SequentialType>(Agg->getType())) {
297       return UndefValue::get(STy->getElementType());
298     }
299   }
300   return 0;
301 }
302
303
304 /// CleanupConstantGlobalUsers - We just marked GV constant.  Loop over all
305 /// users of the global, cleaning up the obvious ones.  This is largely just a
306 /// quick scan over the use list to clean up the easy and obvious cruft.  This
307 /// returns true if it made a change.
308 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
309   bool Changed = false;
310   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
311     User *U = *UI++;
312
313     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
314       if (Init) {
315         // Replace the load with the initializer.
316         LI->replaceAllUsesWith(Init);
317         LI->eraseFromParent();
318         Changed = true;
319       }
320     } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
321       // Store must be unreachable or storing Init into the global.
322       SI->eraseFromParent();
323       Changed = true;
324     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
325       if (CE->getOpcode() == Instruction::GetElementPtr) {
326         Constant *SubInit = 0;
327         if (Init)
328           SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
329         Changed |= CleanupConstantGlobalUsers(CE, SubInit);
330       } else if (CE->getOpcode() == Instruction::BitCast && 
331                  isa<PointerType>(CE->getType())) {
332         // Pointer cast, delete any stores and memsets to the global.
333         Changed |= CleanupConstantGlobalUsers(CE, 0);
334       }
335
336       if (CE->use_empty()) {
337         CE->destroyConstant();
338         Changed = true;
339       }
340     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
341       Constant *SubInit = 0;
342       ConstantExpr *CE = 
343         dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
344       if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
345         SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
346       Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
347
348       if (GEP->use_empty()) {
349         GEP->eraseFromParent();
350         Changed = true;
351       }
352     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
353       if (MI->getRawDest() == V) {
354         MI->eraseFromParent();
355         Changed = true;
356       }
357
358     } else if (Constant *C = dyn_cast<Constant>(U)) {
359       // If we have a chain of dead constantexprs or other things dangling from
360       // us, and if they are all dead, nuke them without remorse.
361       if (ConstantIsDead(C)) {
362         C->destroyConstant();
363         // This could have invalidated UI, start over from scratch.
364         CleanupConstantGlobalUsers(V, Init);
365         return true;
366       }
367     }
368   }
369   return Changed;
370 }
371
372 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
373 /// variable.  This opens the door for other optimizations by exposing the
374 /// behavior of the program in a more fine-grained way.  We have determined that
375 /// this transformation is safe already.  We return the first global variable we
376 /// insert so that the caller can reprocess it.
377 static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
378   assert(GV->hasInternalLinkage() && !GV->isConstant());
379   Constant *Init = GV->getInitializer();
380   const Type *Ty = Init->getType();
381
382   std::vector<GlobalVariable*> NewGlobals;
383   Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
384
385   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
386     NewGlobals.reserve(STy->getNumElements());
387     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
388       Constant *In = getAggregateConstantElement(Init,
389                                             ConstantInt::get(Type::Int32Ty, i));
390       assert(In && "Couldn't get element of initializer?");
391       GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
392                                                GlobalVariable::InternalLinkage,
393                                                In, GV->getName()+"."+utostr(i));
394       Globals.insert(GV, NGV);
395       NewGlobals.push_back(NGV);
396     }
397   } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
398     unsigned NumElements = 0;
399     if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
400       NumElements = ATy->getNumElements();
401     else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
402       NumElements = PTy->getNumElements();
403     else
404       assert(0 && "Unknown aggregate sequential type!");
405
406     if (NumElements > 16 && GV->hasNUsesOrMore(16))
407       return 0; // It's not worth it.
408     NewGlobals.reserve(NumElements);
409     for (unsigned i = 0, e = NumElements; i != e; ++i) {
410       Constant *In = getAggregateConstantElement(Init,
411                                             ConstantInt::get(Type::Int32Ty, i));
412       assert(In && "Couldn't get element of initializer?");
413
414       GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
415                                                GlobalVariable::InternalLinkage,
416                                                In, GV->getName()+"."+utostr(i));
417       Globals.insert(GV, NGV);
418       NewGlobals.push_back(NGV);
419     }
420   }
421
422   if (NewGlobals.empty())
423     return 0;
424
425   DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
426
427   Constant *NullInt = Constant::getNullValue(Type::Int32Ty);
428
429   // Loop over all of the uses of the global, replacing the constantexpr geps,
430   // with smaller constantexpr geps or direct references.
431   while (!GV->use_empty()) {
432     User *GEP = GV->use_back();
433     assert(((isa<ConstantExpr>(GEP) &&
434              cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
435             isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
436
437     // Ignore the 1th operand, which has to be zero or else the program is quite
438     // broken (undefined).  Get the 2nd operand, which is the structure or array
439     // index.
440     unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
441     if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
442
443     Value *NewPtr = NewGlobals[Val];
444
445     // Form a shorter GEP if needed.
446     if (GEP->getNumOperands() > 3)
447       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
448         SmallVector<Constant*, 8> Idxs;
449         Idxs.push_back(NullInt);
450         for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
451           Idxs.push_back(CE->getOperand(i));
452         NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
453                                                 &Idxs[0], Idxs.size());
454       } else {
455         GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
456         SmallVector<Value*, 8> Idxs;
457         Idxs.push_back(NullInt);
458         for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
459           Idxs.push_back(GEPI->getOperand(i));
460         NewPtr = new GetElementPtrInst(NewPtr, &Idxs[0], Idxs.size(),
461                                        GEPI->getName()+"."+utostr(Val), GEPI);
462       }
463     GEP->replaceAllUsesWith(NewPtr);
464
465     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
466       GEPI->eraseFromParent();
467     else
468       cast<ConstantExpr>(GEP)->destroyConstant();
469   }
470
471   // Delete the old global, now that it is dead.
472   Globals.erase(GV);
473   ++NumSRA;
474
475   // Loop over the new globals array deleting any globals that are obviously
476   // dead.  This can arise due to scalarization of a structure or an array that
477   // has elements that are dead.
478   unsigned FirstGlobal = 0;
479   for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
480     if (NewGlobals[i]->use_empty()) {
481       Globals.erase(NewGlobals[i]);
482       if (FirstGlobal == i) ++FirstGlobal;
483     }
484
485   return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
486 }
487
488 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
489 /// value will trap if the value is dynamically null.
490 static bool AllUsesOfValueWillTrapIfNull(Value *V) {
491   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
492     if (isa<LoadInst>(*UI)) {
493       // Will trap.
494     } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
495       if (SI->getOperand(0) == V) {
496         //cerr << "NONTRAPPING USE: " << **UI;
497         return false;  // Storing the value.
498       }
499     } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
500       if (CI->getOperand(0) != V) {
501         //cerr << "NONTRAPPING USE: " << **UI;
502         return false;  // Not calling the ptr
503       }
504     } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
505       if (II->getOperand(0) != V) {
506         //cerr << "NONTRAPPING USE: " << **UI;
507         return false;  // Not calling the ptr
508       }
509     } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
510       if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
511     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
512       if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
513     } else if (isa<ICmpInst>(*UI) &&
514                isa<ConstantPointerNull>(UI->getOperand(1))) {
515       // Ignore setcc X, null
516     } else {
517       //cerr << "NONTRAPPING USE: " << **UI;
518       return false;
519     }
520   return true;
521 }
522
523 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
524 /// from GV will trap if the loaded value is null.  Note that this also permits
525 /// comparisons of the loaded value against null, as a special case.
526 static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
527   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
528     if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
529       if (!AllUsesOfValueWillTrapIfNull(LI))
530         return false;
531     } else if (isa<StoreInst>(*UI)) {
532       // Ignore stores to the global.
533     } else {
534       // We don't know or understand this user, bail out.
535       //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
536       return false;
537     }
538
539   return true;
540 }
541
542 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
543   bool Changed = false;
544   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
545     Instruction *I = cast<Instruction>(*UI++);
546     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
547       LI->setOperand(0, NewV);
548       Changed = true;
549     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
550       if (SI->getOperand(1) == V) {
551         SI->setOperand(1, NewV);
552         Changed = true;
553       }
554     } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
555       if (I->getOperand(0) == V) {
556         // Calling through the pointer!  Turn into a direct call, but be careful
557         // that the pointer is not also being passed as an argument.
558         I->setOperand(0, NewV);
559         Changed = true;
560         bool PassedAsArg = false;
561         for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
562           if (I->getOperand(i) == V) {
563             PassedAsArg = true;
564             I->setOperand(i, NewV);
565           }
566
567         if (PassedAsArg) {
568           // Being passed as an argument also.  Be careful to not invalidate UI!
569           UI = V->use_begin();
570         }
571       }
572     } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
573       Changed |= OptimizeAwayTrappingUsesOfValue(CI,
574                                 ConstantExpr::getCast(CI->getOpcode(),
575                                                       NewV, CI->getType()));
576       if (CI->use_empty()) {
577         Changed = true;
578         CI->eraseFromParent();
579       }
580     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
581       // Should handle GEP here.
582       SmallVector<Constant*, 8> Idxs;
583       Idxs.reserve(GEPI->getNumOperands()-1);
584       for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
585         if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
586           Idxs.push_back(C);
587         else
588           break;
589       if (Idxs.size() == GEPI->getNumOperands()-1)
590         Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
591                                 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
592                                                                Idxs.size()));
593       if (GEPI->use_empty()) {
594         Changed = true;
595         GEPI->eraseFromParent();
596       }
597     }
598   }
599
600   return Changed;
601 }
602
603
604 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
605 /// value stored into it.  If there are uses of the loaded value that would trap
606 /// if the loaded value is dynamically null, then we know that they cannot be
607 /// reachable with a null optimize away the load.
608 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
609   std::vector<LoadInst*> Loads;
610   bool Changed = false;
611
612   // Replace all uses of loads with uses of uses of the stored value.
613   for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
614        GUI != E; ++GUI)
615     if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
616       Loads.push_back(LI);
617       Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
618     } else {
619       assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
620     }
621
622   if (Changed) {
623     DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
624     ++NumGlobUses;
625   }
626
627   // Delete all of the loads we can, keeping track of whether we nuked them all!
628   bool AllLoadsGone = true;
629   while (!Loads.empty()) {
630     LoadInst *L = Loads.back();
631     if (L->use_empty()) {
632       L->eraseFromParent();
633       Changed = true;
634     } else {
635       AllLoadsGone = false;
636     }
637     Loads.pop_back();
638   }
639
640   // If we nuked all of the loads, then none of the stores are needed either,
641   // nor is the global.
642   if (AllLoadsGone) {
643     DOUT << "  *** GLOBAL NOW DEAD!\n";
644     CleanupConstantGlobalUsers(GV, 0);
645     if (GV->use_empty()) {
646       GV->eraseFromParent();
647       ++NumDeleted;
648     }
649     Changed = true;
650   }
651   return Changed;
652 }
653
654 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
655 /// instructions that are foldable.
656 static void ConstantPropUsersOf(Value *V) {
657   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
658     if (Instruction *I = dyn_cast<Instruction>(*UI++))
659       if (Constant *NewC = ConstantFoldInstruction(I)) {
660         I->replaceAllUsesWith(NewC);
661
662         // Advance UI to the next non-I use to avoid invalidating it!
663         // Instructions could multiply use V.
664         while (UI != E && *UI == I)
665           ++UI;
666         I->eraseFromParent();
667       }
668 }
669
670 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
671 /// variable, and transforms the program as if it always contained the result of
672 /// the specified malloc.  Because it is always the result of the specified
673 /// malloc, there is no reason to actually DO the malloc.  Instead, turn the
674 /// malloc into a global, and any loads of GV as uses of the new global.
675 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
676                                                      MallocInst *MI) {
677   DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << "  MALLOC = " << *MI;
678   ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
679
680   if (NElements->getZExtValue() != 1) {
681     // If we have an array allocation, transform it to a single element
682     // allocation to make the code below simpler.
683     Type *NewTy = ArrayType::get(MI->getAllocatedType(),
684                                  NElements->getZExtValue());
685     MallocInst *NewMI =
686       new MallocInst(NewTy, Constant::getNullValue(Type::Int32Ty),
687                      MI->getAlignment(), MI->getName(), MI);
688     Value* Indices[2];
689     Indices[0] = Indices[1] = Constant::getNullValue(Type::Int32Ty);
690     Value *NewGEP = new GetElementPtrInst(NewMI, Indices, 2,
691                                           NewMI->getName()+".el0", MI);
692     MI->replaceAllUsesWith(NewGEP);
693     MI->eraseFromParent();
694     MI = NewMI;
695   }
696
697   // Create the new global variable.  The contents of the malloc'd memory is
698   // undefined, so initialize with an undef value.
699   Constant *Init = UndefValue::get(MI->getAllocatedType());
700   GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
701                                              GlobalValue::InternalLinkage, Init,
702                                              GV->getName()+".body");
703   GV->getParent()->getGlobalList().insert(GV, NewGV);
704
705   // Anything that used the malloc now uses the global directly.
706   MI->replaceAllUsesWith(NewGV);
707
708   Constant *RepValue = NewGV;
709   if (NewGV->getType() != GV->getType()->getElementType())
710     RepValue = ConstantExpr::getBitCast(RepValue, 
711                                         GV->getType()->getElementType());
712
713   // If there is a comparison against null, we will insert a global bool to
714   // keep track of whether the global was initialized yet or not.
715   GlobalVariable *InitBool =
716     new GlobalVariable(Type::Int1Ty, false, GlobalValue::InternalLinkage,
717                        ConstantInt::getFalse(), GV->getName()+".init");
718   bool InitBoolUsed = false;
719
720   // Loop over all uses of GV, processing them in turn.
721   std::vector<StoreInst*> Stores;
722   while (!GV->use_empty())
723     if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
724       while (!LI->use_empty()) {
725         Use &LoadUse = LI->use_begin().getUse();
726         if (!isa<ICmpInst>(LoadUse.getUser()))
727           LoadUse = RepValue;
728         else {
729           ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
730           // Replace the cmp X, 0 with a use of the bool value.
731           Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
732           InitBoolUsed = true;
733           switch (CI->getPredicate()) {
734           default: assert(0 && "Unknown ICmp Predicate!");
735           case ICmpInst::ICMP_ULT:
736           case ICmpInst::ICMP_SLT:
737             LV = ConstantInt::getFalse();   // X < null -> always false
738             break;
739           case ICmpInst::ICMP_ULE:
740           case ICmpInst::ICMP_SLE:
741           case ICmpInst::ICMP_EQ:
742             LV = BinaryOperator::createNot(LV, "notinit", CI);
743             break;
744           case ICmpInst::ICMP_NE:
745           case ICmpInst::ICMP_UGE:
746           case ICmpInst::ICMP_SGE:
747           case ICmpInst::ICMP_UGT:
748           case ICmpInst::ICMP_SGT:
749             break;  // no change.
750           }
751           CI->replaceAllUsesWith(LV);
752           CI->eraseFromParent();
753         }
754       }
755       LI->eraseFromParent();
756     } else {
757       StoreInst *SI = cast<StoreInst>(GV->use_back());
758       // The global is initialized when the store to it occurs.
759       new StoreInst(ConstantInt::getTrue(), InitBool, SI);
760       SI->eraseFromParent();
761     }
762
763   // If the initialization boolean was used, insert it, otherwise delete it.
764   if (!InitBoolUsed) {
765     while (!InitBool->use_empty())  // Delete initializations
766       cast<Instruction>(InitBool->use_back())->eraseFromParent();
767     delete InitBool;
768   } else
769     GV->getParent()->getGlobalList().insert(GV, InitBool);
770
771
772   // Now the GV is dead, nuke it and the malloc.
773   GV->eraseFromParent();
774   MI->eraseFromParent();
775
776   // To further other optimizations, loop over all users of NewGV and try to
777   // constant prop them.  This will promote GEP instructions with constant
778   // indices into GEP constant-exprs, which will allow global-opt to hack on it.
779   ConstantPropUsersOf(NewGV);
780   if (RepValue != NewGV)
781     ConstantPropUsersOf(RepValue);
782
783   return NewGV;
784 }
785
786 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
787 /// to make sure that there are no complex uses of V.  We permit simple things
788 /// like dereferencing the pointer, but not storing through the address, unless
789 /// it is to the specified global.
790 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
791                                                       GlobalVariable *GV) {
792   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI)
793     if (isa<LoadInst>(*UI) || isa<CmpInst>(*UI)) {
794       // Fine, ignore.
795     } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
796       if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
797         return false;  // Storing the pointer itself... bad.
798       // Otherwise, storing through it, or storing into GV... fine.
799     } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) {
800       if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV))
801         return false;
802     } else {
803       return false;
804     }
805   return true;
806 }
807
808 /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
809 /// somewhere.  Transform all uses of the allocation into loads from the
810 /// global and uses of the resultant pointer.  Further, delete the store into
811 /// GV.  This assumes that these value pass the 
812 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
813 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc, 
814                                           GlobalVariable *GV) {
815   while (!Alloc->use_empty()) {
816     Instruction *U = Alloc->use_back();
817     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
818       // If this is the store of the allocation into the global, remove it.
819       if (SI->getOperand(1) == GV) {
820         SI->eraseFromParent();
821         continue;
822       }
823     }
824     
825     // Insert a load from the global, and use it instead of the malloc.
826     Value *NL = new LoadInst(GV, GV->getName()+".val", U);
827     U->replaceUsesOfWith(Alloc, NL);
828   }
829 }
830
831 /// GlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
832 /// GV are simple enough to perform HeapSRA, return true.
833 static bool GlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV) {
834   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E; 
835        ++UI)
836     if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
837       // We permit two users of the load: setcc comparing against the null
838       // pointer, and a getelementptr of a specific form.
839       for (Value::use_iterator UI = LI->use_begin(), E = LI->use_end(); UI != E; 
840            ++UI) {
841         // Comparison against null is ok.
842         if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
843           if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
844             return false;
845           continue;
846         }
847         
848         // getelementptr is also ok, but only a simple form.
849         GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI);
850         if (!GEPI) return false;
851         
852         // Must index into the array and into the struct.
853         if (GEPI->getNumOperands() < 3)
854           return false;
855         
856         // Otherwise the GEP is ok.
857         continue;
858       }
859     }
860   return true;
861 }
862
863 /// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global.  Ptr
864 /// is a value loaded from the global.  Eliminate all uses of Ptr, making them
865 /// use FieldGlobals instead.  All uses of loaded values satisfy
866 /// GlobalLoadUsesSimpleEnoughForHeapSRA.
867 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Ptr, 
868                              const std::vector<GlobalVariable*> &FieldGlobals) {
869   std::vector<Value *> InsertedLoadsForPtr;
870   //InsertedLoadsForPtr.resize(FieldGlobals.size());
871   while (!Ptr->use_empty()) {
872     Instruction *User = Ptr->use_back();
873     
874     // If this is a comparison against null, handle it.
875     if (ICmpInst *SCI = dyn_cast<ICmpInst>(User)) {
876       assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
877       // If we have a setcc of the loaded pointer, we can use a setcc of any
878       // field.
879       Value *NPtr;
880       if (InsertedLoadsForPtr.empty()) {
881         NPtr = new LoadInst(FieldGlobals[0], Ptr->getName()+".f0", Ptr);
882         InsertedLoadsForPtr.push_back(Ptr);
883       } else {
884         NPtr = InsertedLoadsForPtr.back();
885       }
886       
887       Value *New = new ICmpInst(SCI->getPredicate(), NPtr,
888                                 Constant::getNullValue(NPtr->getType()),
889                                 SCI->getName(), SCI);
890       SCI->replaceAllUsesWith(New);
891       SCI->eraseFromParent();
892       continue;
893     }
894     
895     // Otherwise, this should be: 'getelementptr Ptr, Idx, uint FieldNo ...'
896     GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
897     assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
898            && "Unexpected GEPI!");
899     
900     // Load the pointer for this field.
901     unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
902     if (InsertedLoadsForPtr.size() <= FieldNo)
903       InsertedLoadsForPtr.resize(FieldNo+1);
904     if (InsertedLoadsForPtr[FieldNo] == 0)
905       InsertedLoadsForPtr[FieldNo] = new LoadInst(FieldGlobals[FieldNo],
906                                                   Ptr->getName()+".f" + 
907                                                   utostr(FieldNo), Ptr);
908     Value *NewPtr = InsertedLoadsForPtr[FieldNo];
909
910     // Create the new GEP idx vector.
911     std::vector<Value*> GEPIdx;
912     GEPIdx.push_back(GEPI->getOperand(1));
913     GEPIdx.insert(GEPIdx.end(), GEPI->op_begin()+3, GEPI->op_end());
914
915     Value *NGEPI = new GetElementPtrInst(NewPtr, GEPIdx, GEPI->getName(), GEPI);
916     GEPI->replaceAllUsesWith(NGEPI);
917     GEPI->eraseFromParent();
918   }
919 }
920
921 /// PerformHeapAllocSRoA - MI is an allocation of an array of structures.  Break
922 /// it up into multiple allocations of arrays of the fields.
923 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
924   DOUT << "SROA HEAP ALLOC: " << *GV << "  MALLOC = " << *MI;
925   const StructType *STy = cast<StructType>(MI->getAllocatedType());
926
927   // There is guaranteed to be at least one use of the malloc (storing
928   // it into GV).  If there are other uses, change them to be uses of
929   // the global to simplify later code.  This also deletes the store
930   // into GV.
931   ReplaceUsesOfMallocWithGlobal(MI, GV);
932   
933   // Okay, at this point, there are no users of the malloc.  Insert N
934   // new mallocs at the same place as MI, and N globals.
935   std::vector<GlobalVariable*> FieldGlobals;
936   std::vector<MallocInst*> FieldMallocs;
937   
938   for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
939     const Type *FieldTy = STy->getElementType(FieldNo);
940     const Type *PFieldTy = PointerType::get(FieldTy);
941     
942     GlobalVariable *NGV =
943       new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
944                          Constant::getNullValue(PFieldTy),
945                          GV->getName() + ".f" + utostr(FieldNo), GV);
946     FieldGlobals.push_back(NGV);
947     
948     MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
949                                      MI->getName() + ".f" + utostr(FieldNo),MI);
950     FieldMallocs.push_back(NMI);
951     new StoreInst(NMI, NGV, MI);
952   }
953   
954   // The tricky aspect of this transformation is handling the case when malloc
955   // fails.  In the original code, malloc failing would set the result pointer
956   // of malloc to null.  In this case, some mallocs could succeed and others
957   // could fail.  As such, we emit code that looks like this:
958   //    F0 = malloc(field0)
959   //    F1 = malloc(field1)
960   //    F2 = malloc(field2)
961   //    if (F0 == 0 || F1 == 0 || F2 == 0) {
962   //      if (F0) { free(F0); F0 = 0; }
963   //      if (F1) { free(F1); F1 = 0; }
964   //      if (F2) { free(F2); F2 = 0; }
965   //    }
966   Value *RunningOr = 0;
967   for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
968     Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, FieldMallocs[i],
969                              Constant::getNullValue(FieldMallocs[i]->getType()),
970                                   "isnull", MI);
971     if (!RunningOr)
972       RunningOr = Cond;   // First seteq
973     else
974       RunningOr = BinaryOperator::createOr(RunningOr, Cond, "tmp", MI);
975   }
976
977   // Split the basic block at the old malloc.
978   BasicBlock *OrigBB = MI->getParent();
979   BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
980   
981   // Create the block to check the first condition.  Put all these blocks at the
982   // end of the function as they are unlikely to be executed.
983   BasicBlock *NullPtrBlock = new BasicBlock("malloc_ret_null",
984                                             OrigBB->getParent());
985   
986   // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
987   // branch on RunningOr.
988   OrigBB->getTerminator()->eraseFromParent();
989   new BranchInst(NullPtrBlock, ContBB, RunningOr, OrigBB);
990   
991   // Within the NullPtrBlock, we need to emit a comparison and branch for each
992   // pointer, because some may be null while others are not.
993   for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
994     Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
995     Value *Cmp = new ICmpInst(ICmpInst::ICMP_NE, GVVal, 
996                               Constant::getNullValue(GVVal->getType()),
997                               "tmp", NullPtrBlock);
998     BasicBlock *FreeBlock = new BasicBlock("free_it", OrigBB->getParent());
999     BasicBlock *NextBlock = new BasicBlock("next", OrigBB->getParent());
1000     new BranchInst(FreeBlock, NextBlock, Cmp, NullPtrBlock);
1001
1002     // Fill in FreeBlock.
1003     new FreeInst(GVVal, FreeBlock);
1004     new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1005                   FreeBlock);
1006     new BranchInst(NextBlock, FreeBlock);
1007     
1008     NullPtrBlock = NextBlock;
1009   }
1010   
1011   new BranchInst(ContBB, NullPtrBlock);
1012   
1013   
1014   // MI is no longer needed, remove it.
1015   MI->eraseFromParent();
1016
1017   
1018   // Okay, the malloc site is completely handled.  All of the uses of GV are now
1019   // loads, and all uses of those loads are simple.  Rewrite them to use loads
1020   // of the per-field globals instead.
1021   while (!GV->use_empty()) {
1022     if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
1023       RewriteUsesOfLoadForHeapSRoA(LI, FieldGlobals);
1024       LI->eraseFromParent();
1025     } else {
1026       // Must be a store of null.
1027       StoreInst *SI = cast<StoreInst>(GV->use_back());
1028       assert(isa<Constant>(SI->getOperand(0)) &&
1029              cast<Constant>(SI->getOperand(0))->isNullValue() &&
1030              "Unexpected heap-sra user!");
1031       
1032       // Insert a store of null into each global.
1033       for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1034         Constant *Null = 
1035           Constant::getNullValue(FieldGlobals[i]->getType()->getElementType());
1036         new StoreInst(Null, FieldGlobals[i], SI);
1037       }
1038       // Erase the original store.
1039       SI->eraseFromParent();
1040     }
1041   }
1042
1043   // The old global is now dead, remove it.
1044   GV->eraseFromParent();
1045
1046   ++NumHeapSRA;
1047   return FieldGlobals[0];
1048 }
1049
1050
1051 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1052 // that only one value (besides its initializer) is ever stored to the global.
1053 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1054                                      Module::global_iterator &GVI,
1055                                      TargetData &TD) {
1056   if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
1057     StoredOnceVal = CI->getOperand(0);
1058   else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
1059     // "getelementptr Ptr, 0, 0, 0" is really just a cast.
1060     bool IsJustACast = true;
1061     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
1062       if (!isa<Constant>(GEPI->getOperand(i)) ||
1063           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
1064         IsJustACast = false;
1065         break;
1066       }
1067     if (IsJustACast)
1068       StoredOnceVal = GEPI->getOperand(0);
1069   }
1070
1071   // If we are dealing with a pointer global that is initialized to null and
1072   // only has one (non-null) value stored into it, then we can optimize any
1073   // users of the loaded value (often calls and loads) that would trap if the
1074   // value was null.
1075   if (isa<PointerType>(GV->getInitializer()->getType()) &&
1076       GV->getInitializer()->isNullValue()) {
1077     if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1078       if (GV->getInitializer()->getType() != SOVC->getType())
1079         SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
1080
1081       // Optimize away any trapping uses of the loaded value.
1082       if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
1083         return true;
1084     } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
1085       // If this is a malloc of an abstract type, don't touch it.
1086       if (!MI->getAllocatedType()->isSized())
1087         return false;
1088       
1089       // We can't optimize this global unless all uses of it are *known* to be
1090       // of the malloc value, not of the null initializer value (consider a use
1091       // that compares the global's value against zero to see if the malloc has
1092       // been reached).  To do this, we check to see if all uses of the global
1093       // would trap if the global were null: this proves that they must all
1094       // happen after the malloc.
1095       if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1096         return false;
1097
1098       // We can't optimize this if the malloc itself is used in a complex way,
1099       // for example, being stored into multiple globals.  This allows the
1100       // malloc to be stored into the specified global, loaded setcc'd, and
1101       // GEP'd.  These are all things we could transform to using the global
1102       // for.
1103       if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV))
1104         return false;
1105
1106       
1107       // If we have a global that is only initialized with a fixed size malloc,
1108       // transform the program to use global memory instead of malloc'd memory.
1109       // This eliminates dynamic allocation, avoids an indirection accessing the
1110       // data, and exposes the resultant global to further GlobalOpt.
1111       if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
1112         // Restrict this transformation to only working on small allocations
1113         // (2048 bytes currently), as we don't want to introduce a 16M global or
1114         // something.
1115         if (NElements->getZExtValue()*
1116                      TD.getTypeSize(MI->getAllocatedType()) < 2048) {
1117           GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
1118           return true;
1119         }
1120       }
1121
1122       // If the allocation is an array of structures, consider transforming this
1123       // into multiple malloc'd arrays, one for each field.  This is basically
1124       // SRoA for malloc'd memory.
1125       if (const StructType *AllocTy = 
1126                   dyn_cast<StructType>(MI->getAllocatedType())) {
1127         // This the structure has an unreasonable number of fields, leave it
1128         // alone.
1129         if (AllocTy->getNumElements() <= 16 && AllocTy->getNumElements() > 0 &&
1130             GlobalLoadUsesSimpleEnoughForHeapSRA(GV)) {
1131           GVI = PerformHeapAllocSRoA(GV, MI);
1132           return true;
1133         }
1134       }
1135     }
1136   }
1137
1138   return false;
1139 }
1140
1141 /// ShrinkGlobalToBoolean - At this point, we have learned that the only two
1142 /// values ever stored into GV are its initializer and OtherVal.
1143 static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1144   // Create the new global, initializing it to false.
1145   GlobalVariable *NewGV = new GlobalVariable(Type::Int1Ty, false,
1146          GlobalValue::InternalLinkage, ConstantInt::getFalse(),
1147                                              GV->getName()+".b");
1148   GV->getParent()->getGlobalList().insert(GV, NewGV);
1149
1150   Constant *InitVal = GV->getInitializer();
1151   assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!");
1152
1153   // If initialized to zero and storing one into the global, we can use a cast
1154   // instead of a select to synthesize the desired value.
1155   bool IsOneZero = false;
1156   if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1157     IsOneZero = InitVal->isNullValue() && CI->equalsInt(1);
1158
1159   while (!GV->use_empty()) {
1160     Instruction *UI = cast<Instruction>(GV->use_back());
1161     if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1162       // Change the store into a boolean store.
1163       bool StoringOther = SI->getOperand(0) == OtherVal;
1164       // Only do this if we weren't storing a loaded value.
1165       Value *StoreVal;
1166       if (StoringOther || SI->getOperand(0) == InitVal)
1167         StoreVal = ConstantInt::get(Type::Int1Ty, StoringOther);
1168       else {
1169         // Otherwise, we are storing a previously loaded copy.  To do this,
1170         // change the copy from copying the original value to just copying the
1171         // bool.
1172         Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1173
1174         // If we're already replaced the input, StoredVal will be a cast or
1175         // select instruction.  If not, it will be a load of the original
1176         // global.
1177         if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1178           assert(LI->getOperand(0) == GV && "Not a copy!");
1179           // Insert a new load, to preserve the saved value.
1180           StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1181         } else {
1182           assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1183                  "This is not a form that we understand!");
1184           StoreVal = StoredVal->getOperand(0);
1185           assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1186         }
1187       }
1188       new StoreInst(StoreVal, NewGV, SI);
1189     } else if (!UI->use_empty()) {
1190       // Change the load into a load of bool then a select.
1191       LoadInst *LI = cast<LoadInst>(UI);
1192       LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
1193       Value *NSI;
1194       if (IsOneZero)
1195         NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1196       else
1197         NSI = new SelectInst(NLI, OtherVal, InitVal, "", LI);
1198       NSI->takeName(LI);
1199       LI->replaceAllUsesWith(NSI);
1200     }
1201     UI->eraseFromParent();
1202   }
1203
1204   GV->eraseFromParent();
1205 }
1206
1207
1208 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
1209 /// it if possible.  If we make a change, return true.
1210 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1211                                       Module::global_iterator &GVI) {
1212   std::set<PHINode*> PHIUsers;
1213   GlobalStatus GS;
1214   GV->removeDeadConstantUsers();
1215
1216   if (GV->use_empty()) {
1217     DOUT << "GLOBAL DEAD: " << *GV;
1218     GV->eraseFromParent();
1219     ++NumDeleted;
1220     return true;
1221   }
1222
1223   if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
1224 #if 0
1225     cerr << "Global: " << *GV;
1226     cerr << "  isLoaded = " << GS.isLoaded << "\n";
1227     cerr << "  StoredType = ";
1228     switch (GS.StoredType) {
1229     case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1230     case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1231     case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1232     case GlobalStatus::isStored: cerr << "stored\n"; break;
1233     }
1234     if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
1235       cerr << "  StoredOnceValue = " << *GS.StoredOnceValue << "\n";
1236     if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
1237       cerr << "  AccessingFunction = " << GS.AccessingFunction->getName()
1238                 << "\n";
1239     cerr << "  HasMultipleAccessingFunctions =  "
1240               << GS.HasMultipleAccessingFunctions << "\n";
1241     cerr << "  HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
1242     cerr << "  isNotSuitableForSRA = " << GS.isNotSuitableForSRA << "\n";
1243     cerr << "\n";
1244 #endif
1245     
1246     // If this is a first class global and has only one accessing function
1247     // and this function is main (which we know is not recursive we can make
1248     // this global a local variable) we replace the global with a local alloca
1249     // in this function.
1250     //
1251     // NOTE: It doesn't make sense to promote non first class types since we
1252     // are just replacing static memory to stack memory.
1253     if (!GS.HasMultipleAccessingFunctions &&
1254         GS.AccessingFunction && !GS.HasNonInstructionUser &&
1255         GV->getType()->getElementType()->isFirstClassType() &&
1256         GS.AccessingFunction->getName() == "main" &&
1257         GS.AccessingFunction->hasExternalLinkage()) {
1258       DOUT << "LOCALIZING GLOBAL: " << *GV;
1259       Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1260       const Type* ElemTy = GV->getType()->getElementType();
1261       // FIXME: Pass Global's alignment when globals have alignment
1262       AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1263       if (!isa<UndefValue>(GV->getInitializer()))
1264         new StoreInst(GV->getInitializer(), Alloca, FirstI);
1265
1266       GV->replaceAllUsesWith(Alloca);
1267       GV->eraseFromParent();
1268       ++NumLocalized;
1269       return true;
1270     }
1271     
1272     // If the global is never loaded (but may be stored to), it is dead.
1273     // Delete it now.
1274     if (!GS.isLoaded) {
1275       DOUT << "GLOBAL NEVER LOADED: " << *GV;
1276
1277       // Delete any stores we can find to the global.  We may not be able to
1278       // make it completely dead though.
1279       bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
1280
1281       // If the global is dead now, delete it.
1282       if (GV->use_empty()) {
1283         GV->eraseFromParent();
1284         ++NumDeleted;
1285         Changed = true;
1286       }
1287       return Changed;
1288
1289     } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1290       DOUT << "MARKING CONSTANT: " << *GV;
1291       GV->setConstant(true);
1292
1293       // Clean up any obviously simplifiable users now.
1294       CleanupConstantGlobalUsers(GV, GV->getInitializer());
1295
1296       // If the global is dead now, just nuke it.
1297       if (GV->use_empty()) {
1298         DOUT << "   *** Marking constant allowed us to simplify "
1299              << "all users and delete global!\n";
1300         GV->eraseFromParent();
1301         ++NumDeleted;
1302       }
1303
1304       ++NumMarked;
1305       return true;
1306     } else if (!GS.isNotSuitableForSRA &&
1307                !GV->getInitializer()->getType()->isFirstClassType()) {
1308       if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
1309         GVI = FirstNewGV;  // Don't skip the newly produced globals!
1310         return true;
1311       }
1312     } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1313       // If the initial value for the global was an undef value, and if only
1314       // one other value was stored into it, we can just change the
1315       // initializer to be an undef value, then delete all stores to the
1316       // global.  This allows us to mark it constant.
1317       if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1318         if (isa<UndefValue>(GV->getInitializer())) {
1319           // Change the initial value here.
1320           GV->setInitializer(SOVConstant);
1321
1322           // Clean up any obviously simplifiable users now.
1323           CleanupConstantGlobalUsers(GV, GV->getInitializer());
1324
1325           if (GV->use_empty()) {
1326             DOUT << "   *** Substituting initializer allowed us to "
1327                  << "simplify all users and delete global!\n";
1328             GV->eraseFromParent();
1329             ++NumDeleted;
1330           } else {
1331             GVI = GV;
1332           }
1333           ++NumSubstitute;
1334           return true;
1335         }
1336
1337       // Try to optimize globals based on the knowledge that only one value
1338       // (besides its initializer) is ever stored to the global.
1339       if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1340                                    getAnalysis<TargetData>()))
1341         return true;
1342
1343       // Otherwise, if the global was not a boolean, we can shrink it to be a
1344       // boolean.
1345       if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1346         if (GV->getType()->getElementType() != Type::Int1Ty &&
1347             !GV->getType()->getElementType()->isFloatingPoint() &&
1348             !isa<PackedType>(GV->getType()->getElementType()) &&
1349             !GS.HasPHIUser) {
1350           DOUT << "   *** SHRINKING TO BOOL: " << *GV;
1351           ShrinkGlobalToBoolean(GV, SOVConstant);
1352           ++NumShrunkToBool;
1353           return true;
1354         }
1355     }
1356   }
1357   return false;
1358 }
1359
1360 /// OnlyCalledDirectly - Return true if the specified function is only called
1361 /// directly.  In other words, its address is never taken.
1362 static bool OnlyCalledDirectly(Function *F) {
1363   for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1364     Instruction *User = dyn_cast<Instruction>(*UI);
1365     if (!User) return false;
1366     if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1367
1368     // See if the function address is passed as an argument.
1369     for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i)
1370       if (User->getOperand(i) == F) return false;
1371   }
1372   return true;
1373 }
1374
1375 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1376 /// function, changing them to FastCC.
1377 static void ChangeCalleesToFastCall(Function *F) {
1378   for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1379     Instruction *User = cast<Instruction>(*UI);
1380     if (CallInst *CI = dyn_cast<CallInst>(User))
1381       CI->setCallingConv(CallingConv::Fast);
1382     else
1383       cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast);
1384   }
1385 }
1386
1387 bool GlobalOpt::OptimizeFunctions(Module &M) {
1388   bool Changed = false;
1389   // Optimize functions.
1390   for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1391     Function *F = FI++;
1392     F->removeDeadConstantUsers();
1393     if (F->use_empty() && (F->hasInternalLinkage() ||
1394                            F->hasLinkOnceLinkage())) {
1395       M.getFunctionList().erase(F);
1396       Changed = true;
1397       ++NumFnDeleted;
1398     } else if (F->hasInternalLinkage() &&
1399                F->getCallingConv() == CallingConv::C &&  !F->isVarArg() &&
1400                OnlyCalledDirectly(F)) {
1401       // If this function has C calling conventions, is not a varargs
1402       // function, and is only called directly, promote it to use the Fast
1403       // calling convention.
1404       F->setCallingConv(CallingConv::Fast);
1405       ChangeCalleesToFastCall(F);
1406       ++NumFastCallFns;
1407       Changed = true;
1408     }
1409   }
1410   return Changed;
1411 }
1412
1413 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1414   bool Changed = false;
1415   for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1416        GVI != E; ) {
1417     GlobalVariable *GV = GVI++;
1418     if (!GV->isConstant() && GV->hasInternalLinkage() &&
1419         GV->hasInitializer())
1420       Changed |= ProcessInternalGlobal(GV, GVI);
1421   }
1422   return Changed;
1423 }
1424
1425 /// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1426 /// initializers have an init priority of 65535.
1427 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1428   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1429        I != E; ++I)
1430     if (I->getName() == "llvm.global_ctors") {
1431       // Found it, verify it's an array of { int, void()* }.
1432       const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1433       if (!ATy) return 0;
1434       const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1435       if (!STy || STy->getNumElements() != 2 ||
1436           STy->getElementType(0) != Type::Int32Ty) return 0;
1437       const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1438       if (!PFTy) return 0;
1439       const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1440       if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1441           FTy->getNumParams() != 0)
1442         return 0;
1443       
1444       // Verify that the initializer is simple enough for us to handle.
1445       if (!I->hasInitializer()) return 0;
1446       ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1447       if (!CA) return 0;
1448       for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1449         if (ConstantStruct *CS = dyn_cast<ConstantStruct>(CA->getOperand(i))) {
1450           if (isa<ConstantPointerNull>(CS->getOperand(1)))
1451             continue;
1452
1453           // Must have a function or null ptr.
1454           if (!isa<Function>(CS->getOperand(1)))
1455             return 0;
1456           
1457           // Init priority must be standard.
1458           ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1459           if (!CI || CI->getZExtValue() != 65535)
1460             return 0;
1461         } else {
1462           return 0;
1463         }
1464       
1465       return I;
1466     }
1467   return 0;
1468 }
1469
1470 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1471 /// return a list of the functions and null terminator as a vector.
1472 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1473   ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1474   std::vector<Function*> Result;
1475   Result.reserve(CA->getNumOperands());
1476   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1477     ConstantStruct *CS = cast<ConstantStruct>(CA->getOperand(i));
1478     Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1479   }
1480   return Result;
1481 }
1482
1483 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1484 /// specified array, returning the new global to use.
1485 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL, 
1486                                           const std::vector<Function*> &Ctors) {
1487   // If we made a change, reassemble the initializer list.
1488   std::vector<Constant*> CSVals;
1489   CSVals.push_back(ConstantInt::get(Type::Int32Ty, 65535));
1490   CSVals.push_back(0);
1491   
1492   // Create the new init list.
1493   std::vector<Constant*> CAList;
1494   for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
1495     if (Ctors[i]) {
1496       CSVals[1] = Ctors[i];
1497     } else {
1498       const Type *FTy = FunctionType::get(Type::VoidTy,
1499                                           std::vector<const Type*>(), false);
1500       const PointerType *PFTy = PointerType::get(FTy);
1501       CSVals[1] = Constant::getNullValue(PFTy);
1502       CSVals[0] = ConstantInt::get(Type::Int32Ty, 2147483647);
1503     }
1504     CAList.push_back(ConstantStruct::get(CSVals));
1505   }
1506   
1507   // Create the array initializer.
1508   const Type *StructTy =
1509     cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1510   Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1511                                     CAList);
1512   
1513   // If we didn't change the number of elements, don't create a new GV.
1514   if (CA->getType() == GCL->getInitializer()->getType()) {
1515     GCL->setInitializer(CA);
1516     return GCL;
1517   }
1518   
1519   // Create the new global and insert it next to the existing list.
1520   GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
1521                                            GCL->getLinkage(), CA);
1522   GCL->getParent()->getGlobalList().insert(GCL, NGV);
1523   NGV->takeName(GCL);
1524   
1525   // Nuke the old list, replacing any uses with the new one.
1526   if (!GCL->use_empty()) {
1527     Constant *V = NGV;
1528     if (V->getType() != GCL->getType())
1529       V = ConstantExpr::getBitCast(V, GCL->getType());
1530     GCL->replaceAllUsesWith(V);
1531   }
1532   GCL->eraseFromParent();
1533   
1534   if (Ctors.size())
1535     return NGV;
1536   else
1537     return 0;
1538 }
1539
1540
1541 static Constant *getVal(std::map<Value*, Constant*> &ComputedValues,
1542                         Value *V) {
1543   if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1544   Constant *R = ComputedValues[V];
1545   assert(R && "Reference to an uncomputed value!");
1546   return R;
1547 }
1548
1549 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1550 /// enough for us to understand.  In particular, if it is a cast of something,
1551 /// we punt.  We basically just support direct accesses to globals and GEP's of
1552 /// globals.  This should be kept up to date with CommitValueTo.
1553 static bool isSimpleEnoughPointerToCommit(Constant *C) {
1554   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
1555     if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
1556       return false;  // do not allow weak/linkonce/dllimport/dllexport linkage.
1557     return !GV->isDeclaration();  // reject external globals.
1558   }
1559   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
1560     // Handle a constantexpr gep.
1561     if (CE->getOpcode() == Instruction::GetElementPtr &&
1562         isa<GlobalVariable>(CE->getOperand(0))) {
1563       GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1564       if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
1565         return false;  // do not allow weak/linkonce/dllimport/dllexport linkage.
1566       return GV->hasInitializer() &&
1567              ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1568     }
1569   return false;
1570 }
1571
1572 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
1573 /// initializer.  This returns 'Init' modified to reflect 'Val' stored into it.
1574 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
1575 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
1576                                    ConstantExpr *Addr, unsigned OpNo) {
1577   // Base case of the recursion.
1578   if (OpNo == Addr->getNumOperands()) {
1579     assert(Val->getType() == Init->getType() && "Type mismatch!");
1580     return Val;
1581   }
1582   
1583   if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1584     std::vector<Constant*> Elts;
1585
1586     // Break up the constant into its elements.
1587     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1588       for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1589         Elts.push_back(CS->getOperand(i));
1590     } else if (isa<ConstantAggregateZero>(Init)) {
1591       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1592         Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
1593     } else if (isa<UndefValue>(Init)) {
1594       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1595         Elts.push_back(UndefValue::get(STy->getElementType(i)));
1596     } else {
1597       assert(0 && "This code is out of sync with "
1598              " ConstantFoldLoadThroughGEPConstantExpr");
1599     }
1600     
1601     // Replace the element that we are supposed to.
1602     ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
1603     unsigned Idx = CU->getZExtValue();
1604     assert(Idx < STy->getNumElements() && "Struct index out of range!");
1605     Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
1606     
1607     // Return the modified struct.
1608     return ConstantStruct::get(Elts);
1609   } else {
1610     ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
1611     const ArrayType *ATy = cast<ArrayType>(Init->getType());
1612
1613     // Break up the array into elements.
1614     std::vector<Constant*> Elts;
1615     if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1616       for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1617         Elts.push_back(CA->getOperand(i));
1618     } else if (isa<ConstantAggregateZero>(Init)) {
1619       Constant *Elt = Constant::getNullValue(ATy->getElementType());
1620       Elts.assign(ATy->getNumElements(), Elt);
1621     } else if (isa<UndefValue>(Init)) {
1622       Constant *Elt = UndefValue::get(ATy->getElementType());
1623       Elts.assign(ATy->getNumElements(), Elt);
1624     } else {
1625       assert(0 && "This code is out of sync with "
1626              " ConstantFoldLoadThroughGEPConstantExpr");
1627     }
1628     
1629     assert(CI->getZExtValue() < ATy->getNumElements());
1630     Elts[CI->getZExtValue()] =
1631       EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
1632     return ConstantArray::get(ATy, Elts);
1633   }    
1634 }
1635
1636 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
1637 /// isSimpleEnoughPointerToCommit) should get Val as its value.  Make it happen.
1638 static void CommitValueTo(Constant *Val, Constant *Addr) {
1639   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
1640     assert(GV->hasInitializer());
1641     GV->setInitializer(Val);
1642     return;
1643   }
1644   
1645   ConstantExpr *CE = cast<ConstantExpr>(Addr);
1646   GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1647   
1648   Constant *Init = GV->getInitializer();
1649   Init = EvaluateStoreInto(Init, Val, CE, 2);
1650   GV->setInitializer(Init);
1651 }
1652
1653 /// ComputeLoadResult - Return the value that would be computed by a load from
1654 /// P after the stores reflected by 'memory' have been performed.  If we can't
1655 /// decide, return null.
1656 static Constant *ComputeLoadResult(Constant *P,
1657                                 const std::map<Constant*, Constant*> &Memory) {
1658   // If this memory location has been recently stored, use the stored value: it
1659   // is the most up-to-date.
1660   std::map<Constant*, Constant*>::const_iterator I = Memory.find(P);
1661   if (I != Memory.end()) return I->second;
1662  
1663   // Access it.
1664   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
1665     if (GV->hasInitializer())
1666       return GV->getInitializer();
1667     return 0;
1668   }
1669   
1670   // Handle a constantexpr getelementptr.
1671   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
1672     if (CE->getOpcode() == Instruction::GetElementPtr &&
1673         isa<GlobalVariable>(CE->getOperand(0))) {
1674       GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1675       if (GV->hasInitializer())
1676         return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1677     }
1678
1679   return 0;  // don't know how to evaluate.
1680 }
1681
1682 /// EvaluateFunction - Evaluate a call to function F, returning true if
1683 /// successful, false if we can't evaluate it.  ActualArgs contains the formal
1684 /// arguments for the function.
1685 static bool EvaluateFunction(Function *F, Constant *&RetVal,
1686                              const std::vector<Constant*> &ActualArgs,
1687                              std::vector<Function*> &CallStack,
1688                              std::map<Constant*, Constant*> &MutatedMemory,
1689                              std::vector<GlobalVariable*> &AllocaTmps) {
1690   // Check to see if this function is already executing (recursion).  If so,
1691   // bail out.  TODO: we might want to accept limited recursion.
1692   if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
1693     return false;
1694   
1695   CallStack.push_back(F);
1696   
1697   /// Values - As we compute SSA register values, we store their contents here.
1698   std::map<Value*, Constant*> Values;
1699   
1700   // Initialize arguments to the incoming values specified.
1701   unsigned ArgNo = 0;
1702   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
1703        ++AI, ++ArgNo)
1704     Values[AI] = ActualArgs[ArgNo];
1705
1706   /// ExecutedBlocks - We only handle non-looping, non-recursive code.  As such,
1707   /// we can only evaluate any one basic block at most once.  This set keeps
1708   /// track of what we have executed so we can detect recursive cases etc.
1709   std::set<BasicBlock*> ExecutedBlocks;
1710   
1711   // CurInst - The current instruction we're evaluating.
1712   BasicBlock::iterator CurInst = F->begin()->begin();
1713   
1714   // This is the main evaluation loop.
1715   while (1) {
1716     Constant *InstResult = 0;
1717     
1718     if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
1719       if (SI->isVolatile()) return false;  // no volatile accesses.
1720       Constant *Ptr = getVal(Values, SI->getOperand(1));
1721       if (!isSimpleEnoughPointerToCommit(Ptr))
1722         // If this is too complex for us to commit, reject it.
1723         return false;
1724       Constant *Val = getVal(Values, SI->getOperand(0));
1725       MutatedMemory[Ptr] = Val;
1726     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
1727       InstResult = ConstantExpr::get(BO->getOpcode(),
1728                                      getVal(Values, BO->getOperand(0)),
1729                                      getVal(Values, BO->getOperand(1)));
1730     } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
1731       InstResult = ConstantExpr::getCompare(CI->getPredicate(),
1732                                             getVal(Values, CI->getOperand(0)),
1733                                             getVal(Values, CI->getOperand(1)));
1734     } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
1735       InstResult = ConstantExpr::getCast(CI->getOpcode(),
1736                                          getVal(Values, CI->getOperand(0)),
1737                                          CI->getType());
1738     } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
1739       InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
1740                                            getVal(Values, SI->getOperand(1)),
1741                                            getVal(Values, SI->getOperand(2)));
1742     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
1743       Constant *P = getVal(Values, GEP->getOperand(0));
1744       SmallVector<Constant*, 8> GEPOps;
1745       for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1746         GEPOps.push_back(getVal(Values, GEP->getOperand(i)));
1747       InstResult = ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
1748     } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
1749       if (LI->isVolatile()) return false;  // no volatile accesses.
1750       InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
1751                                      MutatedMemory);
1752       if (InstResult == 0) return false; // Could not evaluate load.
1753     } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
1754       if (AI->isArrayAllocation()) return false;  // Cannot handle array allocs.
1755       const Type *Ty = AI->getType()->getElementType();
1756       AllocaTmps.push_back(new GlobalVariable(Ty, false,
1757                                               GlobalValue::InternalLinkage,
1758                                               UndefValue::get(Ty),
1759                                               AI->getName()));
1760       InstResult = AllocaTmps.back();     
1761     } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
1762       // Cannot handle inline asm.
1763       if (isa<InlineAsm>(CI->getOperand(0))) return false;
1764
1765       // Resolve function pointers.
1766       Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
1767       if (!Callee) return false;  // Cannot resolve.
1768
1769       std::vector<Constant*> Formals;
1770       for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1771         Formals.push_back(getVal(Values, CI->getOperand(i)));
1772       
1773       if (Callee->isDeclaration()) {
1774         // If this is a function we can constant fold, do it.
1775         if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
1776                                            Formals.size())) {
1777           InstResult = C;
1778         } else {
1779           return false;
1780         }
1781       } else {
1782         if (Callee->getFunctionType()->isVarArg())
1783           return false;
1784         
1785         Constant *RetVal;
1786         
1787         // Execute the call, if successful, use the return value.
1788         if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
1789                               MutatedMemory, AllocaTmps))
1790           return false;
1791         InstResult = RetVal;
1792       }
1793     } else if (isa<TerminatorInst>(CurInst)) {
1794       BasicBlock *NewBB = 0;
1795       if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
1796         if (BI->isUnconditional()) {
1797           NewBB = BI->getSuccessor(0);
1798         } else {
1799           ConstantInt *Cond =
1800             dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
1801           if (!Cond) return false;  // Cannot determine.
1802
1803           NewBB = BI->getSuccessor(!Cond->getZExtValue());          
1804         }
1805       } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
1806         ConstantInt *Val =
1807           dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
1808         if (!Val) return false;  // Cannot determine.
1809         NewBB = SI->getSuccessor(SI->findCaseValue(Val));
1810       } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
1811         if (RI->getNumOperands())
1812           RetVal = getVal(Values, RI->getOperand(0));
1813         
1814         CallStack.pop_back();  // return from fn.
1815         return true;  // We succeeded at evaluating this ctor!
1816       } else {
1817         // invoke, unwind, unreachable.
1818         return false;  // Cannot handle this terminator.
1819       }
1820       
1821       // Okay, we succeeded in evaluating this control flow.  See if we have
1822       // executed the new block before.  If so, we have a looping function,
1823       // which we cannot evaluate in reasonable time.
1824       if (!ExecutedBlocks.insert(NewBB).second)
1825         return false;  // looped!
1826       
1827       // Okay, we have never been in this block before.  Check to see if there
1828       // are any PHI nodes.  If so, evaluate them with information about where
1829       // we came from.
1830       BasicBlock *OldBB = CurInst->getParent();
1831       CurInst = NewBB->begin();
1832       PHINode *PN;
1833       for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
1834         Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
1835
1836       // Do NOT increment CurInst.  We know that the terminator had no value.
1837       continue;
1838     } else {
1839       // Did not know how to evaluate this!
1840       return false;
1841     }
1842     
1843     if (!CurInst->use_empty())
1844       Values[CurInst] = InstResult;
1845     
1846     // Advance program counter.
1847     ++CurInst;
1848   }
1849 }
1850
1851 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
1852 /// we can.  Return true if we can, false otherwise.
1853 static bool EvaluateStaticConstructor(Function *F) {
1854   /// MutatedMemory - For each store we execute, we update this map.  Loads
1855   /// check this to get the most up-to-date value.  If evaluation is successful,
1856   /// this state is committed to the process.
1857   std::map<Constant*, Constant*> MutatedMemory;
1858
1859   /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
1860   /// to represent its body.  This vector is needed so we can delete the
1861   /// temporary globals when we are done.
1862   std::vector<GlobalVariable*> AllocaTmps;
1863   
1864   /// CallStack - This is used to detect recursion.  In pathological situations
1865   /// we could hit exponential behavior, but at least there is nothing
1866   /// unbounded.
1867   std::vector<Function*> CallStack;
1868
1869   // Call the function.
1870   Constant *RetValDummy;
1871   bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
1872                                        CallStack, MutatedMemory, AllocaTmps);
1873   if (EvalSuccess) {
1874     // We succeeded at evaluation: commit the result.
1875     DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
1876          << F->getName() << "' to " << MutatedMemory.size()
1877          << " stores.\n";
1878     for (std::map<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
1879          E = MutatedMemory.end(); I != E; ++I)
1880       CommitValueTo(I->second, I->first);
1881   }
1882   
1883   // At this point, we are done interpreting.  If we created any 'alloca'
1884   // temporaries, release them now.
1885   while (!AllocaTmps.empty()) {
1886     GlobalVariable *Tmp = AllocaTmps.back();
1887     AllocaTmps.pop_back();
1888     
1889     // If there are still users of the alloca, the program is doing something
1890     // silly, e.g. storing the address of the alloca somewhere and using it
1891     // later.  Since this is undefined, we'll just make it be null.
1892     if (!Tmp->use_empty())
1893       Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
1894     delete Tmp;
1895   }
1896   
1897   return EvalSuccess;
1898 }
1899
1900
1901
1902 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
1903 /// Return true if anything changed.
1904 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
1905   std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
1906   bool MadeChange = false;
1907   if (Ctors.empty()) return false;
1908   
1909   // Loop over global ctors, optimizing them when we can.
1910   for (unsigned i = 0; i != Ctors.size(); ++i) {
1911     Function *F = Ctors[i];
1912     // Found a null terminator in the middle of the list, prune off the rest of
1913     // the list.
1914     if (F == 0) {
1915       if (i != Ctors.size()-1) {
1916         Ctors.resize(i+1);
1917         MadeChange = true;
1918       }
1919       break;
1920     }
1921     
1922     // We cannot simplify external ctor functions.
1923     if (F->empty()) continue;
1924     
1925     // If we can evaluate the ctor at compile time, do.
1926     if (EvaluateStaticConstructor(F)) {
1927       Ctors.erase(Ctors.begin()+i);
1928       MadeChange = true;
1929       --i;
1930       ++NumCtorsEvaluated;
1931       continue;
1932     }
1933   }
1934   
1935   if (!MadeChange) return false;
1936   
1937   GCL = InstallGlobalCtors(GCL, Ctors);
1938   return true;
1939 }
1940
1941
1942 bool GlobalOpt::runOnModule(Module &M) {
1943   bool Changed = false;
1944   
1945   // Try to find the llvm.globalctors list.
1946   GlobalVariable *GlobalCtors = FindGlobalCtors(M);
1947
1948   bool LocalChange = true;
1949   while (LocalChange) {
1950     LocalChange = false;
1951     
1952     // Delete functions that are trivially dead, ccc -> fastcc
1953     LocalChange |= OptimizeFunctions(M);
1954     
1955     // Optimize global_ctors list.
1956     if (GlobalCtors)
1957       LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
1958     
1959     // Optimize non-address-taken globals.
1960     LocalChange |= OptimizeGlobalVars(M);
1961     Changed |= LocalChange;
1962   }
1963   
1964   // TODO: Move all global ctors functions to the end of the module for code
1965   // layout.
1966   
1967   return Changed;
1968 }