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