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