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