If a global is just loaded and restored, realize that it is not changing
[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/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Transforms/Utils/Local.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include <set>
29 #include <algorithm>
30 using namespace llvm;
31
32 namespace {
33   Statistic<> NumMarked   ("globalopt", "Number of globals marked constant");
34   Statistic<> NumSRA      ("globalopt", "Number of aggregate globals broken "
35                            "into scalars");
36   Statistic<> NumSubstitute("globalopt",
37                         "Number of globals with initializers stored into them");
38   Statistic<> NumDeleted  ("globalopt", "Number of globals deleted");
39   Statistic<> NumFnDeleted("globalopt", "Number of functions deleted");
40   Statistic<> NumGlobUses ("globalopt", "Number of global uses devirtualized");
41
42   struct GlobalOpt : public ModulePass {
43     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
44       AU.addRequired<TargetData>();
45     }
46     
47     bool runOnModule(Module &M);
48
49   private:
50     bool ProcessInternalGlobal(GlobalVariable *GV, Module::giterator &GVI);
51   };
52
53   RegisterOpt<GlobalOpt> X("globalopt", "Global Variable Optimizer");
54 }
55
56 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
57
58 /// GlobalStatus - As we analyze each global, keep track of some information
59 /// about it.  If we find out that the address of the global is taken, none of
60 /// this info will be accurate.
61 struct GlobalStatus {
62   /// isLoaded - True if the global is ever loaded.  If the global isn't ever
63   /// loaded it can be deleted.
64   bool isLoaded;
65
66   /// StoredType - Keep track of what stores to the global look like.
67   ///
68   enum StoredType {
69     /// NotStored - There is no store to this global.  It can thus be marked
70     /// constant.
71     NotStored,
72
73     /// isInitializerStored - This global is stored to, but the only thing
74     /// stored is the constant it was initialized with.  This is only tracked
75     /// for scalar globals.
76     isInitializerStored,
77
78     /// isStoredOnce - This global is stored to, but only its initializer and
79     /// one other value is ever stored to it.  If this global isStoredOnce, we
80     /// track the value stored to it in StoredOnceValue below.  This is only
81     /// tracked for scalar globals.
82     isStoredOnce,
83
84     /// isStored - This global is stored to by multiple values or something else
85     /// that we cannot track.
86     isStored
87   } StoredType;
88
89   /// StoredOnceValue - If only one value (besides the initializer constant) is
90   /// ever stored to this global, keep track of what value it is.
91   Value *StoredOnceValue;
92
93   /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
94   /// the global exist.  Such users include GEP instruction with variable
95   /// indexes, and non-gep/load/store users like constant expr casts.
96   bool isNotSuitableForSRA;
97
98   GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
99                    isNotSuitableForSRA(false) {}
100 };
101
102
103
104 /// ConstantIsDead - Return true if the specified constant is (transitively)
105 /// dead.  The constant may be used by other constants (e.g. constant arrays and
106 /// constant exprs) as long as they are dead, but it cannot be used by anything
107 /// else.
108 static bool ConstantIsDead(Constant *C) {
109   if (isa<GlobalValue>(C)) return false;
110
111   for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
112     if (Constant *CU = dyn_cast<Constant>(*UI)) {
113       if (!ConstantIsDead(CU)) return false;
114     } else
115       return false;
116   return true;
117 }
118
119
120 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
121 /// structure.  If the global has its address taken, return true to indicate we
122 /// can't do anything with it.
123 ///
124 static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
125                           std::set<PHINode*> &PHIUsers) {
126   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
127     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
128       if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
129       if (CE->getOpcode() != Instruction::GetElementPtr)
130         GS.isNotSuitableForSRA = true;
131       else if (!GS.isNotSuitableForSRA) {
132         // Check to see if this ConstantExpr GEP is SRA'able.  In particular, we
133         // don't like < 3 operand CE's, and we don't like non-constant integer
134         // indices.
135         if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
136           GS.isNotSuitableForSRA = true;
137         else {
138           for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
139             if (!isa<ConstantInt>(CE->getOperand(i))) {
140               GS.isNotSuitableForSRA = true;
141               break;
142             }
143         }
144       }
145
146     } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
147       if (isa<LoadInst>(I)) {
148         GS.isLoaded = true;
149       } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
150         // Don't allow a store OF the address, only stores TO the address.
151         if (SI->getOperand(0) == V) return true;
152
153         // If this is a direct store to the global (i.e., the global is a scalar
154         // value, not an aggregate), keep more specific information about
155         // stores.
156         if (GS.StoredType != GlobalStatus::isStored)
157           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
158             Value *StoredVal = SI->getOperand(0);
159             if (StoredVal == GV->getInitializer()) {
160               if (GS.StoredType < GlobalStatus::isInitializerStored)
161                 GS.StoredType = GlobalStatus::isInitializerStored;
162             } else if (isa<LoadInst>(StoredVal) &&
163                        cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
164               // G = G
165               if (GS.StoredType < GlobalStatus::isInitializerStored)
166                 GS.StoredType = GlobalStatus::isInitializerStored;
167             } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
168               GS.StoredType = GlobalStatus::isStoredOnce;
169               GS.StoredOnceValue = StoredVal;
170             } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
171                        GS.StoredOnceValue == StoredVal) {
172               // noop.
173             } else {
174               GS.StoredType = GlobalStatus::isStored;
175             }
176           } else {
177             GS.StoredType = GlobalStatus::isStored;
178           }
179       } else if (I->getOpcode() == Instruction::GetElementPtr) {
180         if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
181
182         // If the first two indices are constants, this can be SRA'd.
183         if (isa<GlobalVariable>(I->getOperand(0))) {
184           if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
185               !cast<Constant>(I->getOperand(1))->isNullValue() || 
186               !isa<ConstantInt>(I->getOperand(2)))
187             GS.isNotSuitableForSRA = true;
188         } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
189           if (CE->getOpcode() != Instruction::GetElementPtr ||
190               CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
191               !isa<Constant>(I->getOperand(0)) ||
192               !cast<Constant>(I->getOperand(0))->isNullValue())
193             GS.isNotSuitableForSRA = true;
194         } else {
195           GS.isNotSuitableForSRA = true;
196         }
197       } else if (I->getOpcode() == Instruction::Select) {
198         if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
199         GS.isNotSuitableForSRA = true;
200       } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
201         // PHI nodes we can check just like select or GEP instructions, but we
202         // have to be careful about infinite recursion.
203         if (PHIUsers.insert(PN).second)  // Not already visited.
204           if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
205         GS.isNotSuitableForSRA = true;
206       } else if (isa<SetCondInst>(I)) {
207         GS.isNotSuitableForSRA = true;
208       } else {
209         return true;  // Any other non-load instruction might take address!
210       }
211     } else if (Constant *C = dyn_cast<Constant>(*UI)) {
212       // We might have a dead and dangling constant hanging off of here.
213       if (!ConstantIsDead(C))
214         return true;
215     } else {
216       // Otherwise must be a global or some other user.
217       return true;
218     }
219
220   return false;
221 }
222
223 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
224   ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
225   if (!CI) return 0;
226   uint64_t IdxV = CI->getRawValue();
227
228   if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
229     if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
230   } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
231     if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
232   } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
233     if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
234   } else if (isa<ConstantAggregateZero>(Agg)) {
235     if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
236       if (IdxV < STy->getNumElements())
237         return Constant::getNullValue(STy->getElementType(IdxV));
238     } else if (const SequentialType *STy =
239                dyn_cast<SequentialType>(Agg->getType())) {
240       return Constant::getNullValue(STy->getElementType());
241     }
242   } else if (isa<UndefValue>(Agg)) {
243     if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
244       if (IdxV < STy->getNumElements())
245         return UndefValue::get(STy->getElementType(IdxV));
246     } else if (const SequentialType *STy =
247                dyn_cast<SequentialType>(Agg->getType())) {
248       return UndefValue::get(STy->getElementType());
249     }
250   }
251   return 0;
252 }
253
254 static Constant *TraverseGEPInitializer(User *GEP, Constant *Init) {
255   if (GEP->getNumOperands() == 1 ||
256       !isa<Constant>(GEP->getOperand(1)) ||
257       !cast<Constant>(GEP->getOperand(1))->isNullValue())
258     return 0;
259
260   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
261     ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
262     if (!Idx) return 0;
263     Init = getAggregateConstantElement(Init, Idx);
264     if (Init == 0) return 0;
265   }
266   return Init;
267 }
268
269 /// CleanupConstantGlobalUsers - We just marked GV constant.  Loop over all
270 /// users of the global, cleaning up the obvious ones.  This is largely just a
271 /// quick scan over the use list to clean up the easy and obvious cruft.  This
272 /// returns true if it made a change.
273 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
274   bool Changed = false;
275   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
276     User *U = *UI++;
277     
278     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
279       // Replace the load with the initializer.
280       LI->replaceAllUsesWith(Init);
281       LI->eraseFromParent();
282       Changed = true;
283     } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
284       // Store must be unreachable or storing Init into the global.
285       SI->eraseFromParent();
286       Changed = true;
287     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
288       if (CE->getOpcode() == Instruction::GetElementPtr) {
289         if (Constant *SubInit = TraverseGEPInitializer(CE, Init))
290           Changed |= CleanupConstantGlobalUsers(CE, SubInit);
291         if (CE->use_empty()) {
292           CE->destroyConstant();
293           Changed = true;
294         }
295       }
296     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
297       if (Constant *SubInit = TraverseGEPInitializer(GEP, Init))
298         Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
299       else {
300         // If this GEP has variable indexes, we should still be able to delete
301         // any stores through it.
302         for (Value::use_iterator GUI = GEP->use_begin(), E = GEP->use_end();
303              GUI != E;)
304           if (StoreInst *SI = dyn_cast<StoreInst>(*GUI++)) {
305             SI->eraseFromParent();
306             Changed = true;
307           }
308       }
309
310       if (GEP->use_empty()) {
311         GEP->eraseFromParent();
312         Changed = true;
313       }
314     } else if (Constant *C = dyn_cast<Constant>(U)) {
315       // If we have a chain of dead constantexprs or other things dangling from
316       // us, and if they are all dead, nuke them without remorse.
317       if (ConstantIsDead(C)) {
318         C->destroyConstant();
319         // This could have incalidated UI, start over from scratch.x
320         CleanupConstantGlobalUsers(V, Init);
321         return true;
322       }
323     }
324   }
325   return Changed;
326 }
327
328 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
329 /// variable.  This opens the door for other optimizations by exposing the
330 /// behavior of the program in a more fine-grained way.  We have determined that
331 /// this transformation is safe already.  We return the first global variable we
332 /// insert so that the caller can reprocess it.
333 static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
334   assert(GV->hasInternalLinkage() && !GV->isConstant());
335   Constant *Init = GV->getInitializer();
336   const Type *Ty = Init->getType();
337   
338   std::vector<GlobalVariable*> NewGlobals;
339   Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
340
341   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
342     NewGlobals.reserve(STy->getNumElements());
343     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
344       Constant *In = getAggregateConstantElement(Init,
345                                             ConstantUInt::get(Type::UIntTy, i));
346       assert(In && "Couldn't get element of initializer?");
347       GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
348                                                GlobalVariable::InternalLinkage,
349                                                In, GV->getName()+"."+utostr(i));
350       Globals.insert(GV, NGV);
351       NewGlobals.push_back(NGV);
352     }
353   } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
354     unsigned NumElements = 0;
355     if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
356       NumElements = ATy->getNumElements();
357     else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
358       NumElements = PTy->getNumElements();
359     else
360       assert(0 && "Unknown aggregate sequential type!");
361
362     if (NumElements > 16 && GV->use_size() > 16) return 0; // It's not worth it.
363     NewGlobals.reserve(NumElements);
364     for (unsigned i = 0, e = NumElements; i != e; ++i) {
365       Constant *In = getAggregateConstantElement(Init,
366                                             ConstantUInt::get(Type::UIntTy, i));
367       assert(In && "Couldn't get element of initializer?");
368
369       GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
370                                                GlobalVariable::InternalLinkage,
371                                                In, GV->getName()+"."+utostr(i));
372       Globals.insert(GV, NGV);
373       NewGlobals.push_back(NGV);
374     }
375   }
376
377   if (NewGlobals.empty())
378     return 0;
379
380   DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV);
381
382   Constant *NullInt = Constant::getNullValue(Type::IntTy);
383
384   // Loop over all of the uses of the global, replacing the constantexpr geps,
385   // with smaller constantexpr geps or direct references.
386   while (!GV->use_empty()) {
387     User *GEP = GV->use_back();
388     assert(((isa<ConstantExpr>(GEP) &&
389              cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
390             isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
391              
392     // Ignore the 1th operand, which has to be zero or else the program is quite
393     // broken (undefined).  Get the 2nd operand, which is the structure or array
394     // index.
395     unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getRawValue();
396     if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
397
398     Value *NewPtr = NewGlobals[Val];
399
400     // Form a shorter GEP if needed.
401     if (GEP->getNumOperands() > 3)
402       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
403         std::vector<Constant*> Idxs;
404         Idxs.push_back(NullInt);
405         for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
406           Idxs.push_back(CE->getOperand(i));
407         NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
408       } else {
409         GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
410         std::vector<Value*> Idxs;
411         Idxs.push_back(NullInt);
412         for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
413           Idxs.push_back(GEPI->getOperand(i));
414         NewPtr = new GetElementPtrInst(NewPtr, Idxs,
415                                        GEPI->getName()+"."+utostr(Val), GEPI);
416       }
417     GEP->replaceAllUsesWith(NewPtr);
418
419     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
420       GEPI->eraseFromParent();
421     else
422       cast<ConstantExpr>(GEP)->destroyConstant();
423   }
424
425   // Delete the old global, now that it is dead.
426   Globals.erase(GV);
427   ++NumSRA;
428
429   // Loop over the new globals array deleting any globals that are obviously
430   // dead.  This can arise due to scalarization of a structure or an array that
431   // has elements that are dead.
432   unsigned FirstGlobal = 0;
433   for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
434     if (NewGlobals[i]->use_empty()) {
435       Globals.erase(NewGlobals[i]);
436       if (FirstGlobal == i) ++FirstGlobal;
437     }
438
439   return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
440 }
441
442 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
443 /// value will trap if the value is dynamically null.
444 static bool AllUsesOfValueWillTrapIfNull(Value *V) {
445   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
446     if (isa<LoadInst>(*UI)) {
447       // Will trap.
448     } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
449       if (SI->getOperand(0) == V) {
450         //std::cerr << "NONTRAPPING USE: " << **UI;
451         return false;  // Storing the value.
452       }
453     } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
454       if (CI->getOperand(0) != V) {
455         //std::cerr << "NONTRAPPING USE: " << **UI;
456         return false;  // Not calling the ptr
457       }
458     } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
459       if (II->getOperand(0) != V) {
460         //std::cerr << "NONTRAPPING USE: " << **UI;
461         return false;  // Not calling the ptr
462       }
463     } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
464       if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
465     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
466       if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
467     } else if (isa<SetCondInst>(*UI) && 
468                isa<ConstantPointerNull>(UI->getOperand(1))) {
469       // Ignore setcc X, null
470     } else {
471       //std::cerr << "NONTRAPPING USE: " << **UI;
472       return false;
473     }
474   return true;
475 }
476
477 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
478 /// from GV will trap if the loaded value is null.  Note that this also permits
479 /// comparisons of the loaded value against null, as a special case.
480 static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
481   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
482     if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
483       if (!AllUsesOfValueWillTrapIfNull(LI))
484         return false;
485     } else if (isa<StoreInst>(*UI)) {
486       // Ignore stores to the global.
487     } else {
488       // We don't know or understand this user, bail out.
489       //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
490       return false;
491     }
492
493   return true;
494 }
495
496 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
497   bool Changed = false;
498   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
499     Instruction *I = cast<Instruction>(*UI++);
500     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
501       LI->setOperand(0, NewV);
502       Changed = true;
503     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
504       if (SI->getOperand(1) == V) {
505         SI->setOperand(1, NewV);
506         Changed = true;
507       }
508     } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
509       if (I->getOperand(0) == V) {
510         // Calling through the pointer!  Turn into a direct call, but be careful
511         // that the pointer is not also being passed as an argument.
512         I->setOperand(0, NewV);
513         Changed = true;
514         bool PassedAsArg = false;
515         for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
516           if (I->getOperand(i) == V) {
517             PassedAsArg = true;
518             I->setOperand(i, NewV);
519           }
520
521         if (PassedAsArg) {
522           // Being passed as an argument also.  Be careful to not invalidate UI!
523           UI = V->use_begin();
524         }
525       }
526     } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
527       Changed |= OptimizeAwayTrappingUsesOfValue(CI,
528                                     ConstantExpr::getCast(NewV, CI->getType()));
529       if (CI->use_empty()) {
530         Changed = true;
531         CI->eraseFromParent();
532       }
533     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
534       // Should handle GEP here.
535       std::vector<Constant*> Indices;
536       Indices.reserve(GEPI->getNumOperands()-1);
537       for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
538         if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
539           Indices.push_back(C);
540         else
541           break;
542       if (Indices.size() == GEPI->getNumOperands()-1)
543         Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
544                                 ConstantExpr::getGetElementPtr(NewV, Indices));
545       if (GEPI->use_empty()) {
546         Changed = true;
547         GEPI->eraseFromParent();
548       }
549     }
550   }
551
552   return Changed;
553 }
554
555
556 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
557 /// value stored into it.  If there are uses of the loaded value that would trap
558 /// if the loaded value is dynamically null, then we know that they cannot be
559 /// reachable with a null optimize away the load.
560 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
561   std::vector<LoadInst*> Loads;
562   bool Changed = false;
563
564   // Replace all uses of loads with uses of uses of the stored value.
565   for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
566        GUI != E; ++GUI)
567     if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
568       Loads.push_back(LI);
569       Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
570     } else {
571       assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
572     }
573
574   if (Changed) {
575     DEBUG(std::cerr << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
576     ++NumGlobUses;
577   }
578
579   // Delete all of the loads we can, keeping track of whether we nuked them all!
580   bool AllLoadsGone = true;
581   while (!Loads.empty()) {
582     LoadInst *L = Loads.back();
583     if (L->use_empty()) {
584       L->eraseFromParent();
585       Changed = true;
586     } else {
587       AllLoadsGone = false;
588     }
589     Loads.pop_back();
590   }
591
592   // If we nuked all of the loads, then none of the stores are needed either,
593   // nor is the global.
594   if (AllLoadsGone) {
595     DEBUG(std::cerr << "  *** GLOBAL NOW DEAD!\n");
596     CleanupConstantGlobalUsers(GV, 0);
597     if (GV->use_empty()) {
598       GV->eraseFromParent();
599       ++NumDeleted;
600     }
601     Changed = true;
602   }
603   return Changed;
604 }
605
606 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
607 /// instructions that are foldable.
608 static void ConstantPropUsersOf(Value *V) {
609   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
610     if (Instruction *I = dyn_cast<Instruction>(*UI++))
611       if (Constant *NewC = ConstantFoldInstruction(I)) {
612         I->replaceAllUsesWith(NewC);
613
614         // Back up UI to avoid invalidating it!
615         bool AtBegin = false;
616         if (UI == V->use_begin())
617           AtBegin = true;
618         else
619           --UI;
620         I->eraseFromParent();
621         if (AtBegin)
622           UI = V->use_begin();
623         else
624           ++UI;
625       }
626 }
627
628 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
629 /// variable, and transforms the program as if it always contained the result of
630 /// the specified malloc.  Because it is always the result of the specified
631 /// malloc, there is no reason to actually DO the malloc.  Instead, turn the
632 /// malloc into a global, and any laods of GV as uses of the new global.
633 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
634                                                      MallocInst *MI) {
635   DEBUG(std::cerr << "PROMOTING MALLOC GLOBAL: " << *GV << "  MALLOC = " <<*MI);
636   ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
637
638   if (NElements->getRawValue() != 1) {
639     // If we have an array allocation, transform it to a single element
640     // allocation to make the code below simpler.
641     Type *NewTy = ArrayType::get(MI->getAllocatedType(),
642                                  NElements->getRawValue());
643     MallocInst *NewMI =
644       new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy),
645                      MI->getName(), MI);
646     std::vector<Value*> Indices;
647     Indices.push_back(Constant::getNullValue(Type::IntTy));
648     Indices.push_back(Indices[0]);
649     Value *NewGEP = new GetElementPtrInst(NewMI, Indices,
650                                           NewMI->getName()+".el0", MI);
651     MI->replaceAllUsesWith(NewGEP);
652     MI->eraseFromParent();
653     MI = NewMI;
654   }
655   
656   // Create the new global variable.  The contents of the malloc'd memory is
657   // undefined, so initialize with an undef value.
658   Constant *Init = UndefValue::get(MI->getAllocatedType());
659   GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
660                                              GlobalValue::InternalLinkage, Init,
661                                              GV->getName()+".body");
662   GV->getParent()->getGlobalList().insert(GV, NewGV);
663   
664   // Anything that used the malloc now uses the global directly.
665   MI->replaceAllUsesWith(NewGV);
666
667   Constant *RepValue = NewGV;
668   if (NewGV->getType() != GV->getType()->getElementType())
669     RepValue = ConstantExpr::getCast(RepValue, GV->getType()->getElementType());
670
671   // If there is a comparison against null, we will insert a global bool to
672   // keep track of whether the global was initialized yet or not.
673   GlobalVariable *InitBool = 0;
674
675   // Loop over all uses of GV, processing them in turn.
676   while (!GV->use_empty())
677     if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
678       while (!LI->use_empty()) {
679         // FIXME: the iterator should expose a getUse() method.
680         Use &LoadUse = *(const iplist<Use>::iterator&)LI->use_begin();
681         if (!isa<SetCondInst>(LoadUse.getUser()))
682           LoadUse = RepValue;
683         else {
684           if (InitBool == 0) {
685             InitBool = new GlobalVariable(Type::BoolTy, false,
686                                           GlobalValue::InternalLinkage, 
687                                           ConstantBool::False,
688                                           GV->getName()+".init");
689             GV->getParent()->getGlobalList().insert(GV, InitBool);
690             // The global is initialized when the malloc is run.
691             new StoreInst(ConstantBool::True, InitBool, MI);
692           }
693           // Replace the setcc X, 0 with a use of the bool value.
694           SetCondInst *SCI = cast<SetCondInst>(LoadUse.getUser());
695           Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", SCI);
696           switch (SCI->getOpcode()) {
697           default: assert(0 && "Unknown opcode!");
698           case Instruction::SetLT:
699             LV = ConstantBool::False;   // X < null -> always false
700             break;
701           case Instruction::SetEQ:
702           case Instruction::SetLE:
703             LV = BinaryOperator::createNot(LV, "notinit", SCI);
704             break;
705           case Instruction::SetNE:
706           case Instruction::SetGE:
707           case Instruction::SetGT:
708             break;  // no change.
709           }
710           SCI->replaceAllUsesWith(LV);
711           SCI->eraseFromParent();
712         }
713       }
714       LI->eraseFromParent();
715     } else {
716       StoreInst *SI = cast<StoreInst>(GV->use_back());
717       SI->eraseFromParent();
718     }
719
720   // Now the GV is dead, nuke it and the malloc.
721   GV->eraseFromParent();
722   MI->eraseFromParent();
723
724   // To further other optimizations, loop over all users of NewGV and try to
725   // constant prop them.  This will promote GEP instructions with constant
726   // indices into GEP constant-exprs, which will allow global-opt to hack on it.
727   ConstantPropUsersOf(NewGV);
728   if (RepValue != NewGV)
729     ConstantPropUsersOf(RepValue);
730
731   return NewGV;
732 }
733
734 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
735 // that only one value (besides its initializer) is ever stored to the global.
736 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
737                                      Module::giterator &GVI, TargetData &TD) {
738   if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
739     StoredOnceVal = CI->getOperand(0);
740   else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
741     // "getelementptr Ptr, 0, 0, 0" is really just a cast.
742     bool IsJustACast = true;
743     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
744       if (!isa<Constant>(GEPI->getOperand(i)) ||
745           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
746         IsJustACast = false;
747         break;
748       }
749     if (IsJustACast)
750       StoredOnceVal = GEPI->getOperand(0);
751   }
752
753   // If we are dealing with a pointer global that is initialized to null and
754   // only has one (non-null) value stored into it, then we can optimize any
755   // users of the loaded value (often calls and loads) that would trap if the
756   // value was null.
757   if (isa<PointerType>(GV->getInitializer()->getType()) &&
758       GV->getInitializer()->isNullValue()) {
759     if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
760       if (GV->getInitializer()->getType() != SOVC->getType())
761         SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType());
762       
763       // Optimize away any trapping uses of the loaded value.
764       if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
765         return true;
766     } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
767       // If we have a global that is only initialized with a fixed size malloc,
768       // and if all users of the malloc trap, and if the malloc'd address is not
769       // put anywhere else, transform the program to use global memory instead
770       // of malloc'd memory.  This eliminates dynamic allocation (good) and
771       // exposes the resultant global to further GlobalOpt (even better).  Note
772       // that we restrict this transformation to only working on small
773       // allocations (2048 bytes currently), as we don't want to introduce a 16M
774       // global or something.
775       if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize()))
776         if (MI->getAllocatedType()->isSized() &&
777             NElements->getRawValue()*
778                      TD.getTypeSize(MI->getAllocatedType()) < 2048 &&
779             AllUsesOfLoadedValueWillTrapIfNull(GV)) {
780           // FIXME: do more correctness checking to make sure the result of the
781           // malloc isn't squirrelled away somewhere.
782           GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
783           return true;
784         }
785     }
786   }
787
788   return false;
789 }
790
791 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
792 /// it if possible.  If we make a change, return true.
793 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
794                                       Module::giterator &GVI) {
795   std::set<PHINode*> PHIUsers;
796   GlobalStatus GS;
797   PHIUsers.clear();
798   GV->removeDeadConstantUsers();
799
800   if (GV->use_empty()) {
801     DEBUG(std::cerr << "GLOBAL DEAD: " << *GV);
802     GV->eraseFromParent();
803     ++NumDeleted;
804     return true;
805   }
806
807   if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
808     // If the global is never loaded (but may be stored to), it is dead.
809     // Delete it now.
810     if (!GS.isLoaded) {
811       DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV);
812
813       // Delete any stores we can find to the global.  We may not be able to
814       // make it completely dead though.
815       bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
816
817       // If the global is dead now, delete it.
818       if (GV->use_empty()) {
819         GV->eraseFromParent();
820         ++NumDeleted;
821         Changed = true;
822       }
823       return Changed;
824           
825     } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
826       DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
827       GV->setConstant(true);
828           
829       // Clean up any obviously simplifiable users now.
830       CleanupConstantGlobalUsers(GV, GV->getInitializer());
831           
832       // If the global is dead now, just nuke it.
833       if (GV->use_empty()) {
834         DEBUG(std::cerr << "   *** Marking constant allowed us to simplify "
835               "all users and delete global!\n");
836         GV->eraseFromParent();
837         ++NumDeleted;
838       }
839           
840       ++NumMarked;
841       return true;
842     } else if (!GS.isNotSuitableForSRA &&
843                !GV->getInitializer()->getType()->isFirstClassType()) {
844       if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
845         GVI = FirstNewGV;  // Don't skip the newly produced globals!
846         return true;
847       }
848     } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
849       // If the initial value for the global was an undef value, and if only one
850       // other value was stored into it, we can just change the initializer to
851       // be an undef value, then delete all stores to the global.  This allows
852       // us to mark it constant.
853       if (isa<UndefValue>(GV->getInitializer()) &&
854           isa<Constant>(GS.StoredOnceValue)) {
855         // Change the initial value here.
856         GV->setInitializer(cast<Constant>(GS.StoredOnceValue));
857         
858         // Clean up any obviously simplifiable users now.
859         CleanupConstantGlobalUsers(GV, GV->getInitializer());
860
861         if (GV->use_empty()) {
862           DEBUG(std::cerr << "   *** Substituting initializer allowed us to "
863                 "simplify all users and delete global!\n");
864           GV->eraseFromParent();
865           ++NumDeleted;
866         } else {
867           GVI = GV;
868         }
869         ++NumSubstitute;
870         return true;
871       }
872
873       // Try to optimize globals based on the knowledge that only one value
874       // (besides its initializer) is ever stored to the global.
875       if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
876                                    getAnalysis<TargetData>()))
877         return true;
878     }
879   }
880   return false;
881 }
882
883
884 bool GlobalOpt::runOnModule(Module &M) {
885   bool Changed = false;
886
887   // As a prepass, delete functions that are trivially dead.
888   bool LocalChange = true;
889   while (LocalChange) {
890     LocalChange = false;
891     for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
892       Function *F = FI++;
893       F->removeDeadConstantUsers();
894       if (F->use_empty() && (F->hasInternalLinkage() ||
895                              F->hasLinkOnceLinkage())) {
896         M.getFunctionList().erase(F);
897         LocalChange = true;
898         ++NumFnDeleted;
899       }
900     }
901     Changed |= LocalChange;
902   }
903
904   LocalChange = true;
905   while (LocalChange) {
906     LocalChange = false;
907     for (Module::giterator GVI = M.gbegin(), E = M.gend(); GVI != E;) {
908       GlobalVariable *GV = GVI++;
909       if (!GV->isConstant() && GV->hasInternalLinkage() &&
910           GV->hasInitializer())
911         LocalChange |= ProcessInternalGlobal(GV, GVI);
912     }
913     Changed |= LocalChange;
914   }
915   return Changed;
916 }