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