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