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