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