Fix think-o: emit all 8 bytes of the EOF marker. Also reflow a line in a
[llvm/stm8.git] / lib / VMCore / Function.cpp
blob00d1d7873247736ca734b950449f53b38ebf9f10
1 //===-- Function.cpp - Implement the Global object classes ----------------===//
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 Function class for the VMCore library.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Module.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/IntrinsicInst.h"
17 #include "llvm/LLVMContext.h"
18 #include "llvm/CodeGen/ValueTypes.h"
19 #include "llvm/Support/CallSite.h"
20 #include "llvm/Support/LeakDetector.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/StringPool.h"
23 #include "llvm/Support/RWMutex.h"
24 #include "llvm/Support/Threading.h"
25 #include "SymbolTableListTraitsImpl.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/StringExtras.h"
28 using namespace llvm;
31 // Explicit instantiations of SymbolTableListTraits since some of the methods
32 // are not in the public header file...
33 template class llvm::SymbolTableListTraits<Argument, Function>;
34 template class llvm::SymbolTableListTraits<BasicBlock, Function>;
36 //===----------------------------------------------------------------------===//
37 // Argument Implementation
38 //===----------------------------------------------------------------------===//
40 Argument::Argument(const Type *Ty, const Twine &Name, Function *Par)
41 : Value(Ty, Value::ArgumentVal) {
42 Parent = 0;
44 // Make sure that we get added to a function
45 LeakDetector::addGarbageObject(this);
47 if (Par)
48 Par->getArgumentList().push_back(this);
49 setName(Name);
52 void Argument::setParent(Function *parent) {
53 if (getParent())
54 LeakDetector::addGarbageObject(this);
55 Parent = parent;
56 if (getParent())
57 LeakDetector::removeGarbageObject(this);
60 /// getArgNo - Return the index of this formal argument in its containing
61 /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
62 unsigned Argument::getArgNo() const {
63 const Function *F = getParent();
64 assert(F && "Argument is not in a function");
66 Function::const_arg_iterator AI = F->arg_begin();
67 unsigned ArgIdx = 0;
68 for (; &*AI != this; ++AI)
69 ++ArgIdx;
71 return ArgIdx;
74 /// hasByValAttr - Return true if this argument has the byval attribute on it
75 /// in its containing function.
76 bool Argument::hasByValAttr() const {
77 if (!getType()->isPointerTy()) return false;
78 return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
81 /// hasNestAttr - Return true if this argument has the nest attribute on
82 /// it in its containing function.
83 bool Argument::hasNestAttr() const {
84 if (!getType()->isPointerTy()) return false;
85 return getParent()->paramHasAttr(getArgNo()+1, Attribute::Nest);
88 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
89 /// it in its containing function.
90 bool Argument::hasNoAliasAttr() const {
91 if (!getType()->isPointerTy()) return false;
92 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias);
95 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
96 /// on it in its containing function.
97 bool Argument::hasNoCaptureAttr() const {
98 if (!getType()->isPointerTy()) return false;
99 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture);
102 /// hasSRetAttr - Return true if this argument has the sret attribute on
103 /// it in its containing function.
104 bool Argument::hasStructRetAttr() const {
105 if (!getType()->isPointerTy()) return false;
106 if (this != getParent()->arg_begin())
107 return false; // StructRet param must be first param
108 return getParent()->paramHasAttr(1, Attribute::StructRet);
111 /// addAttr - Add a Attribute to an argument
112 void Argument::addAttr(Attributes attr) {
113 getParent()->addAttribute(getArgNo() + 1, attr);
116 /// removeAttr - Remove a Attribute from an argument
117 void Argument::removeAttr(Attributes attr) {
118 getParent()->removeAttribute(getArgNo() + 1, attr);
122 //===----------------------------------------------------------------------===//
123 // Helper Methods in Function
124 //===----------------------------------------------------------------------===//
126 LLVMContext &Function::getContext() const {
127 return getType()->getContext();
130 const FunctionType *Function::getFunctionType() const {
131 return cast<FunctionType>(getType()->getElementType());
134 bool Function::isVarArg() const {
135 return getFunctionType()->isVarArg();
138 const Type *Function::getReturnType() const {
139 return getFunctionType()->getReturnType();
142 void Function::removeFromParent() {
143 getParent()->getFunctionList().remove(this);
146 void Function::eraseFromParent() {
147 getParent()->getFunctionList().erase(this);
150 //===----------------------------------------------------------------------===//
151 // Function Implementation
152 //===----------------------------------------------------------------------===//
154 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
155 const Twine &name, Module *ParentModule)
156 : GlobalValue(PointerType::getUnqual(Ty),
157 Value::FunctionVal, 0, 0, Linkage, name) {
158 assert(FunctionType::isValidReturnType(getReturnType()) &&
159 !getReturnType()->isOpaqueTy() && "invalid return type");
160 SymTab = new ValueSymbolTable();
162 // If the function has arguments, mark them as lazily built.
163 if (Ty->getNumParams())
164 setValueSubclassData(1); // Set the "has lazy arguments" bit.
166 // Make sure that we get added to a function
167 LeakDetector::addGarbageObject(this);
169 if (ParentModule)
170 ParentModule->getFunctionList().push_back(this);
172 // Ensure intrinsics have the right parameter attributes.
173 if (unsigned IID = getIntrinsicID())
174 setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID)));
178 Function::~Function() {
179 dropAllReferences(); // After this it is safe to delete instructions.
181 // Delete all of the method arguments and unlink from symbol table...
182 ArgumentList.clear();
183 delete SymTab;
185 // Remove the function from the on-the-side GC table.
186 clearGC();
189 void Function::BuildLazyArguments() const {
190 // Create the arguments vector, all arguments start out unnamed.
191 const FunctionType *FT = getFunctionType();
192 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
193 assert(!FT->getParamType(i)->isVoidTy() &&
194 "Cannot have void typed arguments!");
195 ArgumentList.push_back(new Argument(FT->getParamType(i)));
198 // Clear the lazy arguments bit.
199 unsigned SDC = getSubclassDataFromValue();
200 const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1);
203 size_t Function::arg_size() const {
204 return getFunctionType()->getNumParams();
206 bool Function::arg_empty() const {
207 return getFunctionType()->getNumParams() == 0;
210 void Function::setParent(Module *parent) {
211 if (getParent())
212 LeakDetector::addGarbageObject(this);
213 Parent = parent;
214 if (getParent())
215 LeakDetector::removeGarbageObject(this);
218 // dropAllReferences() - This function causes all the subinstructions to "let
219 // go" of all references that they are maintaining. This allows one to
220 // 'delete' a whole class at a time, even though there may be circular
221 // references... first all references are dropped, and all use counts go to
222 // zero. Then everything is deleted for real. Note that no operations are
223 // valid on an object that has "dropped all references", except operator
224 // delete.
226 void Function::dropAllReferences() {
227 for (iterator I = begin(), E = end(); I != E; ++I)
228 I->dropAllReferences();
230 // Delete all basic blocks. They are now unused, except possibly by
231 // blockaddresses, but BasicBlock's destructor takes care of those.
232 while (!BasicBlocks.empty())
233 BasicBlocks.begin()->eraseFromParent();
236 void Function::addAttribute(unsigned i, Attributes attr) {
237 AttrListPtr PAL = getAttributes();
238 PAL = PAL.addAttr(i, attr);
239 setAttributes(PAL);
242 void Function::removeAttribute(unsigned i, Attributes attr) {
243 AttrListPtr PAL = getAttributes();
244 PAL = PAL.removeAttr(i, attr);
245 setAttributes(PAL);
248 // Maintain the GC name for each function in an on-the-side table. This saves
249 // allocating an additional word in Function for programs which do not use GC
250 // (i.e., most programs) at the cost of increased overhead for clients which do
251 // use GC.
252 static DenseMap<const Function*,PooledStringPtr> *GCNames;
253 static StringPool *GCNamePool;
254 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
256 bool Function::hasGC() const {
257 sys::SmartScopedReader<true> Reader(*GCLock);
258 return GCNames && GCNames->count(this);
261 const char *Function::getGC() const {
262 assert(hasGC() && "Function has no collector");
263 sys::SmartScopedReader<true> Reader(*GCLock);
264 return *(*GCNames)[this];
267 void Function::setGC(const char *Str) {
268 sys::SmartScopedWriter<true> Writer(*GCLock);
269 if (!GCNamePool)
270 GCNamePool = new StringPool();
271 if (!GCNames)
272 GCNames = new DenseMap<const Function*,PooledStringPtr>();
273 (*GCNames)[this] = GCNamePool->intern(Str);
276 void Function::clearGC() {
277 sys::SmartScopedWriter<true> Writer(*GCLock);
278 if (GCNames) {
279 GCNames->erase(this);
280 if (GCNames->empty()) {
281 delete GCNames;
282 GCNames = 0;
283 if (GCNamePool->empty()) {
284 delete GCNamePool;
285 GCNamePool = 0;
291 /// copyAttributesFrom - copy all additional attributes (those not needed to
292 /// create a Function) from the Function Src to this one.
293 void Function::copyAttributesFrom(const GlobalValue *Src) {
294 assert(isa<Function>(Src) && "Expected a Function!");
295 GlobalValue::copyAttributesFrom(Src);
296 const Function *SrcF = cast<Function>(Src);
297 setCallingConv(SrcF->getCallingConv());
298 setAttributes(SrcF->getAttributes());
299 if (SrcF->hasGC())
300 setGC(SrcF->getGC());
301 else
302 clearGC();
305 /// getIntrinsicID - This method returns the ID number of the specified
306 /// function, or Intrinsic::not_intrinsic if the function is not an
307 /// intrinsic, or if the pointer is null. This value is always defined to be
308 /// zero to allow easy checking for whether a function is intrinsic or not. The
309 /// particular intrinsic functions which correspond to this value are defined in
310 /// llvm/Intrinsics.h.
312 unsigned Function::getIntrinsicID() const {
313 const ValueName *ValName = this->getValueName();
314 if (!ValName)
315 return 0;
316 unsigned Len = ValName->getKeyLength();
317 const char *Name = ValName->getKeyData();
319 if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
320 || Name[2] != 'v' || Name[3] != 'm')
321 return 0; // All intrinsics start with 'llvm.'
323 #define GET_FUNCTION_RECOGNIZER
324 #include "llvm/Intrinsics.gen"
325 #undef GET_FUNCTION_RECOGNIZER
326 return 0;
329 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
330 assert(id < num_intrinsics && "Invalid intrinsic ID!");
331 const char * const Table[] = {
332 "not_intrinsic",
333 #define GET_INTRINSIC_NAME_TABLE
334 #include "llvm/Intrinsics.gen"
335 #undef GET_INTRINSIC_NAME_TABLE
337 if (numTys == 0)
338 return Table[id];
339 std::string Result(Table[id]);
340 for (unsigned i = 0; i < numTys; ++i) {
341 if (const PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
342 Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
343 EVT::getEVT(PTyp->getElementType()).getEVTString();
345 else if (Tys[i])
346 Result += "." + EVT::getEVT(Tys[i]).getEVTString();
348 return Result;
351 const FunctionType *Intrinsic::getType(LLVMContext &Context,
352 ID id, const Type **Tys,
353 unsigned numTys) {
354 const Type *ResultTy = NULL;
355 std::vector<const Type*> ArgTys;
356 bool IsVarArg = false;
358 #define GET_INTRINSIC_GENERATOR
359 #include "llvm/Intrinsics.gen"
360 #undef GET_INTRINSIC_GENERATOR
362 return FunctionType::get(ResultTy, ArgTys, IsVarArg);
365 bool Intrinsic::isOverloaded(ID id) {
366 const bool OTable[] = {
367 false,
368 #define GET_INTRINSIC_OVERLOAD_TABLE
369 #include "llvm/Intrinsics.gen"
370 #undef GET_INTRINSIC_OVERLOAD_TABLE
372 return OTable[id];
375 /// This defines the "Intrinsic::getAttributes(ID id)" method.
376 #define GET_INTRINSIC_ATTRIBUTES
377 #include "llvm/Intrinsics.gen"
378 #undef GET_INTRINSIC_ATTRIBUTES
380 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
381 unsigned numTys) {
382 // There can never be multiple globals with the same name of different types,
383 // because intrinsics must be a specific type.
384 return
385 cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
386 getType(M->getContext(),
387 id, Tys, numTys)));
390 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
391 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
392 #include "llvm/Intrinsics.gen"
393 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
395 /// hasAddressTaken - returns true if there are any uses of this function
396 /// other than direct calls or invokes to it.
397 bool Function::hasAddressTaken(const User* *PutOffender) const {
398 for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
399 const User *U = *I;
400 if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
401 return PutOffender ? (*PutOffender = U, true) : true;
402 ImmutableCallSite CS(cast<Instruction>(U));
403 if (!CS.isCallee(I))
404 return PutOffender ? (*PutOffender = U, true) : true;
406 return false;
409 // vim: sw=2 ai