]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/IR/Module.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / IR / Module.cpp
1 //===- Module.cpp - Implement the Module class ----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Module class for the IR library.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/IR/Module.h"
15 #include "SymbolTableListTraitsImpl.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/IR/Attributes.h"
24 #include "llvm/IR/Comdat.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DebugInfoMetadata.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GVMaterializer.h"
31 #include "llvm/IR/GlobalAlias.h"
32 #include "llvm/IR/GlobalIFunc.h"
33 #include "llvm/IR/GlobalValue.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/IR/Metadata.h"
37 #include "llvm/IR/SymbolTableListTraits.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/IR/TypeFinder.h"
40 #include "llvm/IR/Value.h"
41 #include "llvm/IR/ValueSymbolTable.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/CodeGen.h"
45 #include "llvm/Support/Error.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/Path.h"
48 #include "llvm/Support/RandomNumberGenerator.h"
49 #include "llvm/Support/VersionTuple.h"
50 #include <algorithm>
51 #include <cassert>
52 #include <cstdint>
53 #include <memory>
54 #include <utility>
55 #include <vector>
56
57 using namespace llvm;
58
59 //===----------------------------------------------------------------------===//
60 // Methods to implement the globals and functions lists.
61 //
62
63 // Explicit instantiations of SymbolTableListTraits since some of the methods
64 // are not in the public header file.
65 template class llvm::SymbolTableListTraits<Function>;
66 template class llvm::SymbolTableListTraits<GlobalVariable>;
67 template class llvm::SymbolTableListTraits<GlobalAlias>;
68 template class llvm::SymbolTableListTraits<GlobalIFunc>;
69
70 //===----------------------------------------------------------------------===//
71 // Primitive Module methods.
72 //
73
74 Module::Module(StringRef MID, LLVMContext &C)
75     : Context(C), Materializer(), ModuleID(MID), SourceFileName(MID), DL("") {
76   ValSymTab = new ValueSymbolTable();
77   NamedMDSymTab = new StringMap<NamedMDNode *>();
78   Context.addModule(this);
79 }
80
81 Module::~Module() {
82   Context.removeModule(this);
83   dropAllReferences();
84   GlobalList.clear();
85   FunctionList.clear();
86   AliasList.clear();
87   IFuncList.clear();
88   NamedMDList.clear();
89   delete ValSymTab;
90   delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
91 }
92
93 std::unique_ptr<RandomNumberGenerator> Module::createRNG(const Pass* P) const {
94   SmallString<32> Salt(P->getPassName());
95
96   // This RNG is guaranteed to produce the same random stream only
97   // when the Module ID and thus the input filename is the same. This
98   // might be problematic if the input filename extension changes
99   // (e.g. from .c to .bc or .ll).
100   //
101   // We could store this salt in NamedMetadata, but this would make
102   // the parameter non-const. This would unfortunately make this
103   // interface unusable by any Machine passes, since they only have a
104   // const reference to their IR Module. Alternatively we can always
105   // store salt metadata from the Module constructor.
106   Salt += sys::path::filename(getModuleIdentifier());
107
108   return std::unique_ptr<RandomNumberGenerator>(new RandomNumberGenerator(Salt));
109 }
110
111 /// getNamedValue - Return the first global value in the module with
112 /// the specified name, of arbitrary type.  This method returns null
113 /// if a global with the specified name is not found.
114 GlobalValue *Module::getNamedValue(StringRef Name) const {
115   return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
116 }
117
118 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
119 /// This ID is uniqued across modules in the current LLVMContext.
120 unsigned Module::getMDKindID(StringRef Name) const {
121   return Context.getMDKindID(Name);
122 }
123
124 /// getMDKindNames - Populate client supplied SmallVector with the name for
125 /// custom metadata IDs registered in this LLVMContext.   ID #0 is not used,
126 /// so it is filled in as an empty string.
127 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
128   return Context.getMDKindNames(Result);
129 }
130
131 void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
132   return Context.getOperandBundleTags(Result);
133 }
134
135 //===----------------------------------------------------------------------===//
136 // Methods for easy access to the functions in the module.
137 //
138
139 // getOrInsertFunction - Look up the specified function in the module symbol
140 // table.  If it does not exist, add a prototype for the function and return
141 // it.  This is nice because it allows most passes to get away with not handling
142 // the symbol table directly for this common task.
143 //
144 Constant *Module::getOrInsertFunction(StringRef Name, FunctionType *Ty,
145                                       AttributeList AttributeList) {
146   // See if we have a definition for the specified function already.
147   GlobalValue *F = getNamedValue(Name);
148   if (!F) {
149     // Nope, add it
150     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage,
151                                      DL.getProgramAddressSpace(), Name);
152     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
153       New->setAttributes(AttributeList);
154     FunctionList.push_back(New);
155     return New;                    // Return the new prototype.
156   }
157
158   // If the function exists but has the wrong type, return a bitcast to the
159   // right type.
160   auto *PTy = PointerType::get(Ty, F->getAddressSpace());
161   if (F->getType() != PTy)
162     return ConstantExpr::getBitCast(F, PTy);
163
164   // Otherwise, we just found the existing function or a prototype.
165   return F;
166 }
167
168 Constant *Module::getOrInsertFunction(StringRef Name,
169                                       FunctionType *Ty) {
170   return getOrInsertFunction(Name, Ty, AttributeList());
171 }
172
173 // getFunction - Look up the specified function in the module symbol table.
174 // If it does not exist, return null.
175 //
176 Function *Module::getFunction(StringRef Name) const {
177   return dyn_cast_or_null<Function>(getNamedValue(Name));
178 }
179
180 //===----------------------------------------------------------------------===//
181 // Methods for easy access to the global variables in the module.
182 //
183
184 /// getGlobalVariable - Look up the specified global variable in the module
185 /// symbol table.  If it does not exist, return null.  The type argument
186 /// should be the underlying type of the global, i.e., it should not have
187 /// the top-level PointerType, which represents the address of the global.
188 /// If AllowLocal is set to true, this function will return types that
189 /// have an local. By default, these types are not returned.
190 ///
191 GlobalVariable *Module::getGlobalVariable(StringRef Name,
192                                           bool AllowLocal) const {
193   if (GlobalVariable *Result =
194       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
195     if (AllowLocal || !Result->hasLocalLinkage())
196       return Result;
197   return nullptr;
198 }
199
200 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
201 ///   1. If it does not exist, add a declaration of the global and return it.
202 ///   2. Else, the global exists but has the wrong type: return the function
203 ///      with a constantexpr cast to the right type.
204 ///   3. Finally, if the existing global is the correct declaration, return the
205 ///      existing global.
206 Constant *Module::getOrInsertGlobal(
207     StringRef Name, Type *Ty,
208     function_ref<GlobalVariable *()> CreateGlobalCallback) {
209   // See if we have a definition for the specified global already.
210   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
211   if (!GV)
212     GV = CreateGlobalCallback();
213   assert(GV && "The CreateGlobalCallback is expected to create a global");
214
215   // If the variable exists but has the wrong type, return a bitcast to the
216   // right type.
217   Type *GVTy = GV->getType();
218   PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
219   if (GVTy != PTy)
220     return ConstantExpr::getBitCast(GV, PTy);
221
222   // Otherwise, we just found the existing function or a prototype.
223   return GV;
224 }
225
226 // Overload to construct a global variable using its constructor's defaults.
227 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
228   return getOrInsertGlobal(Name, Ty, [&] {
229     return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
230                               nullptr, Name);
231   });
232 }
233
234 //===----------------------------------------------------------------------===//
235 // Methods for easy access to the global variables in the module.
236 //
237
238 // getNamedAlias - Look up the specified global in the module symbol table.
239 // If it does not exist, return null.
240 //
241 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
242   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
243 }
244
245 GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
246   return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
247 }
248
249 /// getNamedMetadata - Return the first NamedMDNode in the module with the
250 /// specified name. This method returns null if a NamedMDNode with the
251 /// specified name is not found.
252 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
253   SmallString<256> NameData;
254   StringRef NameRef = Name.toStringRef(NameData);
255   return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
256 }
257
258 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
259 /// with the specified name. This method returns a new NamedMDNode if a
260 /// NamedMDNode with the specified name is not found.
261 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
262   NamedMDNode *&NMD =
263     (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
264   if (!NMD) {
265     NMD = new NamedMDNode(Name);
266     NMD->setParent(this);
267     NamedMDList.push_back(NMD);
268   }
269   return NMD;
270 }
271
272 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
273 /// delete it.
274 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
275   static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
276   NamedMDList.erase(NMD->getIterator());
277 }
278
279 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
280   if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
281     uint64_t Val = Behavior->getLimitedValue();
282     if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
283       MFB = static_cast<ModFlagBehavior>(Val);
284       return true;
285     }
286   }
287   return false;
288 }
289
290 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
291 void Module::
292 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
293   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
294   if (!ModFlags) return;
295
296   for (const MDNode *Flag : ModFlags->operands()) {
297     ModFlagBehavior MFB;
298     if (Flag->getNumOperands() >= 3 &&
299         isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
300         dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
301       // Check the operands of the MDNode before accessing the operands.
302       // The verifier will actually catch these failures.
303       MDString *Key = cast<MDString>(Flag->getOperand(1));
304       Metadata *Val = Flag->getOperand(2);
305       Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
306     }
307   }
308 }
309
310 /// Return the corresponding value if Key appears in module flags, otherwise
311 /// return null.
312 Metadata *Module::getModuleFlag(StringRef Key) const {
313   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
314   getModuleFlagsMetadata(ModuleFlags);
315   for (const ModuleFlagEntry &MFE : ModuleFlags) {
316     if (Key == MFE.Key->getString())
317       return MFE.Val;
318   }
319   return nullptr;
320 }
321
322 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
323 /// represents module-level flags. This method returns null if there are no
324 /// module-level flags.
325 NamedMDNode *Module::getModuleFlagsMetadata() const {
326   return getNamedMetadata("llvm.module.flags");
327 }
328
329 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
330 /// represents module-level flags. If module-level flags aren't found, it
331 /// creates the named metadata that contains them.
332 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
333   return getOrInsertNamedMetadata("llvm.module.flags");
334 }
335
336 /// addModuleFlag - Add a module-level flag to the module-level flags
337 /// metadata. It will create the module-level flags named metadata if it doesn't
338 /// already exist.
339 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
340                            Metadata *Val) {
341   Type *Int32Ty = Type::getInt32Ty(Context);
342   Metadata *Ops[3] = {
343       ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
344       MDString::get(Context, Key), Val};
345   getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
346 }
347 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
348                            Constant *Val) {
349   addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
350 }
351 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
352                            uint32_t Val) {
353   Type *Int32Ty = Type::getInt32Ty(Context);
354   addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
355 }
356 void Module::addModuleFlag(MDNode *Node) {
357   assert(Node->getNumOperands() == 3 &&
358          "Invalid number of operands for module flag!");
359   assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
360          isa<MDString>(Node->getOperand(1)) &&
361          "Invalid operand types for module flag!");
362   getOrInsertModuleFlagsMetadata()->addOperand(Node);
363 }
364
365 void Module::setDataLayout(StringRef Desc) {
366   DL.reset(Desc);
367 }
368
369 void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
370
371 const DataLayout &Module::getDataLayout() const { return DL; }
372
373 DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
374   return cast<DICompileUnit>(CUs->getOperand(Idx));
375 }
376 DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
377   return cast<DICompileUnit>(CUs->getOperand(Idx));
378 }
379
380 void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
381   while (CUs && (Idx < CUs->getNumOperands()) &&
382          ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
383     ++Idx;
384 }
385
386 //===----------------------------------------------------------------------===//
387 // Methods to control the materialization of GlobalValues in the Module.
388 //
389 void Module::setMaterializer(GVMaterializer *GVM) {
390   assert(!Materializer &&
391          "Module already has a GVMaterializer.  Call materializeAll"
392          " to clear it out before setting another one.");
393   Materializer.reset(GVM);
394 }
395
396 Error Module::materialize(GlobalValue *GV) {
397   if (!Materializer)
398     return Error::success();
399
400   return Materializer->materialize(GV);
401 }
402
403 Error Module::materializeAll() {
404   if (!Materializer)
405     return Error::success();
406   std::unique_ptr<GVMaterializer> M = std::move(Materializer);
407   return M->materializeModule();
408 }
409
410 Error Module::materializeMetadata() {
411   if (!Materializer)
412     return Error::success();
413   return Materializer->materializeMetadata();
414 }
415
416 //===----------------------------------------------------------------------===//
417 // Other module related stuff.
418 //
419
420 std::vector<StructType *> Module::getIdentifiedStructTypes() const {
421   // If we have a materializer, it is possible that some unread function
422   // uses a type that is currently not visible to a TypeFinder, so ask
423   // the materializer which types it created.
424   if (Materializer)
425     return Materializer->getIdentifiedStructTypes();
426
427   std::vector<StructType *> Ret;
428   TypeFinder SrcStructTypes;
429   SrcStructTypes.run(*this, true);
430   Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
431   return Ret;
432 }
433
434 // dropAllReferences() - This function causes all the subelements to "let go"
435 // of all references that they are maintaining.  This allows one to 'delete' a
436 // whole module at a time, even though there may be circular references... first
437 // all references are dropped, and all use counts go to zero.  Then everything
438 // is deleted for real.  Note that no operations are valid on an object that
439 // has "dropped all references", except operator delete.
440 //
441 void Module::dropAllReferences() {
442   for (Function &F : *this)
443     F.dropAllReferences();
444
445   for (GlobalVariable &GV : globals())
446     GV.dropAllReferences();
447
448   for (GlobalAlias &GA : aliases())
449     GA.dropAllReferences();
450
451   for (GlobalIFunc &GIF : ifuncs())
452     GIF.dropAllReferences();
453 }
454
455 unsigned Module::getNumberRegisterParameters() const {
456   auto *Val =
457       cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
458   if (!Val)
459     return 0;
460   return cast<ConstantInt>(Val->getValue())->getZExtValue();
461 }
462
463 unsigned Module::getDwarfVersion() const {
464   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
465   if (!Val)
466     return 0;
467   return cast<ConstantInt>(Val->getValue())->getZExtValue();
468 }
469
470 unsigned Module::getCodeViewFlag() const {
471   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
472   if (!Val)
473     return 0;
474   return cast<ConstantInt>(Val->getValue())->getZExtValue();
475 }
476
477 unsigned Module::getInstructionCount() {
478   unsigned NumInstrs = 0;
479   for (Function &F : FunctionList)
480     NumInstrs += F.getInstructionCount();
481   return NumInstrs;
482 }
483
484 Comdat *Module::getOrInsertComdat(StringRef Name) {
485   auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
486   Entry.second.Name = &Entry;
487   return &Entry.second;
488 }
489
490 PICLevel::Level Module::getPICLevel() const {
491   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
492
493   if (!Val)
494     return PICLevel::NotPIC;
495
496   return static_cast<PICLevel::Level>(
497       cast<ConstantInt>(Val->getValue())->getZExtValue());
498 }
499
500 void Module::setPICLevel(PICLevel::Level PL) {
501   addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL);
502 }
503
504 PIELevel::Level Module::getPIELevel() const {
505   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
506
507   if (!Val)
508     return PIELevel::Default;
509
510   return static_cast<PIELevel::Level>(
511       cast<ConstantInt>(Val->getValue())->getZExtValue());
512 }
513
514 void Module::setPIELevel(PIELevel::Level PL) {
515   addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
516 }
517
518 Optional<CodeModel::Model> Module::getCodeModel() const {
519   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model"));
520
521   if (!Val)
522     return None;
523
524   return static_cast<CodeModel::Model>(
525       cast<ConstantInt>(Val->getValue())->getZExtValue());
526 }
527
528 void Module::setCodeModel(CodeModel::Model CL) {
529   // Linking object files with different code models is undefined behavior
530   // because the compiler would have to generate additional code (to span
531   // longer jumps) if a larger code model is used with a smaller one.
532   // Therefore we will treat attempts to mix code models as an error.
533   addModuleFlag(ModFlagBehavior::Error, "Code Model", CL);
534 }
535
536 void Module::setProfileSummary(Metadata *M) {
537   addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
538 }
539
540 Metadata *Module::getProfileSummary() {
541   return getModuleFlag("ProfileSummary");
542 }
543
544 void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
545   OwnedMemoryBuffer = std::move(MB);
546 }
547
548 bool Module::getRtLibUseGOT() const {
549   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
550   return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
551 }
552
553 void Module::setRtLibUseGOT() {
554   addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
555 }
556
557 void Module::setSDKVersion(const VersionTuple &V) {
558   SmallVector<unsigned, 3> Entries;
559   Entries.push_back(V.getMajor());
560   if (auto Minor = V.getMinor()) {
561     Entries.push_back(*Minor);
562     if (auto Subminor = V.getSubminor())
563       Entries.push_back(*Subminor);
564     // Ignore the 'build' component as it can't be represented in the object
565     // file.
566   }
567   addModuleFlag(ModFlagBehavior::Warning, "SDK Version",
568                 ConstantDataArray::get(Context, Entries));
569 }
570
571 VersionTuple Module::getSDKVersion() const {
572   auto *CM = dyn_cast_or_null<ConstantAsMetadata>(getModuleFlag("SDK Version"));
573   if (!CM)
574     return {};
575   auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
576   if (!Arr)
577     return {};
578   auto getVersionComponent = [&](unsigned Index) -> Optional<unsigned> {
579     if (Index >= Arr->getNumElements())
580       return None;
581     return (unsigned)Arr->getElementAsInteger(Index);
582   };
583   auto Major = getVersionComponent(0);
584   if (!Major)
585     return {};
586   VersionTuple Result = VersionTuple(*Major);
587   if (auto Minor = getVersionComponent(1)) {
588     Result = VersionTuple(*Major, *Minor);
589     if (auto Subminor = getVersionComponent(2)) {
590       Result = VersionTuple(*Major, *Minor, *Subminor);
591     }
592   }
593   return Result;
594 }
595
596 GlobalVariable *llvm::collectUsedGlobalVariables(
597     const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) {
598   const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
599   GlobalVariable *GV = M.getGlobalVariable(Name);
600   if (!GV || !GV->hasInitializer())
601     return GV;
602
603   const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
604   for (Value *Op : Init->operands()) {
605     GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());
606     Set.insert(G);
607   }
608   return GV;
609 }