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.
11 //
12 //===----------------------------------------------------------------------===//
13
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/DenseSet.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/Support/LeakDetector.h"
25 #include "SymbolTableListTraitsImpl.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
createSentinel()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;
41 }
createSentinel()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;
48 }
49
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>;
55
56 //===----------------------------------------------------------------------===//
57 // Primitive Module methods.
58 //
59
Module(StringRef MID,LLVMContext & C)60 Module::Module(StringRef MID, LLVMContext& C)
61 : Context(C), Materializer(NULL), ModuleID(MID) {
62 ValSymTab = new ValueSymbolTable();
63 NamedMDSymTab = new StringMap<NamedMDNode *>();
64 Context.addModule(this);
65 }
66
~Module()67 Module::~Module() {
68 Context.removeModule(this);
69 dropAllReferences();
70 GlobalList.clear();
71 FunctionList.clear();
72 AliasList.clear();
73 LibraryList.clear();
74 NamedMDList.clear();
75 delete ValSymTab;
76 delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
77 }
78
79 /// Target endian information.
getEndianness() const80 Module::Endianness Module::getEndianness() const {
81 StringRef temp = DataLayout;
82 Module::Endianness ret = AnyEndianness;
83
84 while (!temp.empty()) {
85 StringRef token = DataLayout;
86 tie(token, temp) = getToken(temp, "-");
87
88 if (token[0] == 'e') {
89 ret = LittleEndian;
90 } else if (token[0] == 'E') {
91 ret = BigEndian;
92 }
93 }
94
95 return ret;
96 }
97
98 /// Target Pointer Size information...
getPointerSize() const99 Module::PointerSize Module::getPointerSize() const {
100 StringRef temp = DataLayout;
101 Module::PointerSize ret = AnyPointerSize;
102
103 while (!temp.empty()) {
104 StringRef token, signalToken;
105 tie(token, temp) = getToken(temp, "-");
106 tie(signalToken, token) = getToken(token, ":");
107
108 if (signalToken[0] == 'p') {
109 int size = 0;
110 getToken(token, ":").first.getAsInteger(10, size);
111 if (size == 32)
112 ret = Pointer32;
113 else if (size == 64)
114 ret = Pointer64;
115 }
116 }
117
118 return ret;
119 }
120
121 /// getNamedValue - Return the first global value in the module with
122 /// the specified name, of arbitrary type. This method returns null
123 /// if a global with the specified name is not found.
getNamedValue(StringRef Name) const124 GlobalValue *Module::getNamedValue(StringRef Name) const {
125 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
126 }
127
128 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
129 /// This ID is uniqued across modules in the current LLVMContext.
getMDKindID(StringRef Name) const130 unsigned Module::getMDKindID(StringRef Name) const {
131 return Context.getMDKindID(Name);
132 }
133
134 /// getMDKindNames - Populate client supplied SmallVector with the name for
135 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
136 /// so it is filled in as an empty string.
getMDKindNames(SmallVectorImpl<StringRef> & Result) const137 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
138 return Context.getMDKindNames(Result);
139 }
140
141
142 //===----------------------------------------------------------------------===//
143 // Methods for easy access to the functions in the module.
144 //
145
146 // getOrInsertFunction - Look up the specified function in the module symbol
147 // table. If it does not exist, add a prototype for the function and return
148 // it. This is nice because it allows most passes to get away with not handling
149 // the symbol table directly for this common task.
150 //
getOrInsertFunction(StringRef Name,FunctionType * Ty,AttrListPtr AttributeList)151 Constant *Module::getOrInsertFunction(StringRef Name,
152 FunctionType *Ty,
153 AttrListPtr AttributeList) {
154 // See if we have a definition for the specified function already.
155 GlobalValue *F = getNamedValue(Name);
156 if (F == 0) {
157 // Nope, add it
158 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
159 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
160 New->setAttributes(AttributeList);
161 FunctionList.push_back(New);
162 return New; // Return the new prototype.
163 }
164
165 // Okay, the function exists. Does it have externally visible linkage?
166 if (F->hasLocalLinkage()) {
167 // Clear the function's name.
168 F->setName("");
169 // Retry, now there won't be a conflict.
170 Constant *NewF = getOrInsertFunction(Name, Ty);
171 F->setName(Name);
172 return NewF;
173 }
174
175 // If the function exists but has the wrong type, return a bitcast to the
176 // right type.
177 if (F->getType() != PointerType::getUnqual(Ty))
178 return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
179
180 // Otherwise, we just found the existing function or a prototype.
181 return F;
182 }
183
getOrInsertTargetIntrinsic(StringRef Name,FunctionType * Ty,AttrListPtr AttributeList)184 Constant *Module::getOrInsertTargetIntrinsic(StringRef Name,
185 FunctionType *Ty,
186 AttrListPtr AttributeList) {
187 // See if we have a definition for the specified function already.
188 GlobalValue *F = getNamedValue(Name);
189 if (F == 0) {
190 // Nope, add it
191 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
192 New->setAttributes(AttributeList);
193 FunctionList.push_back(New);
194 return New; // Return the new prototype.
195 }
196
197 // Otherwise, we just found the existing function or a prototype.
198 return F;
199 }
200
getOrInsertFunction(StringRef Name,FunctionType * Ty)201 Constant *Module::getOrInsertFunction(StringRef Name,
202 FunctionType *Ty) {
203 AttrListPtr AttributeList = AttrListPtr::get((AttributeWithIndex *)0, 0);
204 return getOrInsertFunction(Name, Ty, AttributeList);
205 }
206
207 // getOrInsertFunction - Look up the specified function in the module symbol
208 // table. If it does not exist, add a prototype for the function and return it.
209 // This version of the method takes a null terminated list of function
210 // arguments, which makes it easier for clients to use.
211 //
getOrInsertFunction(StringRef Name,AttrListPtr AttributeList,Type * RetTy,...)212 Constant *Module::getOrInsertFunction(StringRef Name,
213 AttrListPtr AttributeList,
214 Type *RetTy, ...) {
215 va_list Args;
216 va_start(Args, RetTy);
217
218 // Build the list of argument types...
219 std::vector<Type*> ArgTys;
220 while (Type *ArgTy = va_arg(Args, Type*))
221 ArgTys.push_back(ArgTy);
222
223 va_end(Args);
224
225 // Build the function type and chain to the other getOrInsertFunction...
226 return getOrInsertFunction(Name,
227 FunctionType::get(RetTy, ArgTys, false),
228 AttributeList);
229 }
230
getOrInsertFunction(StringRef Name,Type * RetTy,...)231 Constant *Module::getOrInsertFunction(StringRef Name,
232 Type *RetTy, ...) {
233 va_list Args;
234 va_start(Args, RetTy);
235
236 // Build the list of argument types...
237 std::vector<Type*> ArgTys;
238 while (Type *ArgTy = va_arg(Args, Type*))
239 ArgTys.push_back(ArgTy);
240
241 va_end(Args);
242
243 // Build the function type and chain to the other getOrInsertFunction...
244 return getOrInsertFunction(Name,
245 FunctionType::get(RetTy, ArgTys, false),
246 AttrListPtr::get((AttributeWithIndex *)0, 0));
247 }
248
249 // getFunction - Look up the specified function in the module symbol table.
250 // If it does not exist, return null.
251 //
getFunction(StringRef Name) const252 Function *Module::getFunction(StringRef Name) const {
253 return dyn_cast_or_null<Function>(getNamedValue(Name));
254 }
255
256 //===----------------------------------------------------------------------===//
257 // Methods for easy access to the global variables in the module.
258 //
259
260 /// getGlobalVariable - Look up the specified global variable in the module
261 /// symbol table. If it does not exist, return null. The type argument
262 /// should be the underlying type of the global, i.e., it should not have
263 /// the top-level PointerType, which represents the address of the global.
264 /// If AllowLocal is set to true, this function will return types that
265 /// have an local. By default, these types are not returned.
266 ///
getGlobalVariable(StringRef Name,bool AllowLocal) const267 GlobalVariable *Module::getGlobalVariable(StringRef Name,
268 bool AllowLocal) const {
269 if (GlobalVariable *Result =
270 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
271 if (AllowLocal || !Result->hasLocalLinkage())
272 return Result;
273 return 0;
274 }
275
276 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
277 /// 1. If it does not exist, add a declaration of the global and return it.
278 /// 2. Else, the global exists but has the wrong type: return the function
279 /// with a constantexpr cast to the right type.
280 /// 3. Finally, if the existing global is the correct delclaration, return the
281 /// existing global.
getOrInsertGlobal(StringRef Name,Type * Ty)282 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
283 // See if we have a definition for the specified global already.
284 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
285 if (GV == 0) {
286 // Nope, add it
287 GlobalVariable *New =
288 new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
289 0, Name);
290 return New; // Return the new declaration.
291 }
292
293 // If the variable exists but has the wrong type, return a bitcast to the
294 // right type.
295 if (GV->getType() != PointerType::getUnqual(Ty))
296 return ConstantExpr::getBitCast(GV, PointerType::getUnqual(Ty));
297
298 // Otherwise, we just found the existing function or a prototype.
299 return GV;
300 }
301
302 //===----------------------------------------------------------------------===//
303 // Methods for easy access to the global variables in the module.
304 //
305
306 // getNamedAlias - Look up the specified global in the module symbol table.
307 // If it does not exist, return null.
308 //
getNamedAlias(StringRef Name) const309 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
310 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
311 }
312
313 /// getNamedMetadata - Return the first NamedMDNode in the module with the
314 /// specified name. This method returns null if a NamedMDNode with the
315 /// specified name is not found.
getNamedMetadata(const Twine & Name) const316 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
317 SmallString<256> NameData;
318 StringRef NameRef = Name.toStringRef(NameData);
319 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
320 }
321
322 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
323 /// with the specified name. This method returns a new NamedMDNode if a
324 /// NamedMDNode with the specified name is not found.
getOrInsertNamedMetadata(StringRef Name)325 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
326 NamedMDNode *&NMD =
327 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
328 if (!NMD) {
329 NMD = new NamedMDNode(Name);
330 NMD->setParent(this);
331 NamedMDList.push_back(NMD);
332 }
333 return NMD;
334 }
335
eraseNamedMetadata(NamedMDNode * NMD)336 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
337 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
338 NamedMDList.erase(NMD);
339 }
340
341
342 //===----------------------------------------------------------------------===//
343 // Methods to control the materialization of GlobalValues in the Module.
344 //
setMaterializer(GVMaterializer * GVM)345 void Module::setMaterializer(GVMaterializer *GVM) {
346 assert(!Materializer &&
347 "Module already has a GVMaterializer. Call MaterializeAllPermanently"
348 " to clear it out before setting another one.");
349 Materializer.reset(GVM);
350 }
351
isMaterializable(const GlobalValue * GV) const352 bool Module::isMaterializable(const GlobalValue *GV) const {
353 if (Materializer)
354 return Materializer->isMaterializable(GV);
355 return false;
356 }
357
isDematerializable(const GlobalValue * GV) const358 bool Module::isDematerializable(const GlobalValue *GV) const {
359 if (Materializer)
360 return Materializer->isDematerializable(GV);
361 return false;
362 }
363
Materialize(GlobalValue * GV,std::string * ErrInfo)364 bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
365 if (Materializer)
366 return Materializer->Materialize(GV, ErrInfo);
367 return false;
368 }
369
Dematerialize(GlobalValue * GV)370 void Module::Dematerialize(GlobalValue *GV) {
371 if (Materializer)
372 return Materializer->Dematerialize(GV);
373 }
374
MaterializeAll(std::string * ErrInfo)375 bool Module::MaterializeAll(std::string *ErrInfo) {
376 if (!Materializer)
377 return false;
378 return Materializer->MaterializeModule(this, ErrInfo);
379 }
380
MaterializeAllPermanently(std::string * ErrInfo)381 bool Module::MaterializeAllPermanently(std::string *ErrInfo) {
382 if (MaterializeAll(ErrInfo))
383 return true;
384 Materializer.reset();
385 return false;
386 }
387
388 //===----------------------------------------------------------------------===//
389 // Other module related stuff.
390 //
391
392
393 // dropAllReferences() - This function causes all the subelementss to "let go"
394 // of all references that they are maintaining. This allows one to 'delete' a
395 // whole module at a time, even though there may be circular references... first
396 // all references are dropped, and all use counts go to zero. Then everything
397 // is deleted for real. Note that no operations are valid on an object that
398 // has "dropped all references", except operator delete.
399 //
dropAllReferences()400 void Module::dropAllReferences() {
401 for(Module::iterator I = begin(), E = end(); I != E; ++I)
402 I->dropAllReferences();
403
404 for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
405 I->dropAllReferences();
406
407 for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
408 I->dropAllReferences();
409 }
410
addLibrary(StringRef Lib)411 void Module::addLibrary(StringRef Lib) {
412 for (Module::lib_iterator I = lib_begin(), E = lib_end(); I != E; ++I)
413 if (*I == Lib)
414 return;
415 LibraryList.push_back(Lib);
416 }
417
removeLibrary(StringRef Lib)418 void Module::removeLibrary(StringRef Lib) {
419 LibraryListType::iterator I = LibraryList.begin();
420 LibraryListType::iterator E = LibraryList.end();
421 for (;I != E; ++I)
422 if (*I == Lib) {
423 LibraryList.erase(I);
424 return;
425 }
426 }
427
428 //===----------------------------------------------------------------------===//
429 // Type finding functionality.
430 //===----------------------------------------------------------------------===//
431
432 namespace {
433 /// TypeFinder - Walk over a module, identifying all of the types that are
434 /// used by the module.
435 class TypeFinder {
436 // To avoid walking constant expressions multiple times and other IR
437 // objects, we keep several helper maps.
438 DenseSet<const Value*> VisitedConstants;
439 DenseSet<Type*> VisitedTypes;
440
441 std::vector<StructType*> &StructTypes;
442 public:
TypeFinder(std::vector<StructType * > & structTypes)443 TypeFinder(std::vector<StructType*> &structTypes)
444 : StructTypes(structTypes) {}
445
run(const Module & M)446 void run(const Module &M) {
447 // Get types from global variables.
448 for (Module::const_global_iterator I = M.global_begin(),
449 E = M.global_end(); I != E; ++I) {
450 incorporateType(I->getType());
451 if (I->hasInitializer())
452 incorporateValue(I->getInitializer());
453 }
454
455 // Get types from aliases.
456 for (Module::const_alias_iterator I = M.alias_begin(),
457 E = M.alias_end(); I != E; ++I) {
458 incorporateType(I->getType());
459 if (const Value *Aliasee = I->getAliasee())
460 incorporateValue(Aliasee);
461 }
462
463 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
464
465 // Get types from functions.
466 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
467 incorporateType(FI->getType());
468
469 for (Function::const_iterator BB = FI->begin(), E = FI->end();
470 BB != E;++BB)
471 for (BasicBlock::const_iterator II = BB->begin(),
472 E = BB->end(); II != E; ++II) {
473 const Instruction &I = *II;
474 // Incorporate the type of the instruction and all its operands.
475 incorporateType(I.getType());
476 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
477 OI != OE; ++OI)
478 incorporateValue(*OI);
479
480 // Incorporate types hiding in metadata.
481 I.getAllMetadataOtherThanDebugLoc(MDForInst);
482 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
483 incorporateMDNode(MDForInst[i].second);
484 MDForInst.clear();
485 }
486 }
487
488 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
489 E = M.named_metadata_end(); I != E; ++I) {
490 const NamedMDNode *NMD = I;
491 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
492 incorporateMDNode(NMD->getOperand(i));
493 }
494 }
495
496 private:
incorporateType(Type * Ty)497 void incorporateType(Type *Ty) {
498 // Check to see if we're already visited this type.
499 if (!VisitedTypes.insert(Ty).second)
500 return;
501
502 // If this is a structure or opaque type, add a name for the type.
503 if (StructType *STy = dyn_cast<StructType>(Ty))
504 StructTypes.push_back(STy);
505
506 // Recursively walk all contained types.
507 for (Type::subtype_iterator I = Ty->subtype_begin(),
508 E = Ty->subtype_end(); I != E; ++I)
509 incorporateType(*I);
510 }
511
512 /// incorporateValue - This method is used to walk operand lists finding
513 /// types hiding in constant expressions and other operands that won't be
514 /// walked in other ways. GlobalValues, basic blocks, instructions, and
515 /// inst operands are all explicitly enumerated.
incorporateValue(const Value * V)516 void incorporateValue(const Value *V) {
517 if (const MDNode *M = dyn_cast<MDNode>(V))
518 return incorporateMDNode(M);
519 if (!isa<Constant>(V) || isa<GlobalValue>(V)) return;
520
521 // Already visited?
522 if (!VisitedConstants.insert(V).second)
523 return;
524
525 // Check this type.
526 incorporateType(V->getType());
527
528 // Look in operands for types.
529 const User *U = cast<User>(V);
530 for (Constant::const_op_iterator I = U->op_begin(),
531 E = U->op_end(); I != E;++I)
532 incorporateValue(*I);
533 }
534
incorporateMDNode(const MDNode * V)535 void incorporateMDNode(const MDNode *V) {
536
537 // Already visited?
538 if (!VisitedConstants.insert(V).second)
539 return;
540
541 // Look in operands for types.
542 for (unsigned i = 0, e = V->getNumOperands(); i != e; ++i)
543 if (Value *Op = V->getOperand(i))
544 incorporateValue(Op);
545 }
546 };
547 } // end anonymous namespace
548
findUsedStructTypes(std::vector<StructType * > & StructTypes) const549 void Module::findUsedStructTypes(std::vector<StructType*> &StructTypes) const {
550 TypeFinder(StructTypes).run(*this);
551 }
552
553
554