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 VMCore library.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Module.h"
15#include "llvm/InstrTypes.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/GVMaterializer.h"
19#include "llvm/LLVMContext.h"
20#include "llvm/ADT/DenseSet.h"
21#include "llvm/ADT/SmallString.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/Support/LeakDetector.h"
25#include "SymbolTableListTraitsImpl.h"
26#include <algorithm>
27#include <cstdarg>
28#include <cstdlib>
29using namespace llvm;
30
31//===----------------------------------------------------------------------===//
32// Methods to implement the globals and functions lists.
33//
34
35// Explicit instantiations of SymbolTableListTraits since some of the methods
36// are not in the public header file.
37template class llvm::SymbolTableListTraits<Function, Module>;
38template class llvm::SymbolTableListTraits<GlobalVariable, Module>;
39template class llvm::SymbolTableListTraits<GlobalAlias, Module>;
40
41//===----------------------------------------------------------------------===//
42// Primitive Module methods.
43//
44
45Module::Module(StringRef MID, LLVMContext& C)
46  : Context(C), Materializer(NULL), ModuleID(MID) {
47  ValSymTab = new ValueSymbolTable();
48  NamedMDSymTab = new StringMap<NamedMDNode *>();
49  Context.addModule(this);
50}
51
52Module::~Module() {
53  Context.removeModule(this);
54  dropAllReferences();
55  GlobalList.clear();
56  FunctionList.clear();
57  AliasList.clear();
58  LibraryList.clear();
59  NamedMDList.clear();
60  delete ValSymTab;
61  delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
62}
63
64/// Target endian information.
65Module::Endianness Module::getEndianness() const {
66  StringRef temp = DataLayout;
67  Module::Endianness ret = AnyEndianness;
68
69  while (!temp.empty()) {
70    std::pair<StringRef, StringRef> P = getToken(temp, "-");
71
72    StringRef token = P.first;
73    temp = P.second;
74
75    if (token[0] == 'e') {
76      ret = LittleEndian;
77    } else if (token[0] == 'E') {
78      ret = BigEndian;
79    }
80  }
81
82  return ret;
83}
84
85/// Target Pointer Size information.
86Module::PointerSize Module::getPointerSize() const {
87  StringRef temp = DataLayout;
88  Module::PointerSize ret = AnyPointerSize;
89
90  while (!temp.empty()) {
91    std::pair<StringRef, StringRef> TmpP = getToken(temp, "-");
92    temp = TmpP.second;
93    TmpP = getToken(TmpP.first, ":");
94    StringRef token = TmpP.second, signalToken = TmpP.first;
95
96    if (signalToken[0] == 'p') {
97      int size = 0;
98      getToken(token, ":").first.getAsInteger(10, size);
99      if (size == 32)
100        ret = Pointer32;
101      else if (size == 64)
102        ret = Pointer64;
103    }
104  }
105
106  return ret;
107}
108
109/// getNamedValue - Return the first global value in the module with
110/// the specified name, of arbitrary type.  This method returns null
111/// if a global with the specified name is not found.
112GlobalValue *Module::getNamedValue(StringRef Name) const {
113  return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
114}
115
116/// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
117/// This ID is uniqued across modules in the current LLVMContext.
118unsigned Module::getMDKindID(StringRef Name) const {
119  return Context.getMDKindID(Name);
120}
121
122/// getMDKindNames - Populate client supplied SmallVector with the name for
123/// custom metadata IDs registered in this LLVMContext.   ID #0 is not used,
124/// so it is filled in as an empty string.
125void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
126  return Context.getMDKindNames(Result);
127}
128
129
130//===----------------------------------------------------------------------===//
131// Methods for easy access to the functions in the module.
132//
133
134// getOrInsertFunction - Look up the specified function in the module symbol
135// table.  If it does not exist, add a prototype for the function and return
136// it.  This is nice because it allows most passes to get away with not handling
137// the symbol table directly for this common task.
138//
139Constant *Module::getOrInsertFunction(StringRef Name,
140                                      FunctionType *Ty,
141                                      AttrListPtr AttributeList) {
142  // See if we have a definition for the specified function already.
143  GlobalValue *F = getNamedValue(Name);
144  if (F == 0) {
145    // Nope, add it
146    Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
147    if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
148      New->setAttributes(AttributeList);
149    FunctionList.push_back(New);
150    return New;                    // Return the new prototype.
151  }
152
153  // Okay, the function exists.  Does it have externally visible linkage?
154  if (F->hasLocalLinkage()) {
155    // Clear the function's name.
156    F->setName("");
157    // Retry, now there won't be a conflict.
158    Constant *NewF = getOrInsertFunction(Name, Ty);
159    F->setName(Name);
160    return NewF;
161  }
162
163  // If the function exists but has the wrong type, return a bitcast to the
164  // right type.
165  if (F->getType() != PointerType::getUnqual(Ty))
166    return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
167
168  // Otherwise, we just found the existing function or a prototype.
169  return F;
170}
171
172Constant *Module::getOrInsertTargetIntrinsic(StringRef Name,
173                                             FunctionType *Ty,
174                                             AttrListPtr AttributeList) {
175  // See if we have a definition for the specified function already.
176  GlobalValue *F = getNamedValue(Name);
177  if (F == 0) {
178    // Nope, add it
179    Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
180    New->setAttributes(AttributeList);
181    FunctionList.push_back(New);
182    return New; // Return the new prototype.
183  }
184
185  // Otherwise, we just found the existing function or a prototype.
186  return F;
187}
188
189Constant *Module::getOrInsertFunction(StringRef Name,
190                                      FunctionType *Ty) {
191  return getOrInsertFunction(Name, Ty, AttrListPtr());
192}
193
194// getOrInsertFunction - Look up the specified function in the module symbol
195// table.  If it does not exist, add a prototype for the function and return it.
196// This version of the method takes a null terminated list of function
197// arguments, which makes it easier for clients to use.
198//
199Constant *Module::getOrInsertFunction(StringRef Name,
200                                      AttrListPtr AttributeList,
201                                      Type *RetTy, ...) {
202  va_list Args;
203  va_start(Args, RetTy);
204
205  // Build the list of argument types...
206  std::vector<Type*> ArgTys;
207  while (Type *ArgTy = va_arg(Args, Type*))
208    ArgTys.push_back(ArgTy);
209
210  va_end(Args);
211
212  // Build the function type and chain to the other getOrInsertFunction...
213  return getOrInsertFunction(Name,
214                             FunctionType::get(RetTy, ArgTys, false),
215                             AttributeList);
216}
217
218Constant *Module::getOrInsertFunction(StringRef Name,
219                                      Type *RetTy, ...) {
220  va_list Args;
221  va_start(Args, RetTy);
222
223  // Build the list of argument types...
224  std::vector<Type*> ArgTys;
225  while (Type *ArgTy = va_arg(Args, Type*))
226    ArgTys.push_back(ArgTy);
227
228  va_end(Args);
229
230  // Build the function type and chain to the other getOrInsertFunction...
231  return getOrInsertFunction(Name,
232                             FunctionType::get(RetTy, ArgTys, false),
233                             AttrListPtr());
234}
235
236// getFunction - Look up the specified function in the module symbol table.
237// If it does not exist, return null.
238//
239Function *Module::getFunction(StringRef Name) const {
240  return dyn_cast_or_null<Function>(getNamedValue(Name));
241}
242
243//===----------------------------------------------------------------------===//
244// Methods for easy access to the global variables in the module.
245//
246
247/// getGlobalVariable - Look up the specified global variable in the module
248/// symbol table.  If it does not exist, return null.  The type argument
249/// should be the underlying type of the global, i.e., it should not have
250/// the top-level PointerType, which represents the address of the global.
251/// If AllowLocal is set to true, this function will return types that
252/// have an local. By default, these types are not returned.
253///
254GlobalVariable *Module::getGlobalVariable(StringRef Name,
255                                          bool AllowLocal) const {
256  if (GlobalVariable *Result =
257      dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
258    if (AllowLocal || !Result->hasLocalLinkage())
259      return Result;
260  return 0;
261}
262
263/// getOrInsertGlobal - Look up the specified global in the module symbol table.
264///   1. If it does not exist, add a declaration of the global and return it.
265///   2. Else, the global exists but has the wrong type: return the function
266///      with a constantexpr cast to the right type.
267///   3. Finally, if the existing global is the correct delclaration, return the
268///      existing global.
269Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
270  // See if we have a definition for the specified global already.
271  GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
272  if (GV == 0) {
273    // Nope, add it
274    GlobalVariable *New =
275      new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
276                         0, Name);
277     return New;                    // Return the new declaration.
278  }
279
280  // If the variable exists but has the wrong type, return a bitcast to the
281  // right type.
282  if (GV->getType() != PointerType::getUnqual(Ty))
283    return ConstantExpr::getBitCast(GV, PointerType::getUnqual(Ty));
284
285  // Otherwise, we just found the existing function or a prototype.
286  return GV;
287}
288
289//===----------------------------------------------------------------------===//
290// Methods for easy access to the global variables in the module.
291//
292
293// getNamedAlias - Look up the specified global in the module symbol table.
294// If it does not exist, return null.
295//
296GlobalAlias *Module::getNamedAlias(StringRef Name) const {
297  return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
298}
299
300/// getNamedMetadata - Return the first NamedMDNode in the module with the
301/// specified name. This method returns null if a NamedMDNode with the
302/// specified name is not found.
303NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
304  SmallString<256> NameData;
305  StringRef NameRef = Name.toStringRef(NameData);
306  return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
307}
308
309/// getOrInsertNamedMetadata - Return the first named MDNode in the module
310/// with the specified name. This method returns a new NamedMDNode if a
311/// NamedMDNode with the specified name is not found.
312NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
313  NamedMDNode *&NMD =
314    (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
315  if (!NMD) {
316    NMD = new NamedMDNode(Name);
317    NMD->setParent(this);
318    NamedMDList.push_back(NMD);
319  }
320  return NMD;
321}
322
323/// eraseNamedMetadata - Remove the given NamedMDNode from this module and
324/// delete it.
325void Module::eraseNamedMetadata(NamedMDNode *NMD) {
326  static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
327  NamedMDList.erase(NMD);
328}
329
330/// getModuleFlagsMetadata - Returns the module flags in the provided vector.
331void Module::
332getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
333  const NamedMDNode *ModFlags = getModuleFlagsMetadata();
334  if (!ModFlags) return;
335
336  for (unsigned i = 0, e = ModFlags->getNumOperands(); i != e; ++i) {
337    MDNode *Flag = ModFlags->getOperand(i);
338    ConstantInt *Behavior = cast<ConstantInt>(Flag->getOperand(0));
339    MDString *Key = cast<MDString>(Flag->getOperand(1));
340    Value *Val = Flag->getOperand(2);
341    Flags.push_back(ModuleFlagEntry(ModFlagBehavior(Behavior->getZExtValue()),
342                                    Key, Val));
343  }
344}
345
346/// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
347/// represents module-level flags. This method returns null if there are no
348/// module-level flags.
349NamedMDNode *Module::getModuleFlagsMetadata() const {
350  return getNamedMetadata("llvm.module.flags");
351}
352
353/// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
354/// represents module-level flags. If module-level flags aren't found, it
355/// creates the named metadata that contains them.
356NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
357  return getOrInsertNamedMetadata("llvm.module.flags");
358}
359
360/// addModuleFlag - Add a module-level flag to the module-level flags
361/// metadata. It will create the module-level flags named metadata if it doesn't
362/// already exist.
363void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
364                           Value *Val) {
365  Type *Int32Ty = Type::getInt32Ty(Context);
366  Value *Ops[3] = {
367    ConstantInt::get(Int32Ty, Behavior), MDString::get(Context, Key), Val
368  };
369  getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
370}
371void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
372                           uint32_t Val) {
373  Type *Int32Ty = Type::getInt32Ty(Context);
374  addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
375}
376void Module::addModuleFlag(MDNode *Node) {
377  assert(Node->getNumOperands() == 3 &&
378         "Invalid number of operands for module flag!");
379  assert(isa<ConstantInt>(Node->getOperand(0)) &&
380         isa<MDString>(Node->getOperand(1)) &&
381         "Invalid operand types for module flag!");
382  getOrInsertModuleFlagsMetadata()->addOperand(Node);
383}
384
385//===----------------------------------------------------------------------===//
386// Methods to control the materialization of GlobalValues in the Module.
387//
388void Module::setMaterializer(GVMaterializer *GVM) {
389  assert(!Materializer &&
390         "Module already has a GVMaterializer.  Call MaterializeAllPermanently"
391         " to clear it out before setting another one.");
392  Materializer.reset(GVM);
393}
394
395bool Module::isMaterializable(const GlobalValue *GV) const {
396  if (Materializer)
397    return Materializer->isMaterializable(GV);
398  return false;
399}
400
401bool Module::isDematerializable(const GlobalValue *GV) const {
402  if (Materializer)
403    return Materializer->isDematerializable(GV);
404  return false;
405}
406
407bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
408  if (Materializer)
409    return Materializer->Materialize(GV, ErrInfo);
410  return false;
411}
412
413void Module::Dematerialize(GlobalValue *GV) {
414  if (Materializer)
415    return Materializer->Dematerialize(GV);
416}
417
418bool Module::MaterializeAll(std::string *ErrInfo) {
419  if (!Materializer)
420    return false;
421  return Materializer->MaterializeModule(this, ErrInfo);
422}
423
424bool Module::MaterializeAllPermanently(std::string *ErrInfo) {
425  if (MaterializeAll(ErrInfo))
426    return true;
427  Materializer.reset();
428  return false;
429}
430
431//===----------------------------------------------------------------------===//
432// Other module related stuff.
433//
434
435
436// dropAllReferences() - This function causes all the subelements to "let go"
437// of all references that they are maintaining.  This allows one to 'delete' a
438// whole module at a time, even though there may be circular references... first
439// all references are dropped, and all use counts go to zero.  Then everything
440// is deleted for real.  Note that no operations are valid on an object that
441// has "dropped all references", except operator delete.
442//
443void Module::dropAllReferences() {
444  for(Module::iterator I = begin(), E = end(); I != E; ++I)
445    I->dropAllReferences();
446
447  for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
448    I->dropAllReferences();
449
450  for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
451    I->dropAllReferences();
452}
453
454void Module::addLibrary(StringRef Lib) {
455  for (Module::lib_iterator I = lib_begin(), E = lib_end(); I != E; ++I)
456    if (*I == Lib)
457      return;
458  LibraryList.push_back(Lib);
459}
460
461void Module::removeLibrary(StringRef Lib) {
462  LibraryListType::iterator I = LibraryList.begin();
463  LibraryListType::iterator E = LibraryList.end();
464  for (;I != E; ++I)
465    if (*I == Lib) {
466      LibraryList.erase(I);
467      return;
468    }
469}
470