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