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