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