1 //===-- Module.cpp - Implement the Module class ---------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Module class for the IR library.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/IR/Module.h"
15 #include "SymbolTableListTraitsImpl.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/GVMaterializer.h"
23 #include "llvm/IR/InstrTypes.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/TypeFinder.h"
26 #include "llvm/Support/Dwarf.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/RandomNumberGenerator.h"
29 #include <algorithm>
30 #include <cstdarg>
31 #include <cstdlib>
32 
33 using namespace llvm;
34 
35 //===----------------------------------------------------------------------===//
36 // Methods to implement the globals and functions lists.
37 //
38 
39 // Explicit instantiations of SymbolTableListTraits since some of the methods
40 // are not in the public header file.
41 template class llvm::SymbolTableListTraits<Function>;
42 template class llvm::SymbolTableListTraits<GlobalVariable>;
43 template class llvm::SymbolTableListTraits<GlobalAlias>;
44 
45 //===----------------------------------------------------------------------===//
46 // Primitive Module methods.
47 //
48 
Module(StringRef MID,LLVMContext & C)49 Module::Module(StringRef MID, LLVMContext &C)
50     : Context(C), Materializer(), ModuleID(MID), DL("") {
51   ValSymTab = new ValueSymbolTable();
52   NamedMDSymTab = new StringMap<NamedMDNode *>();
53   Context.addModule(this);
54 }
55 
~Module()56 Module::~Module() {
57   Context.removeModule(this);
58   dropAllReferences();
59   GlobalList.clear();
60   FunctionList.clear();
61   AliasList.clear();
62   NamedMDList.clear();
63   delete ValSymTab;
64   delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
65 }
66 
createRNG(const Pass * P) const67 RandomNumberGenerator *Module::createRNG(const Pass* P) const {
68   SmallString<32> Salt(P->getPassName());
69 
70   // This RNG is guaranteed to produce the same random stream only
71   // when the Module ID and thus the input filename is the same. This
72   // might be problematic if the input filename extension changes
73   // (e.g. from .c to .bc or .ll).
74   //
75   // We could store this salt in NamedMetadata, but this would make
76   // the parameter non-const. This would unfortunately make this
77   // interface unusable by any Machine passes, since they only have a
78   // const reference to their IR Module. Alternatively we can always
79   // store salt metadata from the Module constructor.
80   Salt += sys::path::filename(getModuleIdentifier());
81 
82   return new RandomNumberGenerator(Salt);
83 }
84 
85 /// getNamedValue - Return the first global value in the module with
86 /// the specified name, of arbitrary type.  This method returns null
87 /// if a global with the specified name is not found.
getNamedValue(StringRef Name) const88 GlobalValue *Module::getNamedValue(StringRef Name) const {
89   return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
90 }
91 
92 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
93 /// This ID is uniqued across modules in the current LLVMContext.
getMDKindID(StringRef Name) const94 unsigned Module::getMDKindID(StringRef Name) const {
95   return Context.getMDKindID(Name);
96 }
97 
98 /// getMDKindNames - Populate client supplied SmallVector with the name for
99 /// custom metadata IDs registered in this LLVMContext.   ID #0 is not used,
100 /// so it is filled in as an empty string.
getMDKindNames(SmallVectorImpl<StringRef> & Result) const101 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
102   return Context.getMDKindNames(Result);
103 }
104 
getOperandBundleTags(SmallVectorImpl<StringRef> & Result) const105 void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
106   return Context.getOperandBundleTags(Result);
107 }
108 
109 //===----------------------------------------------------------------------===//
110 // Methods for easy access to the functions in the module.
111 //
112 
113 // getOrInsertFunction - Look up the specified function in the module symbol
114 // table.  If it does not exist, add a prototype for the function and return
115 // it.  This is nice because it allows most passes to get away with not handling
116 // the symbol table directly for this common task.
117 //
getOrInsertFunction(StringRef Name,FunctionType * Ty,AttributeSet AttributeList)118 Constant *Module::getOrInsertFunction(StringRef Name,
119                                       FunctionType *Ty,
120                                       AttributeSet AttributeList) {
121   // See if we have a definition for the specified function already.
122   GlobalValue *F = getNamedValue(Name);
123   if (!F) {
124     // Nope, add it
125     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
126     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
127       New->setAttributes(AttributeList);
128     FunctionList.push_back(New);
129     return New;                    // Return the new prototype.
130   }
131 
132   // If the function exists but has the wrong type, return a bitcast to the
133   // right type.
134   if (F->getType() != PointerType::getUnqual(Ty))
135     return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
136 
137   // Otherwise, we just found the existing function or a prototype.
138   return F;
139 }
140 
getOrInsertFunction(StringRef Name,FunctionType * Ty)141 Constant *Module::getOrInsertFunction(StringRef Name,
142                                       FunctionType *Ty) {
143   return getOrInsertFunction(Name, Ty, AttributeSet());
144 }
145 
146 // getOrInsertFunction - Look up the specified function in the module symbol
147 // table.  If it does not exist, add a prototype for the function and return it.
148 // This version of the method takes a null terminated list of function
149 // arguments, which makes it easier for clients to use.
150 //
getOrInsertFunction(StringRef Name,AttributeSet AttributeList,Type * RetTy,...)151 Constant *Module::getOrInsertFunction(StringRef Name,
152                                       AttributeSet AttributeList,
153                                       Type *RetTy, ...) {
154   va_list Args;
155   va_start(Args, RetTy);
156 
157   // Build the list of argument types...
158   std::vector<Type*> ArgTys;
159   while (Type *ArgTy = va_arg(Args, Type*))
160     ArgTys.push_back(ArgTy);
161 
162   va_end(Args);
163 
164   // Build the function type and chain to the other getOrInsertFunction...
165   return getOrInsertFunction(Name,
166                              FunctionType::get(RetTy, ArgTys, false),
167                              AttributeList);
168 }
169 
getOrInsertFunction(StringRef Name,Type * RetTy,...)170 Constant *Module::getOrInsertFunction(StringRef Name,
171                                       Type *RetTy, ...) {
172   va_list Args;
173   va_start(Args, RetTy);
174 
175   // Build the list of argument types...
176   std::vector<Type*> ArgTys;
177   while (Type *ArgTy = va_arg(Args, Type*))
178     ArgTys.push_back(ArgTy);
179 
180   va_end(Args);
181 
182   // Build the function type and chain to the other getOrInsertFunction...
183   return getOrInsertFunction(Name,
184                              FunctionType::get(RetTy, ArgTys, false),
185                              AttributeSet());
186 }
187 
188 // getFunction - Look up the specified function in the module symbol table.
189 // If it does not exist, return null.
190 //
getFunction(StringRef Name) const191 Function *Module::getFunction(StringRef Name) const {
192   return dyn_cast_or_null<Function>(getNamedValue(Name));
193 }
194 
195 //===----------------------------------------------------------------------===//
196 // Methods for easy access to the global variables in the module.
197 //
198 
199 /// getGlobalVariable - Look up the specified global variable in the module
200 /// symbol table.  If it does not exist, return null.  The type argument
201 /// should be the underlying type of the global, i.e., it should not have
202 /// the top-level PointerType, which represents the address of the global.
203 /// If AllowLocal is set to true, this function will return types that
204 /// have an local. By default, these types are not returned.
205 ///
getGlobalVariable(StringRef Name,bool AllowLocal)206 GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
207   if (GlobalVariable *Result =
208       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
209     if (AllowLocal || !Result->hasLocalLinkage())
210       return Result;
211   return nullptr;
212 }
213 
214 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
215 ///   1. If it does not exist, add a declaration of the global and return it.
216 ///   2. Else, the global exists but has the wrong type: return the function
217 ///      with a constantexpr cast to the right type.
218 ///   3. Finally, if the existing global is the correct declaration, return the
219 ///      existing global.
getOrInsertGlobal(StringRef Name,Type * Ty)220 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
221   // See if we have a definition for the specified global already.
222   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
223   if (!GV) {
224     // Nope, add it
225     GlobalVariable *New =
226       new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
227                          nullptr, Name);
228      return New;                    // Return the new declaration.
229   }
230 
231   // If the variable exists but has the wrong type, return a bitcast to the
232   // right type.
233   Type *GVTy = GV->getType();
234   PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
235   if (GVTy != PTy)
236     return ConstantExpr::getBitCast(GV, PTy);
237 
238   // Otherwise, we just found the existing function or a prototype.
239   return GV;
240 }
241 
242 //===----------------------------------------------------------------------===//
243 // Methods for easy access to the global variables in the module.
244 //
245 
246 // getNamedAlias - Look up the specified global in the module symbol table.
247 // If it does not exist, return null.
248 //
getNamedAlias(StringRef Name) const249 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
250   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
251 }
252 
253 /// getNamedMetadata - Return the first NamedMDNode in the module with the
254 /// specified name. This method returns null if a NamedMDNode with the
255 /// specified name is not found.
getNamedMetadata(const Twine & Name) const256 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
257   SmallString<256> NameData;
258   StringRef NameRef = Name.toStringRef(NameData);
259   return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
260 }
261 
262 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
263 /// with the specified name. This method returns a new NamedMDNode if a
264 /// NamedMDNode with the specified name is not found.
getOrInsertNamedMetadata(StringRef Name)265 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
266   NamedMDNode *&NMD =
267     (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
268   if (!NMD) {
269     NMD = new NamedMDNode(Name);
270     NMD->setParent(this);
271     NamedMDList.push_back(NMD);
272   }
273   return NMD;
274 }
275 
276 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
277 /// delete it.
eraseNamedMetadata(NamedMDNode * NMD)278 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
279   static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
280   NamedMDList.erase(NMD->getIterator());
281 }
282 
isValidModFlagBehavior(Metadata * MD,ModFlagBehavior & MFB)283 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
284   if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
285     uint64_t Val = Behavior->getLimitedValue();
286     if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
287       MFB = static_cast<ModFlagBehavior>(Val);
288       return true;
289     }
290   }
291   return false;
292 }
293 
294 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
295 void Module::
getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> & Flags) const296 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
297   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
298   if (!ModFlags) return;
299 
300   for (const MDNode *Flag : ModFlags->operands()) {
301     ModFlagBehavior MFB;
302     if (Flag->getNumOperands() >= 3 &&
303         isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
304         dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
305       // Check the operands of the MDNode before accessing the operands.
306       // The verifier will actually catch these failures.
307       MDString *Key = cast<MDString>(Flag->getOperand(1));
308       Metadata *Val = Flag->getOperand(2);
309       Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
310     }
311   }
312 }
313 
314 /// Return the corresponding value if Key appears in module flags, otherwise
315 /// return null.
getModuleFlag(StringRef Key) const316 Metadata *Module::getModuleFlag(StringRef Key) const {
317   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
318   getModuleFlagsMetadata(ModuleFlags);
319   for (const ModuleFlagEntry &MFE : ModuleFlags) {
320     if (Key == MFE.Key->getString())
321       return MFE.Val;
322   }
323   return nullptr;
324 }
325 
326 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
327 /// represents module-level flags. This method returns null if there are no
328 /// module-level flags.
getModuleFlagsMetadata() const329 NamedMDNode *Module::getModuleFlagsMetadata() const {
330   return getNamedMetadata("llvm.module.flags");
331 }
332 
333 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
334 /// represents module-level flags. If module-level flags aren't found, it
335 /// creates the named metadata that contains them.
getOrInsertModuleFlagsMetadata()336 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
337   return getOrInsertNamedMetadata("llvm.module.flags");
338 }
339 
340 /// addModuleFlag - Add a module-level flag to the module-level flags
341 /// metadata. It will create the module-level flags named metadata if it doesn't
342 /// already exist.
addModuleFlag(ModFlagBehavior Behavior,StringRef Key,Metadata * Val)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 }
addModuleFlag(ModFlagBehavior Behavior,StringRef Key,Constant * Val)351 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
352                            Constant *Val) {
353   addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
354 }
addModuleFlag(ModFlagBehavior Behavior,StringRef Key,uint32_t Val)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 }
addModuleFlag(MDNode * Node)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 
setDataLayout(StringRef Desc)369 void Module::setDataLayout(StringRef Desc) {
370   DL.reset(Desc);
371 }
372 
setDataLayout(const DataLayout & Other)373 void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
374 
getDataLayout() const375 const DataLayout &Module::getDataLayout() const { return DL; }
376 
377 //===----------------------------------------------------------------------===//
378 // Methods to control the materialization of GlobalValues in the Module.
379 //
setMaterializer(GVMaterializer * GVM)380 void Module::setMaterializer(GVMaterializer *GVM) {
381   assert(!Materializer &&
382          "Module already has a GVMaterializer.  Call materializeAll"
383          " to clear it out before setting another one.");
384   Materializer.reset(GVM);
385 }
386 
materialize(GlobalValue * GV)387 std::error_code Module::materialize(GlobalValue *GV) {
388   if (!Materializer)
389     return std::error_code();
390 
391   return Materializer->materialize(GV);
392 }
393 
materializeAll()394 std::error_code Module::materializeAll() {
395   if (!Materializer)
396     return std::error_code();
397   std::unique_ptr<GVMaterializer> M = std::move(Materializer);
398   return M->materializeModule();
399 }
400 
materializeMetadata()401 std::error_code Module::materializeMetadata() {
402   if (!Materializer)
403     return std::error_code();
404   return Materializer->materializeMetadata();
405 }
406 
407 //===----------------------------------------------------------------------===//
408 // Other module related stuff.
409 //
410 
getIdentifiedStructTypes() const411 std::vector<StructType *> Module::getIdentifiedStructTypes() const {
412   // If we have a materializer, it is possible that some unread function
413   // uses a type that is currently not visible to a TypeFinder, so ask
414   // the materializer which types it created.
415   if (Materializer)
416     return Materializer->getIdentifiedStructTypes();
417 
418   std::vector<StructType *> Ret;
419   TypeFinder SrcStructTypes;
420   SrcStructTypes.run(*this, true);
421   Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
422   return Ret;
423 }
424 
425 // dropAllReferences() - This function causes all the subelements to "let go"
426 // of all references that they are maintaining.  This allows one to 'delete' a
427 // whole module at a time, even though there may be circular references... first
428 // all references are dropped, and all use counts go to zero.  Then everything
429 // is deleted for real.  Note that no operations are valid on an object that
430 // has "dropped all references", except operator delete.
431 //
dropAllReferences()432 void Module::dropAllReferences() {
433   for (Function &F : *this)
434     F.dropAllReferences();
435 
436   for (GlobalVariable &GV : globals())
437     GV.dropAllReferences();
438 
439   for (GlobalAlias &GA : aliases())
440     GA.dropAllReferences();
441 }
442 
getDwarfVersion() const443 unsigned Module::getDwarfVersion() const {
444   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
445   if (!Val)
446     return 0;
447   return cast<ConstantInt>(Val->getValue())->getZExtValue();
448 }
449 
getCodeViewFlag() const450 unsigned Module::getCodeViewFlag() const {
451   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
452   if (!Val)
453     return 0;
454   return cast<ConstantInt>(Val->getValue())->getZExtValue();
455 }
456 
getOrInsertComdat(StringRef Name)457 Comdat *Module::getOrInsertComdat(StringRef Name) {
458   auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
459   Entry.second.Name = &Entry;
460   return &Entry.second;
461 }
462 
getPICLevel() const463 PICLevel::Level Module::getPICLevel() const {
464   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
465 
466   if (!Val)
467     return PICLevel::Default;
468 
469   return static_cast<PICLevel::Level>(
470       cast<ConstantInt>(Val->getValue())->getZExtValue());
471 }
472 
setPICLevel(PICLevel::Level PL)473 void Module::setPICLevel(PICLevel::Level PL) {
474   addModuleFlag(ModFlagBehavior::Error, "PIC Level", PL);
475 }
476 
setMaximumFunctionCount(uint64_t Count)477 void Module::setMaximumFunctionCount(uint64_t Count) {
478   addModuleFlag(ModFlagBehavior::Error, "MaxFunctionCount", Count);
479 }
480 
getMaximumFunctionCount()481 Optional<uint64_t> Module::getMaximumFunctionCount() {
482   auto *Val =
483       cast_or_null<ConstantAsMetadata>(getModuleFlag("MaxFunctionCount"));
484   if (!Val)
485     return None;
486   return cast<ConstantInt>(Val->getValue())->getZExtValue();
487 }
488