LLVM API Documentation

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Module.cpp
Go to the documentation of this file.
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"
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/GVMaterializer.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/InstrTypes.h"
24 #include "llvm/IR/LLVMContext.h"
26 #include <algorithm>
27 #include <cstdarg>
28 #include <cstdlib>
29 using 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.
40 
41 //===----------------------------------------------------------------------===//
42 // Primitive Module methods.
43 //
44 
46  : Context(C), Materializer(NULL), ModuleID(MID) {
47  ValSymTab = new ValueSymbolTable();
48  NamedMDSymTab = new StringMap<NamedMDNode *>();
49  Context.addModule(this);
50 }
51 
53  Context.removeModule(this);
55  GlobalList.clear();
56  FunctionList.clear();
57  AliasList.clear();
58  NamedMDList.clear();
59  delete ValSymTab;
60  delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
61 }
62 
63 /// Target endian information.
65  StringRef temp = DataLayout;
67 
68  while (!temp.empty()) {
69  std::pair<StringRef, StringRef> P = getToken(temp, "-");
70 
71  StringRef token = P.first;
72  temp = P.second;
73 
74  if (token[0] == 'e') {
75  ret = LittleEndian;
76  } else if (token[0] == 'E') {
77  ret = BigEndian;
78  }
79  }
80 
81  return ret;
82 }
83 
84 /// Target Pointer Size information.
86  StringRef temp = DataLayout;
88 
89  while (!temp.empty()) {
90  std::pair<StringRef, StringRef> TmpP = getToken(temp, "-");
91  temp = TmpP.second;
92  TmpP = getToken(TmpP.first, ":");
93  StringRef token = TmpP.second, signalToken = TmpP.first;
94 
95  if (signalToken[0] == 'p') {
96  int size = 0;
97  getToken(token, ":").first.getAsInteger(10, size);
98  if (size == 32)
99  ret = Pointer32;
100  else if (size == 64)
101  ret = Pointer64;
102  }
103  }
104 
105  return ret;
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.
112  return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
113 }
114 
115 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
116 /// This ID is uniqued across modules in the current LLVMContext.
118  return Context.getMDKindID(Name);
119 }
120 
121 /// getMDKindNames - Populate client supplied SmallVector with the name for
122 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
123 /// so it is filled in as an empty string.
125  return Context.getMDKindNames(Result);
126 }
127 
128 
129 //===----------------------------------------------------------------------===//
130 // Methods for easy access to the functions in the module.
131 //
132 
133 // getOrInsertFunction - Look up the specified function in the module symbol
134 // table. If it does not exist, add a prototype for the function and return
135 // it. This is nice because it allows most passes to get away with not handling
136 // the symbol table directly for this common task.
137 //
139  FunctionType *Ty,
140  AttributeSet AttributeList) {
141  // See if we have a definition for the specified function already.
142  GlobalValue *F = getNamedValue(Name);
143  if (F == 0) {
144  // Nope, add it
146  if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
147  New->setAttributes(AttributeList);
148  FunctionList.push_back(New);
149  return New; // Return the new prototype.
150  }
151 
152  // Okay, the function exists. Does it have externally visible linkage?
153  if (F->hasLocalLinkage()) {
154  // Clear the function's name.
155  F->setName("");
156  // Retry, now there won't be a conflict.
157  Constant *NewF = getOrInsertFunction(Name, Ty);
158  F->setName(Name);
159  return NewF;
160  }
161 
162  // If the function exists but has the wrong type, return a bitcast to the
163  // right type.
164  if (F->getType() != PointerType::getUnqual(Ty))
166 
167  // Otherwise, we just found the existing function or a prototype.
168  return F;
169 }
170 
172  FunctionType *Ty) {
173  return getOrInsertFunction(Name, Ty, AttributeSet());
174 }
175 
176 // getOrInsertFunction - Look up the specified function in the module symbol
177 // table. If it does not exist, add a prototype for the function and return it.
178 // This version of the method takes a null terminated list of function
179 // arguments, which makes it easier for clients to use.
180 //
182  AttributeSet AttributeList,
183  Type *RetTy, ...) {
184  va_list Args;
185  va_start(Args, RetTy);
186 
187  // Build the list of argument types...
188  std::vector<Type*> ArgTys;
189  while (Type *ArgTy = va_arg(Args, Type*))
190  ArgTys.push_back(ArgTy);
191 
192  va_end(Args);
193 
194  // Build the function type and chain to the other getOrInsertFunction...
195  return getOrInsertFunction(Name,
196  FunctionType::get(RetTy, ArgTys, false),
197  AttributeList);
198 }
199 
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  AttributeSet());
216 }
217 
218 // getFunction - Look up the specified function in the module symbol table.
219 // If it does not exist, return null.
220 //
222  return dyn_cast_or_null<Function>(getNamedValue(Name));
223 }
224 
225 //===----------------------------------------------------------------------===//
226 // Methods for easy access to the global variables in the module.
227 //
228 
229 /// getGlobalVariable - Look up the specified global variable in the module
230 /// symbol table. If it does not exist, return null. The type argument
231 /// should be the underlying type of the global, i.e., it should not have
232 /// the top-level PointerType, which represents the address of the global.
233 /// If AllowLocal is set to true, this function will return types that
234 /// have an local. By default, these types are not returned.
235 ///
237  if (GlobalVariable *Result =
238  dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
239  if (AllowLocal || !Result->hasLocalLinkage())
240  return Result;
241  return 0;
242 }
243 
244 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
245 /// 1. If it does not exist, add a declaration of the global and return it.
246 /// 2. Else, the global exists but has the wrong type: return the function
247 /// with a constantexpr cast to the right type.
248 /// 3. Finally, if the existing global is the correct declaration, return the
249 /// existing global.
251  // See if we have a definition for the specified global already.
252  GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
253  if (GV == 0) {
254  // Nope, add it
255  GlobalVariable *New =
256  new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
257  0, Name);
258  return New; // Return the new declaration.
259  }
260 
261  // If the variable exists but has the wrong type, return a bitcast to the
262  // right type.
263  Type *GVTy = GV->getType();
265  if (GVTy != PTy)
266  return ConstantExpr::getBitCast(GV, PTy);
267 
268  // Otherwise, we just found the existing function or a prototype.
269  return GV;
270 }
271 
272 //===----------------------------------------------------------------------===//
273 // Methods for easy access to the global variables in the module.
274 //
275 
276 // getNamedAlias - Look up the specified global in the module symbol table.
277 // If it does not exist, return null.
278 //
280  return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
281 }
282 
283 /// getNamedMetadata - Return the first NamedMDNode in the module with the
284 /// specified name. This method returns null if a NamedMDNode with the
285 /// specified name is not found.
287  SmallString<256> NameData;
288  StringRef NameRef = Name.toStringRef(NameData);
289  return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
290 }
291 
292 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
293 /// with the specified name. This method returns a new NamedMDNode if a
294 /// NamedMDNode with the specified name is not found.
296  NamedMDNode *&NMD =
297  (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
298  if (!NMD) {
299  NMD = new NamedMDNode(Name);
300  NMD->setParent(this);
301  NamedMDList.push_back(NMD);
302  }
303  return NMD;
304 }
305 
306 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
307 /// delete it.
309  static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
310  NamedMDList.erase(NMD);
311 }
312 
313 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
314 void Module::
316  const NamedMDNode *ModFlags = getModuleFlagsMetadata();
317  if (!ModFlags) return;
318 
319  for (unsigned i = 0, e = ModFlags->getNumOperands(); i != e; ++i) {
320  MDNode *Flag = ModFlags->getOperand(i);
321  ConstantInt *Behavior = cast<ConstantInt>(Flag->getOperand(0));
322  MDString *Key = cast<MDString>(Flag->getOperand(1));
323  Value *Val = Flag->getOperand(2);
325  Key, Val));
326  }
327 }
328 
329 /// Return the corresponding value if Key appears in module flags, otherwise
330 /// return null.
333  getModuleFlagsMetadata(ModuleFlags);
334  for (unsigned I = 0, E = ModuleFlags.size(); I < E; ++I) {
335  const ModuleFlagEntry &MFE = ModuleFlags[I];
336  if (Key == MFE.Key->getString())
337  return MFE.Val;
338  }
339  return 0;
340 }
341 
342 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
343 /// represents module-level flags. This method returns null if there are no
344 /// module-level flags.
346  return getNamedMetadata("llvm.module.flags");
347 }
348 
349 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
350 /// represents module-level flags. If module-level flags aren't found, it
351 /// creates the named metadata that contains them.
353  return getOrInsertNamedMetadata("llvm.module.flags");
354 }
355 
356 /// addModuleFlag - Add a module-level flag to the module-level flags
357 /// metadata. It will create the module-level flags named metadata if it doesn't
358 /// already exist.
360  Value *Val) {
361  Type *Int32Ty = Type::getInt32Ty(Context);
362  Value *Ops[3] = {
363  ConstantInt::get(Int32Ty, Behavior), MDString::get(Context, Key), Val
364  };
366 }
368  uint32_t Val) {
369  Type *Int32Ty = Type::getInt32Ty(Context);
370  addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
371 }
373  assert(Node->getNumOperands() == 3 &&
374  "Invalid number of operands for module flag!");
375  assert(isa<ConstantInt>(Node->getOperand(0)) &&
376  isa<MDString>(Node->getOperand(1)) &&
377  "Invalid operand types for module flag!");
379 }
380 
381 //===----------------------------------------------------------------------===//
382 // Methods to control the materialization of GlobalValues in the Module.
383 //
385  assert(!Materializer &&
386  "Module already has a GVMaterializer. Call MaterializeAllPermanently"
387  " to clear it out before setting another one.");
388  Materializer.reset(GVM);
389 }
390 
391 bool Module::isMaterializable(const GlobalValue *GV) const {
392  if (Materializer)
393  return Materializer->isMaterializable(GV);
394  return false;
395 }
396 
398  if (Materializer)
399  return Materializer->isDematerializable(GV);
400  return false;
401 }
402 
403 bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
404  if (!Materializer)
405  return false;
406 
407  error_code EC = Materializer->Materialize(GV);
408  if (!EC)
409  return false;
410  if (ErrInfo)
411  *ErrInfo = EC.message();
412  return true;
413 }
414 
416  if (Materializer)
417  return Materializer->Dematerialize(GV);
418 }
419 
420 bool Module::MaterializeAll(std::string *ErrInfo) {
421  if (!Materializer)
422  return false;
423  error_code EC = Materializer->MaterializeModule(this);
424  if (!EC)
425  return false;
426  if (ErrInfo)
427  *ErrInfo = EC.message();
428  return true;
429 }
430 
431 bool Module::MaterializeAllPermanently(std::string *ErrInfo) {
432  if (MaterializeAll(ErrInfo))
433  return true;
434  Materializer.reset();
435  return false;
436 }
437 
438 //===----------------------------------------------------------------------===//
439 // Other module related stuff.
440 //
441 
442 
443 // dropAllReferences() - This function causes all the subelements to "let go"
444 // of all references that they are maintaining. This allows one to 'delete' a
445 // whole module at a time, even though there may be circular references... first
446 // all references are dropped, and all use counts go to zero. Then everything
447 // is deleted for real. Note that no operations are valid on an object that
448 // has "dropped all references", except operator delete.
449 //
451  for(Module::iterator I = begin(), E = end(); I != E; ++I)
452  I->dropAllReferences();
453 
454  for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
455  I->dropAllReferences();
456 
457  for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
458  I->dropAllReferences();
459 }
StringRef getName() const
getName - Return a constant reference to this named metadata's name.
Definition: Metadata.cpp:569
PointerSize getPointerSize() const
Target Pointer Size information.
Definition: Module.cpp:85
StringRef getString() const
Definition: Metadata.h:46
const ValueSymbolTable & getValueSymbolTable() const
Get the symbol table of global variable and function identifiers.
Definition: Module.h:513
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:38
unsigned getNumOperands() const
getNumOperands - Return number of MDNode operands.
Definition: Metadata.h:142
void setMaterializer(GVMaterializer *GVM)
Definition: Module.cpp:384
void addOperand(MDNode *M)
addOperand - Add metadata operand.
Definition: Metadata.cpp:551
bool isIntrinsic() const
Definition: Function.h:156
static PointerType * get(Type *ElementType, unsigned AddressSpace)
Definition: Type.cpp:730
Endianness
An enumeration for describing the endianess of the target machine.
Definition: Module.h:146
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Definition: Module.cpp:295
Externally visible function.
Definition: GlobalValue.h:34
MDNode - a tuple of other values.
Definition: Metadata.h:69
F(f)
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: Type.cpp:218
const GlobalVariable * getGlobalVariable(StringRef Name, bool AllowInternal=false) const
Definition: Module.h:355
static MDNode * get(LLVMContext &Context, ArrayRef< Value * > Vals)
Definition: Metadata.cpp:268
Value * getOperand(unsigned i) const LLVM_READONLY
getOperand - Return specified operand.
Definition: Metadata.cpp:307
void getMDKindNames(SmallVectorImpl< StringRef > &Result) const
Definition: Module.cpp:124
void push_back(NodeTy *val)
Definition: ilist.h:554
void eraseNamedMetadata(NamedMDNode *NMD)
Definition: Module.cpp:308
std::pair< StringRef, StringRef > getToken(StringRef Source, StringRef Delimiters=" \t\n\v\f\r")
void setName(const Twine &Name)
Definition: Value.cpp:175
void clear()
Definition: ilist.h:550
bool Materialize(GlobalValue *GV, std::string *ErrInfo=0)
Definition: Module.cpp:403
uint64_t getZExtValue() const
Return the zero extended value.
Definition: Constants.h:116
global_iterator global_begin()
Definition: Module.h:521
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
Definition: Type.cpp:361
void dropAllReferences()
Definition: Module.cpp:450
bool MaterializeAllPermanently(std::string *ErrInfo=0)
Definition: Module.cpp:431
Function * getFunction(StringRef Name) const
Definition: Module.cpp:221
void getMDKindNames(SmallVectorImpl< StringRef > &Result) const
#define P(N)
Module(StringRef ModuleID, LLVMContext &C)
Definition: Module.cpp:45
bool MaterializeAll(std::string *ErrInfo=0)
Definition: Module.cpp:420
alias_iterator alias_end()
Definition: Module.h:544
bool isDematerializable(const GlobalValue *GV) const
Definition: Module.cpp:397
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeSet AttributeList)
Definition: Module.cpp:138
Constant * getOrInsertGlobal(StringRef Name, Type *Ty)
Definition: Module.cpp:250
Type * Int32Ty
NamedMDNode * getModuleFlagsMetadata() const
Definition: Module.cpp:345
LLVM Constant Representation.
Definition: Constant.h:41
ModFlagBehavior
This enumeration defines the supported behaviors of module flags.
Definition: Module.h:152
PointerSize
An enumeration for describing the size of a pointer on the target machine.
Definition: Module.h:149
MDNode * getOperand(unsigned i) const
getOperand - Return specified operand.
Definition: Metadata.cpp:545
unsigned getMDKindID(StringRef Name) const
getMDKindID - Return a unique non-zero ID for the specified metadata kind.
void Dematerialize(GlobalValue *GV)
Definition: Module.cpp:415
iterator erase(iterator where)
Definition: ilist.h:465
global_iterator global_end()
Definition: Module.h:523
static Constant * getBitCast(Constant *C, Type *Ty)
Definition: Constants.cpp:1661
static PointerType * getUnqual(Type *ElementType)
Definition: DerivedTypes.h:436
Class for constant integers.
Definition: Constants.h:51
StringRef toStringRef(SmallVectorImpl< char > &Out) const
Definition: Twine.cpp:31
NamedMDNode * getOrInsertModuleFlagsMetadata()
Definition: Module.cpp:352
alias_iterator alias_begin()
Definition: Module.h:542
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
Definition: Constants.cpp:492
std::string message() const
size_t size() const
Definition: Module.h:535
GlobalAlias * getNamedAlias(StringRef Name) const
Definition: Module.cpp:279
Value * getModuleFlag(StringRef Key) const
Definition: Module.cpp:331
static const uint16_t * lookup(unsigned opcode, unsigned domain)
PointerType * getType() const
getType - Global values are always pointers.
Definition: GlobalValue.h:107
NamedMDNode * getNamedMetadata(const Twine &Name) const
Definition: Module.cpp:286
iterator end()
Definition: Module.h:533
Endianness getEndianness() const
Target endian information.
Definition: Module.cpp:64
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:241
#define I(x, y, z)
Definition: MD5.cpp:54
iterator begin()
Definition: Module.h:531
bool isMaterializable(const GlobalValue *GV) const
Definition: Module.cpp:391
~Module()
The module destructor. This will dropAllReferences.
Definition: Module.cpp:52
void setAttributes(AttributeSet attrs)
Set the attribute list for this Function.
Definition: Function.h:173
bool hasLocalLinkage() const
Definition: GlobalValue.h:211
LLVM Value Representation.
Definition: Value.h:66
unsigned getNumOperands() const
getNumOperands - Return the number of NamedMDNode operands.
Definition: Metadata.cpp:540
unsigned getMDKindID(StringRef Name) const
Definition: Module.cpp:117
GlobalValue * getNamedValue(StringRef Name) const
Definition: Module.cpp:111
Value * lookup(StringRef Name) const
Lookup a named Value.
void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Value *Val)
Definition: Module.cpp:359
void push_back(const NodeTy &val)
Definition: ilist.h:671
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=0)
Definition: Function.h:128
bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:110