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