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