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