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