1249259Sdim//===-- Module.cpp - Implement the Module class ---------------------------===//
2249259Sdim//
3249259Sdim//                     The LLVM Compiler Infrastructure
4249259Sdim//
5249259Sdim// This file is distributed under the University of Illinois Open Source
6249259Sdim// License. See LICENSE.TXT for details.
7249259Sdim//
8249259Sdim//===----------------------------------------------------------------------===//
9249259Sdim//
10249259Sdim// This file implements the Module class for the IR library.
11249259Sdim//
12249259Sdim//===----------------------------------------------------------------------===//
13249259Sdim
14249259Sdim#include "llvm/IR/Module.h"
15249259Sdim#include "SymbolTableListTraitsImpl.h"
16249259Sdim#include "llvm/ADT/DenseSet.h"
17249259Sdim#include "llvm/ADT/STLExtras.h"
18249259Sdim#include "llvm/ADT/SmallString.h"
19249259Sdim#include "llvm/ADT/StringExtras.h"
20249259Sdim#include "llvm/GVMaterializer.h"
21249259Sdim#include "llvm/IR/Constants.h"
22249259Sdim#include "llvm/IR/DerivedTypes.h"
23249259Sdim#include "llvm/IR/InstrTypes.h"
24249259Sdim#include "llvm/IR/LLVMContext.h"
25249259Sdim#include "llvm/Support/LeakDetector.h"
26249259Sdim#include <algorithm>
27249259Sdim#include <cstdarg>
28249259Sdim#include <cstdlib>
29249259Sdimusing namespace llvm;
30249259Sdim
31249259Sdim//===----------------------------------------------------------------------===//
32249259Sdim// Methods to implement the globals and functions lists.
33249259Sdim//
34249259Sdim
35249259Sdim// Explicit instantiations of SymbolTableListTraits since some of the methods
36249259Sdim// are not in the public header file.
37249259Sdimtemplate class llvm::SymbolTableListTraits<Function, Module>;
38249259Sdimtemplate class llvm::SymbolTableListTraits<GlobalVariable, Module>;
39249259Sdimtemplate class llvm::SymbolTableListTraits<GlobalAlias, Module>;
40249259Sdim
41249259Sdim//===----------------------------------------------------------------------===//
42249259Sdim// Primitive Module methods.
43249259Sdim//
44249259Sdim
45249259SdimModule::Module(StringRef MID, LLVMContext& C)
46249259Sdim  : Context(C), Materializer(NULL), ModuleID(MID) {
47249259Sdim  ValSymTab = new ValueSymbolTable();
48249259Sdim  NamedMDSymTab = new StringMap<NamedMDNode *>();
49249259Sdim  Context.addModule(this);
50249259Sdim}
51249259Sdim
52249259SdimModule::~Module() {
53249259Sdim  Context.removeModule(this);
54249259Sdim  dropAllReferences();
55249259Sdim  GlobalList.clear();
56249259Sdim  FunctionList.clear();
57249259Sdim  AliasList.clear();
58249259Sdim  NamedMDList.clear();
59249259Sdim  delete ValSymTab;
60249259Sdim  delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
61249259Sdim}
62249259Sdim
63249259Sdim/// Target endian information.
64249259SdimModule::Endianness Module::getEndianness() const {
65249259Sdim  StringRef temp = DataLayout;
66249259Sdim  Module::Endianness ret = AnyEndianness;
67249259Sdim
68249259Sdim  while (!temp.empty()) {
69249259Sdim    std::pair<StringRef, StringRef> P = getToken(temp, "-");
70249259Sdim
71249259Sdim    StringRef token = P.first;
72249259Sdim    temp = P.second;
73249259Sdim
74249259Sdim    if (token[0] == 'e') {
75249259Sdim      ret = LittleEndian;
76249259Sdim    } else if (token[0] == 'E') {
77249259Sdim      ret = BigEndian;
78249259Sdim    }
79249259Sdim  }
80249259Sdim
81249259Sdim  return ret;
82249259Sdim}
83249259Sdim
84249259Sdim/// Target Pointer Size information.
85249259SdimModule::PointerSize Module::getPointerSize() const {
86249259Sdim  StringRef temp = DataLayout;
87249259Sdim  Module::PointerSize ret = AnyPointerSize;
88249259Sdim
89249259Sdim  while (!temp.empty()) {
90249259Sdim    std::pair<StringRef, StringRef> TmpP = getToken(temp, "-");
91249259Sdim    temp = TmpP.second;
92249259Sdim    TmpP = getToken(TmpP.first, ":");
93249259Sdim    StringRef token = TmpP.second, signalToken = TmpP.first;
94249259Sdim
95249259Sdim    if (signalToken[0] == 'p') {
96249259Sdim      int size = 0;
97249259Sdim      getToken(token, ":").first.getAsInteger(10, size);
98249259Sdim      if (size == 32)
99249259Sdim        ret = Pointer32;
100249259Sdim      else if (size == 64)
101249259Sdim        ret = Pointer64;
102249259Sdim    }
103249259Sdim  }
104249259Sdim
105249259Sdim  return ret;
106249259Sdim}
107249259Sdim
108249259Sdim/// getNamedValue - Return the first global value in the module with
109249259Sdim/// the specified name, of arbitrary type.  This method returns null
110249259Sdim/// if a global with the specified name is not found.
111249259SdimGlobalValue *Module::getNamedValue(StringRef Name) const {
112249259Sdim  return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
113249259Sdim}
114249259Sdim
115249259Sdim/// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
116249259Sdim/// This ID is uniqued across modules in the current LLVMContext.
117249259Sdimunsigned Module::getMDKindID(StringRef Name) const {
118249259Sdim  return Context.getMDKindID(Name);
119249259Sdim}
120249259Sdim
121249259Sdim/// getMDKindNames - Populate client supplied SmallVector with the name for
122249259Sdim/// custom metadata IDs registered in this LLVMContext.   ID #0 is not used,
123249259Sdim/// so it is filled in as an empty string.
124249259Sdimvoid Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
125249259Sdim  return Context.getMDKindNames(Result);
126249259Sdim}
127249259Sdim
128249259Sdim
129249259Sdim//===----------------------------------------------------------------------===//
130249259Sdim// Methods for easy access to the functions in the module.
131249259Sdim//
132249259Sdim
133249259Sdim// getOrInsertFunction - Look up the specified function in the module symbol
134249259Sdim// table.  If it does not exist, add a prototype for the function and return
135249259Sdim// it.  This is nice because it allows most passes to get away with not handling
136249259Sdim// the symbol table directly for this common task.
137249259Sdim//
138249259SdimConstant *Module::getOrInsertFunction(StringRef Name,
139249259Sdim                                      FunctionType *Ty,
140249259Sdim                                      AttributeSet AttributeList) {
141249259Sdim  // See if we have a definition for the specified function already.
142249259Sdim  GlobalValue *F = getNamedValue(Name);
143249259Sdim  if (F == 0) {
144249259Sdim    // Nope, add it
145249259Sdim    Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
146249259Sdim    if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
147249259Sdim      New->setAttributes(AttributeList);
148249259Sdim    FunctionList.push_back(New);
149249259Sdim    return New;                    // Return the new prototype.
150249259Sdim  }
151249259Sdim
152249259Sdim  // Okay, the function exists.  Does it have externally visible linkage?
153249259Sdim  if (F->hasLocalLinkage()) {
154249259Sdim    // Clear the function's name.
155249259Sdim    F->setName("");
156249259Sdim    // Retry, now there won't be a conflict.
157249259Sdim    Constant *NewF = getOrInsertFunction(Name, Ty);
158249259Sdim    F->setName(Name);
159249259Sdim    return NewF;
160249259Sdim  }
161249259Sdim
162249259Sdim  // If the function exists but has the wrong type, return a bitcast to the
163249259Sdim  // right type.
164249259Sdim  if (F->getType() != PointerType::getUnqual(Ty))
165249259Sdim    return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
166249259Sdim
167249259Sdim  // Otherwise, we just found the existing function or a prototype.
168249259Sdim  return F;
169249259Sdim}
170249259Sdim
171249259SdimConstant *Module::getOrInsertFunction(StringRef Name,
172249259Sdim                                      FunctionType *Ty) {
173249259Sdim  return getOrInsertFunction(Name, Ty, AttributeSet());
174249259Sdim}
175249259Sdim
176249259Sdim// getOrInsertFunction - Look up the specified function in the module symbol
177249259Sdim// table.  If it does not exist, add a prototype for the function and return it.
178249259Sdim// This version of the method takes a null terminated list of function
179249259Sdim// arguments, which makes it easier for clients to use.
180249259Sdim//
181249259SdimConstant *Module::getOrInsertFunction(StringRef Name,
182249259Sdim                                      AttributeSet AttributeList,
183249259Sdim                                      Type *RetTy, ...) {
184249259Sdim  va_list Args;
185249259Sdim  va_start(Args, RetTy);
186249259Sdim
187249259Sdim  // Build the list of argument types...
188249259Sdim  std::vector<Type*> ArgTys;
189249259Sdim  while (Type *ArgTy = va_arg(Args, Type*))
190249259Sdim    ArgTys.push_back(ArgTy);
191249259Sdim
192249259Sdim  va_end(Args);
193249259Sdim
194249259Sdim  // Build the function type and chain to the other getOrInsertFunction...
195249259Sdim  return getOrInsertFunction(Name,
196249259Sdim                             FunctionType::get(RetTy, ArgTys, false),
197249259Sdim                             AttributeList);
198249259Sdim}
199249259Sdim
200249259SdimConstant *Module::getOrInsertFunction(StringRef Name,
201249259Sdim                                      Type *RetTy, ...) {
202249259Sdim  va_list Args;
203249259Sdim  va_start(Args, RetTy);
204249259Sdim
205249259Sdim  // Build the list of argument types...
206249259Sdim  std::vector<Type*> ArgTys;
207249259Sdim  while (Type *ArgTy = va_arg(Args, Type*))
208249259Sdim    ArgTys.push_back(ArgTy);
209249259Sdim
210249259Sdim  va_end(Args);
211249259Sdim
212249259Sdim  // Build the function type and chain to the other getOrInsertFunction...
213249259Sdim  return getOrInsertFunction(Name,
214249259Sdim                             FunctionType::get(RetTy, ArgTys, false),
215249259Sdim                             AttributeSet());
216249259Sdim}
217249259Sdim
218249259Sdim// getFunction - Look up the specified function in the module symbol table.
219249259Sdim// If it does not exist, return null.
220249259Sdim//
221249259SdimFunction *Module::getFunction(StringRef Name) const {
222249259Sdim  return dyn_cast_or_null<Function>(getNamedValue(Name));
223249259Sdim}
224249259Sdim
225249259Sdim//===----------------------------------------------------------------------===//
226249259Sdim// Methods for easy access to the global variables in the module.
227249259Sdim//
228249259Sdim
229249259Sdim/// getGlobalVariable - Look up the specified global variable in the module
230249259Sdim/// symbol table.  If it does not exist, return null.  The type argument
231249259Sdim/// should be the underlying type of the global, i.e., it should not have
232249259Sdim/// the top-level PointerType, which represents the address of the global.
233249259Sdim/// If AllowLocal is set to true, this function will return types that
234249259Sdim/// have an local. By default, these types are not returned.
235249259Sdim///
236263509SdimGlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
237249259Sdim  if (GlobalVariable *Result =
238249259Sdim      dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
239249259Sdim    if (AllowLocal || !Result->hasLocalLinkage())
240249259Sdim      return Result;
241249259Sdim  return 0;
242249259Sdim}
243249259Sdim
244249259Sdim/// getOrInsertGlobal - Look up the specified global in the module symbol table.
245249259Sdim///   1. If it does not exist, add a declaration of the global and return it.
246249259Sdim///   2. Else, the global exists but has the wrong type: return the function
247249259Sdim///      with a constantexpr cast to the right type.
248263509Sdim///   3. Finally, if the existing global is the correct declaration, return the
249249259Sdim///      existing global.
250249259SdimConstant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
251249259Sdim  // See if we have a definition for the specified global already.
252249259Sdim  GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
253249259Sdim  if (GV == 0) {
254249259Sdim    // Nope, add it
255249259Sdim    GlobalVariable *New =
256249259Sdim      new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
257249259Sdim                         0, Name);
258249259Sdim     return New;                    // Return the new declaration.
259249259Sdim  }
260249259Sdim
261249259Sdim  // If the variable exists but has the wrong type, return a bitcast to the
262249259Sdim  // right type.
263263509Sdim  Type *GVTy = GV->getType();
264263509Sdim  PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
265263509Sdim  if (GVTy != PTy)
266263509Sdim    return ConstantExpr::getBitCast(GV, PTy);
267249259Sdim
268249259Sdim  // Otherwise, we just found the existing function or a prototype.
269249259Sdim  return GV;
270249259Sdim}
271249259Sdim
272249259Sdim//===----------------------------------------------------------------------===//
273249259Sdim// Methods for easy access to the global variables in the module.
274249259Sdim//
275249259Sdim
276249259Sdim// getNamedAlias - Look up the specified global in the module symbol table.
277249259Sdim// If it does not exist, return null.
278249259Sdim//
279249259SdimGlobalAlias *Module::getNamedAlias(StringRef Name) const {
280249259Sdim  return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
281249259Sdim}
282249259Sdim
283249259Sdim/// getNamedMetadata - Return the first NamedMDNode in the module with the
284249259Sdim/// specified name. This method returns null if a NamedMDNode with the
285249259Sdim/// specified name is not found.
286249259SdimNamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
287249259Sdim  SmallString<256> NameData;
288249259Sdim  StringRef NameRef = Name.toStringRef(NameData);
289249259Sdim  return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
290249259Sdim}
291249259Sdim
292249259Sdim/// getOrInsertNamedMetadata - Return the first named MDNode in the module
293249259Sdim/// with the specified name. This method returns a new NamedMDNode if a
294249259Sdim/// NamedMDNode with the specified name is not found.
295249259SdimNamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
296249259Sdim  NamedMDNode *&NMD =
297249259Sdim    (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
298249259Sdim  if (!NMD) {
299249259Sdim    NMD = new NamedMDNode(Name);
300249259Sdim    NMD->setParent(this);
301249259Sdim    NamedMDList.push_back(NMD);
302249259Sdim  }
303249259Sdim  return NMD;
304249259Sdim}
305249259Sdim
306249259Sdim/// eraseNamedMetadata - Remove the given NamedMDNode from this module and
307249259Sdim/// delete it.
308249259Sdimvoid Module::eraseNamedMetadata(NamedMDNode *NMD) {
309249259Sdim  static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
310249259Sdim  NamedMDList.erase(NMD);
311249259Sdim}
312249259Sdim
313249259Sdim/// getModuleFlagsMetadata - Returns the module flags in the provided vector.
314249259Sdimvoid Module::
315249259SdimgetModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
316249259Sdim  const NamedMDNode *ModFlags = getModuleFlagsMetadata();
317249259Sdim  if (!ModFlags) return;
318249259Sdim
319249259Sdim  for (unsigned i = 0, e = ModFlags->getNumOperands(); i != e; ++i) {
320249259Sdim    MDNode *Flag = ModFlags->getOperand(i);
321263509Sdim    if (Flag->getNumOperands() >= 3 && isa<ConstantInt>(Flag->getOperand(0)) &&
322263509Sdim        isa<MDString>(Flag->getOperand(1))) {
323263509Sdim      // Check the operands of the MDNode before accessing the operands.
324263509Sdim      // The verifier will actually catch these failures.
325263509Sdim      ConstantInt *Behavior = cast<ConstantInt>(Flag->getOperand(0));
326263509Sdim      MDString *Key = cast<MDString>(Flag->getOperand(1));
327263509Sdim      Value *Val = Flag->getOperand(2);
328263509Sdim      Flags.push_back(ModuleFlagEntry(ModFlagBehavior(Behavior->getZExtValue()),
329263509Sdim                                      Key, Val));
330263509Sdim    }
331249259Sdim  }
332249259Sdim}
333249259Sdim
334263509Sdim/// Return the corresponding value if Key appears in module flags, otherwise
335263509Sdim/// return null.
336263509SdimValue *Module::getModuleFlag(StringRef Key) const {
337263509Sdim  SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
338263509Sdim  getModuleFlagsMetadata(ModuleFlags);
339263509Sdim  for (unsigned I = 0, E = ModuleFlags.size(); I < E; ++I) {
340263509Sdim    const ModuleFlagEntry &MFE = ModuleFlags[I];
341263509Sdim    if (Key == MFE.Key->getString())
342263509Sdim      return MFE.Val;
343263509Sdim  }
344263509Sdim  return 0;
345263509Sdim}
346263509Sdim
347249259Sdim/// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
348249259Sdim/// represents module-level flags. This method returns null if there are no
349249259Sdim/// module-level flags.
350249259SdimNamedMDNode *Module::getModuleFlagsMetadata() const {
351249259Sdim  return getNamedMetadata("llvm.module.flags");
352249259Sdim}
353249259Sdim
354249259Sdim/// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
355249259Sdim/// represents module-level flags. If module-level flags aren't found, it
356249259Sdim/// creates the named metadata that contains them.
357249259SdimNamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
358249259Sdim  return getOrInsertNamedMetadata("llvm.module.flags");
359249259Sdim}
360249259Sdim
361249259Sdim/// addModuleFlag - Add a module-level flag to the module-level flags
362249259Sdim/// metadata. It will create the module-level flags named metadata if it doesn't
363249259Sdim/// already exist.
364249259Sdimvoid Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
365249259Sdim                           Value *Val) {
366249259Sdim  Type *Int32Ty = Type::getInt32Ty(Context);
367249259Sdim  Value *Ops[3] = {
368249259Sdim    ConstantInt::get(Int32Ty, Behavior), MDString::get(Context, Key), Val
369249259Sdim  };
370249259Sdim  getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
371249259Sdim}
372249259Sdimvoid Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
373249259Sdim                           uint32_t Val) {
374249259Sdim  Type *Int32Ty = Type::getInt32Ty(Context);
375249259Sdim  addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
376249259Sdim}
377249259Sdimvoid Module::addModuleFlag(MDNode *Node) {
378249259Sdim  assert(Node->getNumOperands() == 3 &&
379249259Sdim         "Invalid number of operands for module flag!");
380249259Sdim  assert(isa<ConstantInt>(Node->getOperand(0)) &&
381249259Sdim         isa<MDString>(Node->getOperand(1)) &&
382249259Sdim         "Invalid operand types for module flag!");
383249259Sdim  getOrInsertModuleFlagsMetadata()->addOperand(Node);
384249259Sdim}
385249259Sdim
386249259Sdim//===----------------------------------------------------------------------===//
387249259Sdim// Methods to control the materialization of GlobalValues in the Module.
388249259Sdim//
389249259Sdimvoid Module::setMaterializer(GVMaterializer *GVM) {
390249259Sdim  assert(!Materializer &&
391249259Sdim         "Module already has a GVMaterializer.  Call MaterializeAllPermanently"
392249259Sdim         " to clear it out before setting another one.");
393249259Sdim  Materializer.reset(GVM);
394249259Sdim}
395249259Sdim
396249259Sdimbool Module::isMaterializable(const GlobalValue *GV) const {
397249259Sdim  if (Materializer)
398249259Sdim    return Materializer->isMaterializable(GV);
399249259Sdim  return false;
400249259Sdim}
401249259Sdim
402249259Sdimbool Module::isDematerializable(const GlobalValue *GV) const {
403249259Sdim  if (Materializer)
404249259Sdim    return Materializer->isDematerializable(GV);
405249259Sdim  return false;
406249259Sdim}
407249259Sdim
408249259Sdimbool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
409263509Sdim  if (!Materializer)
410263509Sdim    return false;
411263509Sdim
412263509Sdim  error_code EC = Materializer->Materialize(GV);
413263509Sdim  if (!EC)
414263509Sdim    return false;
415263509Sdim  if (ErrInfo)
416263509Sdim    *ErrInfo = EC.message();
417263509Sdim  return true;
418249259Sdim}
419249259Sdim
420249259Sdimvoid Module::Dematerialize(GlobalValue *GV) {
421249259Sdim  if (Materializer)
422249259Sdim    return Materializer->Dematerialize(GV);
423249259Sdim}
424249259Sdim
425249259Sdimbool Module::MaterializeAll(std::string *ErrInfo) {
426249259Sdim  if (!Materializer)
427249259Sdim    return false;
428263509Sdim  error_code EC = Materializer->MaterializeModule(this);
429263509Sdim  if (!EC)
430263509Sdim    return false;
431263509Sdim  if (ErrInfo)
432263509Sdim    *ErrInfo = EC.message();
433263509Sdim  return true;
434249259Sdim}
435249259Sdim
436249259Sdimbool Module::MaterializeAllPermanently(std::string *ErrInfo) {
437249259Sdim  if (MaterializeAll(ErrInfo))
438249259Sdim    return true;
439249259Sdim  Materializer.reset();
440249259Sdim  return false;
441249259Sdim}
442249259Sdim
443249259Sdim//===----------------------------------------------------------------------===//
444249259Sdim// Other module related stuff.
445249259Sdim//
446249259Sdim
447249259Sdim
448249259Sdim// dropAllReferences() - This function causes all the subelements to "let go"
449249259Sdim// of all references that they are maintaining.  This allows one to 'delete' a
450249259Sdim// whole module at a time, even though there may be circular references... first
451249259Sdim// all references are dropped, and all use counts go to zero.  Then everything
452249259Sdim// is deleted for real.  Note that no operations are valid on an object that
453249259Sdim// has "dropped all references", except operator delete.
454249259Sdim//
455249259Sdimvoid Module::dropAllReferences() {
456249259Sdim  for(Module::iterator I = begin(), E = end(); I != E; ++I)
457249259Sdim    I->dropAllReferences();
458249259Sdim
459249259Sdim  for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
460249259Sdim    I->dropAllReferences();
461249259Sdim
462249259Sdim  for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
463249259Sdim    I->dropAllReferences();
464249259Sdim}
465