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