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