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