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