xref: /llvm-project/llvm/lib/IR/Module.cpp (revision b7cd564fa3ecc2a9ed0fded98c24f68e2dad63ad)
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/SmallString.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/IR/Attributes.h"
21 #include "llvm/IR/Comdat.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DebugInfoMetadata.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/GVMaterializer.h"
28 #include "llvm/IR/GlobalAlias.h"
29 #include "llvm/IR/GlobalIFunc.h"
30 #include "llvm/IR/GlobalValue.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/Metadata.h"
34 #include "llvm/IR/ModuleSummaryIndex.h"
35 #include "llvm/IR/SymbolTableListTraits.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/IR/TypeFinder.h"
38 #include "llvm/IR/Value.h"
39 #include "llvm/IR/ValueSymbolTable.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/CodeGen.h"
42 #include "llvm/Support/Error.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/RandomNumberGenerator.h"
46 #include "llvm/Support/VersionTuple.h"
47 #include <algorithm>
48 #include <cassert>
49 #include <cstdint>
50 #include <memory>
51 #include <optional>
52 #include <utility>
53 #include <vector>
54 
55 using namespace llvm;
56 
57 extern cl::opt<bool> UseNewDbgInfoFormat;
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), ValSymTab(std::make_unique<ValueSymbolTable>(-1)),
76       ModuleID(std::string(MID)), SourceFileName(std::string(MID)), DL(""),
77       IsNewDbgInfoFormat(UseNewDbgInfoFormat) {
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 }
89 
90 void Module::removeDebugIntrinsicDeclarations() {
91   auto *DeclareIntrinsicFn =
92       Intrinsic::getDeclaration(this, Intrinsic::dbg_declare);
93   assert((!isMaterialized() || DeclareIntrinsicFn->hasZeroLiveUses()) &&
94          "Debug declare intrinsic should have had uses removed.");
95   DeclareIntrinsicFn->eraseFromParent();
96   auto *ValueIntrinsicFn =
97       Intrinsic::getDeclaration(this, Intrinsic::dbg_value);
98   assert((!isMaterialized() || ValueIntrinsicFn->hasZeroLiveUses()) &&
99          "Debug value intrinsic should have had uses removed.");
100   ValueIntrinsicFn->eraseFromParent();
101   auto *AssignIntrinsicFn =
102       Intrinsic::getDeclaration(this, Intrinsic::dbg_assign);
103   assert((!isMaterialized() || AssignIntrinsicFn->hasZeroLiveUses()) &&
104          "Debug assign intrinsic should have had uses removed.");
105   AssignIntrinsicFn->eraseFromParent();
106   auto *LabelntrinsicFn = Intrinsic::getDeclaration(this, Intrinsic::dbg_label);
107   assert((!isMaterialized() || LabelntrinsicFn->hasZeroLiveUses()) &&
108          "Debug label intrinsic should have had uses removed.");
109   LabelntrinsicFn->eraseFromParent();
110 }
111 
112 std::unique_ptr<RandomNumberGenerator>
113 Module::createRNG(const StringRef Name) const {
114   SmallString<32> Salt(Name);
115 
116   // This RNG is guaranteed to produce the same random stream only
117   // when the Module ID and thus the input filename is the same. This
118   // might be problematic if the input filename extension changes
119   // (e.g. from .c to .bc or .ll).
120   //
121   // We could store this salt in NamedMetadata, but this would make
122   // the parameter non-const. This would unfortunately make this
123   // interface unusable by any Machine passes, since they only have a
124   // const reference to their IR Module. Alternatively we can always
125   // store salt metadata from the Module constructor.
126   Salt += sys::path::filename(getModuleIdentifier());
127 
128   return std::unique_ptr<RandomNumberGenerator>(
129       new RandomNumberGenerator(Salt));
130 }
131 
132 /// getNamedValue - Return the first global value in the module with
133 /// the specified name, of arbitrary type.  This method returns null
134 /// if a global with the specified name is not found.
135 GlobalValue *Module::getNamedValue(StringRef Name) const {
136   return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
137 }
138 
139 unsigned Module::getNumNamedValues() const {
140   return getValueSymbolTable().size();
141 }
142 
143 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
144 /// This ID is uniqued across modules in the current LLVMContext.
145 unsigned Module::getMDKindID(StringRef Name) const {
146   return Context.getMDKindID(Name);
147 }
148 
149 /// getMDKindNames - Populate client supplied SmallVector with the name for
150 /// custom metadata IDs registered in this LLVMContext.   ID #0 is not used,
151 /// so it is filled in as an empty string.
152 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
153   return Context.getMDKindNames(Result);
154 }
155 
156 void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
157   return Context.getOperandBundleTags(Result);
158 }
159 
160 //===----------------------------------------------------------------------===//
161 // Methods for easy access to the functions in the module.
162 //
163 
164 // getOrInsertFunction - Look up the specified function in the module symbol
165 // table.  If it does not exist, add a prototype for the function and return
166 // it.  This is nice because it allows most passes to get away with not handling
167 // the symbol table directly for this common task.
168 //
169 FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty,
170                                            AttributeList AttributeList) {
171   // See if we have a definition for the specified function already.
172   GlobalValue *F = getNamedValue(Name);
173   if (!F) {
174     // Nope, add it
175     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage,
176                                      DL.getProgramAddressSpace(), Name, this);
177     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
178       New->setAttributes(AttributeList);
179     return {Ty, New}; // Return the new prototype.
180   }
181 
182   // Otherwise, we just found the existing function or a prototype.
183   return {Ty, F};
184 }
185 
186 FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty) {
187   return getOrInsertFunction(Name, Ty, AttributeList());
188 }
189 
190 // getFunction - Look up the specified function in the module symbol table.
191 // If it does not exist, return null.
192 //
193 Function *Module::getFunction(StringRef Name) const {
194   return dyn_cast_or_null<Function>(getNamedValue(Name));
195 }
196 
197 //===----------------------------------------------------------------------===//
198 // Methods for easy access to the global variables in the module.
199 //
200 
201 /// getGlobalVariable - Look up the specified global variable in the module
202 /// symbol table.  If it does not exist, return null.  The type argument
203 /// should be the underlying type of the global, i.e., it should not have
204 /// the top-level PointerType, which represents the address of the global.
205 /// If AllowLocal is set to true, this function will return types that
206 /// have an local. By default, these types are not returned.
207 ///
208 GlobalVariable *Module::getGlobalVariable(StringRef Name,
209                                           bool AllowLocal) const {
210   if (GlobalVariable *Result =
211       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
212     if (AllowLocal || !Result->hasLocalLinkage())
213       return Result;
214   return nullptr;
215 }
216 
217 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
218 ///   1. If it does not exist, add a declaration of the global and return it.
219 ///   2. Else, the global exists but has the wrong type: return the function
220 ///      with a constantexpr cast to the right type.
221 ///   3. Finally, if the existing global is the correct declaration, return the
222 ///      existing global.
223 Constant *Module::getOrInsertGlobal(
224     StringRef Name, Type *Ty,
225     function_ref<GlobalVariable *()> CreateGlobalCallback) {
226   // See if we have a definition for the specified global already.
227   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
228   if (!GV)
229     GV = CreateGlobalCallback();
230   assert(GV && "The CreateGlobalCallback is expected to create a global");
231 
232   // Otherwise, we just found the existing function or a prototype.
233   return GV;
234 }
235 
236 // Overload to construct a global variable using its constructor's defaults.
237 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
238   return getOrInsertGlobal(Name, Ty, [&] {
239     return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
240                               nullptr, Name);
241   });
242 }
243 
244 //===----------------------------------------------------------------------===//
245 // Methods for easy access to the global variables in the module.
246 //
247 
248 // getNamedAlias - Look up the specified global in the module symbol table.
249 // If it does not exist, return null.
250 //
251 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
252   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
253 }
254 
255 GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
256   return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
257 }
258 
259 /// getNamedMetadata - Return the first NamedMDNode in the module with the
260 /// specified name. This method returns null if a NamedMDNode with the
261 /// specified name is not found.
262 NamedMDNode *Module::getNamedMetadata(StringRef Name) const {
263   return NamedMDSymTab.lookup(Name);
264 }
265 
266 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
267 /// with the specified name. This method returns a new NamedMDNode if a
268 /// NamedMDNode with the specified name is not found.
269 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
270   NamedMDNode *&NMD = NamedMDSymTab[Name];
271   if (!NMD) {
272     NMD = new NamedMDNode(Name);
273     NMD->setParent(this);
274     insertNamedMDNode(NMD);
275   }
276   return NMD;
277 }
278 
279 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
280 /// delete it.
281 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
282   NamedMDSymTab.erase(NMD->getName());
283   eraseNamedMDNode(NMD);
284 }
285 
286 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
287   if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
288     uint64_t Val = Behavior->getLimitedValue();
289     if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
290       MFB = static_cast<ModFlagBehavior>(Val);
291       return true;
292     }
293   }
294   return false;
295 }
296 
297 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
298 void Module::
299 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
300   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
301   if (!ModFlags) return;
302 
303   for (const MDNode *Flag : ModFlags->operands()) {
304     // The verifier will catch errors, so no need to check them here.
305     auto *MFBConstant = mdconst::extract<ConstantInt>(Flag->getOperand(0));
306     auto MFB = static_cast<ModFlagBehavior>(MFBConstant->getLimitedValue());
307     MDString *Key = cast<MDString>(Flag->getOperand(1));
308     Metadata *Val = Flag->getOperand(2);
309     Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
310   }
311 }
312 
313 /// Return the corresponding value if Key appears in module flags, otherwise
314 /// return null.
315 Metadata *Module::getModuleFlag(StringRef Key) const {
316   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
317   if (!ModFlags)
318     return nullptr;
319   for (const MDNode *Flag : ModFlags->operands()) {
320     if (Key == cast<MDString>(Flag->getOperand(1))->getString())
321       return Flag->getOperand(2);
322   }
323   return nullptr;
324 }
325 
326 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
327 /// represents module-level flags. This method returns null if there are no
328 /// module-level flags.
329 NamedMDNode *Module::getModuleFlagsMetadata() const {
330   return getNamedMetadata("llvm.module.flags");
331 }
332 
333 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
334 /// represents module-level flags. If module-level flags aren't found, it
335 /// creates the named metadata that contains them.
336 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
337   return getOrInsertNamedMetadata("llvm.module.flags");
338 }
339 
340 /// addModuleFlag - Add a module-level flag to the module-level flags
341 /// metadata. It will create the module-level flags named metadata if it doesn't
342 /// already exist.
343 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
344                            Metadata *Val) {
345   Type *Int32Ty = Type::getInt32Ty(Context);
346   Metadata *Ops[3] = {
347       ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
348       MDString::get(Context, Key), Val};
349   getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
350 }
351 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
352                            Constant *Val) {
353   addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
354 }
355 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
356                            uint32_t Val) {
357   Type *Int32Ty = Type::getInt32Ty(Context);
358   addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
359 }
360 void Module::addModuleFlag(MDNode *Node) {
361   assert(Node->getNumOperands() == 3 &&
362          "Invalid number of operands for module flag!");
363   assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
364          isa<MDString>(Node->getOperand(1)) &&
365          "Invalid operand types for module flag!");
366   getOrInsertModuleFlagsMetadata()->addOperand(Node);
367 }
368 
369 void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
370                            Metadata *Val) {
371   NamedMDNode *ModFlags = getOrInsertModuleFlagsMetadata();
372   // Replace the flag if it already exists.
373   for (MDNode *Flag : ModFlags->operands()) {
374     if (cast<MDString>(Flag->getOperand(1))->getString() == Key) {
375       Flag->replaceOperandWith(2, Val);
376       return;
377     }
378   }
379   addModuleFlag(Behavior, Key, Val);
380 }
381 void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
382                            Constant *Val) {
383   setModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
384 }
385 void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
386                            uint32_t Val) {
387   Type *Int32Ty = Type::getInt32Ty(Context);
388   setModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
389 }
390 
391 void Module::setDataLayout(StringRef Desc) {
392   DL.reset(Desc);
393 }
394 
395 void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
396 
397 DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
398   return cast<DICompileUnit>(CUs->getOperand(Idx));
399 }
400 DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
401   return cast<DICompileUnit>(CUs->getOperand(Idx));
402 }
403 
404 void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
405   while (CUs && (Idx < CUs->getNumOperands()) &&
406          ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
407     ++Idx;
408 }
409 
410 iterator_range<Module::global_object_iterator> Module::global_objects() {
411   return concat<GlobalObject>(functions(), globals());
412 }
413 iterator_range<Module::const_global_object_iterator>
414 Module::global_objects() const {
415   return concat<const GlobalObject>(functions(), globals());
416 }
417 
418 iterator_range<Module::global_value_iterator> Module::global_values() {
419   return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs());
420 }
421 iterator_range<Module::const_global_value_iterator>
422 Module::global_values() const {
423   return concat<const GlobalValue>(functions(), globals(), aliases(), ifuncs());
424 }
425 
426 //===----------------------------------------------------------------------===//
427 // Methods to control the materialization of GlobalValues in the Module.
428 //
429 void Module::setMaterializer(GVMaterializer *GVM) {
430   assert(!Materializer &&
431          "Module already has a GVMaterializer.  Call materializeAll"
432          " to clear it out before setting another one.");
433   Materializer.reset(GVM);
434 }
435 
436 Error Module::materialize(GlobalValue *GV) {
437   if (!Materializer)
438     return Error::success();
439 
440   return Materializer->materialize(GV);
441 }
442 
443 Error Module::materializeAll() {
444   if (!Materializer)
445     return Error::success();
446   std::unique_ptr<GVMaterializer> M = std::move(Materializer);
447   return M->materializeModule();
448 }
449 
450 Error Module::materializeMetadata() {
451   if (!Materializer)
452     return Error::success();
453   return Materializer->materializeMetadata();
454 }
455 
456 //===----------------------------------------------------------------------===//
457 // Other module related stuff.
458 //
459 
460 std::vector<StructType *> Module::getIdentifiedStructTypes() const {
461   // If we have a materializer, it is possible that some unread function
462   // uses a type that is currently not visible to a TypeFinder, so ask
463   // the materializer which types it created.
464   if (Materializer)
465     return Materializer->getIdentifiedStructTypes();
466 
467   std::vector<StructType *> Ret;
468   TypeFinder SrcStructTypes;
469   SrcStructTypes.run(*this, true);
470   Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
471   return Ret;
472 }
473 
474 std::string Module::getUniqueIntrinsicName(StringRef BaseName, Intrinsic::ID Id,
475                                            const FunctionType *Proto) {
476   auto Encode = [&BaseName](unsigned Suffix) {
477     return (Twine(BaseName) + "." + Twine(Suffix)).str();
478   };
479 
480   {
481     // fast path - the prototype is already known
482     auto UinItInserted = UniquedIntrinsicNames.insert({{Id, Proto}, 0});
483     if (!UinItInserted.second)
484       return Encode(UinItInserted.first->second);
485   }
486 
487   // Not known yet. A new entry was created with index 0. Check if there already
488   // exists a matching declaration, or select a new entry.
489 
490   // Start looking for names with the current known maximum count (or 0).
491   auto NiidItInserted = CurrentIntrinsicIds.insert({BaseName, 0});
492   unsigned Count = NiidItInserted.first->second;
493 
494   // This might be slow if a whole population of intrinsics already existed, but
495   // we cache the values for later usage.
496   std::string NewName;
497   while (true) {
498     NewName = Encode(Count);
499     GlobalValue *F = getNamedValue(NewName);
500     if (!F) {
501       // Reserve this entry for the new proto
502       UniquedIntrinsicNames[{Id, Proto}] = Count;
503       break;
504     }
505 
506     // A declaration with this name already exists. Remember it.
507     FunctionType *FT = dyn_cast<FunctionType>(F->getValueType());
508     auto UinItInserted = UniquedIntrinsicNames.insert({{Id, FT}, Count});
509     if (FT == Proto) {
510       // It was a declaration for our prototype. This entry was allocated in the
511       // beginning. Update the count to match the existing declaration.
512       UinItInserted.first->second = Count;
513       break;
514     }
515 
516     ++Count;
517   }
518 
519   NiidItInserted.first->second = Count + 1;
520 
521   return NewName;
522 }
523 
524 // dropAllReferences() - This function causes all the subelements to "let go"
525 // of all references that they are maintaining.  This allows one to 'delete' a
526 // whole module at a time, even though there may be circular references... first
527 // all references are dropped, and all use counts go to zero.  Then everything
528 // is deleted for real.  Note that no operations are valid on an object that
529 // has "dropped all references", except operator delete.
530 //
531 void Module::dropAllReferences() {
532   for (Function &F : *this)
533     F.dropAllReferences();
534 
535   for (GlobalVariable &GV : globals())
536     GV.dropAllReferences();
537 
538   for (GlobalAlias &GA : aliases())
539     GA.dropAllReferences();
540 
541   for (GlobalIFunc &GIF : ifuncs())
542     GIF.dropAllReferences();
543 }
544 
545 unsigned Module::getNumberRegisterParameters() const {
546   auto *Val =
547       cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
548   if (!Val)
549     return 0;
550   return cast<ConstantInt>(Val->getValue())->getZExtValue();
551 }
552 
553 unsigned Module::getDwarfVersion() const {
554   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
555   if (!Val)
556     return 0;
557   return cast<ConstantInt>(Val->getValue())->getZExtValue();
558 }
559 
560 bool Module::isDwarf64() const {
561   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("DWARF64"));
562   return Val && cast<ConstantInt>(Val->getValue())->isOne();
563 }
564 
565 unsigned Module::getCodeViewFlag() const {
566   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
567   if (!Val)
568     return 0;
569   return cast<ConstantInt>(Val->getValue())->getZExtValue();
570 }
571 
572 unsigned Module::getInstructionCount() const {
573   unsigned NumInstrs = 0;
574   for (const Function &F : FunctionList)
575     NumInstrs += F.getInstructionCount();
576   return NumInstrs;
577 }
578 
579 Comdat *Module::getOrInsertComdat(StringRef Name) {
580   auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
581   Entry.second.Name = &Entry;
582   return &Entry.second;
583 }
584 
585 PICLevel::Level Module::getPICLevel() const {
586   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
587 
588   if (!Val)
589     return PICLevel::NotPIC;
590 
591   return static_cast<PICLevel::Level>(
592       cast<ConstantInt>(Val->getValue())->getZExtValue());
593 }
594 
595 void Module::setPICLevel(PICLevel::Level PL) {
596   // The merge result of a non-PIC object and a PIC object can only be reliably
597   // used as a non-PIC object, so use the Min merge behavior.
598   addModuleFlag(ModFlagBehavior::Min, "PIC Level", PL);
599 }
600 
601 PIELevel::Level Module::getPIELevel() const {
602   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
603 
604   if (!Val)
605     return PIELevel::Default;
606 
607   return static_cast<PIELevel::Level>(
608       cast<ConstantInt>(Val->getValue())->getZExtValue());
609 }
610 
611 void Module::setPIELevel(PIELevel::Level PL) {
612   addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
613 }
614 
615 std::optional<CodeModel::Model> Module::getCodeModel() const {
616   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model"));
617 
618   if (!Val)
619     return std::nullopt;
620 
621   return static_cast<CodeModel::Model>(
622       cast<ConstantInt>(Val->getValue())->getZExtValue());
623 }
624 
625 void Module::setCodeModel(CodeModel::Model CL) {
626   // Linking object files with different code models is undefined behavior
627   // because the compiler would have to generate additional code (to span
628   // longer jumps) if a larger code model is used with a smaller one.
629   // Therefore we will treat attempts to mix code models as an error.
630   addModuleFlag(ModFlagBehavior::Error, "Code Model", CL);
631 }
632 
633 std::optional<uint64_t> Module::getLargeDataThreshold() const {
634   auto *Val =
635       cast_or_null<ConstantAsMetadata>(getModuleFlag("Large Data Threshold"));
636 
637   if (!Val)
638     return std::nullopt;
639 
640   return cast<ConstantInt>(Val->getValue())->getZExtValue();
641 }
642 
643 void Module::setLargeDataThreshold(uint64_t Threshold) {
644   // Since the large data threshold goes along with the code model, the merge
645   // behavior is the same.
646   addModuleFlag(ModFlagBehavior::Error, "Large Data Threshold",
647                 ConstantInt::get(Type::getInt64Ty(Context), Threshold));
648 }
649 
650 void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) {
651   if (Kind == ProfileSummary::PSK_CSInstr)
652     setModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M);
653   else
654     setModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
655 }
656 
657 Metadata *Module::getProfileSummary(bool IsCS) const {
658   return (IsCS ? getModuleFlag("CSProfileSummary")
659                : getModuleFlag("ProfileSummary"));
660 }
661 
662 bool Module::getSemanticInterposition() const {
663   Metadata *MF = getModuleFlag("SemanticInterposition");
664 
665   auto *Val = cast_or_null<ConstantAsMetadata>(MF);
666   if (!Val)
667     return false;
668 
669   return cast<ConstantInt>(Val->getValue())->getZExtValue();
670 }
671 
672 void Module::setSemanticInterposition(bool SI) {
673   addModuleFlag(ModFlagBehavior::Error, "SemanticInterposition", SI);
674 }
675 
676 void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
677   OwnedMemoryBuffer = std::move(MB);
678 }
679 
680 bool Module::getRtLibUseGOT() const {
681   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
682   return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
683 }
684 
685 void Module::setRtLibUseGOT() {
686   addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
687 }
688 
689 bool Module::getDirectAccessExternalData() const {
690   auto *Val = cast_or_null<ConstantAsMetadata>(
691       getModuleFlag("direct-access-external-data"));
692   if (Val)
693     return cast<ConstantInt>(Val->getValue())->getZExtValue() > 0;
694   return getPICLevel() == PICLevel::NotPIC;
695 }
696 
697 void Module::setDirectAccessExternalData(bool Value) {
698   addModuleFlag(ModFlagBehavior::Max, "direct-access-external-data", Value);
699 }
700 
701 UWTableKind Module::getUwtable() const {
702   if (auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("uwtable")))
703     return UWTableKind(cast<ConstantInt>(Val->getValue())->getZExtValue());
704   return UWTableKind::None;
705 }
706 
707 void Module::setUwtable(UWTableKind Kind) {
708   addModuleFlag(ModFlagBehavior::Max, "uwtable", uint32_t(Kind));
709 }
710 
711 FramePointerKind Module::getFramePointer() const {
712   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("frame-pointer"));
713   return static_cast<FramePointerKind>(
714       Val ? cast<ConstantInt>(Val->getValue())->getZExtValue() : 0);
715 }
716 
717 void Module::setFramePointer(FramePointerKind Kind) {
718   addModuleFlag(ModFlagBehavior::Max, "frame-pointer", static_cast<int>(Kind));
719 }
720 
721 StringRef Module::getStackProtectorGuard() const {
722   Metadata *MD = getModuleFlag("stack-protector-guard");
723   if (auto *MDS = dyn_cast_or_null<MDString>(MD))
724     return MDS->getString();
725   return {};
726 }
727 
728 void Module::setStackProtectorGuard(StringRef Kind) {
729   MDString *ID = MDString::get(getContext(), Kind);
730   addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard", ID);
731 }
732 
733 StringRef Module::getStackProtectorGuardReg() const {
734   Metadata *MD = getModuleFlag("stack-protector-guard-reg");
735   if (auto *MDS = dyn_cast_or_null<MDString>(MD))
736     return MDS->getString();
737   return {};
738 }
739 
740 void Module::setStackProtectorGuardReg(StringRef Reg) {
741   MDString *ID = MDString::get(getContext(), Reg);
742   addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-reg", ID);
743 }
744 
745 StringRef Module::getStackProtectorGuardSymbol() const {
746   Metadata *MD = getModuleFlag("stack-protector-guard-symbol");
747   if (auto *MDS = dyn_cast_or_null<MDString>(MD))
748     return MDS->getString();
749   return {};
750 }
751 
752 void Module::setStackProtectorGuardSymbol(StringRef Symbol) {
753   MDString *ID = MDString::get(getContext(), Symbol);
754   addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-symbol", ID);
755 }
756 
757 int Module::getStackProtectorGuardOffset() const {
758   Metadata *MD = getModuleFlag("stack-protector-guard-offset");
759   if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
760     return CI->getSExtValue();
761   return INT_MAX;
762 }
763 
764 void Module::setStackProtectorGuardOffset(int Offset) {
765   addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-offset", Offset);
766 }
767 
768 unsigned Module::getOverrideStackAlignment() const {
769   Metadata *MD = getModuleFlag("override-stack-alignment");
770   if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
771     return CI->getZExtValue();
772   return 0;
773 }
774 
775 unsigned Module::getMaxTLSAlignment() const {
776   Metadata *MD = getModuleFlag("MaxTLSAlign");
777   if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
778     return CI->getZExtValue();
779   return 0;
780 }
781 
782 void Module::setOverrideStackAlignment(unsigned Align) {
783   addModuleFlag(ModFlagBehavior::Error, "override-stack-alignment", Align);
784 }
785 
786 static void addSDKVersionMD(const VersionTuple &V, Module &M, StringRef Name) {
787   SmallVector<unsigned, 3> Entries;
788   Entries.push_back(V.getMajor());
789   if (auto Minor = V.getMinor()) {
790     Entries.push_back(*Minor);
791     if (auto Subminor = V.getSubminor())
792       Entries.push_back(*Subminor);
793     // Ignore the 'build' component as it can't be represented in the object
794     // file.
795   }
796   M.addModuleFlag(Module::ModFlagBehavior::Warning, Name,
797                   ConstantDataArray::get(M.getContext(), Entries));
798 }
799 
800 void Module::setSDKVersion(const VersionTuple &V) {
801   addSDKVersionMD(V, *this, "SDK Version");
802 }
803 
804 static VersionTuple getSDKVersionMD(Metadata *MD) {
805   auto *CM = dyn_cast_or_null<ConstantAsMetadata>(MD);
806   if (!CM)
807     return {};
808   auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
809   if (!Arr)
810     return {};
811   auto getVersionComponent = [&](unsigned Index) -> std::optional<unsigned> {
812     if (Index >= Arr->getNumElements())
813       return std::nullopt;
814     return (unsigned)Arr->getElementAsInteger(Index);
815   };
816   auto Major = getVersionComponent(0);
817   if (!Major)
818     return {};
819   VersionTuple Result = VersionTuple(*Major);
820   if (auto Minor = getVersionComponent(1)) {
821     Result = VersionTuple(*Major, *Minor);
822     if (auto Subminor = getVersionComponent(2)) {
823       Result = VersionTuple(*Major, *Minor, *Subminor);
824     }
825   }
826   return Result;
827 }
828 
829 VersionTuple Module::getSDKVersion() const {
830   return getSDKVersionMD(getModuleFlag("SDK Version"));
831 }
832 
833 GlobalVariable *llvm::collectUsedGlobalVariables(
834     const Module &M, SmallVectorImpl<GlobalValue *> &Vec, bool CompilerUsed) {
835   const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
836   GlobalVariable *GV = M.getGlobalVariable(Name);
837   if (!GV || !GV->hasInitializer())
838     return GV;
839 
840   const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
841   for (Value *Op : Init->operands()) {
842     GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts());
843     Vec.push_back(G);
844   }
845   return GV;
846 }
847 
848 void Module::setPartialSampleProfileRatio(const ModuleSummaryIndex &Index) {
849   if (auto *SummaryMD = getProfileSummary(/*IsCS*/ false)) {
850     std::unique_ptr<ProfileSummary> ProfileSummary(
851         ProfileSummary::getFromMD(SummaryMD));
852     if (ProfileSummary) {
853       if (ProfileSummary->getKind() != ProfileSummary::PSK_Sample ||
854           !ProfileSummary->isPartialProfile())
855         return;
856       uint64_t BlockCount = Index.getBlockCount();
857       uint32_t NumCounts = ProfileSummary->getNumCounts();
858       if (!NumCounts)
859         return;
860       double Ratio = (double)BlockCount / NumCounts;
861       ProfileSummary->setPartialProfileRatio(Ratio);
862       setProfileSummary(ProfileSummary->getMD(getContext()),
863                         ProfileSummary::PSK_Sample);
864     }
865   }
866 }
867 
868 StringRef Module::getDarwinTargetVariantTriple() const {
869   if (const auto *MD = getModuleFlag("darwin.target_variant.triple"))
870     return cast<MDString>(MD)->getString();
871   return "";
872 }
873 
874 void Module::setDarwinTargetVariantTriple(StringRef T) {
875   addModuleFlag(ModFlagBehavior::Warning, "darwin.target_variant.triple",
876                 MDString::get(getContext(), T));
877 }
878 
879 VersionTuple Module::getDarwinTargetVariantSDKVersion() const {
880   return getSDKVersionMD(getModuleFlag("darwin.target_variant.SDK Version"));
881 }
882 
883 void Module::setDarwinTargetVariantSDKVersion(VersionTuple Version) {
884   addSDKVersionMD(Version, *this, "darwin.target_variant.SDK Version");
885 }
886