xref: /llvm-project/llvm/lib/IR/Module.cpp (revision 6cf3e7d06706fe79e87d1816c92b074416b5f8f8)
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)),
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     if (Name == "llvm.module.flags")
276       ModuleFlags = NMD;
277   }
278   return NMD;
279 }
280 
281 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
282 /// delete it.
283 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
284   NamedMDSymTab.erase(NMD->getName());
285   if (NMD == ModuleFlags)
286     ModuleFlags = nullptr;
287   eraseNamedMDNode(NMD);
288 }
289 
290 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
291   if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
292     uint64_t Val = Behavior->getLimitedValue();
293     if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
294       MFB = static_cast<ModFlagBehavior>(Val);
295       return true;
296     }
297   }
298   return false;
299 }
300 
301 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
302 void Module::
303 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
304   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
305   if (!ModFlags) return;
306 
307   for (const MDNode *Flag : ModFlags->operands()) {
308     // The verifier will catch errors, so no need to check them here.
309     auto *MFBConstant = mdconst::extract<ConstantInt>(Flag->getOperand(0));
310     auto MFB = static_cast<ModFlagBehavior>(MFBConstant->getLimitedValue());
311     MDString *Key = cast<MDString>(Flag->getOperand(1));
312     Metadata *Val = Flag->getOperand(2);
313     Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
314   }
315 }
316 
317 /// Return the corresponding value if Key appears in module flags, otherwise
318 /// return null.
319 Metadata *Module::getModuleFlag(StringRef Key) const {
320   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
321   if (!ModFlags)
322     return nullptr;
323   for (const MDNode *Flag : ModFlags->operands()) {
324     if (Key == cast<MDString>(Flag->getOperand(1))->getString())
325       return Flag->getOperand(2);
326   }
327   return nullptr;
328 }
329 
330 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
331 /// represents module-level flags. If module-level flags aren't found, it
332 /// creates the named metadata that contains them.
333 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
334   if (ModuleFlags)
335     return ModuleFlags;
336   return getOrInsertNamedMetadata("llvm.module.flags");
337 }
338 
339 /// addModuleFlag - Add a module-level flag to the module-level flags
340 /// metadata. It will create the module-level flags named metadata if it doesn't
341 /// already exist.
342 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
343                            Metadata *Val) {
344   Type *Int32Ty = Type::getInt32Ty(Context);
345   Metadata *Ops[3] = {
346       ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
347       MDString::get(Context, Key), Val};
348   getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
349 }
350 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
351                            Constant *Val) {
352   addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
353 }
354 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
355                            uint32_t Val) {
356   Type *Int32Ty = Type::getInt32Ty(Context);
357   addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
358 }
359 void Module::addModuleFlag(MDNode *Node) {
360   assert(Node->getNumOperands() == 3 &&
361          "Invalid number of operands for module flag!");
362   assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
363          isa<MDString>(Node->getOperand(1)) &&
364          "Invalid operand types for module flag!");
365   getOrInsertModuleFlagsMetadata()->addOperand(Node);
366 }
367 
368 void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
369                            Metadata *Val) {
370   NamedMDNode *ModFlags = getOrInsertModuleFlagsMetadata();
371   // Replace the flag if it already exists.
372   for (MDNode *Flag : ModFlags->operands()) {
373     if (cast<MDString>(Flag->getOperand(1))->getString() == Key) {
374       Flag->replaceOperandWith(2, Val);
375       return;
376     }
377   }
378   addModuleFlag(Behavior, Key, Val);
379 }
380 void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
381                            Constant *Val) {
382   setModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
383 }
384 void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
385                            uint32_t Val) {
386   Type *Int32Ty = Type::getInt32Ty(Context);
387   setModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
388 }
389 
390 void Module::setDataLayout(StringRef Desc) { DL = DataLayout(Desc); }
391 
392 void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
393 
394 DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
395   return cast<DICompileUnit>(CUs->getOperand(Idx));
396 }
397 DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
398   return cast<DICompileUnit>(CUs->getOperand(Idx));
399 }
400 
401 void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
402   while (CUs && (Idx < CUs->getNumOperands()) &&
403          ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
404     ++Idx;
405 }
406 
407 iterator_range<Module::global_object_iterator> Module::global_objects() {
408   return concat<GlobalObject>(functions(), globals());
409 }
410 iterator_range<Module::const_global_object_iterator>
411 Module::global_objects() const {
412   return concat<const GlobalObject>(functions(), globals());
413 }
414 
415 iterator_range<Module::global_value_iterator> Module::global_values() {
416   return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs());
417 }
418 iterator_range<Module::const_global_value_iterator>
419 Module::global_values() const {
420   return concat<const GlobalValue>(functions(), globals(), aliases(), ifuncs());
421 }
422 
423 //===----------------------------------------------------------------------===//
424 // Methods to control the materialization of GlobalValues in the Module.
425 //
426 void Module::setMaterializer(GVMaterializer *GVM) {
427   assert(!Materializer &&
428          "Module already has a GVMaterializer.  Call materializeAll"
429          " to clear it out before setting another one.");
430   Materializer.reset(GVM);
431 }
432 
433 Error Module::materialize(GlobalValue *GV) {
434   if (!Materializer)
435     return Error::success();
436 
437   return Materializer->materialize(GV);
438 }
439 
440 Error Module::materializeAll() {
441   if (!Materializer)
442     return Error::success();
443   std::unique_ptr<GVMaterializer> M = std::move(Materializer);
444   return M->materializeModule();
445 }
446 
447 Error Module::materializeMetadata() {
448   if (!Materializer)
449     return Error::success();
450   return Materializer->materializeMetadata();
451 }
452 
453 //===----------------------------------------------------------------------===//
454 // Other module related stuff.
455 //
456 
457 std::vector<StructType *> Module::getIdentifiedStructTypes() const {
458   // If we have a materializer, it is possible that some unread function
459   // uses a type that is currently not visible to a TypeFinder, so ask
460   // the materializer which types it created.
461   if (Materializer)
462     return Materializer->getIdentifiedStructTypes();
463 
464   std::vector<StructType *> Ret;
465   TypeFinder SrcStructTypes;
466   SrcStructTypes.run(*this, true);
467   Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
468   return Ret;
469 }
470 
471 std::string Module::getUniqueIntrinsicName(StringRef BaseName, Intrinsic::ID Id,
472                                            const FunctionType *Proto) {
473   auto Encode = [&BaseName](unsigned Suffix) {
474     return (Twine(BaseName) + "." + Twine(Suffix)).str();
475   };
476 
477   {
478     // fast path - the prototype is already known
479     auto UinItInserted = UniquedIntrinsicNames.insert({{Id, Proto}, 0});
480     if (!UinItInserted.second)
481       return Encode(UinItInserted.first->second);
482   }
483 
484   // Not known yet. A new entry was created with index 0. Check if there already
485   // exists a matching declaration, or select a new entry.
486 
487   // Start looking for names with the current known maximum count (or 0).
488   auto NiidItInserted = CurrentIntrinsicIds.insert({BaseName, 0});
489   unsigned Count = NiidItInserted.first->second;
490 
491   // This might be slow if a whole population of intrinsics already existed, but
492   // we cache the values for later usage.
493   std::string NewName;
494   while (true) {
495     NewName = Encode(Count);
496     GlobalValue *F = getNamedValue(NewName);
497     if (!F) {
498       // Reserve this entry for the new proto
499       UniquedIntrinsicNames[{Id, Proto}] = Count;
500       break;
501     }
502 
503     // A declaration with this name already exists. Remember it.
504     FunctionType *FT = dyn_cast<FunctionType>(F->getValueType());
505     auto UinItInserted = UniquedIntrinsicNames.insert({{Id, FT}, Count});
506     if (FT == Proto) {
507       // It was a declaration for our prototype. This entry was allocated in the
508       // beginning. Update the count to match the existing declaration.
509       UinItInserted.first->second = Count;
510       break;
511     }
512 
513     ++Count;
514   }
515 
516   NiidItInserted.first->second = Count + 1;
517 
518   return NewName;
519 }
520 
521 // dropAllReferences() - This function causes all the subelements to "let go"
522 // of all references that they are maintaining.  This allows one to 'delete' a
523 // whole module at a time, even though there may be circular references... first
524 // all references are dropped, and all use counts go to zero.  Then everything
525 // is deleted for real.  Note that no operations are valid on an object that
526 // has "dropped all references", except operator delete.
527 //
528 void Module::dropAllReferences() {
529   for (Function &F : *this)
530     F.dropAllReferences();
531 
532   for (GlobalVariable &GV : globals())
533     GV.dropAllReferences();
534 
535   for (GlobalAlias &GA : aliases())
536     GA.dropAllReferences();
537 
538   for (GlobalIFunc &GIF : ifuncs())
539     GIF.dropAllReferences();
540 }
541 
542 unsigned Module::getNumberRegisterParameters() const {
543   auto *Val =
544       cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
545   if (!Val)
546     return 0;
547   return cast<ConstantInt>(Val->getValue())->getZExtValue();
548 }
549 
550 unsigned Module::getDwarfVersion() const {
551   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
552   if (!Val)
553     return 0;
554   return cast<ConstantInt>(Val->getValue())->getZExtValue();
555 }
556 
557 bool Module::isDwarf64() const {
558   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("DWARF64"));
559   return Val && cast<ConstantInt>(Val->getValue())->isOne();
560 }
561 
562 unsigned Module::getCodeViewFlag() const {
563   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
564   if (!Val)
565     return 0;
566   return cast<ConstantInt>(Val->getValue())->getZExtValue();
567 }
568 
569 unsigned Module::getInstructionCount() const {
570   unsigned NumInstrs = 0;
571   for (const Function &F : FunctionList)
572     NumInstrs += F.getInstructionCount();
573   return NumInstrs;
574 }
575 
576 Comdat *Module::getOrInsertComdat(StringRef Name) {
577   auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
578   Entry.second.Name = &Entry;
579   return &Entry.second;
580 }
581 
582 PICLevel::Level Module::getPICLevel() const {
583   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
584 
585   if (!Val)
586     return PICLevel::NotPIC;
587 
588   return static_cast<PICLevel::Level>(
589       cast<ConstantInt>(Val->getValue())->getZExtValue());
590 }
591 
592 void Module::setPICLevel(PICLevel::Level PL) {
593   // The merge result of a non-PIC object and a PIC object can only be reliably
594   // used as a non-PIC object, so use the Min merge behavior.
595   addModuleFlag(ModFlagBehavior::Min, "PIC Level", PL);
596 }
597 
598 PIELevel::Level Module::getPIELevel() const {
599   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
600 
601   if (!Val)
602     return PIELevel::Default;
603 
604   return static_cast<PIELevel::Level>(
605       cast<ConstantInt>(Val->getValue())->getZExtValue());
606 }
607 
608 void Module::setPIELevel(PIELevel::Level PL) {
609   addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
610 }
611 
612 std::optional<CodeModel::Model> Module::getCodeModel() const {
613   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model"));
614 
615   if (!Val)
616     return std::nullopt;
617 
618   return static_cast<CodeModel::Model>(
619       cast<ConstantInt>(Val->getValue())->getZExtValue());
620 }
621 
622 void Module::setCodeModel(CodeModel::Model CL) {
623   // Linking object files with different code models is undefined behavior
624   // because the compiler would have to generate additional code (to span
625   // longer jumps) if a larger code model is used with a smaller one.
626   // Therefore we will treat attempts to mix code models as an error.
627   addModuleFlag(ModFlagBehavior::Error, "Code Model", CL);
628 }
629 
630 std::optional<uint64_t> Module::getLargeDataThreshold() const {
631   auto *Val =
632       cast_or_null<ConstantAsMetadata>(getModuleFlag("Large Data Threshold"));
633 
634   if (!Val)
635     return std::nullopt;
636 
637   return cast<ConstantInt>(Val->getValue())->getZExtValue();
638 }
639 
640 void Module::setLargeDataThreshold(uint64_t Threshold) {
641   // Since the large data threshold goes along with the code model, the merge
642   // behavior is the same.
643   addModuleFlag(ModFlagBehavior::Error, "Large Data Threshold",
644                 ConstantInt::get(Type::getInt64Ty(Context), Threshold));
645 }
646 
647 void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) {
648   if (Kind == ProfileSummary::PSK_CSInstr)
649     setModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M);
650   else
651     setModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
652 }
653 
654 Metadata *Module::getProfileSummary(bool IsCS) const {
655   return (IsCS ? getModuleFlag("CSProfileSummary")
656                : getModuleFlag("ProfileSummary"));
657 }
658 
659 bool Module::getSemanticInterposition() const {
660   Metadata *MF = getModuleFlag("SemanticInterposition");
661 
662   auto *Val = cast_or_null<ConstantAsMetadata>(MF);
663   if (!Val)
664     return false;
665 
666   return cast<ConstantInt>(Val->getValue())->getZExtValue();
667 }
668 
669 void Module::setSemanticInterposition(bool SI) {
670   addModuleFlag(ModFlagBehavior::Error, "SemanticInterposition", SI);
671 }
672 
673 void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
674   OwnedMemoryBuffer = std::move(MB);
675 }
676 
677 bool Module::getRtLibUseGOT() const {
678   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
679   return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
680 }
681 
682 void Module::setRtLibUseGOT() {
683   addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
684 }
685 
686 bool Module::getDirectAccessExternalData() const {
687   auto *Val = cast_or_null<ConstantAsMetadata>(
688       getModuleFlag("direct-access-external-data"));
689   if (Val)
690     return cast<ConstantInt>(Val->getValue())->getZExtValue() > 0;
691   return getPICLevel() == PICLevel::NotPIC;
692 }
693 
694 void Module::setDirectAccessExternalData(bool Value) {
695   addModuleFlag(ModFlagBehavior::Max, "direct-access-external-data", Value);
696 }
697 
698 UWTableKind Module::getUwtable() const {
699   if (auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("uwtable")))
700     return UWTableKind(cast<ConstantInt>(Val->getValue())->getZExtValue());
701   return UWTableKind::None;
702 }
703 
704 void Module::setUwtable(UWTableKind Kind) {
705   addModuleFlag(ModFlagBehavior::Max, "uwtable", uint32_t(Kind));
706 }
707 
708 FramePointerKind Module::getFramePointer() const {
709   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("frame-pointer"));
710   return static_cast<FramePointerKind>(
711       Val ? cast<ConstantInt>(Val->getValue())->getZExtValue() : 0);
712 }
713 
714 void Module::setFramePointer(FramePointerKind Kind) {
715   addModuleFlag(ModFlagBehavior::Max, "frame-pointer", static_cast<int>(Kind));
716 }
717 
718 StringRef Module::getStackProtectorGuard() const {
719   Metadata *MD = getModuleFlag("stack-protector-guard");
720   if (auto *MDS = dyn_cast_or_null<MDString>(MD))
721     return MDS->getString();
722   return {};
723 }
724 
725 void Module::setStackProtectorGuard(StringRef Kind) {
726   MDString *ID = MDString::get(getContext(), Kind);
727   addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard", ID);
728 }
729 
730 StringRef Module::getStackProtectorGuardReg() const {
731   Metadata *MD = getModuleFlag("stack-protector-guard-reg");
732   if (auto *MDS = dyn_cast_or_null<MDString>(MD))
733     return MDS->getString();
734   return {};
735 }
736 
737 void Module::setStackProtectorGuardReg(StringRef Reg) {
738   MDString *ID = MDString::get(getContext(), Reg);
739   addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-reg", ID);
740 }
741 
742 StringRef Module::getStackProtectorGuardSymbol() const {
743   Metadata *MD = getModuleFlag("stack-protector-guard-symbol");
744   if (auto *MDS = dyn_cast_or_null<MDString>(MD))
745     return MDS->getString();
746   return {};
747 }
748 
749 void Module::setStackProtectorGuardSymbol(StringRef Symbol) {
750   MDString *ID = MDString::get(getContext(), Symbol);
751   addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-symbol", ID);
752 }
753 
754 int Module::getStackProtectorGuardOffset() const {
755   Metadata *MD = getModuleFlag("stack-protector-guard-offset");
756   if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
757     return CI->getSExtValue();
758   return INT_MAX;
759 }
760 
761 void Module::setStackProtectorGuardOffset(int Offset) {
762   addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-offset", Offset);
763 }
764 
765 unsigned Module::getOverrideStackAlignment() const {
766   Metadata *MD = getModuleFlag("override-stack-alignment");
767   if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
768     return CI->getZExtValue();
769   return 0;
770 }
771 
772 unsigned Module::getMaxTLSAlignment() const {
773   Metadata *MD = getModuleFlag("MaxTLSAlign");
774   if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
775     return CI->getZExtValue();
776   return 0;
777 }
778 
779 void Module::setOverrideStackAlignment(unsigned Align) {
780   addModuleFlag(ModFlagBehavior::Error, "override-stack-alignment", Align);
781 }
782 
783 static void addSDKVersionMD(const VersionTuple &V, Module &M, StringRef Name) {
784   SmallVector<unsigned, 3> Entries;
785   Entries.push_back(V.getMajor());
786   if (auto Minor = V.getMinor()) {
787     Entries.push_back(*Minor);
788     if (auto Subminor = V.getSubminor())
789       Entries.push_back(*Subminor);
790     // Ignore the 'build' component as it can't be represented in the object
791     // file.
792   }
793   M.addModuleFlag(Module::ModFlagBehavior::Warning, Name,
794                   ConstantDataArray::get(M.getContext(), Entries));
795 }
796 
797 void Module::setSDKVersion(const VersionTuple &V) {
798   addSDKVersionMD(V, *this, "SDK Version");
799 }
800 
801 static VersionTuple getSDKVersionMD(Metadata *MD) {
802   auto *CM = dyn_cast_or_null<ConstantAsMetadata>(MD);
803   if (!CM)
804     return {};
805   auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
806   if (!Arr)
807     return {};
808   auto getVersionComponent = [&](unsigned Index) -> std::optional<unsigned> {
809     if (Index >= Arr->getNumElements())
810       return std::nullopt;
811     return (unsigned)Arr->getElementAsInteger(Index);
812   };
813   auto Major = getVersionComponent(0);
814   if (!Major)
815     return {};
816   VersionTuple Result = VersionTuple(*Major);
817   if (auto Minor = getVersionComponent(1)) {
818     Result = VersionTuple(*Major, *Minor);
819     if (auto Subminor = getVersionComponent(2)) {
820       Result = VersionTuple(*Major, *Minor, *Subminor);
821     }
822   }
823   return Result;
824 }
825 
826 VersionTuple Module::getSDKVersion() const {
827   return getSDKVersionMD(getModuleFlag("SDK Version"));
828 }
829 
830 GlobalVariable *llvm::collectUsedGlobalVariables(
831     const Module &M, SmallVectorImpl<GlobalValue *> &Vec, bool CompilerUsed) {
832   const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
833   GlobalVariable *GV = M.getGlobalVariable(Name);
834   if (!GV || !GV->hasInitializer())
835     return GV;
836 
837   const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
838   for (Value *Op : Init->operands()) {
839     GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts());
840     Vec.push_back(G);
841   }
842   return GV;
843 }
844 
845 void Module::setPartialSampleProfileRatio(const ModuleSummaryIndex &Index) {
846   if (auto *SummaryMD = getProfileSummary(/*IsCS*/ false)) {
847     std::unique_ptr<ProfileSummary> ProfileSummary(
848         ProfileSummary::getFromMD(SummaryMD));
849     if (ProfileSummary) {
850       if (ProfileSummary->getKind() != ProfileSummary::PSK_Sample ||
851           !ProfileSummary->isPartialProfile())
852         return;
853       uint64_t BlockCount = Index.getBlockCount();
854       uint32_t NumCounts = ProfileSummary->getNumCounts();
855       if (!NumCounts)
856         return;
857       double Ratio = (double)BlockCount / NumCounts;
858       ProfileSummary->setPartialProfileRatio(Ratio);
859       setProfileSummary(ProfileSummary->getMD(getContext()),
860                         ProfileSummary::PSK_Sample);
861     }
862   }
863 }
864 
865 StringRef Module::getDarwinTargetVariantTriple() const {
866   if (const auto *MD = getModuleFlag("darwin.target_variant.triple"))
867     return cast<MDString>(MD)->getString();
868   return "";
869 }
870 
871 void Module::setDarwinTargetVariantTriple(StringRef T) {
872   addModuleFlag(ModFlagBehavior::Warning, "darwin.target_variant.triple",
873                 MDString::get(getContext(), T));
874 }
875 
876 VersionTuple Module::getDarwinTargetVariantSDKVersion() const {
877   return getSDKVersionMD(getModuleFlag("darwin.target_variant.SDK Version"));
878 }
879 
880 void Module::setDarwinTargetVariantSDKVersion(VersionTuple Version) {
881   addSDKVersionMD(Version, *this, "darwin.target_variant.SDK Version");
882 }
883