zpu: wip - add pass to convert registers to stack slots
[llvm/zpu.git] / lib / VMCore / Module.cpp
blob341e527acb5b4150770ca2b59e6d223d9211cea1
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 VMCore library.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Module.h"
15 #include "llvm/InstrTypes.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GVMaterializer.h"
19 #include "llvm/LLVMContext.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/Support/LeakDetector.h"
24 #include "SymbolTableListTraitsImpl.h"
25 #include "llvm/TypeSymbolTable.h"
26 #include <algorithm>
27 #include <cstdarg>
28 #include <cstdlib>
29 using namespace llvm;
31 //===----------------------------------------------------------------------===//
32 // Methods to implement the globals and functions lists.
35 GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() {
36 GlobalVariable *Ret = new GlobalVariable(Type::getInt32Ty(getGlobalContext()),
37 false, GlobalValue::ExternalLinkage);
38 // This should not be garbage monitored.
39 LeakDetector::removeGarbageObject(Ret);
40 return Ret;
42 GlobalAlias *ilist_traits<GlobalAlias>::createSentinel() {
43 GlobalAlias *Ret = new GlobalAlias(Type::getInt32Ty(getGlobalContext()),
44 GlobalValue::ExternalLinkage);
45 // This should not be garbage monitored.
46 LeakDetector::removeGarbageObject(Ret);
47 return Ret;
50 // Explicit instantiations of SymbolTableListTraits since some of the methods
51 // are not in the public header file.
52 template class llvm::SymbolTableListTraits<GlobalVariable, Module>;
53 template class llvm::SymbolTableListTraits<Function, Module>;
54 template class llvm::SymbolTableListTraits<GlobalAlias, Module>;
56 //===----------------------------------------------------------------------===//
57 // Primitive Module methods.
60 Module::Module(StringRef MID, LLVMContext& C)
61 : Context(C), Materializer(NULL), ModuleID(MID) {
62 ValSymTab = new ValueSymbolTable();
63 TypeSymTab = new TypeSymbolTable();
64 NamedMDSymTab = new StringMap<NamedMDNode *>();
65 Context.addModule(this);
68 Module::~Module() {
69 Context.removeModule(this);
70 dropAllReferences();
71 GlobalList.clear();
72 FunctionList.clear();
73 AliasList.clear();
74 LibraryList.clear();
75 NamedMDList.clear();
76 delete ValSymTab;
77 delete TypeSymTab;
78 delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
81 /// Target endian information...
82 Module::Endianness Module::getEndianness() const {
83 StringRef temp = DataLayout;
84 Module::Endianness ret = AnyEndianness;
86 while (!temp.empty()) {
87 StringRef token = DataLayout;
88 tie(token, temp) = getToken(temp, "-");
90 if (token[0] == 'e') {
91 ret = LittleEndian;
92 } else if (token[0] == 'E') {
93 ret = BigEndian;
97 return ret;
100 /// Target Pointer Size information...
101 Module::PointerSize Module::getPointerSize() const {
102 StringRef temp = DataLayout;
103 Module::PointerSize ret = AnyPointerSize;
105 while (!temp.empty()) {
106 StringRef token, signalToken;
107 tie(token, temp) = getToken(temp, "-");
108 tie(signalToken, token) = getToken(token, ":");
110 if (signalToken[0] == 'p') {
111 int size = 0;
112 getToken(token, ":").first.getAsInteger(10, size);
113 if (size == 32)
114 ret = Pointer32;
115 else if (size == 64)
116 ret = Pointer64;
120 return ret;
123 /// getNamedValue - Return the first global value in the module with
124 /// the specified name, of arbitrary type. This method returns null
125 /// if a global with the specified name is not found.
126 GlobalValue *Module::getNamedValue(StringRef Name) const {
127 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
130 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
131 /// This ID is uniqued across modules in the current LLVMContext.
132 unsigned Module::getMDKindID(StringRef Name) const {
133 return Context.getMDKindID(Name);
136 /// getMDKindNames - Populate client supplied SmallVector with the name for
137 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
138 /// so it is filled in as an empty string.
139 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
140 return Context.getMDKindNames(Result);
144 //===----------------------------------------------------------------------===//
145 // Methods for easy access to the functions in the module.
148 // getOrInsertFunction - Look up the specified function in the module symbol
149 // table. If it does not exist, add a prototype for the function and return
150 // it. This is nice because it allows most passes to get away with not handling
151 // the symbol table directly for this common task.
153 Constant *Module::getOrInsertFunction(StringRef Name,
154 const FunctionType *Ty,
155 AttrListPtr AttributeList) {
156 // See if we have a definition for the specified function already.
157 GlobalValue *F = getNamedValue(Name);
158 if (F == 0) {
159 // Nope, add it
160 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
161 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
162 New->setAttributes(AttributeList);
163 FunctionList.push_back(New);
164 return New; // Return the new prototype.
167 // Okay, the function exists. Does it have externally visible linkage?
168 if (F->hasLocalLinkage()) {
169 // Clear the function's name.
170 F->setName("");
171 // Retry, now there won't be a conflict.
172 Constant *NewF = getOrInsertFunction(Name, Ty);
173 F->setName(Name);
174 return NewF;
177 // If the function exists but has the wrong type, return a bitcast to the
178 // right type.
179 if (F->getType() != PointerType::getUnqual(Ty))
180 return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
182 // Otherwise, we just found the existing function or a prototype.
183 return F;
186 Constant *Module::getOrInsertTargetIntrinsic(StringRef Name,
187 const FunctionType *Ty,
188 AttrListPtr AttributeList) {
189 // See if we have a definition for the specified function already.
190 GlobalValue *F = getNamedValue(Name);
191 if (F == 0) {
192 // Nope, add it
193 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
194 New->setAttributes(AttributeList);
195 FunctionList.push_back(New);
196 return New; // Return the new prototype.
199 // Otherwise, we just found the existing function or a prototype.
200 return F;
203 Constant *Module::getOrInsertFunction(StringRef Name,
204 const FunctionType *Ty) {
205 AttrListPtr AttributeList = AttrListPtr::get((AttributeWithIndex *)0, 0);
206 return getOrInsertFunction(Name, Ty, AttributeList);
209 // getOrInsertFunction - Look up the specified function in the module symbol
210 // table. If it does not exist, add a prototype for the function and return it.
211 // This version of the method takes a null terminated list of function
212 // arguments, which makes it easier for clients to use.
214 Constant *Module::getOrInsertFunction(StringRef Name,
215 AttrListPtr AttributeList,
216 const Type *RetTy, ...) {
217 va_list Args;
218 va_start(Args, RetTy);
220 // Build the list of argument types...
221 std::vector<const Type*> ArgTys;
222 while (const Type *ArgTy = va_arg(Args, const Type*))
223 ArgTys.push_back(ArgTy);
225 va_end(Args);
227 // Build the function type and chain to the other getOrInsertFunction...
228 return getOrInsertFunction(Name,
229 FunctionType::get(RetTy, ArgTys, false),
230 AttributeList);
233 Constant *Module::getOrInsertFunction(StringRef Name,
234 const Type *RetTy, ...) {
235 va_list Args;
236 va_start(Args, RetTy);
238 // Build the list of argument types...
239 std::vector<const Type*> ArgTys;
240 while (const Type *ArgTy = va_arg(Args, const Type*))
241 ArgTys.push_back(ArgTy);
243 va_end(Args);
245 // Build the function type and chain to the other getOrInsertFunction...
246 return getOrInsertFunction(Name,
247 FunctionType::get(RetTy, ArgTys, false),
248 AttrListPtr::get((AttributeWithIndex *)0, 0));
251 // getFunction - Look up the specified function in the module symbol table.
252 // If it does not exist, return null.
254 Function *Module::getFunction(StringRef Name) const {
255 return dyn_cast_or_null<Function>(getNamedValue(Name));
258 //===----------------------------------------------------------------------===//
259 // Methods for easy access to the global variables in the module.
262 /// getGlobalVariable - Look up the specified global variable in the module
263 /// symbol table. If it does not exist, return null. The type argument
264 /// should be the underlying type of the global, i.e., it should not have
265 /// the top-level PointerType, which represents the address of the global.
266 /// If AllowLocal is set to true, this function will return types that
267 /// have an local. By default, these types are not returned.
269 GlobalVariable *Module::getGlobalVariable(StringRef Name,
270 bool AllowLocal) const {
271 if (GlobalVariable *Result =
272 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
273 if (AllowLocal || !Result->hasLocalLinkage())
274 return Result;
275 return 0;
278 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
279 /// 1. If it does not exist, add a declaration of the global and return it.
280 /// 2. Else, the global exists but has the wrong type: return the function
281 /// with a constantexpr cast to the right type.
282 /// 3. Finally, if the existing global is the correct delclaration, return the
283 /// existing global.
284 Constant *Module::getOrInsertGlobal(StringRef Name, const Type *Ty) {
285 // See if we have a definition for the specified global already.
286 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
287 if (GV == 0) {
288 // Nope, add it
289 GlobalVariable *New =
290 new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
291 0, Name);
292 return New; // Return the new declaration.
295 // If the variable exists but has the wrong type, return a bitcast to the
296 // right type.
297 if (GV->getType() != PointerType::getUnqual(Ty))
298 return ConstantExpr::getBitCast(GV, PointerType::getUnqual(Ty));
300 // Otherwise, we just found the existing function or a prototype.
301 return GV;
304 //===----------------------------------------------------------------------===//
305 // Methods for easy access to the global variables in the module.
308 // getNamedAlias - Look up the specified global in the module symbol table.
309 // If it does not exist, return null.
311 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
312 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
315 /// getNamedMetadata - Return the first NamedMDNode in the module with the
316 /// specified name. This method returns null if a NamedMDNode with the
317 /// specified name is not found.
318 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
319 SmallString<256> NameData;
320 StringRef NameRef = Name.toStringRef(NameData);
321 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
324 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
325 /// with the specified name. This method returns a new NamedMDNode if a
326 /// NamedMDNode with the specified name is not found.
327 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
328 NamedMDNode *&NMD =
329 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
330 if (!NMD) {
331 NMD = new NamedMDNode(Name);
332 NMD->setParent(this);
333 NamedMDList.push_back(NMD);
335 return NMD;
338 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
339 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
340 NamedMDList.erase(NMD);
343 //===----------------------------------------------------------------------===//
344 // Methods for easy access to the types in the module.
348 // addTypeName - Insert an entry in the symbol table mapping Str to Type. If
349 // there is already an entry for this name, true is returned and the symbol
350 // table is not modified.
352 bool Module::addTypeName(StringRef Name, const Type *Ty) {
353 TypeSymbolTable &ST = getTypeSymbolTable();
355 if (ST.lookup(Name)) return true; // Already in symtab...
357 // Not in symbol table? Set the name with the Symtab as an argument so the
358 // type knows what to update...
359 ST.insert(Name, Ty);
361 return false;
364 /// getTypeByName - Return the type with the specified name in this module, or
365 /// null if there is none by that name.
366 const Type *Module::getTypeByName(StringRef Name) const {
367 const TypeSymbolTable &ST = getTypeSymbolTable();
368 return cast_or_null<Type>(ST.lookup(Name));
371 // getTypeName - If there is at least one entry in the symbol table for the
372 // specified type, return it.
374 std::string Module::getTypeName(const Type *Ty) const {
375 const TypeSymbolTable &ST = getTypeSymbolTable();
377 TypeSymbolTable::const_iterator TI = ST.begin();
378 TypeSymbolTable::const_iterator TE = ST.end();
379 if ( TI == TE ) return ""; // No names for types
381 while (TI != TE && TI->second != Ty)
382 ++TI;
384 if (TI != TE) // Must have found an entry!
385 return TI->first;
386 return ""; // Must not have found anything...
389 //===----------------------------------------------------------------------===//
390 // Methods to control the materialization of GlobalValues in the Module.
392 void Module::setMaterializer(GVMaterializer *GVM) {
393 assert(!Materializer &&
394 "Module already has a GVMaterializer. Call MaterializeAllPermanently"
395 " to clear it out before setting another one.");
396 Materializer.reset(GVM);
399 bool Module::isMaterializable(const GlobalValue *GV) const {
400 if (Materializer)
401 return Materializer->isMaterializable(GV);
402 return false;
405 bool Module::isDematerializable(const GlobalValue *GV) const {
406 if (Materializer)
407 return Materializer->isDematerializable(GV);
408 return false;
411 bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
412 if (Materializer)
413 return Materializer->Materialize(GV, ErrInfo);
414 return false;
417 void Module::Dematerialize(GlobalValue *GV) {
418 if (Materializer)
419 return Materializer->Dematerialize(GV);
422 bool Module::MaterializeAll(std::string *ErrInfo) {
423 if (!Materializer)
424 return false;
425 return Materializer->MaterializeModule(this, ErrInfo);
428 bool Module::MaterializeAllPermanently(std::string *ErrInfo) {
429 if (MaterializeAll(ErrInfo))
430 return true;
431 Materializer.reset();
432 return false;
435 //===----------------------------------------------------------------------===//
436 // Other module related stuff.
440 // dropAllReferences() - This function causes all the subelementss 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.
447 void Module::dropAllReferences() {
448 for(Module::iterator I = begin(), E = end(); I != E; ++I)
449 I->dropAllReferences();
451 for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
452 I->dropAllReferences();
454 for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
455 I->dropAllReferences();
458 void Module::addLibrary(StringRef Lib) {
459 for (Module::lib_iterator I = lib_begin(), E = lib_end(); I != E; ++I)
460 if (*I == Lib)
461 return;
462 LibraryList.push_back(Lib);
465 void Module::removeLibrary(StringRef Lib) {
466 LibraryListType::iterator I = LibraryList.begin();
467 LibraryListType::iterator E = LibraryList.end();
468 for (;I != E; ++I)
469 if (*I == Lib) {
470 LibraryList.erase(I);
471 return;