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