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