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