Fix bug where array malloc with unexpected computation of the size argument resulted...
[oota-llvm.git] / lib / Transforms / IPO / GlobalOpt.cpp
1 //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass transforms simple global variables that never have their address
11 // taken.  If obviously true, it marks read/write globals as constant, deletes
12 // variables only stored to, etc.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "globalopt"
17 #include "llvm/Transforms/IPO.h"
18 #include "llvm/CallingConv.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/IntrinsicInst.h"
23 #include "llvm/LLVMContext.h"
24 #include "llvm/Module.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Analysis/ConstantFolding.h"
27 #include "llvm/Analysis/MallocHelper.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Support/CallSite.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/GetElementPtrTypeIterator.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include <algorithm>
42 using namespace llvm;
43
44 STATISTIC(NumMarked    , "Number of globals marked constant");
45 STATISTIC(NumSRA       , "Number of aggregate globals broken into scalars");
46 STATISTIC(NumHeapSRA   , "Number of heap objects SRA'd");
47 STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
48 STATISTIC(NumDeleted   , "Number of globals deleted");
49 STATISTIC(NumFnDeleted , "Number of functions deleted");
50 STATISTIC(NumGlobUses  , "Number of global uses devirtualized");
51 STATISTIC(NumLocalized , "Number of globals localized");
52 STATISTIC(NumShrunkToBool  , "Number of global vars shrunk to booleans");
53 STATISTIC(NumFastCallFns   , "Number of functions converted to fastcc");
54 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
55 STATISTIC(NumNestRemoved   , "Number of nest attributes removed");
56 STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
57 STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
58
59 namespace {
60   struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
61     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
62     }
63     static char ID; // Pass identification, replacement for typeid
64     GlobalOpt() : ModulePass(&ID) {}
65
66     bool runOnModule(Module &M);
67
68   private:
69     GlobalVariable *FindGlobalCtors(Module &M);
70     bool OptimizeFunctions(Module &M);
71     bool OptimizeGlobalVars(Module &M);
72     bool OptimizeGlobalAliases(Module &M);
73     bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
74     bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
75   };
76 }
77
78 char GlobalOpt::ID = 0;
79 static RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
80
81 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
82
83 namespace {
84
85 /// GlobalStatus - As we analyze each global, keep track of some information
86 /// about it.  If we find out that the address of the global is taken, none of
87 /// this info will be accurate.
88 struct VISIBILITY_HIDDEN GlobalStatus {
89   /// isLoaded - True if the global is ever loaded.  If the global isn't ever
90   /// loaded it can be deleted.
91   bool isLoaded;
92
93   /// StoredType - Keep track of what stores to the global look like.
94   ///
95   enum StoredType {
96     /// NotStored - There is no store to this global.  It can thus be marked
97     /// constant.
98     NotStored,
99
100     /// isInitializerStored - This global is stored to, but the only thing
101     /// stored is the constant it was initialized with.  This is only tracked
102     /// for scalar globals.
103     isInitializerStored,
104
105     /// isStoredOnce - This global is stored to, but only its initializer and
106     /// one other value is ever stored to it.  If this global isStoredOnce, we
107     /// track the value stored to it in StoredOnceValue below.  This is only
108     /// tracked for scalar globals.
109     isStoredOnce,
110
111     /// isStored - This global is stored to by multiple values or something else
112     /// that we cannot track.
113     isStored
114   } StoredType;
115
116   /// StoredOnceValue - If only one value (besides the initializer constant) is
117   /// ever stored to this global, keep track of what value it is.
118   Value *StoredOnceValue;
119
120   /// AccessingFunction/HasMultipleAccessingFunctions - These start out
121   /// null/false.  When the first accessing function is noticed, it is recorded.
122   /// When a second different accessing function is noticed,
123   /// HasMultipleAccessingFunctions is set to true.
124   Function *AccessingFunction;
125   bool HasMultipleAccessingFunctions;
126
127   /// HasNonInstructionUser - Set to true if this global has a user that is not
128   /// an instruction (e.g. a constant expr or GV initializer).
129   bool HasNonInstructionUser;
130
131   /// HasPHIUser - Set to true if this global has a user that is a PHI node.
132   bool HasPHIUser;
133   
134   GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
135                    AccessingFunction(0), HasMultipleAccessingFunctions(false),
136                    HasNonInstructionUser(false), HasPHIUser(false) {}
137 };
138
139 }
140
141 // SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
142 // by constants itself.  Note that constants cannot be cyclic, so this test is
143 // pretty easy to implement recursively.
144 //
145 static bool SafeToDestroyConstant(Constant *C) {
146   if (isa<GlobalValue>(C)) return false;
147
148   for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
149     if (Constant *CU = dyn_cast<Constant>(*UI)) {
150       if (!SafeToDestroyConstant(CU)) return false;
151     } else
152       return false;
153   return true;
154 }
155
156
157 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
158 /// structure.  If the global has its address taken, return true to indicate we
159 /// can't do anything with it.
160 ///
161 static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
162                           SmallPtrSet<PHINode*, 16> &PHIUsers) {
163   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
164     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
165       GS.HasNonInstructionUser = true;
166
167       if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
168
169     } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
170       if (!GS.HasMultipleAccessingFunctions) {
171         Function *F = I->getParent()->getParent();
172         if (GS.AccessingFunction == 0)
173           GS.AccessingFunction = F;
174         else if (GS.AccessingFunction != F)
175           GS.HasMultipleAccessingFunctions = true;
176       }
177       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
178         GS.isLoaded = true;
179         if (LI->isVolatile()) return true;  // Don't hack on volatile loads.
180       } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
181         // Don't allow a store OF the address, only stores TO the address.
182         if (SI->getOperand(0) == V) return true;
183
184         if (SI->isVolatile()) return true;  // Don't hack on volatile stores.
185
186         // If this is a direct store to the global (i.e., the global is a scalar
187         // value, not an aggregate), keep more specific information about
188         // stores.
189         if (GS.StoredType != GlobalStatus::isStored) {
190           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
191             Value *StoredVal = SI->getOperand(0);
192             if (StoredVal == GV->getInitializer()) {
193               if (GS.StoredType < GlobalStatus::isInitializerStored)
194                 GS.StoredType = GlobalStatus::isInitializerStored;
195             } else if (isa<LoadInst>(StoredVal) &&
196                        cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
197               // G = G
198               if (GS.StoredType < GlobalStatus::isInitializerStored)
199                 GS.StoredType = GlobalStatus::isInitializerStored;
200             } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
201               GS.StoredType = GlobalStatus::isStoredOnce;
202               GS.StoredOnceValue = StoredVal;
203             } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
204                        GS.StoredOnceValue == StoredVal) {
205               // noop.
206             } else {
207               GS.StoredType = GlobalStatus::isStored;
208             }
209           } else {
210             GS.StoredType = GlobalStatus::isStored;
211           }
212         }
213       } else if (isa<GetElementPtrInst>(I)) {
214         if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
215       } else if (isa<SelectInst>(I)) {
216         if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
217       } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
218         // PHI nodes we can check just like select or GEP instructions, but we
219         // have to be careful about infinite recursion.
220         if (PHIUsers.insert(PN))  // Not already visited.
221           if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
222         GS.HasPHIUser = true;
223       } else if (isa<CmpInst>(I)) {
224       } else if (isa<MemTransferInst>(I)) {
225         if (I->getOperand(1) == V)
226           GS.StoredType = GlobalStatus::isStored;
227         if (I->getOperand(2) == V)
228           GS.isLoaded = true;
229       } else if (isa<MemSetInst>(I)) {
230         assert(I->getOperand(1) == V && "Memset only takes one pointer!");
231         GS.StoredType = GlobalStatus::isStored;
232       } else {
233         return true;  // Any other non-load instruction might take address!
234       }
235     } else if (Constant *C = dyn_cast<Constant>(*UI)) {
236       GS.HasNonInstructionUser = true;
237       // We might have a dead and dangling constant hanging off of here.
238       if (!SafeToDestroyConstant(C))
239         return true;
240     } else {
241       GS.HasNonInstructionUser = true;
242       // Otherwise must be some other user.
243       return true;
244     }
245
246   return false;
247 }
248
249 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx,
250                                              LLVMContext &Context) {
251   ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
252   if (!CI) return 0;
253   unsigned IdxV = CI->getZExtValue();
254
255   if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
256     if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
257   } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
258     if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
259   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
260     if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
261   } else if (isa<ConstantAggregateZero>(Agg)) {
262     if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
263       if (IdxV < STy->getNumElements())
264         return Constant::getNullValue(STy->getElementType(IdxV));
265     } else if (const SequentialType *STy =
266                dyn_cast<SequentialType>(Agg->getType())) {
267       return Constant::getNullValue(STy->getElementType());
268     }
269   } else if (isa<UndefValue>(Agg)) {
270     if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
271       if (IdxV < STy->getNumElements())
272         return UndefValue::get(STy->getElementType(IdxV));
273     } else if (const SequentialType *STy =
274                dyn_cast<SequentialType>(Agg->getType())) {
275       return UndefValue::get(STy->getElementType());
276     }
277   }
278   return 0;
279 }
280
281
282 /// CleanupConstantGlobalUsers - We just marked GV constant.  Loop over all
283 /// users of the global, cleaning up the obvious ones.  This is largely just a
284 /// quick scan over the use list to clean up the easy and obvious cruft.  This
285 /// returns true if it made a change.
286 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
287                                        LLVMContext &Context) {
288   bool Changed = false;
289   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
290     User *U = *UI++;
291
292     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
293       if (Init) {
294         // Replace the load with the initializer.
295         LI->replaceAllUsesWith(Init);
296         LI->eraseFromParent();
297         Changed = true;
298       }
299     } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
300       // Store must be unreachable or storing Init into the global.
301       SI->eraseFromParent();
302       Changed = true;
303     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
304       if (CE->getOpcode() == Instruction::GetElementPtr) {
305         Constant *SubInit = 0;
306         if (Init)
307           SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
308         Changed |= CleanupConstantGlobalUsers(CE, SubInit, Context);
309       } else if (CE->getOpcode() == Instruction::BitCast && 
310                  isa<PointerType>(CE->getType())) {
311         // Pointer cast, delete any stores and memsets to the global.
312         Changed |= CleanupConstantGlobalUsers(CE, 0, Context);
313       }
314
315       if (CE->use_empty()) {
316         CE->destroyConstant();
317         Changed = true;
318       }
319     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
320       // Do not transform "gepinst (gep constexpr (GV))" here, because forming
321       // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
322       // and will invalidate our notion of what Init is.
323       Constant *SubInit = 0;
324       if (!isa<ConstantExpr>(GEP->getOperand(0))) {
325         ConstantExpr *CE = 
326           dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, Context));
327         if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
328           SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
329       }
330       Changed |= CleanupConstantGlobalUsers(GEP, SubInit, Context);
331
332       if (GEP->use_empty()) {
333         GEP->eraseFromParent();
334         Changed = true;
335       }
336     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
337       if (MI->getRawDest() == V) {
338         MI->eraseFromParent();
339         Changed = true;
340       }
341
342     } else if (Constant *C = dyn_cast<Constant>(U)) {
343       // If we have a chain of dead constantexprs or other things dangling from
344       // us, and if they are all dead, nuke them without remorse.
345       if (SafeToDestroyConstant(C)) {
346         C->destroyConstant();
347         // This could have invalidated UI, start over from scratch.
348         CleanupConstantGlobalUsers(V, Init, Context);
349         return true;
350       }
351     }
352   }
353   return Changed;
354 }
355
356 /// isSafeSROAElementUse - Return true if the specified instruction is a safe
357 /// user of a derived expression from a global that we want to SROA.
358 static bool isSafeSROAElementUse(Value *V) {
359   // We might have a dead and dangling constant hanging off of here.
360   if (Constant *C = dyn_cast<Constant>(V))
361     return SafeToDestroyConstant(C);
362   
363   Instruction *I = dyn_cast<Instruction>(V);
364   if (!I) return false;
365
366   // Loads are ok.
367   if (isa<LoadInst>(I)) return true;
368
369   // Stores *to* the pointer are ok.
370   if (StoreInst *SI = dyn_cast<StoreInst>(I))
371     return SI->getOperand(0) != V;
372     
373   // Otherwise, it must be a GEP.
374   GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
375   if (GEPI == 0) return false;
376   
377   if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
378       !cast<Constant>(GEPI->getOperand(1))->isNullValue())
379     return false;
380   
381   for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
382        I != E; ++I)
383     if (!isSafeSROAElementUse(*I))
384       return false;
385   return true;
386 }
387
388
389 /// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
390 /// Look at it and its uses and decide whether it is safe to SROA this global.
391 ///
392 static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
393   // The user of the global must be a GEP Inst or a ConstantExpr GEP.
394   if (!isa<GetElementPtrInst>(U) && 
395       (!isa<ConstantExpr>(U) || 
396        cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
397     return false;
398   
399   // Check to see if this ConstantExpr GEP is SRA'able.  In particular, we
400   // don't like < 3 operand CE's, and we don't like non-constant integer
401   // indices.  This enforces that all uses are 'gep GV, 0, C, ...' for some
402   // value of C.
403   if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
404       !cast<Constant>(U->getOperand(1))->isNullValue() ||
405       !isa<ConstantInt>(U->getOperand(2)))
406     return false;
407
408   gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
409   ++GEPI;  // Skip over the pointer index.
410   
411   // If this is a use of an array allocation, do a bit more checking for sanity.
412   if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
413     uint64_t NumElements = AT->getNumElements();
414     ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
415     
416     // Check to make sure that index falls within the array.  If not,
417     // something funny is going on, so we won't do the optimization.
418     //
419     if (Idx->getZExtValue() >= NumElements)
420       return false;
421       
422     // We cannot scalar repl this level of the array unless any array
423     // sub-indices are in-range constants.  In particular, consider:
424     // A[0][i].  We cannot know that the user isn't doing invalid things like
425     // allowing i to index an out-of-range subscript that accesses A[1].
426     //
427     // Scalar replacing *just* the outer index of the array is probably not
428     // going to be a win anyway, so just give up.
429     for (++GEPI; // Skip array index.
430          GEPI != E;
431          ++GEPI) {
432       uint64_t NumElements;
433       if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
434         NumElements = SubArrayTy->getNumElements();
435       else if (const VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
436         NumElements = SubVectorTy->getNumElements();
437       else {
438         assert(isa<StructType>(*GEPI) &&
439                "Indexed GEP type is not array, vector, or struct!");
440         continue;
441       }
442       
443       ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
444       if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
445         return false;
446     }
447   }
448
449   for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
450     if (!isSafeSROAElementUse(*I))
451       return false;
452   return true;
453 }
454
455 /// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
456 /// is safe for us to perform this transformation.
457 ///
458 static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
459   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
460        UI != E; ++UI) {
461     if (!IsUserOfGlobalSafeForSRA(*UI, GV))
462       return false;
463   }
464   return true;
465 }
466  
467
468 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
469 /// variable.  This opens the door for other optimizations by exposing the
470 /// behavior of the program in a more fine-grained way.  We have determined that
471 /// this transformation is safe already.  We return the first global variable we
472 /// insert so that the caller can reprocess it.
473 static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD,
474                                  LLVMContext &Context) {
475   // Make sure this global only has simple uses that we can SRA.
476   if (!GlobalUsersSafeToSRA(GV))
477     return 0;
478   
479   assert(GV->hasLocalLinkage() && !GV->isConstant());
480   Constant *Init = GV->getInitializer();
481   const Type *Ty = Init->getType();
482
483   std::vector<GlobalVariable*> NewGlobals;
484   Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
485
486   // Get the alignment of the global, either explicit or target-specific.
487   unsigned StartAlignment = GV->getAlignment();
488   if (StartAlignment == 0)
489     StartAlignment = TD.getABITypeAlignment(GV->getType());
490    
491   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
492     NewGlobals.reserve(STy->getNumElements());
493     const StructLayout &Layout = *TD.getStructLayout(STy);
494     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
495       Constant *In = getAggregateConstantElement(Init,
496                                 ConstantInt::get(Type::getInt32Ty(Context), i),
497                                     Context);
498       assert(In && "Couldn't get element of initializer?");
499       GlobalVariable *NGV = new GlobalVariable(Context,
500                                                STy->getElementType(i), false,
501                                                GlobalVariable::InternalLinkage,
502                                                In, GV->getName()+"."+Twine(i),
503                                                GV->isThreadLocal(),
504                                               GV->getType()->getAddressSpace());
505       Globals.insert(GV, NGV);
506       NewGlobals.push_back(NGV);
507       
508       // Calculate the known alignment of the field.  If the original aggregate
509       // had 256 byte alignment for example, something might depend on that:
510       // propagate info to each field.
511       uint64_t FieldOffset = Layout.getElementOffset(i);
512       unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
513       if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
514         NGV->setAlignment(NewAlign);
515     }
516   } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
517     unsigned NumElements = 0;
518     if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
519       NumElements = ATy->getNumElements();
520     else
521       NumElements = cast<VectorType>(STy)->getNumElements();
522
523     if (NumElements > 16 && GV->hasNUsesOrMore(16))
524       return 0; // It's not worth it.
525     NewGlobals.reserve(NumElements);
526     
527     uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
528     unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
529     for (unsigned i = 0, e = NumElements; i != e; ++i) {
530       Constant *In = getAggregateConstantElement(Init,
531                                 ConstantInt::get(Type::getInt32Ty(Context), i),
532                                     Context);
533       assert(In && "Couldn't get element of initializer?");
534
535       GlobalVariable *NGV = new GlobalVariable(Context,
536                                                STy->getElementType(), false,
537                                                GlobalVariable::InternalLinkage,
538                                                In, GV->getName()+"."+Twine(i),
539                                                GV->isThreadLocal(),
540                                               GV->getType()->getAddressSpace());
541       Globals.insert(GV, NGV);
542       NewGlobals.push_back(NGV);
543       
544       // Calculate the known alignment of the field.  If the original aggregate
545       // had 256 byte alignment for example, something might depend on that:
546       // propagate info to each field.
547       unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
548       if (NewAlign > EltAlign)
549         NGV->setAlignment(NewAlign);
550     }
551   }
552
553   if (NewGlobals.empty())
554     return 0;
555
556   DEBUG(errs() << "PERFORMING GLOBAL SRA ON: " << *GV);
557
558   Constant *NullInt = Constant::getNullValue(Type::getInt32Ty(Context));
559
560   // Loop over all of the uses of the global, replacing the constantexpr geps,
561   // with smaller constantexpr geps or direct references.
562   while (!GV->use_empty()) {
563     User *GEP = GV->use_back();
564     assert(((isa<ConstantExpr>(GEP) &&
565              cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
566             isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
567
568     // Ignore the 1th operand, which has to be zero or else the program is quite
569     // broken (undefined).  Get the 2nd operand, which is the structure or array
570     // index.
571     unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
572     if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
573
574     Value *NewPtr = NewGlobals[Val];
575
576     // Form a shorter GEP if needed.
577     if (GEP->getNumOperands() > 3) {
578       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
579         SmallVector<Constant*, 8> Idxs;
580         Idxs.push_back(NullInt);
581         for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
582           Idxs.push_back(CE->getOperand(i));
583         NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
584                                                 &Idxs[0], Idxs.size());
585       } else {
586         GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
587         SmallVector<Value*, 8> Idxs;
588         Idxs.push_back(NullInt);
589         for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
590           Idxs.push_back(GEPI->getOperand(i));
591         NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
592                                            GEPI->getName()+"."+Twine(Val),GEPI);
593       }
594     }
595     GEP->replaceAllUsesWith(NewPtr);
596
597     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
598       GEPI->eraseFromParent();
599     else
600       cast<ConstantExpr>(GEP)->destroyConstant();
601   }
602
603   // Delete the old global, now that it is dead.
604   Globals.erase(GV);
605   ++NumSRA;
606
607   // Loop over the new globals array deleting any globals that are obviously
608   // dead.  This can arise due to scalarization of a structure or an array that
609   // has elements that are dead.
610   unsigned FirstGlobal = 0;
611   for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
612     if (NewGlobals[i]->use_empty()) {
613       Globals.erase(NewGlobals[i]);
614       if (FirstGlobal == i) ++FirstGlobal;
615     }
616
617   return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
618 }
619
620 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
621 /// value will trap if the value is dynamically null.  PHIs keeps track of any 
622 /// phi nodes we've seen to avoid reprocessing them.
623 static bool AllUsesOfValueWillTrapIfNull(Value *V,
624                                          SmallPtrSet<PHINode*, 8> &PHIs) {
625   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
626     if (isa<LoadInst>(*UI)) {
627       // Will trap.
628     } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
629       if (SI->getOperand(0) == V) {
630         //cerr << "NONTRAPPING USE: " << **UI;
631         return false;  // Storing the value.
632       }
633     } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
634       if (CI->getOperand(0) != V) {
635         //cerr << "NONTRAPPING USE: " << **UI;
636         return false;  // Not calling the ptr
637       }
638     } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
639       if (II->getOperand(0) != V) {
640         //cerr << "NONTRAPPING USE: " << **UI;
641         return false;  // Not calling the ptr
642       }
643     } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
644       if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
645     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
646       if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
647     } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
648       // If we've already seen this phi node, ignore it, it has already been
649       // checked.
650       if (PHIs.insert(PN))
651         return AllUsesOfValueWillTrapIfNull(PN, PHIs);
652     } else if (isa<ICmpInst>(*UI) &&
653                isa<ConstantPointerNull>(UI->getOperand(1))) {
654       // Ignore setcc X, null
655     } else {
656       //cerr << "NONTRAPPING USE: " << **UI;
657       return false;
658     }
659   return true;
660 }
661
662 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
663 /// from GV will trap if the loaded value is null.  Note that this also permits
664 /// comparisons of the loaded value against null, as a special case.
665 static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
666   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
667     if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
668       SmallPtrSet<PHINode*, 8> PHIs;
669       if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
670         return false;
671     } else if (isa<StoreInst>(*UI)) {
672       // Ignore stores to the global.
673     } else {
674       // We don't know or understand this user, bail out.
675       //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
676       return false;
677     }
678
679   return true;
680 }
681
682 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV,
683                                            LLVMContext &Context) {
684   bool Changed = false;
685   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
686     Instruction *I = cast<Instruction>(*UI++);
687     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
688       LI->setOperand(0, NewV);
689       Changed = true;
690     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
691       if (SI->getOperand(1) == V) {
692         SI->setOperand(1, NewV);
693         Changed = true;
694       }
695     } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
696       if (I->getOperand(0) == V) {
697         // Calling through the pointer!  Turn into a direct call, but be careful
698         // that the pointer is not also being passed as an argument.
699         I->setOperand(0, NewV);
700         Changed = true;
701         bool PassedAsArg = false;
702         for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
703           if (I->getOperand(i) == V) {
704             PassedAsArg = true;
705             I->setOperand(i, NewV);
706           }
707
708         if (PassedAsArg) {
709           // Being passed as an argument also.  Be careful to not invalidate UI!
710           UI = V->use_begin();
711         }
712       }
713     } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
714       Changed |= OptimizeAwayTrappingUsesOfValue(CI,
715                                 ConstantExpr::getCast(CI->getOpcode(),
716                                                 NewV, CI->getType()), Context);
717       if (CI->use_empty()) {
718         Changed = true;
719         CI->eraseFromParent();
720       }
721     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
722       // Should handle GEP here.
723       SmallVector<Constant*, 8> Idxs;
724       Idxs.reserve(GEPI->getNumOperands()-1);
725       for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
726            i != e; ++i)
727         if (Constant *C = dyn_cast<Constant>(*i))
728           Idxs.push_back(C);
729         else
730           break;
731       if (Idxs.size() == GEPI->getNumOperands()-1)
732         Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
733                           ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
734                                                         Idxs.size()), Context);
735       if (GEPI->use_empty()) {
736         Changed = true;
737         GEPI->eraseFromParent();
738       }
739     }
740   }
741
742   return Changed;
743 }
744
745
746 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
747 /// value stored into it.  If there are uses of the loaded value that would trap
748 /// if the loaded value is dynamically null, then we know that they cannot be
749 /// reachable with a null optimize away the load.
750 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
751                                             LLVMContext &Context) {
752   bool Changed = false;
753
754   // Keep track of whether we are able to remove all the uses of the global
755   // other than the store that defines it.
756   bool AllNonStoreUsesGone = true;
757   
758   // Replace all uses of loads with uses of uses of the stored value.
759   for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
760     User *GlobalUser = *GUI++;
761     if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
762       Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV, Context);
763       // If we were able to delete all uses of the loads
764       if (LI->use_empty()) {
765         LI->eraseFromParent();
766         Changed = true;
767       } else {
768         AllNonStoreUsesGone = false;
769       }
770     } else if (isa<StoreInst>(GlobalUser)) {
771       // Ignore the store that stores "LV" to the global.
772       assert(GlobalUser->getOperand(1) == GV &&
773              "Must be storing *to* the global");
774     } else {
775       AllNonStoreUsesGone = false;
776
777       // If we get here we could have other crazy uses that are transitively
778       // loaded.
779       assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
780               isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
781     }
782   }
783
784   if (Changed) {
785     DEBUG(errs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
786     ++NumGlobUses;
787   }
788
789   // If we nuked all of the loads, then none of the stores are needed either,
790   // nor is the global.
791   if (AllNonStoreUsesGone) {
792     DEBUG(errs() << "  *** GLOBAL NOW DEAD!\n");
793     CleanupConstantGlobalUsers(GV, 0, Context);
794     if (GV->use_empty()) {
795       GV->eraseFromParent();
796       ++NumDeleted;
797     }
798     Changed = true;
799   }
800   return Changed;
801 }
802
803 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
804 /// instructions that are foldable.
805 static void ConstantPropUsersOf(Value *V, LLVMContext &Context) {
806   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
807     if (Instruction *I = dyn_cast<Instruction>(*UI++))
808       if (Constant *NewC = ConstantFoldInstruction(I, Context)) {
809         I->replaceAllUsesWith(NewC);
810
811         // Advance UI to the next non-I use to avoid invalidating it!
812         // Instructions could multiply use V.
813         while (UI != E && *UI == I)
814           ++UI;
815         I->eraseFromParent();
816       }
817 }
818
819 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
820 /// variable, and transforms the program as if it always contained the result of
821 /// the specified malloc.  Because it is always the result of the specified
822 /// malloc, there is no reason to actually DO the malloc.  Instead, turn the
823 /// malloc into a global, and any loads of GV as uses of the new global.
824 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
825                                                      MallocInst *MI,
826                                                      LLVMContext &Context) {
827   DEBUG(errs() << "PROMOTING MALLOC GLOBAL: " << *GV << "  MALLOC = " << *MI);
828   ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
829
830   if (NElements->getZExtValue() != 1) {
831     // If we have an array allocation, transform it to a single element
832     // allocation to make the code below simpler.
833     Type *NewTy = ArrayType::get(MI->getAllocatedType(),
834                                  NElements->getZExtValue());
835     MallocInst *NewMI =
836       new MallocInst(NewTy, Constant::getNullValue(Type::getInt32Ty(Context)),
837                      MI->getAlignment(), MI->getName(), MI);
838     Value* Indices[2];
839     Indices[0] = Indices[1] = Constant::getNullValue(Type::getInt32Ty(Context));
840     Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
841                                               NewMI->getName()+".el0", MI);
842     MI->replaceAllUsesWith(NewGEP);
843     MI->eraseFromParent();
844     MI = NewMI;
845   }
846
847   // Create the new global variable.  The contents of the malloc'd memory is
848   // undefined, so initialize with an undef value.
849   // FIXME: This new global should have the alignment returned by malloc.  Code
850   // could depend on malloc returning large alignment (on the mac, 16 bytes) but
851   // this would only guarantee some lower alignment.
852   Constant *Init = UndefValue::get(MI->getAllocatedType());
853   GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(), 
854                                              MI->getAllocatedType(), false,
855                                              GlobalValue::InternalLinkage, Init,
856                                              GV->getName()+".body",
857                                              GV,
858                                              GV->isThreadLocal());
859   
860   // Anything that used the malloc now uses the global directly.
861   MI->replaceAllUsesWith(NewGV);
862
863   Constant *RepValue = NewGV;
864   if (NewGV->getType() != GV->getType()->getElementType())
865     RepValue = ConstantExpr::getBitCast(RepValue, 
866                                         GV->getType()->getElementType());
867
868   // If there is a comparison against null, we will insert a global bool to
869   // keep track of whether the global was initialized yet or not.
870   GlobalVariable *InitBool =
871     new GlobalVariable(Context, Type::getInt1Ty(Context), false,
872                        GlobalValue::InternalLinkage,
873                        ConstantInt::getFalse(Context), GV->getName()+".init",
874                        GV->isThreadLocal());
875   bool InitBoolUsed = false;
876
877   // Loop over all uses of GV, processing them in turn.
878   std::vector<StoreInst*> Stores;
879   while (!GV->use_empty())
880     if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
881       while (!LI->use_empty()) {
882         Use &LoadUse = LI->use_begin().getUse();
883         if (!isa<ICmpInst>(LoadUse.getUser()))
884           LoadUse = RepValue;
885         else {
886           ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
887           // Replace the cmp X, 0 with a use of the bool value.
888           Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
889           InitBoolUsed = true;
890           switch (CI->getPredicate()) {
891           default: llvm_unreachable("Unknown ICmp Predicate!");
892           case ICmpInst::ICMP_ULT:
893           case ICmpInst::ICMP_SLT:
894             LV = ConstantInt::getFalse(Context);   // X < null -> always false
895             break;
896           case ICmpInst::ICMP_ULE:
897           case ICmpInst::ICMP_SLE:
898           case ICmpInst::ICMP_EQ:
899             LV = BinaryOperator::CreateNot(LV, "notinit", CI);
900             break;
901           case ICmpInst::ICMP_NE:
902           case ICmpInst::ICMP_UGE:
903           case ICmpInst::ICMP_SGE:
904           case ICmpInst::ICMP_UGT:
905           case ICmpInst::ICMP_SGT:
906             break;  // no change.
907           }
908           CI->replaceAllUsesWith(LV);
909           CI->eraseFromParent();
910         }
911       }
912       LI->eraseFromParent();
913     } else {
914       StoreInst *SI = cast<StoreInst>(GV->use_back());
915       // The global is initialized when the store to it occurs.
916       new StoreInst(ConstantInt::getTrue(Context), InitBool, SI);
917       SI->eraseFromParent();
918     }
919
920   // If the initialization boolean was used, insert it, otherwise delete it.
921   if (!InitBoolUsed) {
922     while (!InitBool->use_empty())  // Delete initializations
923       cast<Instruction>(InitBool->use_back())->eraseFromParent();
924     delete InitBool;
925   } else
926     GV->getParent()->getGlobalList().insert(GV, InitBool);
927
928
929   // Now the GV is dead, nuke it and the malloc.
930   GV->eraseFromParent();
931   MI->eraseFromParent();
932
933   // To further other optimizations, loop over all users of NewGV and try to
934   // constant prop them.  This will promote GEP instructions with constant
935   // indices into GEP constant-exprs, which will allow global-opt to hack on it.
936   ConstantPropUsersOf(NewGV, Context);
937   if (RepValue != NewGV)
938     ConstantPropUsersOf(RepValue, Context);
939
940   return NewGV;
941 }
942
943 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
944 /// variable, and transforms the program as if it always contained the result of
945 /// the specified malloc.  Because it is always the result of the specified
946 /// malloc, there is no reason to actually DO the malloc.  Instead, turn the
947 /// malloc into a global, and any loads of GV as uses of the new global.
948 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
949                                                      CallInst *CI,
950                                                      BitCastInst *BCI,
951                                                      LLVMContext &Context,
952                                                      TargetData* TD) {
953   DEBUG(errs() << "PROMOTING MALLOC GLOBAL: " << *GV
954                << "  CALL = " << *CI << "  BCI = " << *BCI << '\n');
955
956   const Type *IntPtrTy = TD->getIntPtrType(Context);
957   
958   Value* ArraySize = getMallocArraySize(CI, Context, TD);
959   assert(ArraySize && "not a malloc whose array size can be determined");
960   ConstantInt *NElements = cast<ConstantInt>(ArraySize);
961   if (NElements->getZExtValue() != 1) {
962     // If we have an array allocation, transform it to a single element
963     // allocation to make the code below simpler.
964     Type *NewTy = ArrayType::get(getMallocAllocatedType(CI),
965                                  NElements->getZExtValue());
966     Value* NewM = CallInst::CreateMalloc(CI, IntPtrTy, NewTy);
967     Instruction* NewMI = cast<Instruction>(NewM);
968     Value* Indices[2];
969     Indices[0] = Indices[1] = Constant::getNullValue(IntPtrTy);
970     Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
971                                               NewMI->getName()+".el0", CI);
972     BCI->replaceAllUsesWith(NewGEP);
973     BCI->eraseFromParent();
974     CI->eraseFromParent();
975     BCI = cast<BitCastInst>(NewMI);
976     CI = extractMallocCallFromBitCast(NewMI);
977   }
978
979   // Create the new global variable.  The contents of the malloc'd memory is
980   // undefined, so initialize with an undef value.
981   const Type *MAT = getMallocAllocatedType(CI);
982   Constant *Init = UndefValue::get(MAT);
983   GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(), 
984                                              MAT, false,
985                                              GlobalValue::InternalLinkage, Init,
986                                              GV->getName()+".body",
987                                              GV,
988                                              GV->isThreadLocal());
989   
990   // Anything that used the malloc now uses the global directly.
991   BCI->replaceAllUsesWith(NewGV);
992
993   Constant *RepValue = NewGV;
994   if (NewGV->getType() != GV->getType()->getElementType())
995     RepValue = ConstantExpr::getBitCast(RepValue, 
996                                         GV->getType()->getElementType());
997
998   // If there is a comparison against null, we will insert a global bool to
999   // keep track of whether the global was initialized yet or not.
1000   GlobalVariable *InitBool =
1001     new GlobalVariable(Context, Type::getInt1Ty(Context), false,
1002                        GlobalValue::InternalLinkage,
1003                        ConstantInt::getFalse(Context), GV->getName()+".init",
1004                        GV->isThreadLocal());
1005   bool InitBoolUsed = false;
1006
1007   // Loop over all uses of GV, processing them in turn.
1008   std::vector<StoreInst*> Stores;
1009   while (!GV->use_empty())
1010     if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
1011       while (!LI->use_empty()) {
1012         Use &LoadUse = LI->use_begin().getUse();
1013         if (!isa<ICmpInst>(LoadUse.getUser()))
1014           LoadUse = RepValue;
1015         else {
1016           ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
1017           // Replace the cmp X, 0 with a use of the bool value.
1018           Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI);
1019           InitBoolUsed = true;
1020           switch (ICI->getPredicate()) {
1021           default: llvm_unreachable("Unknown ICmp Predicate!");
1022           case ICmpInst::ICMP_ULT:
1023           case ICmpInst::ICMP_SLT:
1024             LV = ConstantInt::getFalse(Context);   // X < null -> always false
1025             break;
1026           case ICmpInst::ICMP_ULE:
1027           case ICmpInst::ICMP_SLE:
1028           case ICmpInst::ICMP_EQ:
1029             LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
1030             break;
1031           case ICmpInst::ICMP_NE:
1032           case ICmpInst::ICMP_UGE:
1033           case ICmpInst::ICMP_SGE:
1034           case ICmpInst::ICMP_UGT:
1035           case ICmpInst::ICMP_SGT:
1036             break;  // no change.
1037           }
1038           ICI->replaceAllUsesWith(LV);
1039           ICI->eraseFromParent();
1040         }
1041       }
1042       LI->eraseFromParent();
1043     } else {
1044       StoreInst *SI = cast<StoreInst>(GV->use_back());
1045       // The global is initialized when the store to it occurs.
1046       new StoreInst(ConstantInt::getTrue(Context), InitBool, SI);
1047       SI->eraseFromParent();
1048     }
1049
1050   // If the initialization boolean was used, insert it, otherwise delete it.
1051   if (!InitBoolUsed) {
1052     while (!InitBool->use_empty())  // Delete initializations
1053       cast<Instruction>(InitBool->use_back())->eraseFromParent();
1054     delete InitBool;
1055   } else
1056     GV->getParent()->getGlobalList().insert(GV, InitBool);
1057
1058
1059   // Now the GV is dead, nuke it and the malloc.
1060   GV->eraseFromParent();
1061   BCI->eraseFromParent();
1062   CI->eraseFromParent();
1063
1064   // To further other optimizations, loop over all users of NewGV and try to
1065   // constant prop them.  This will promote GEP instructions with constant
1066   // indices into GEP constant-exprs, which will allow global-opt to hack on it.
1067   ConstantPropUsersOf(NewGV, Context);
1068   if (RepValue != NewGV)
1069     ConstantPropUsersOf(RepValue, Context);
1070
1071   return NewGV;
1072 }
1073
1074 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
1075 /// to make sure that there are no complex uses of V.  We permit simple things
1076 /// like dereferencing the pointer, but not storing through the address, unless
1077 /// it is to the specified global.
1078 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
1079                                                       GlobalVariable *GV,
1080                                               SmallPtrSet<PHINode*, 8> &PHIs) {
1081   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1082     Instruction *Inst = cast<Instruction>(*UI);
1083     
1084     if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
1085       continue; // Fine, ignore.
1086     }
1087     
1088     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1089       if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
1090         return false;  // Storing the pointer itself... bad.
1091       continue; // Otherwise, storing through it, or storing into GV... fine.
1092     }
1093     
1094     if (isa<GetElementPtrInst>(Inst)) {
1095       if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
1096         return false;
1097       continue;
1098     }
1099     
1100     if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
1101       // PHIs are ok if all uses are ok.  Don't infinitely recurse through PHI
1102       // cycles.
1103       if (PHIs.insert(PN))
1104         if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1105           return false;
1106       continue;
1107     }
1108     
1109     if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
1110       if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1111         return false;
1112       continue;
1113     }
1114     
1115     return false;
1116   }
1117   return true;
1118 }
1119
1120 /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1121 /// somewhere.  Transform all uses of the allocation into loads from the
1122 /// global and uses of the resultant pointer.  Further, delete the store into
1123 /// GV.  This assumes that these value pass the 
1124 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
1125 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc, 
1126                                           GlobalVariable *GV) {
1127   while (!Alloc->use_empty()) {
1128     Instruction *U = cast<Instruction>(*Alloc->use_begin());
1129     Instruction *InsertPt = U;
1130     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1131       // If this is the store of the allocation into the global, remove it.
1132       if (SI->getOperand(1) == GV) {
1133         SI->eraseFromParent();
1134         continue;
1135       }
1136     } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1137       // Insert the load in the corresponding predecessor, not right before the
1138       // PHI.
1139       InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
1140     } else if (isa<BitCastInst>(U)) {
1141       // Must be bitcast between the malloc and store to initialize the global.
1142       ReplaceUsesOfMallocWithGlobal(U, GV);
1143       U->eraseFromParent();
1144       continue;
1145     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1146       // If this is a "GEP bitcast" and the user is a store to the global, then
1147       // just process it as a bitcast.
1148       if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1149         if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1150           if (SI->getOperand(1) == GV) {
1151             // Must be bitcast GEP between the malloc and store to initialize
1152             // the global.
1153             ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1154             GEPI->eraseFromParent();
1155             continue;
1156           }
1157     }
1158       
1159     // Insert a load from the global, and use it instead of the malloc.
1160     Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
1161     U->replaceUsesOfWith(Alloc, NL);
1162   }
1163 }
1164
1165 /// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1166 /// of a load) are simple enough to perform heap SRA on.  This permits GEP's
1167 /// that index through the array and struct field, icmps of null, and PHIs.
1168 static bool LoadUsesSimpleEnoughForHeapSRA(Value *V,
1169                               SmallPtrSet<PHINode*, 32> &LoadUsingPHIs,
1170                               SmallPtrSet<PHINode*, 32> &LoadUsingPHIsPerLoad) {
1171   // We permit two users of the load: setcc comparing against the null
1172   // pointer, and a getelementptr of a specific form.
1173   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1174     Instruction *User = cast<Instruction>(*UI);
1175     
1176     // Comparison against null is ok.
1177     if (ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1178       if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1179         return false;
1180       continue;
1181     }
1182     
1183     // getelementptr is also ok, but only a simple form.
1184     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1185       // Must index into the array and into the struct.
1186       if (GEPI->getNumOperands() < 3)
1187         return false;
1188       
1189       // Otherwise the GEP is ok.
1190       continue;
1191     }
1192     
1193     if (PHINode *PN = dyn_cast<PHINode>(User)) {
1194       if (!LoadUsingPHIsPerLoad.insert(PN))
1195         // This means some phi nodes are dependent on each other.
1196         // Avoid infinite looping!
1197         return false;
1198       if (!LoadUsingPHIs.insert(PN))
1199         // If we have already analyzed this PHI, then it is safe.
1200         continue;
1201       
1202       // Make sure all uses of the PHI are simple enough to transform.
1203       if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1204                                           LoadUsingPHIs, LoadUsingPHIsPerLoad))
1205         return false;
1206       
1207       continue;
1208     }
1209     
1210     // Otherwise we don't know what this is, not ok.
1211     return false;
1212   }
1213   
1214   return true;
1215 }
1216
1217
1218 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1219 /// GV are simple enough to perform HeapSRA, return true.
1220 static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
1221                                                     Instruction *StoredVal) {
1222   SmallPtrSet<PHINode*, 32> LoadUsingPHIs;
1223   SmallPtrSet<PHINode*, 32> LoadUsingPHIsPerLoad;
1224   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E; 
1225        ++UI)
1226     if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1227       if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1228                                           LoadUsingPHIsPerLoad))
1229         return false;
1230       LoadUsingPHIsPerLoad.clear();
1231     }
1232   
1233   // If we reach here, we know that all uses of the loads and transitive uses
1234   // (through PHI nodes) are simple enough to transform.  However, we don't know
1235   // that all inputs the to the PHI nodes are in the same equivalence sets. 
1236   // Check to verify that all operands of the PHIs are either PHIS that can be
1237   // transformed, loads from GV, or MI itself.
1238   for (SmallPtrSet<PHINode*, 32>::iterator I = LoadUsingPHIs.begin(),
1239        E = LoadUsingPHIs.end(); I != E; ++I) {
1240     PHINode *PN = *I;
1241     for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1242       Value *InVal = PN->getIncomingValue(op);
1243       
1244       // PHI of the stored value itself is ok.
1245       if (InVal == StoredVal) continue;
1246       
1247       if (PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1248         // One of the PHIs in our set is (optimistically) ok.
1249         if (LoadUsingPHIs.count(InPN))
1250           continue;
1251         return false;
1252       }
1253       
1254       // Load from GV is ok.
1255       if (LoadInst *LI = dyn_cast<LoadInst>(InVal))
1256         if (LI->getOperand(0) == GV)
1257           continue;
1258       
1259       // UNDEF? NULL?
1260       
1261       // Anything else is rejected.
1262       return false;
1263     }
1264   }
1265   
1266   return true;
1267 }
1268
1269 static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1270                DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1271                    std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
1272                    LLVMContext &Context) {
1273   std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1274   
1275   if (FieldNo >= FieldVals.size())
1276     FieldVals.resize(FieldNo+1);
1277   
1278   // If we already have this value, just reuse the previously scalarized
1279   // version.
1280   if (Value *FieldVal = FieldVals[FieldNo])
1281     return FieldVal;
1282   
1283   // Depending on what instruction this is, we have several cases.
1284   Value *Result;
1285   if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1286     // This is a scalarized version of the load from the global.  Just create
1287     // a new Load of the scalarized global.
1288     Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1289                                            InsertedScalarizedValues,
1290                                            PHIsToRewrite, Context),
1291                           LI->getName()+".f"+Twine(FieldNo), LI);
1292   } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1293     // PN's type is pointer to struct.  Make a new PHI of pointer to struct
1294     // field.
1295     const StructType *ST = 
1296       cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1297     
1298     Result =
1299      PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
1300                      PN->getName()+".f"+Twine(FieldNo), PN);
1301     PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1302   } else {
1303     llvm_unreachable("Unknown usable value");
1304     Result = 0;
1305   }
1306   
1307   return FieldVals[FieldNo] = Result;
1308 }
1309
1310 /// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1311 /// the load, rewrite the derived value to use the HeapSRoA'd load.
1312 static void RewriteHeapSROALoadUser(Instruction *LoadUser, 
1313              DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1314                    std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
1315                    LLVMContext &Context) {
1316   // If this is a comparison against null, handle it.
1317   if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1318     assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1319     // If we have a setcc of the loaded pointer, we can use a setcc of any
1320     // field.
1321     Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
1322                                    InsertedScalarizedValues, PHIsToRewrite,
1323                                    Context);
1324     
1325     Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
1326                               Constant::getNullValue(NPtr->getType()), 
1327                               SCI->getName());
1328     SCI->replaceAllUsesWith(New);
1329     SCI->eraseFromParent();
1330     return;
1331   }
1332   
1333   // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
1334   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1335     assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1336            && "Unexpected GEPI!");
1337   
1338     // Load the pointer for this field.
1339     unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1340     Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
1341                                      InsertedScalarizedValues, PHIsToRewrite,
1342                                      Context);
1343     
1344     // Create the new GEP idx vector.
1345     SmallVector<Value*, 8> GEPIdx;
1346     GEPIdx.push_back(GEPI->getOperand(1));
1347     GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1348     
1349     Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1350                                              GEPIdx.begin(), GEPIdx.end(),
1351                                              GEPI->getName(), GEPI);
1352     GEPI->replaceAllUsesWith(NGEPI);
1353     GEPI->eraseFromParent();
1354     return;
1355   }
1356
1357   // Recursively transform the users of PHI nodes.  This will lazily create the
1358   // PHIs that are needed for individual elements.  Keep track of what PHIs we
1359   // see in InsertedScalarizedValues so that we don't get infinite loops (very
1360   // antisocial).  If the PHI is already in InsertedScalarizedValues, it has
1361   // already been seen first by another load, so its uses have already been
1362   // processed.
1363   PHINode *PN = cast<PHINode>(LoadUser);
1364   bool Inserted;
1365   DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1366   tie(InsertPos, Inserted) =
1367     InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1368   if (!Inserted) return;
1369   
1370   // If this is the first time we've seen this PHI, recursively process all
1371   // users.
1372   for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1373     Instruction *User = cast<Instruction>(*UI++);
1374     RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1375                             Context);
1376   }
1377 }
1378
1379 /// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global.  Ptr
1380 /// is a value loaded from the global.  Eliminate all uses of Ptr, making them
1381 /// use FieldGlobals instead.  All uses of loaded values satisfy
1382 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
1383 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load, 
1384                DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1385                    std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
1386                    LLVMContext &Context) {
1387   for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
1388        UI != E; ) {
1389     Instruction *User = cast<Instruction>(*UI++);
1390     RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1391                             Context);
1392   }
1393   
1394   if (Load->use_empty()) {
1395     Load->eraseFromParent();
1396     InsertedScalarizedValues.erase(Load);
1397   }
1398 }
1399
1400 /// PerformHeapAllocSRoA - MI is an allocation of an array of structures.  Break
1401 /// it up into multiple allocations of arrays of the fields.
1402 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI,
1403                                             LLVMContext &Context){
1404   DEBUG(errs() << "SROA HEAP ALLOC: " << *GV << "  MALLOC = " << *MI);
1405   const StructType *STy = cast<StructType>(MI->getAllocatedType());
1406
1407   // There is guaranteed to be at least one use of the malloc (storing
1408   // it into GV).  If there are other uses, change them to be uses of
1409   // the global to simplify later code.  This also deletes the store
1410   // into GV.
1411   ReplaceUsesOfMallocWithGlobal(MI, GV);
1412   
1413   // Okay, at this point, there are no users of the malloc.  Insert N
1414   // new mallocs at the same place as MI, and N globals.
1415   std::vector<Value*> FieldGlobals;
1416   std::vector<MallocInst*> FieldMallocs;
1417   
1418   for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1419     const Type *FieldTy = STy->getElementType(FieldNo);
1420     const Type *PFieldTy = PointerType::getUnqual(FieldTy);
1421     
1422     GlobalVariable *NGV =
1423       new GlobalVariable(*GV->getParent(),
1424                          PFieldTy, false, GlobalValue::InternalLinkage,
1425                          Constant::getNullValue(PFieldTy),
1426                          GV->getName() + ".f" + Twine(FieldNo), GV,
1427                          GV->isThreadLocal());
1428     FieldGlobals.push_back(NGV);
1429     
1430     MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
1431                                      MI->getName() + ".f" + Twine(FieldNo), MI);
1432     FieldMallocs.push_back(NMI);
1433     new StoreInst(NMI, NGV, MI);
1434   }
1435   
1436   // The tricky aspect of this transformation is handling the case when malloc
1437   // fails.  In the original code, malloc failing would set the result pointer
1438   // of malloc to null.  In this case, some mallocs could succeed and others
1439   // could fail.  As such, we emit code that looks like this:
1440   //    F0 = malloc(field0)
1441   //    F1 = malloc(field1)
1442   //    F2 = malloc(field2)
1443   //    if (F0 == 0 || F1 == 0 || F2 == 0) {
1444   //      if (F0) { free(F0); F0 = 0; }
1445   //      if (F1) { free(F1); F1 = 0; }
1446   //      if (F2) { free(F2); F2 = 0; }
1447   //    }
1448   Value *RunningOr = 0;
1449   for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1450     Value *Cond = new ICmpInst(MI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1451                               Constant::getNullValue(FieldMallocs[i]->getType()),
1452                                   "isnull");
1453     if (!RunningOr)
1454       RunningOr = Cond;   // First seteq
1455     else
1456       RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", MI);
1457   }
1458
1459   // Split the basic block at the old malloc.
1460   BasicBlock *OrigBB = MI->getParent();
1461   BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
1462   
1463   // Create the block to check the first condition.  Put all these blocks at the
1464   // end of the function as they are unlikely to be executed.
1465   BasicBlock *NullPtrBlock = BasicBlock::Create(Context, "malloc_ret_null",
1466                                                 OrigBB->getParent());
1467   
1468   // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1469   // branch on RunningOr.
1470   OrigBB->getTerminator()->eraseFromParent();
1471   BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
1472   
1473   // Within the NullPtrBlock, we need to emit a comparison and branch for each
1474   // pointer, because some may be null while others are not.
1475   for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1476     Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1477     Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal, 
1478                               Constant::getNullValue(GVVal->getType()),
1479                               "tmp");
1480     BasicBlock *FreeBlock = BasicBlock::Create(Context, "free_it", 
1481                                                OrigBB->getParent());
1482     BasicBlock *NextBlock = BasicBlock::Create(Context, "next", 
1483                                                OrigBB->getParent());
1484     BranchInst::Create(FreeBlock, NextBlock, Cmp, NullPtrBlock);
1485
1486     // Fill in FreeBlock.
1487     new FreeInst(GVVal, FreeBlock);
1488     new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1489                   FreeBlock);
1490     BranchInst::Create(NextBlock, FreeBlock);
1491     
1492     NullPtrBlock = NextBlock;
1493   }
1494   
1495   BranchInst::Create(ContBB, NullPtrBlock);
1496   
1497   // MI is no longer needed, remove it.
1498   MI->eraseFromParent();
1499
1500   /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1501   /// update all uses of the load, keep track of what scalarized loads are
1502   /// inserted for a given load.
1503   DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1504   InsertedScalarizedValues[GV] = FieldGlobals;
1505   
1506   std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1507   
1508   // Okay, the malloc site is completely handled.  All of the uses of GV are now
1509   // loads, and all uses of those loads are simple.  Rewrite them to use loads
1510   // of the per-field globals instead.
1511   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1512     Instruction *User = cast<Instruction>(*UI++);
1513     
1514     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1515       RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite,
1516                                    Context);
1517       continue;
1518     }
1519     
1520     // Must be a store of null.
1521     StoreInst *SI = cast<StoreInst>(User);
1522     assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1523            "Unexpected heap-sra user!");
1524     
1525     // Insert a store of null into each global.
1526     for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1527       const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1528       Constant *Null = Constant::getNullValue(PT->getElementType());
1529       new StoreInst(Null, FieldGlobals[i], SI);
1530     }
1531     // Erase the original store.
1532     SI->eraseFromParent();
1533   }
1534
1535   // While we have PHIs that are interesting to rewrite, do it.
1536   while (!PHIsToRewrite.empty()) {
1537     PHINode *PN = PHIsToRewrite.back().first;
1538     unsigned FieldNo = PHIsToRewrite.back().second;
1539     PHIsToRewrite.pop_back();
1540     PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1541     assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1542
1543     // Add all the incoming values.  This can materialize more phis.
1544     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1545       Value *InVal = PN->getIncomingValue(i);
1546       InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
1547                                PHIsToRewrite, Context);
1548       FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1549     }
1550   }
1551   
1552   // Drop all inter-phi links and any loads that made it this far.
1553   for (DenseMap<Value*, std::vector<Value*> >::iterator
1554        I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1555        I != E; ++I) {
1556     if (PHINode *PN = dyn_cast<PHINode>(I->first))
1557       PN->dropAllReferences();
1558     else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1559       LI->dropAllReferences();
1560   }
1561   
1562   // Delete all the phis and loads now that inter-references are dead.
1563   for (DenseMap<Value*, std::vector<Value*> >::iterator
1564        I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1565        I != E; ++I) {
1566     if (PHINode *PN = dyn_cast<PHINode>(I->first))
1567       PN->eraseFromParent();
1568     else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1569       LI->eraseFromParent();
1570   }
1571   
1572   // The old global is now dead, remove it.
1573   GV->eraseFromParent();
1574
1575   ++NumHeapSRA;
1576   return cast<GlobalVariable>(FieldGlobals[0]);
1577 }
1578
1579 /// PerformHeapAllocSRoA - CI is an allocation of an array of structures.  Break
1580 /// it up into multiple allocations of arrays of the fields.
1581 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV,
1582                                             CallInst *CI, BitCastInst* BCI, 
1583                                             LLVMContext &Context,
1584                                             TargetData *TD){
1585   DEBUG(errs() << "SROA HEAP ALLOC: " << *GV << "  MALLOC CALL = " << *CI 
1586                << " BITCAST = " << *BCI << '\n');
1587   const Type* MAT = getMallocAllocatedType(CI);
1588   const StructType *STy = cast<StructType>(MAT);
1589
1590   // There is guaranteed to be at least one use of the malloc (storing
1591   // it into GV).  If there are other uses, change them to be uses of
1592   // the global to simplify later code.  This also deletes the store
1593   // into GV.
1594   ReplaceUsesOfMallocWithGlobal(BCI, GV);
1595   
1596   // Okay, at this point, there are no users of the malloc.  Insert N
1597   // new mallocs at the same place as CI, and N globals.
1598   std::vector<Value*> FieldGlobals;
1599   std::vector<Value*> FieldMallocs;
1600   
1601   for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1602     const Type *FieldTy = STy->getElementType(FieldNo);
1603     const PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
1604     
1605     GlobalVariable *NGV =
1606       new GlobalVariable(*GV->getParent(),
1607                          PFieldTy, false, GlobalValue::InternalLinkage,
1608                          Constant::getNullValue(PFieldTy),
1609                          GV->getName() + ".f" + Twine(FieldNo), GV,
1610                          GV->isThreadLocal());
1611     FieldGlobals.push_back(NGV);
1612     
1613     Value *NMI = CallInst::CreateMalloc(CI, TD->getIntPtrType(Context), FieldTy,
1614                                         getMallocArraySize(CI, Context, TD),
1615                                         BCI->getName() + ".f" + Twine(FieldNo));
1616     FieldMallocs.push_back(NMI);
1617     new StoreInst(NMI, NGV, BCI);
1618   }
1619   
1620   // The tricky aspect of this transformation is handling the case when malloc
1621   // fails.  In the original code, malloc failing would set the result pointer
1622   // of malloc to null.  In this case, some mallocs could succeed and others
1623   // could fail.  As such, we emit code that looks like this:
1624   //    F0 = malloc(field0)
1625   //    F1 = malloc(field1)
1626   //    F2 = malloc(field2)
1627   //    if (F0 == 0 || F1 == 0 || F2 == 0) {
1628   //      if (F0) { free(F0); F0 = 0; }
1629   //      if (F1) { free(F1); F1 = 0; }
1630   //      if (F2) { free(F2); F2 = 0; }
1631   //    }
1632   Value *RunningOr = 0;
1633   for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1634     Value *Cond = new ICmpInst(BCI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1635                               Constant::getNullValue(FieldMallocs[i]->getType()),
1636                                   "isnull");
1637     if (!RunningOr)
1638       RunningOr = Cond;   // First seteq
1639     else
1640       RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", BCI);
1641   }
1642
1643   // Split the basic block at the old malloc.
1644   BasicBlock *OrigBB = BCI->getParent();
1645   BasicBlock *ContBB = OrigBB->splitBasicBlock(BCI, "malloc_cont");
1646   
1647   // Create the block to check the first condition.  Put all these blocks at the
1648   // end of the function as they are unlikely to be executed.
1649   BasicBlock *NullPtrBlock = BasicBlock::Create(Context, "malloc_ret_null",
1650                                                 OrigBB->getParent());
1651   
1652   // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1653   // branch on RunningOr.
1654   OrigBB->getTerminator()->eraseFromParent();
1655   BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
1656   
1657   // Within the NullPtrBlock, we need to emit a comparison and branch for each
1658   // pointer, because some may be null while others are not.
1659   for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1660     Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1661     Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal, 
1662                               Constant::getNullValue(GVVal->getType()),
1663                               "tmp");
1664     BasicBlock *FreeBlock = BasicBlock::Create(Context, "free_it",
1665                                                OrigBB->getParent());
1666     BasicBlock *NextBlock = BasicBlock::Create(Context, "next",
1667                                                OrigBB->getParent());
1668     BranchInst::Create(FreeBlock, NextBlock, Cmp, NullPtrBlock);
1669
1670     // Fill in FreeBlock.
1671     new FreeInst(GVVal, FreeBlock);
1672     new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1673                   FreeBlock);
1674     BranchInst::Create(NextBlock, FreeBlock);
1675     
1676     NullPtrBlock = NextBlock;
1677   }
1678   
1679   BranchInst::Create(ContBB, NullPtrBlock);
1680   
1681   // CI and BCI are no longer needed, remove them.
1682   BCI->eraseFromParent();
1683   CI->eraseFromParent();
1684
1685   /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1686   /// update all uses of the load, keep track of what scalarized loads are
1687   /// inserted for a given load.
1688   DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1689   InsertedScalarizedValues[GV] = FieldGlobals;
1690   
1691   std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1692   
1693   // Okay, the malloc site is completely handled.  All of the uses of GV are now
1694   // loads, and all uses of those loads are simple.  Rewrite them to use loads
1695   // of the per-field globals instead.
1696   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1697     Instruction *User = cast<Instruction>(*UI++);
1698     
1699     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1700       RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite,
1701                                    Context);
1702       continue;
1703     }
1704     
1705     // Must be a store of null.
1706     StoreInst *SI = cast<StoreInst>(User);
1707     assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1708            "Unexpected heap-sra user!");
1709     
1710     // Insert a store of null into each global.
1711     for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1712       const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1713       Constant *Null = Constant::getNullValue(PT->getElementType());
1714       new StoreInst(Null, FieldGlobals[i], SI);
1715     }
1716     // Erase the original store.
1717     SI->eraseFromParent();
1718   }
1719
1720   // While we have PHIs that are interesting to rewrite, do it.
1721   while (!PHIsToRewrite.empty()) {
1722     PHINode *PN = PHIsToRewrite.back().first;
1723     unsigned FieldNo = PHIsToRewrite.back().second;
1724     PHIsToRewrite.pop_back();
1725     PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1726     assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1727
1728     // Add all the incoming values.  This can materialize more phis.
1729     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1730       Value *InVal = PN->getIncomingValue(i);
1731       InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
1732                                PHIsToRewrite, Context);
1733       FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1734     }
1735   }
1736   
1737   // Drop all inter-phi links and any loads that made it this far.
1738   for (DenseMap<Value*, std::vector<Value*> >::iterator
1739        I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1740        I != E; ++I) {
1741     if (PHINode *PN = dyn_cast<PHINode>(I->first))
1742       PN->dropAllReferences();
1743     else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1744       LI->dropAllReferences();
1745   }
1746   
1747   // Delete all the phis and loads now that inter-references are dead.
1748   for (DenseMap<Value*, std::vector<Value*> >::iterator
1749        I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1750        I != E; ++I) {
1751     if (PHINode *PN = dyn_cast<PHINode>(I->first))
1752       PN->eraseFromParent();
1753     else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1754       LI->eraseFromParent();
1755   }
1756   
1757   // The old global is now dead, remove it.
1758   GV->eraseFromParent();
1759
1760   ++NumHeapSRA;
1761   return cast<GlobalVariable>(FieldGlobals[0]);
1762 }
1763
1764 /// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1765 /// pointer global variable with a single value stored it that is a malloc or
1766 /// cast of malloc.
1767 static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1768                                                MallocInst *MI,
1769                                                Module::global_iterator &GVI,
1770                                                TargetData *TD,
1771                                                LLVMContext &Context) {
1772   // If this is a malloc of an abstract type, don't touch it.
1773   if (!MI->getAllocatedType()->isSized())
1774     return false;
1775   
1776   // We can't optimize this global unless all uses of it are *known* to be
1777   // of the malloc value, not of the null initializer value (consider a use
1778   // that compares the global's value against zero to see if the malloc has
1779   // been reached).  To do this, we check to see if all uses of the global
1780   // would trap if the global were null: this proves that they must all
1781   // happen after the malloc.
1782   if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1783     return false;
1784   
1785   // We can't optimize this if the malloc itself is used in a complex way,
1786   // for example, being stored into multiple globals.  This allows the
1787   // malloc to be stored into the specified global, loaded setcc'd, and
1788   // GEP'd.  These are all things we could transform to using the global
1789   // for.
1790   {
1791     SmallPtrSet<PHINode*, 8> PHIs;
1792     if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV, PHIs))
1793       return false;
1794   }
1795   
1796   
1797   // If we have a global that is only initialized with a fixed size malloc,
1798   // transform the program to use global memory instead of malloc'd memory.
1799   // This eliminates dynamic allocation, avoids an indirection accessing the
1800   // data, and exposes the resultant global to further GlobalOpt.
1801   if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
1802     // Restrict this transformation to only working on small allocations
1803     // (2048 bytes currently), as we don't want to introduce a 16M global or
1804     // something.
1805     if (TD &&
1806         NElements->getZExtValue()*
1807         TD->getTypeAllocSize(MI->getAllocatedType()) < 2048) {
1808       GVI = OptimizeGlobalAddressOfMalloc(GV, MI, Context);
1809       return true;
1810     }
1811   }
1812   
1813   // If the allocation is an array of structures, consider transforming this
1814   // into multiple malloc'd arrays, one for each field.  This is basically
1815   // SRoA for malloc'd memory.
1816   const Type *AllocTy = MI->getAllocatedType();
1817   
1818   // If this is an allocation of a fixed size array of structs, analyze as a
1819   // variable size array.  malloc [100 x struct],1 -> malloc struct, 100
1820   if (!MI->isArrayAllocation())
1821     if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1822       AllocTy = AT->getElementType();
1823   
1824   if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
1825     // This the structure has an unreasonable number of fields, leave it
1826     // alone.
1827     if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1828         AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, MI)) {
1829       
1830       // If this is a fixed size array, transform the Malloc to be an alloc of
1831       // structs.  malloc [100 x struct],1 -> malloc struct, 100
1832       if (const ArrayType *AT = dyn_cast<ArrayType>(MI->getAllocatedType())) {
1833         MallocInst *NewMI = 
1834           new MallocInst(AllocSTy, 
1835                   ConstantInt::get(Type::getInt32Ty(Context),
1836                   AT->getNumElements()),
1837                          "", MI);
1838         NewMI->takeName(MI);
1839         Value *Cast = new BitCastInst(NewMI, MI->getType(), "tmp", MI);
1840         MI->replaceAllUsesWith(Cast);
1841         MI->eraseFromParent();
1842         MI = NewMI;
1843       }
1844       
1845       GVI = PerformHeapAllocSRoA(GV, MI, Context);
1846       return true;
1847     }
1848   }
1849   
1850   return false;
1851 }  
1852
1853 /// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1854 /// pointer global variable with a single value stored it that is a malloc or
1855 /// cast of malloc.
1856 static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1857                                                CallInst *CI,
1858                                                BitCastInst *BCI,
1859                                                Module::global_iterator &GVI,
1860                                                TargetData *TD,
1861                                                LLVMContext &Context) {
1862   // If we can't figure out the type being malloced, then we can't optimize.
1863   const Type *AllocTy = getMallocAllocatedType(CI);
1864   assert(AllocTy);
1865
1866   // If this is a malloc of an abstract type, don't touch it.
1867   if (!AllocTy->isSized())
1868     return false;
1869
1870   // We can't optimize this global unless all uses of it are *known* to be
1871   // of the malloc value, not of the null initializer value (consider a use
1872   // that compares the global's value against zero to see if the malloc has
1873   // been reached).  To do this, we check to see if all uses of the global
1874   // would trap if the global were null: this proves that they must all
1875   // happen after the malloc.
1876   if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1877     return false;
1878
1879   // We can't optimize this if the malloc itself is used in a complex way,
1880   // for example, being stored into multiple globals.  This allows the
1881   // malloc to be stored into the specified global, loaded setcc'd, and
1882   // GEP'd.  These are all things we could transform to using the global
1883   // for.
1884   {
1885     SmallPtrSet<PHINode*, 8> PHIs;
1886     if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1887       return false;
1888   }  
1889
1890   // If we have a global that is only initialized with a fixed size malloc,
1891   // transform the program to use global memory instead of malloc'd memory.
1892   // This eliminates dynamic allocation, avoids an indirection accessing the
1893   // data, and exposes the resultant global to further GlobalOpt.
1894   Value *NElems = getMallocArraySize(CI, Context, TD);
1895   if (NElems) {
1896     if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1897       // Restrict this transformation to only working on small allocations
1898       // (2048 bytes currently), as we don't want to introduce a 16M global or
1899       // something.
1900       if (TD && 
1901           NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1902         GVI = OptimizeGlobalAddressOfMalloc(GV, CI, BCI, Context, TD);
1903         return true;
1904       }
1905   }
1906   
1907   // If the allocation is an array of structures, consider transforming this
1908   // into multiple malloc'd arrays, one for each field.  This is basically
1909   // SRoA for malloc'd memory.
1910
1911   // If this is an allocation of a fixed size array of structs, analyze as a
1912   // variable size array.  malloc [100 x struct],1 -> malloc struct, 100
1913   if (!isArrayMalloc(CI, Context, TD))
1914     if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1915       AllocTy = AT->getElementType();
1916   
1917   if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
1918     // This the structure has an unreasonable number of fields, leave it
1919     // alone.
1920     if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1921         AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, BCI)) {
1922
1923       // If this is a fixed size array, transform the Malloc to be an alloc of
1924       // structs.  malloc [100 x struct],1 -> malloc struct, 100
1925       if (const ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1926         Value* NumElements = ConstantInt::get(Type::getInt32Ty(Context),
1927                                               AT->getNumElements());
1928         Value* NewMI = CallInst::CreateMalloc(CI, TD->getIntPtrType(Context),
1929                                               AllocSTy, NumElements,
1930                                               BCI->getName());
1931         Value *Cast = new BitCastInst(NewMI, getMallocType(CI), "tmp", CI);
1932         BCI->replaceAllUsesWith(Cast);
1933         BCI->eraseFromParent();
1934         CI->eraseFromParent();
1935         BCI = cast<BitCastInst>(NewMI);
1936         CI = extractMallocCallFromBitCast(NewMI);
1937       }
1938       
1939       GVI = PerformHeapAllocSRoA(GV, CI, BCI, Context, TD);
1940       return true;
1941     }
1942   }
1943   
1944   return false;
1945 }  
1946
1947 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1948 // that only one value (besides its initializer) is ever stored to the global.
1949 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1950                                      Module::global_iterator &GVI,
1951                                      TargetData *TD, LLVMContext &Context) {
1952   // Ignore no-op GEPs and bitcasts.
1953   StoredOnceVal = StoredOnceVal->stripPointerCasts();
1954
1955   // If we are dealing with a pointer global that is initialized to null and
1956   // only has one (non-null) value stored into it, then we can optimize any
1957   // users of the loaded value (often calls and loads) that would trap if the
1958   // value was null.
1959   if (isa<PointerType>(GV->getInitializer()->getType()) &&
1960       GV->getInitializer()->isNullValue()) {
1961     if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1962       if (GV->getInitializer()->getType() != SOVC->getType())
1963         SOVC = 
1964          ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
1965
1966       // Optimize away any trapping uses of the loaded value.
1967       if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, Context))
1968         return true;
1969     } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
1970       if (TryToOptimizeStoreOfMallocToGlobal(GV, MI, GVI, TD, Context))
1971         return true;
1972     } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
1973       if (getMallocAllocatedType(CI)) {
1974         BitCastInst* BCI = NULL;
1975         for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
1976              UI != E; )
1977           BCI = dyn_cast<BitCastInst>(cast<Instruction>(*UI++));
1978         if (BCI &&
1979             TryToOptimizeStoreOfMallocToGlobal(GV, CI, BCI, GVI, TD, Context))
1980           return true;
1981       }
1982     }
1983   }
1984
1985   return false;
1986 }
1987
1988 /// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1989 /// two values ever stored into GV are its initializer and OtherVal.  See if we
1990 /// can shrink the global into a boolean and select between the two values
1991 /// whenever it is used.  This exposes the values to other scalar optimizations.
1992 static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal,
1993                                        LLVMContext &Context) {
1994   const Type *GVElType = GV->getType()->getElementType();
1995   
1996   // If GVElType is already i1, it is already shrunk.  If the type of the GV is
1997   // an FP value, pointer or vector, don't do this optimization because a select
1998   // between them is very expensive and unlikely to lead to later
1999   // simplification.  In these cases, we typically end up with "cond ? v1 : v2"
2000   // where v1 and v2 both require constant pool loads, a big loss.
2001   if (GVElType == Type::getInt1Ty(Context) || GVElType->isFloatingPoint() ||
2002       isa<PointerType>(GVElType) || isa<VectorType>(GVElType))
2003     return false;
2004   
2005   // Walk the use list of the global seeing if all the uses are load or store.
2006   // If there is anything else, bail out.
2007   for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
2008     if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
2009       return false;
2010   
2011   DEBUG(errs() << "   *** SHRINKING TO BOOL: " << *GV);
2012   
2013   // Create the new global, initializing it to false.
2014   GlobalVariable *NewGV = new GlobalVariable(Context,
2015                                              Type::getInt1Ty(Context), false,
2016          GlobalValue::InternalLinkage, ConstantInt::getFalse(Context),
2017                                              GV->getName()+".b",
2018                                              GV->isThreadLocal());
2019   GV->getParent()->getGlobalList().insert(GV, NewGV);
2020
2021   Constant *InitVal = GV->getInitializer();
2022   assert(InitVal->getType() != Type::getInt1Ty(Context) &&
2023          "No reason to shrink to bool!");
2024
2025   // If initialized to zero and storing one into the global, we can use a cast
2026   // instead of a select to synthesize the desired value.
2027   bool IsOneZero = false;
2028   if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
2029     IsOneZero = InitVal->isNullValue() && CI->isOne();
2030
2031   while (!GV->use_empty()) {
2032     Instruction *UI = cast<Instruction>(GV->use_back());
2033     if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
2034       // Change the store into a boolean store.
2035       bool StoringOther = SI->getOperand(0) == OtherVal;
2036       // Only do this if we weren't storing a loaded value.
2037       Value *StoreVal;
2038       if (StoringOther || SI->getOperand(0) == InitVal)
2039         StoreVal = ConstantInt::get(Type::getInt1Ty(Context), StoringOther);
2040       else {
2041         // Otherwise, we are storing a previously loaded copy.  To do this,
2042         // change the copy from copying the original value to just copying the
2043         // bool.
2044         Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
2045
2046         // If we're already replaced the input, StoredVal will be a cast or
2047         // select instruction.  If not, it will be a load of the original
2048         // global.
2049         if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
2050           assert(LI->getOperand(0) == GV && "Not a copy!");
2051           // Insert a new load, to preserve the saved value.
2052           StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
2053         } else {
2054           assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
2055                  "This is not a form that we understand!");
2056           StoreVal = StoredVal->getOperand(0);
2057           assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
2058         }
2059       }
2060       new StoreInst(StoreVal, NewGV, SI);
2061     } else {
2062       // Change the load into a load of bool then a select.
2063       LoadInst *LI = cast<LoadInst>(UI);
2064       LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
2065       Value *NSI;
2066       if (IsOneZero)
2067         NSI = new ZExtInst(NLI, LI->getType(), "", LI);
2068       else
2069         NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
2070       NSI->takeName(LI);
2071       LI->replaceAllUsesWith(NSI);
2072     }
2073     UI->eraseFromParent();
2074   }
2075
2076   GV->eraseFromParent();
2077   return true;
2078 }
2079
2080
2081 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
2082 /// it if possible.  If we make a change, return true.
2083 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
2084                                       Module::global_iterator &GVI) {
2085   SmallPtrSet<PHINode*, 16> PHIUsers;
2086   GlobalStatus GS;
2087   GV->removeDeadConstantUsers();
2088
2089   if (GV->use_empty()) {
2090     DEBUG(errs() << "GLOBAL DEAD: " << *GV);
2091     GV->eraseFromParent();
2092     ++NumDeleted;
2093     return true;
2094   }
2095
2096   if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
2097 #if 0
2098     cerr << "Global: " << *GV;
2099     cerr << "  isLoaded = " << GS.isLoaded << "\n";
2100     cerr << "  StoredType = ";
2101     switch (GS.StoredType) {
2102     case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
2103     case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
2104     case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
2105     case GlobalStatus::isStored: cerr << "stored\n"; break;
2106     }
2107     if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
2108       cerr << "  StoredOnceValue = " << *GS.StoredOnceValue << "\n";
2109     if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
2110       cerr << "  AccessingFunction = " << GS.AccessingFunction->getName()
2111                 << "\n";
2112     cerr << "  HasMultipleAccessingFunctions =  "
2113               << GS.HasMultipleAccessingFunctions << "\n";
2114     cerr << "  HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
2115     cerr << "\n";
2116 #endif
2117     
2118     // If this is a first class global and has only one accessing function
2119     // and this function is main (which we know is not recursive we can make
2120     // this global a local variable) we replace the global with a local alloca
2121     // in this function.
2122     //
2123     // NOTE: It doesn't make sense to promote non single-value types since we
2124     // are just replacing static memory to stack memory.
2125     //
2126     // If the global is in different address space, don't bring it to stack.
2127     if (!GS.HasMultipleAccessingFunctions &&
2128         GS.AccessingFunction && !GS.HasNonInstructionUser &&
2129         GV->getType()->getElementType()->isSingleValueType() &&
2130         GS.AccessingFunction->getName() == "main" &&
2131         GS.AccessingFunction->hasExternalLinkage() &&
2132         GV->getType()->getAddressSpace() == 0) {
2133       DEBUG(errs() << "LOCALIZING GLOBAL: " << *GV);
2134       Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
2135       const Type* ElemTy = GV->getType()->getElementType();
2136       // FIXME: Pass Global's alignment when globals have alignment
2137       AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
2138       if (!isa<UndefValue>(GV->getInitializer()))
2139         new StoreInst(GV->getInitializer(), Alloca, FirstI);
2140
2141       GV->replaceAllUsesWith(Alloca);
2142       GV->eraseFromParent();
2143       ++NumLocalized;
2144       return true;
2145     }
2146     
2147     // If the global is never loaded (but may be stored to), it is dead.
2148     // Delete it now.
2149     if (!GS.isLoaded) {
2150       DEBUG(errs() << "GLOBAL NEVER LOADED: " << *GV);
2151
2152       // Delete any stores we can find to the global.  We may not be able to
2153       // make it completely dead though.
2154       bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), 
2155                                                 GV->getContext());
2156
2157       // If the global is dead now, delete it.
2158       if (GV->use_empty()) {
2159         GV->eraseFromParent();
2160         ++NumDeleted;
2161         Changed = true;
2162       }
2163       return Changed;
2164
2165     } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
2166       DEBUG(errs() << "MARKING CONSTANT: " << *GV);
2167       GV->setConstant(true);
2168
2169       // Clean up any obviously simplifiable users now.
2170       CleanupConstantGlobalUsers(GV, GV->getInitializer(), GV->getContext());
2171
2172       // If the global is dead now, just nuke it.
2173       if (GV->use_empty()) {
2174         DEBUG(errs() << "   *** Marking constant allowed us to simplify "
2175                      << "all users and delete global!\n");
2176         GV->eraseFromParent();
2177         ++NumDeleted;
2178       }
2179
2180       ++NumMarked;
2181       return true;
2182     } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
2183       if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
2184         if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD,
2185                                                    GV->getContext())) {
2186           GVI = FirstNewGV;  // Don't skip the newly produced globals!
2187           return true;
2188         }
2189     } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
2190       // If the initial value for the global was an undef value, and if only
2191       // one other value was stored into it, we can just change the
2192       // initializer to be the stored value, then delete all stores to the
2193       // global.  This allows us to mark it constant.
2194       if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2195         if (isa<UndefValue>(GV->getInitializer())) {
2196           // Change the initial value here.
2197           GV->setInitializer(SOVConstant);
2198
2199           // Clean up any obviously simplifiable users now.
2200           CleanupConstantGlobalUsers(GV, GV->getInitializer(), 
2201                                      GV->getContext());
2202
2203           if (GV->use_empty()) {
2204             DEBUG(errs() << "   *** Substituting initializer allowed us to "
2205                          << "simplify all users and delete global!\n");
2206             GV->eraseFromParent();
2207             ++NumDeleted;
2208           } else {
2209             GVI = GV;
2210           }
2211           ++NumSubstitute;
2212           return true;
2213         }
2214
2215       // Try to optimize globals based on the knowledge that only one value
2216       // (besides its initializer) is ever stored to the global.
2217       if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
2218                                    getAnalysisIfAvailable<TargetData>(),
2219                                    GV->getContext()))
2220         return true;
2221
2222       // Otherwise, if the global was not a boolean, we can shrink it to be a
2223       // boolean.
2224       if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2225         if (TryToShrinkGlobalToBoolean(GV, SOVConstant, GV->getContext())) {
2226           ++NumShrunkToBool;
2227           return true;
2228         }
2229     }
2230   }
2231   return false;
2232 }
2233
2234 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
2235 /// function, changing them to FastCC.
2236 static void ChangeCalleesToFastCall(Function *F) {
2237   for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
2238     CallSite User(cast<Instruction>(*UI));
2239     User.setCallingConv(CallingConv::Fast);
2240   }
2241 }
2242
2243 static AttrListPtr StripNest(const AttrListPtr &Attrs) {
2244   for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
2245     if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
2246       continue;
2247
2248     // There can be only one.
2249     return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
2250   }
2251
2252   return Attrs;
2253 }
2254
2255 static void RemoveNestAttribute(Function *F) {
2256   F->setAttributes(StripNest(F->getAttributes()));
2257   for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
2258     CallSite User(cast<Instruction>(*UI));
2259     User.setAttributes(StripNest(User.getAttributes()));
2260   }
2261 }
2262
2263 bool GlobalOpt::OptimizeFunctions(Module &M) {
2264   bool Changed = false;
2265   // Optimize functions.
2266   for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
2267     Function *F = FI++;
2268     // Functions without names cannot be referenced outside this module.
2269     if (!F->hasName() && !F->isDeclaration())
2270       F->setLinkage(GlobalValue::InternalLinkage);
2271     F->removeDeadConstantUsers();
2272     if (F->use_empty() && (F->hasLocalLinkage() ||
2273                            F->hasLinkOnceLinkage())) {
2274       M.getFunctionList().erase(F);
2275       Changed = true;
2276       ++NumFnDeleted;
2277     } else if (F->hasLocalLinkage()) {
2278       if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
2279           !F->hasAddressTaken()) {
2280         // If this function has C calling conventions, is not a varargs
2281         // function, and is only called directly, promote it to use the Fast
2282         // calling convention.
2283         F->setCallingConv(CallingConv::Fast);
2284         ChangeCalleesToFastCall(F);
2285         ++NumFastCallFns;
2286         Changed = true;
2287       }
2288
2289       if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
2290           !F->hasAddressTaken()) {
2291         // The function is not used by a trampoline intrinsic, so it is safe
2292         // to remove the 'nest' attribute.
2293         RemoveNestAttribute(F);
2294         ++NumNestRemoved;
2295         Changed = true;
2296       }
2297     }
2298   }
2299   return Changed;
2300 }
2301
2302 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
2303   bool Changed = false;
2304   for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
2305        GVI != E; ) {
2306     GlobalVariable *GV = GVI++;
2307     // Global variables without names cannot be referenced outside this module.
2308     if (!GV->hasName() && !GV->isDeclaration())
2309       GV->setLinkage(GlobalValue::InternalLinkage);
2310     if (!GV->isConstant() && GV->hasLocalLinkage() &&
2311         GV->hasInitializer())
2312       Changed |= ProcessInternalGlobal(GV, GVI);
2313   }
2314   return Changed;
2315 }
2316
2317 /// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
2318 /// initializers have an init priority of 65535.
2319 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
2320   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
2321        I != E; ++I)
2322     if (I->getName() == "llvm.global_ctors") {
2323       // Found it, verify it's an array of { int, void()* }.
2324       const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
2325       if (!ATy) return 0;
2326       const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
2327       if (!STy || STy->getNumElements() != 2 ||
2328           STy->getElementType(0) != Type::getInt32Ty(M.getContext())) return 0;
2329       const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
2330       if (!PFTy) return 0;
2331       const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
2332       if (!FTy || FTy->getReturnType() != Type::getVoidTy(M.getContext()) ||
2333           FTy->isVarArg() || FTy->getNumParams() != 0)
2334         return 0;
2335       
2336       // Verify that the initializer is simple enough for us to handle.
2337       if (!I->hasDefinitiveInitializer()) return 0;
2338       ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
2339       if (!CA) return 0;
2340       for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2341         if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
2342           if (isa<ConstantPointerNull>(CS->getOperand(1)))
2343             continue;
2344
2345           // Must have a function or null ptr.
2346           if (!isa<Function>(CS->getOperand(1)))
2347             return 0;
2348           
2349           // Init priority must be standard.
2350           ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
2351           if (!CI || CI->getZExtValue() != 65535)
2352             return 0;
2353         } else {
2354           return 0;
2355         }
2356       
2357       return I;
2358     }
2359   return 0;
2360 }
2361
2362 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
2363 /// return a list of the functions and null terminator as a vector.
2364 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
2365   ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
2366   std::vector<Function*> Result;
2367   Result.reserve(CA->getNumOperands());
2368   for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2369     ConstantStruct *CS = cast<ConstantStruct>(*i);
2370     Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2371   }
2372   return Result;
2373 }
2374
2375 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2376 /// specified array, returning the new global to use.
2377 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL, 
2378                                           const std::vector<Function*> &Ctors,
2379                                           LLVMContext &Context) {
2380   // If we made a change, reassemble the initializer list.
2381   std::vector<Constant*> CSVals;
2382   CSVals.push_back(ConstantInt::get(Type::getInt32Ty(Context), 65535));
2383   CSVals.push_back(0);
2384   
2385   // Create the new init list.
2386   std::vector<Constant*> CAList;
2387   for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
2388     if (Ctors[i]) {
2389       CSVals[1] = Ctors[i];
2390     } else {
2391       const Type *FTy = FunctionType::get(Type::getVoidTy(Context), false);
2392       const PointerType *PFTy = PointerType::getUnqual(FTy);
2393       CSVals[1] = Constant::getNullValue(PFTy);
2394       CSVals[0] = ConstantInt::get(Type::getInt32Ty(Context), 2147483647);
2395     }
2396     CAList.push_back(ConstantStruct::get(Context, CSVals, false));
2397   }
2398   
2399   // Create the array initializer.
2400   const Type *StructTy =
2401       cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
2402   Constant *CA = ConstantArray::get(ArrayType::get(StructTy, 
2403                                                    CAList.size()), CAList);
2404   
2405   // If we didn't change the number of elements, don't create a new GV.
2406   if (CA->getType() == GCL->getInitializer()->getType()) {
2407     GCL->setInitializer(CA);
2408     return GCL;
2409   }
2410   
2411   // Create the new global and insert it next to the existing list.
2412   GlobalVariable *NGV = new GlobalVariable(Context, CA->getType(), 
2413                                            GCL->isConstant(),
2414                                            GCL->getLinkage(), CA, "",
2415                                            GCL->isThreadLocal());
2416   GCL->getParent()->getGlobalList().insert(GCL, NGV);
2417   NGV->takeName(GCL);
2418   
2419   // Nuke the old list, replacing any uses with the new one.
2420   if (!GCL->use_empty()) {
2421     Constant *V = NGV;
2422     if (V->getType() != GCL->getType())
2423       V = ConstantExpr::getBitCast(V, GCL->getType());
2424     GCL->replaceAllUsesWith(V);
2425   }
2426   GCL->eraseFromParent();
2427   
2428   if (Ctors.size())
2429     return NGV;
2430   else
2431     return 0;
2432 }
2433
2434
2435 static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
2436                         Value *V) {
2437   if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2438   Constant *R = ComputedValues[V];
2439   assert(R && "Reference to an uncomputed value!");
2440   return R;
2441 }
2442
2443 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2444 /// enough for us to understand.  In particular, if it is a cast of something,
2445 /// we punt.  We basically just support direct accesses to globals and GEP's of
2446 /// globals.  This should be kept up to date with CommitValueTo.
2447 static bool isSimpleEnoughPointerToCommit(Constant *C, LLVMContext &Context) {
2448   // Conservatively, avoid aggregate types. This is because we don't
2449   // want to worry about them partially overlapping other stores.
2450   if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2451     return false;
2452
2453   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2454     // Do not allow weak/linkonce/dllimport/dllexport linkage or
2455     // external globals.
2456     return GV->hasDefinitiveInitializer();
2457
2458   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2459     // Handle a constantexpr gep.
2460     if (CE->getOpcode() == Instruction::GetElementPtr &&
2461         isa<GlobalVariable>(CE->getOperand(0)) &&
2462         cast<GEPOperator>(CE)->isInBounds()) {
2463       GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2464       // Do not allow weak/linkonce/dllimport/dllexport linkage or
2465       // external globals.
2466       if (!GV->hasDefinitiveInitializer())
2467         return false;
2468
2469       // The first index must be zero.
2470       ConstantInt *CI = dyn_cast<ConstantInt>(*next(CE->op_begin()));
2471       if (!CI || !CI->isZero()) return false;
2472
2473       // The remaining indices must be compile-time known integers within the
2474       // notional bounds of the corresponding static array types.
2475       if (!CE->isGEPWithNoNotionalOverIndexing())
2476         return false;
2477
2478       return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2479     }
2480   return false;
2481 }
2482
2483 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2484 /// initializer.  This returns 'Init' modified to reflect 'Val' stored into it.
2485 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2486 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
2487                                    ConstantExpr *Addr, unsigned OpNo,
2488                                    LLVMContext &Context) {
2489   // Base case of the recursion.
2490   if (OpNo == Addr->getNumOperands()) {
2491     assert(Val->getType() == Init->getType() && "Type mismatch!");
2492     return Val;
2493   }
2494   
2495   if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2496     std::vector<Constant*> Elts;
2497
2498     // Break up the constant into its elements.
2499     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2500       for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2501         Elts.push_back(cast<Constant>(*i));
2502     } else if (isa<ConstantAggregateZero>(Init)) {
2503       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2504         Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
2505     } else if (isa<UndefValue>(Init)) {
2506       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2507         Elts.push_back(UndefValue::get(STy->getElementType(i)));
2508     } else {
2509       llvm_unreachable("This code is out of sync with "
2510              " ConstantFoldLoadThroughGEPConstantExpr");
2511     }
2512     
2513     // Replace the element that we are supposed to.
2514     ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2515     unsigned Idx = CU->getZExtValue();
2516     assert(Idx < STy->getNumElements() && "Struct index out of range!");
2517     Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1, Context);
2518     
2519     // Return the modified struct.
2520     return ConstantStruct::get(Context, &Elts[0], Elts.size(), STy->isPacked());
2521   } else {
2522     ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2523     const ArrayType *ATy = cast<ArrayType>(Init->getType());
2524
2525     // Break up the array into elements.
2526     std::vector<Constant*> Elts;
2527     if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2528       for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2529         Elts.push_back(cast<Constant>(*i));
2530     } else if (isa<ConstantAggregateZero>(Init)) {
2531       Constant *Elt = Constant::getNullValue(ATy->getElementType());
2532       Elts.assign(ATy->getNumElements(), Elt);
2533     } else if (isa<UndefValue>(Init)) {
2534       Constant *Elt = UndefValue::get(ATy->getElementType());
2535       Elts.assign(ATy->getNumElements(), Elt);
2536     } else {
2537       llvm_unreachable("This code is out of sync with "
2538              " ConstantFoldLoadThroughGEPConstantExpr");
2539     }
2540     
2541     assert(CI->getZExtValue() < ATy->getNumElements());
2542     Elts[CI->getZExtValue()] =
2543       EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1, Context);
2544     return ConstantArray::get(ATy, Elts);
2545   }    
2546 }
2547
2548 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
2549 /// isSimpleEnoughPointerToCommit) should get Val as its value.  Make it happen.
2550 static void CommitValueTo(Constant *Val, Constant *Addr,
2551                           LLVMContext &Context) {
2552   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2553     assert(GV->hasInitializer());
2554     GV->setInitializer(Val);
2555     return;
2556   }
2557   
2558   ConstantExpr *CE = cast<ConstantExpr>(Addr);
2559   GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2560   
2561   Constant *Init = GV->getInitializer();
2562   Init = EvaluateStoreInto(Init, Val, CE, 2, Context);
2563   GV->setInitializer(Init);
2564 }
2565
2566 /// ComputeLoadResult - Return the value that would be computed by a load from
2567 /// P after the stores reflected by 'memory' have been performed.  If we can't
2568 /// decide, return null.
2569 static Constant *ComputeLoadResult(Constant *P,
2570                                 const DenseMap<Constant*, Constant*> &Memory,
2571                                 LLVMContext &Context) {
2572   // If this memory location has been recently stored, use the stored value: it
2573   // is the most up-to-date.
2574   DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
2575   if (I != Memory.end()) return I->second;
2576  
2577   // Access it.
2578   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2579     if (GV->hasDefinitiveInitializer())
2580       return GV->getInitializer();
2581     return 0;
2582   }
2583   
2584   // Handle a constantexpr getelementptr.
2585   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2586     if (CE->getOpcode() == Instruction::GetElementPtr &&
2587         isa<GlobalVariable>(CE->getOperand(0))) {
2588       GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2589       if (GV->hasDefinitiveInitializer())
2590         return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2591     }
2592
2593   return 0;  // don't know how to evaluate.
2594 }
2595
2596 /// EvaluateFunction - Evaluate a call to function F, returning true if
2597 /// successful, false if we can't evaluate it.  ActualArgs contains the formal
2598 /// arguments for the function.
2599 static bool EvaluateFunction(Function *F, Constant *&RetVal,
2600                              const SmallVectorImpl<Constant*> &ActualArgs,
2601                              std::vector<Function*> &CallStack,
2602                              DenseMap<Constant*, Constant*> &MutatedMemory,
2603                              std::vector<GlobalVariable*> &AllocaTmps) {
2604   // Check to see if this function is already executing (recursion).  If so,
2605   // bail out.  TODO: we might want to accept limited recursion.
2606   if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2607     return false;
2608   
2609   LLVMContext &Context = F->getContext();
2610   
2611   CallStack.push_back(F);
2612   
2613   /// Values - As we compute SSA register values, we store their contents here.
2614   DenseMap<Value*, Constant*> Values;
2615   
2616   // Initialize arguments to the incoming values specified.
2617   unsigned ArgNo = 0;
2618   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2619        ++AI, ++ArgNo)
2620     Values[AI] = ActualArgs[ArgNo];
2621
2622   /// ExecutedBlocks - We only handle non-looping, non-recursive code.  As such,
2623   /// we can only evaluate any one basic block at most once.  This set keeps
2624   /// track of what we have executed so we can detect recursive cases etc.
2625   SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2626   
2627   // CurInst - The current instruction we're evaluating.
2628   BasicBlock::iterator CurInst = F->begin()->begin();
2629   
2630   // This is the main evaluation loop.
2631   while (1) {
2632     Constant *InstResult = 0;
2633     
2634     if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
2635       if (SI->isVolatile()) return false;  // no volatile accesses.
2636       Constant *Ptr = getVal(Values, SI->getOperand(1));
2637       if (!isSimpleEnoughPointerToCommit(Ptr, Context))
2638         // If this is too complex for us to commit, reject it.
2639         return false;
2640       Constant *Val = getVal(Values, SI->getOperand(0));
2641       MutatedMemory[Ptr] = Val;
2642     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
2643       InstResult = ConstantExpr::get(BO->getOpcode(),
2644                                      getVal(Values, BO->getOperand(0)),
2645                                      getVal(Values, BO->getOperand(1)));
2646     } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
2647       InstResult = ConstantExpr::getCompare(CI->getPredicate(),
2648                                             getVal(Values, CI->getOperand(0)),
2649                                             getVal(Values, CI->getOperand(1)));
2650     } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
2651       InstResult = ConstantExpr::getCast(CI->getOpcode(),
2652                                          getVal(Values, CI->getOperand(0)),
2653                                          CI->getType());
2654     } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
2655       InstResult =
2656             ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
2657                                            getVal(Values, SI->getOperand(1)),
2658                                            getVal(Values, SI->getOperand(2)));
2659     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2660       Constant *P = getVal(Values, GEP->getOperand(0));
2661       SmallVector<Constant*, 8> GEPOps;
2662       for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2663            i != e; ++i)
2664         GEPOps.push_back(getVal(Values, *i));
2665       InstResult = cast<GEPOperator>(GEP)->isInBounds() ?
2666           ConstantExpr::getInBoundsGetElementPtr(P, &GEPOps[0], GEPOps.size()) :
2667           ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
2668     } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
2669       if (LI->isVolatile()) return false;  // no volatile accesses.
2670       InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
2671                                      MutatedMemory, Context);
2672       if (InstResult == 0) return false; // Could not evaluate load.
2673     } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
2674       if (AI->isArrayAllocation()) return false;  // Cannot handle array allocs.
2675       const Type *Ty = AI->getType()->getElementType();
2676       AllocaTmps.push_back(new GlobalVariable(Context, Ty, false,
2677                                               GlobalValue::InternalLinkage,
2678                                               UndefValue::get(Ty),
2679                                               AI->getName()));
2680       InstResult = AllocaTmps.back();     
2681     } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
2682
2683       // Debug info can safely be ignored here.
2684       if (isa<DbgInfoIntrinsic>(CI)) {
2685         ++CurInst;
2686         continue;
2687       }
2688
2689       // Cannot handle inline asm.
2690       if (isa<InlineAsm>(CI->getOperand(0))) return false;
2691
2692       // Resolve function pointers.
2693       Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2694       if (!Callee) return false;  // Cannot resolve.
2695
2696       SmallVector<Constant*, 8> Formals;
2697       for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2698            i != e; ++i)
2699         Formals.push_back(getVal(Values, *i));
2700
2701       if (Callee->isDeclaration()) {
2702         // If this is a function we can constant fold, do it.
2703         if (Constant *C = ConstantFoldCall(Callee, Formals.data(),
2704                                            Formals.size())) {
2705           InstResult = C;
2706         } else {
2707           return false;
2708         }
2709       } else {
2710         if (Callee->getFunctionType()->isVarArg())
2711           return false;
2712         
2713         Constant *RetVal;
2714         // Execute the call, if successful, use the return value.
2715         if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2716                               MutatedMemory, AllocaTmps))
2717           return false;
2718         InstResult = RetVal;
2719       }
2720     } else if (isa<TerminatorInst>(CurInst)) {
2721       BasicBlock *NewBB = 0;
2722       if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2723         if (BI->isUnconditional()) {
2724           NewBB = BI->getSuccessor(0);
2725         } else {
2726           ConstantInt *Cond =
2727             dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
2728           if (!Cond) return false;  // Cannot determine.
2729
2730           NewBB = BI->getSuccessor(!Cond->getZExtValue());          
2731         }
2732       } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2733         ConstantInt *Val =
2734           dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
2735         if (!Val) return false;  // Cannot determine.
2736         NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2737       } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
2738         if (RI->getNumOperands())
2739           RetVal = getVal(Values, RI->getOperand(0));
2740         
2741         CallStack.pop_back();  // return from fn.
2742         return true;  // We succeeded at evaluating this ctor!
2743       } else {
2744         // invoke, unwind, unreachable.
2745         return false;  // Cannot handle this terminator.
2746       }
2747       
2748       // Okay, we succeeded in evaluating this control flow.  See if we have
2749       // executed the new block before.  If so, we have a looping function,
2750       // which we cannot evaluate in reasonable time.
2751       if (!ExecutedBlocks.insert(NewBB))
2752         return false;  // looped!
2753       
2754       // Okay, we have never been in this block before.  Check to see if there
2755       // are any PHI nodes.  If so, evaluate them with information about where
2756       // we came from.
2757       BasicBlock *OldBB = CurInst->getParent();
2758       CurInst = NewBB->begin();
2759       PHINode *PN;
2760       for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2761         Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2762
2763       // Do NOT increment CurInst.  We know that the terminator had no value.
2764       continue;
2765     } else {
2766       // Did not know how to evaluate this!
2767       return false;
2768     }
2769     
2770     if (!CurInst->use_empty())
2771       Values[CurInst] = InstResult;
2772     
2773     // Advance program counter.
2774     ++CurInst;
2775   }
2776 }
2777
2778 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2779 /// we can.  Return true if we can, false otherwise.
2780 static bool EvaluateStaticConstructor(Function *F) {
2781   /// MutatedMemory - For each store we execute, we update this map.  Loads
2782   /// check this to get the most up-to-date value.  If evaluation is successful,
2783   /// this state is committed to the process.
2784   DenseMap<Constant*, Constant*> MutatedMemory;
2785
2786   /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2787   /// to represent its body.  This vector is needed so we can delete the
2788   /// temporary globals when we are done.
2789   std::vector<GlobalVariable*> AllocaTmps;
2790   
2791   /// CallStack - This is used to detect recursion.  In pathological situations
2792   /// we could hit exponential behavior, but at least there is nothing
2793   /// unbounded.
2794   std::vector<Function*> CallStack;
2795
2796   // Call the function.
2797   Constant *RetValDummy;
2798   bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2799                                       SmallVector<Constant*, 0>(), CallStack,
2800                                       MutatedMemory, AllocaTmps);
2801   if (EvalSuccess) {
2802     // We succeeded at evaluation: commit the result.
2803     DEBUG(errs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2804           << F->getName() << "' to " << MutatedMemory.size()
2805           << " stores.\n");
2806     for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
2807          E = MutatedMemory.end(); I != E; ++I)
2808       CommitValueTo(I->second, I->first, F->getContext());
2809   }
2810   
2811   // At this point, we are done interpreting.  If we created any 'alloca'
2812   // temporaries, release them now.
2813   while (!AllocaTmps.empty()) {
2814     GlobalVariable *Tmp = AllocaTmps.back();
2815     AllocaTmps.pop_back();
2816     
2817     // If there are still users of the alloca, the program is doing something
2818     // silly, e.g. storing the address of the alloca somewhere and using it
2819     // later.  Since this is undefined, we'll just make it be null.
2820     if (!Tmp->use_empty())
2821       Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2822     delete Tmp;
2823   }
2824   
2825   return EvalSuccess;
2826 }
2827
2828
2829
2830 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2831 /// Return true if anything changed.
2832 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2833   std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2834   bool MadeChange = false;
2835   if (Ctors.empty()) return false;
2836   
2837   // Loop over global ctors, optimizing them when we can.
2838   for (unsigned i = 0; i != Ctors.size(); ++i) {
2839     Function *F = Ctors[i];
2840     // Found a null terminator in the middle of the list, prune off the rest of
2841     // the list.
2842     if (F == 0) {
2843       if (i != Ctors.size()-1) {
2844         Ctors.resize(i+1);
2845         MadeChange = true;
2846       }
2847       break;
2848     }
2849     
2850     // We cannot simplify external ctor functions.
2851     if (F->empty()) continue;
2852     
2853     // If we can evaluate the ctor at compile time, do.
2854     if (EvaluateStaticConstructor(F)) {
2855       Ctors.erase(Ctors.begin()+i);
2856       MadeChange = true;
2857       --i;
2858       ++NumCtorsEvaluated;
2859       continue;
2860     }
2861   }
2862   
2863   if (!MadeChange) return false;
2864   
2865   GCL = InstallGlobalCtors(GCL, Ctors, GCL->getContext());
2866   return true;
2867 }
2868
2869 bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
2870   bool Changed = false;
2871
2872   for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
2873        I != E;) {
2874     Module::alias_iterator J = I++;
2875     // Aliases without names cannot be referenced outside this module.
2876     if (!J->hasName() && !J->isDeclaration())
2877       J->setLinkage(GlobalValue::InternalLinkage);
2878     // If the aliasee may change at link time, nothing can be done - bail out.
2879     if (J->mayBeOverridden())
2880       continue;
2881
2882     Constant *Aliasee = J->getAliasee();
2883     GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2884     Target->removeDeadConstantUsers();
2885     bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2886
2887     // Make all users of the alias use the aliasee instead.
2888     if (!J->use_empty()) {
2889       J->replaceAllUsesWith(Aliasee);
2890       ++NumAliasesResolved;
2891       Changed = true;
2892     }
2893
2894     // If the aliasee has internal linkage, give it the name and linkage
2895     // of the alias, and delete the alias.  This turns:
2896     //   define internal ... @f(...)
2897     //   @a = alias ... @f
2898     // into:
2899     //   define ... @a(...)
2900     if (!Target->hasLocalLinkage())
2901       continue;
2902
2903     // The transform is only useful if the alias does not have internal linkage.
2904     if (J->hasLocalLinkage())
2905       continue;
2906
2907     // Do not perform the transform if multiple aliases potentially target the
2908     // aliasee.  This check also ensures that it is safe to replace the section
2909     // and other attributes of the aliasee with those of the alias.
2910     if (!hasOneUse)
2911       continue;
2912
2913     // Give the aliasee the name, linkage and other attributes of the alias.
2914     Target->takeName(J);
2915     Target->setLinkage(J->getLinkage());
2916     Target->GlobalValue::copyAttributesFrom(J);
2917
2918     // Delete the alias.
2919     M.getAliasList().erase(J);
2920     ++NumAliasesRemoved;
2921     Changed = true;
2922   }
2923
2924   return Changed;
2925 }
2926
2927 bool GlobalOpt::runOnModule(Module &M) {
2928   bool Changed = false;
2929   
2930   // Try to find the llvm.globalctors list.
2931   GlobalVariable *GlobalCtors = FindGlobalCtors(M);
2932
2933   bool LocalChange = true;
2934   while (LocalChange) {
2935     LocalChange = false;
2936     
2937     // Delete functions that are trivially dead, ccc -> fastcc
2938     LocalChange |= OptimizeFunctions(M);
2939     
2940     // Optimize global_ctors list.
2941     if (GlobalCtors)
2942       LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2943     
2944     // Optimize non-address-taken globals.
2945     LocalChange |= OptimizeGlobalVars(M);
2946
2947     // Resolve aliases, when possible.
2948     LocalChange |= OptimizeGlobalAliases(M);
2949     Changed |= LocalChange;
2950   }
2951   
2952   // TODO: Move all global ctors functions to the end of the module for code
2953   // layout.
2954   
2955   return Changed;
2956 }