6d418a4c366a08a3e8e681a0775146c8ae15e909
[oota-llvm.git] / lib / IR / Function.cpp
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 IR library.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/IR/Function.h"
15 #include "LLVMContextImpl.h"
16 #include "SymbolTableListTraitsImpl.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/CodeGen/ValueTypes.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/InstIterator.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/Support/LeakDetector.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/RWMutex.h"
30 #include "llvm/Support/StringPool.h"
31 #include "llvm/Support/Threading.h"
32 using namespace llvm;
33
34 // Explicit instantiations of SymbolTableListTraits since some of the methods
35 // are not in the public header file...
36 template class llvm::SymbolTableListTraits<Argument, Function>;
37 template class llvm::SymbolTableListTraits<BasicBlock, Function>;
38
39 //===----------------------------------------------------------------------===//
40 // Argument Implementation
41 //===----------------------------------------------------------------------===//
42
43 void Argument::anchor() { }
44
45 Argument::Argument(Type *Ty, const Twine &Name, Function *Par)
46   : Value(Ty, Value::ArgumentVal) {
47   Parent = 0;
48
49   // Make sure that we get added to a function
50   LeakDetector::addGarbageObject(this);
51
52   if (Par)
53     Par->getArgumentList().push_back(this);
54   setName(Name);
55 }
56
57 void Argument::setParent(Function *parent) {
58   if (getParent())
59     LeakDetector::addGarbageObject(this);
60   Parent = parent;
61   if (getParent())
62     LeakDetector::removeGarbageObject(this);
63 }
64
65 /// getArgNo - Return the index of this formal argument in its containing
66 /// function.  For example in "void foo(int a, float b)" a is 0 and b is 1.
67 unsigned Argument::getArgNo() const {
68   const Function *F = getParent();
69   assert(F && "Argument is not in a function");
70
71   Function::const_arg_iterator AI = F->arg_begin();
72   unsigned ArgIdx = 0;
73   for (; &*AI != this; ++AI)
74     ++ArgIdx;
75
76   return ArgIdx;
77 }
78
79 /// hasByValAttr - Return true if this argument has the byval attribute on it
80 /// in its containing function.
81 bool Argument::hasByValAttr() const {
82   if (!getType()->isPointerTy()) return false;
83   return getParent()->getAttributes().
84     hasAttribute(getArgNo()+1, Attribute::ByVal);
85 }
86
87 /// \brief Return true if this argument has the inalloca attribute on it in
88 /// its containing function.
89 bool Argument::hasInAllocaAttr() const {
90   if (!getType()->isPointerTy()) return false;
91   return getParent()->getAttributes().
92     hasAttribute(getArgNo()+1, Attribute::InAlloca);
93 }
94
95 bool Argument::hasByValOrInAllocaAttr() const {
96   if (!getType()->isPointerTy()) return false;
97   AttributeSet Attrs = getParent()->getAttributes();
98   return Attrs.hasAttribute(getArgNo() + 1, Attribute::ByVal) ||
99          Attrs.hasAttribute(getArgNo() + 1, Attribute::InAlloca);
100 }
101
102 unsigned Argument::getParamAlignment() const {
103   assert(getType()->isPointerTy() && "Only pointers have alignments");
104   return getParent()->getParamAlignment(getArgNo()+1);
105
106 }
107
108 /// hasNestAttr - Return true if this argument has the nest attribute on
109 /// it in its containing function.
110 bool Argument::hasNestAttr() const {
111   if (!getType()->isPointerTy()) return false;
112   return getParent()->getAttributes().
113     hasAttribute(getArgNo()+1, Attribute::Nest);
114 }
115
116 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
117 /// it in its containing function.
118 bool Argument::hasNoAliasAttr() const {
119   if (!getType()->isPointerTy()) return false;
120   return getParent()->getAttributes().
121     hasAttribute(getArgNo()+1, Attribute::NoAlias);
122 }
123
124 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
125 /// on it in its containing function.
126 bool Argument::hasNoCaptureAttr() const {
127   if (!getType()->isPointerTy()) return false;
128   return getParent()->getAttributes().
129     hasAttribute(getArgNo()+1, Attribute::NoCapture);
130 }
131
132 /// hasSRetAttr - Return true if this argument has the sret attribute on
133 /// it in its containing function.
134 bool Argument::hasStructRetAttr() const {
135   if (!getType()->isPointerTy()) return false;
136   if (this != getParent()->arg_begin())
137     return false; // StructRet param must be first param
138   return getParent()->getAttributes().
139     hasAttribute(1, Attribute::StructRet);
140 }
141
142 /// hasReturnedAttr - Return true if this argument has the returned attribute on
143 /// it in its containing function.
144 bool Argument::hasReturnedAttr() const {
145   return getParent()->getAttributes().
146     hasAttribute(getArgNo()+1, Attribute::Returned);
147 }
148
149 /// Return true if this argument has the readonly or readnone attribute on it
150 /// in its containing function.
151 bool Argument::onlyReadsMemory() const {
152   return getParent()->getAttributes().
153       hasAttribute(getArgNo()+1, Attribute::ReadOnly) ||
154       getParent()->getAttributes().
155       hasAttribute(getArgNo()+1, Attribute::ReadNone);
156 }
157
158 /// addAttr - Add attributes to an argument.
159 void Argument::addAttr(AttributeSet AS) {
160   assert(AS.getNumSlots() <= 1 &&
161          "Trying to add more than one attribute set to an argument!");
162   AttrBuilder B(AS, AS.getSlotIndex(0));
163   getParent()->addAttributes(getArgNo() + 1,
164                              AttributeSet::get(Parent->getContext(),
165                                                getArgNo() + 1, B));
166 }
167
168 /// removeAttr - Remove attributes from an argument.
169 void Argument::removeAttr(AttributeSet AS) {
170   assert(AS.getNumSlots() <= 1 &&
171          "Trying to remove more than one attribute set from an argument!");
172   AttrBuilder B(AS, AS.getSlotIndex(0));
173   getParent()->removeAttributes(getArgNo() + 1,
174                                 AttributeSet::get(Parent->getContext(),
175                                                   getArgNo() + 1, B));
176 }
177
178 //===----------------------------------------------------------------------===//
179 // Helper Methods in Function
180 //===----------------------------------------------------------------------===//
181
182 LLVMContext &Function::getContext() const {
183   return getType()->getContext();
184 }
185
186 FunctionType *Function::getFunctionType() const {
187   return cast<FunctionType>(getType()->getElementType());
188 }
189
190 bool Function::isVarArg() const {
191   return getFunctionType()->isVarArg();
192 }
193
194 Type *Function::getReturnType() const {
195   return getFunctionType()->getReturnType();
196 }
197
198 void Function::removeFromParent() {
199   getParent()->getFunctionList().remove(this);
200 }
201
202 void Function::eraseFromParent() {
203   getParent()->getFunctionList().erase(this);
204 }
205
206 //===----------------------------------------------------------------------===//
207 // Function Implementation
208 //===----------------------------------------------------------------------===//
209
210 Function::Function(FunctionType *Ty, LinkageTypes Linkage,
211                    const Twine &name, Module *ParentModule)
212   : GlobalValue(PointerType::getUnqual(Ty),
213                 Value::FunctionVal, 0, 0, Linkage, name) {
214   assert(FunctionType::isValidReturnType(getReturnType()) &&
215          "invalid return type");
216   SymTab = new ValueSymbolTable();
217
218   // If the function has arguments, mark them as lazily built.
219   if (Ty->getNumParams())
220     setValueSubclassData(1);   // Set the "has lazy arguments" bit.
221
222   // Make sure that we get added to a function
223   LeakDetector::addGarbageObject(this);
224
225   if (ParentModule)
226     ParentModule->getFunctionList().push_back(this);
227
228   // Ensure intrinsics have the right parameter attributes.
229   if (unsigned IID = getIntrinsicID())
230     setAttributes(Intrinsic::getAttributes(getContext(), Intrinsic::ID(IID)));
231
232 }
233
234 Function::~Function() {
235   dropAllReferences();    // After this it is safe to delete instructions.
236
237   // Delete all of the method arguments and unlink from symbol table...
238   ArgumentList.clear();
239   delete SymTab;
240
241   // Remove the function from the on-the-side GC table.
242   clearGC();
243
244   // Remove the intrinsicID from the Cache.
245   if (getValueName() && isIntrinsic())
246     getContext().pImpl->IntrinsicIDCache.erase(this);
247 }
248
249 void Function::BuildLazyArguments() const {
250   // Create the arguments vector, all arguments start out unnamed.
251   FunctionType *FT = getFunctionType();
252   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
253     assert(!FT->getParamType(i)->isVoidTy() &&
254            "Cannot have void typed arguments!");
255     ArgumentList.push_back(new Argument(FT->getParamType(i)));
256   }
257
258   // Clear the lazy arguments bit.
259   unsigned SDC = getSubclassDataFromValue();
260   const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1);
261 }
262
263 size_t Function::arg_size() const {
264   return getFunctionType()->getNumParams();
265 }
266 bool Function::arg_empty() const {
267   return getFunctionType()->getNumParams() == 0;
268 }
269
270 void Function::setParent(Module *parent) {
271   if (getParent())
272     LeakDetector::addGarbageObject(this);
273   Parent = parent;
274   if (getParent())
275     LeakDetector::removeGarbageObject(this);
276 }
277
278 // dropAllReferences() - This function causes all the subinstructions to "let
279 // go" of all references that they are maintaining.  This allows one to
280 // 'delete' a whole class at a time, even though there may be circular
281 // references... first all references are dropped, and all use counts go to
282 // zero.  Then everything is deleted for real.  Note that no operations are
283 // valid on an object that has "dropped all references", except operator
284 // delete.
285 //
286 void Function::dropAllReferences() {
287   for (iterator I = begin(), E = end(); I != E; ++I)
288     I->dropAllReferences();
289
290   // Delete all basic blocks. They are now unused, except possibly by
291   // blockaddresses, but BasicBlock's destructor takes care of those.
292   while (!BasicBlocks.empty())
293     BasicBlocks.begin()->eraseFromParent();
294
295   // Prefix data is stored in a side table.
296   setPrefixData(0);
297 }
298
299 void Function::addAttribute(unsigned i, Attribute::AttrKind attr) {
300   AttributeSet PAL = getAttributes();
301   PAL = PAL.addAttribute(getContext(), i, attr);
302   setAttributes(PAL);
303 }
304
305 void Function::addAttributes(unsigned i, AttributeSet attrs) {
306   AttributeSet PAL = getAttributes();
307   PAL = PAL.addAttributes(getContext(), i, attrs);
308   setAttributes(PAL);
309 }
310
311 void Function::removeAttributes(unsigned i, AttributeSet attrs) {
312   AttributeSet PAL = getAttributes();
313   PAL = PAL.removeAttributes(getContext(), i, attrs);
314   setAttributes(PAL);
315 }
316
317 // Maintain the GC name for each function in an on-the-side table. This saves
318 // allocating an additional word in Function for programs which do not use GC
319 // (i.e., most programs) at the cost of increased overhead for clients which do
320 // use GC.
321 static DenseMap<const Function*,PooledStringPtr> *GCNames;
322 static StringPool *GCNamePool;
323 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
324
325 bool Function::hasGC() const {
326   sys::SmartScopedReader<true> Reader(*GCLock);
327   return GCNames && GCNames->count(this);
328 }
329
330 const char *Function::getGC() const {
331   assert(hasGC() && "Function has no collector");
332   sys::SmartScopedReader<true> Reader(*GCLock);
333   return *(*GCNames)[this];
334 }
335
336 void Function::setGC(const char *Str) {
337   sys::SmartScopedWriter<true> Writer(*GCLock);
338   if (!GCNamePool)
339     GCNamePool = new StringPool();
340   if (!GCNames)
341     GCNames = new DenseMap<const Function*,PooledStringPtr>();
342   (*GCNames)[this] = GCNamePool->intern(Str);
343 }
344
345 void Function::clearGC() {
346   sys::SmartScopedWriter<true> Writer(*GCLock);
347   if (GCNames) {
348     GCNames->erase(this);
349     if (GCNames->empty()) {
350       delete GCNames;
351       GCNames = 0;
352       if (GCNamePool->empty()) {
353         delete GCNamePool;
354         GCNamePool = 0;
355       }
356     }
357   }
358 }
359
360 /// copyAttributesFrom - copy all additional attributes (those not needed to
361 /// create a Function) from the Function Src to this one.
362 void Function::copyAttributesFrom(const GlobalValue *Src) {
363   assert(isa<Function>(Src) && "Expected a Function!");
364   GlobalValue::copyAttributesFrom(Src);
365   const Function *SrcF = cast<Function>(Src);
366   setCallingConv(SrcF->getCallingConv());
367   setAttributes(SrcF->getAttributes());
368   if (SrcF->hasGC())
369     setGC(SrcF->getGC());
370   else
371     clearGC();
372   if (SrcF->hasPrefixData())
373     setPrefixData(SrcF->getPrefixData());
374   else
375     setPrefixData(0);
376 }
377
378 /// getIntrinsicID - This method returns the ID number of the specified
379 /// function, or Intrinsic::not_intrinsic if the function is not an
380 /// intrinsic, or if the pointer is null.  This value is always defined to be
381 /// zero to allow easy checking for whether a function is intrinsic or not.  The
382 /// particular intrinsic functions which correspond to this value are defined in
383 /// llvm/Intrinsics.h.  Results are cached in the LLVM context, subsequent
384 /// requests for the same ID return results much faster from the cache.
385 ///
386 unsigned Function::getIntrinsicID() const {
387   const ValueName *ValName = this->getValueName();
388   if (!ValName || !isIntrinsic())
389     return 0;
390
391   LLVMContextImpl::IntrinsicIDCacheTy &IntrinsicIDCache =
392     getContext().pImpl->IntrinsicIDCache;
393   if (!IntrinsicIDCache.count(this)) {
394     unsigned Id = lookupIntrinsicID();
395     IntrinsicIDCache[this]=Id;
396     return Id;
397   }
398   return IntrinsicIDCache[this];
399 }
400
401 /// This private method does the actual lookup of an intrinsic ID when the query
402 /// could not be answered from the cache.
403 unsigned Function::lookupIntrinsicID() const {
404   const ValueName *ValName = this->getValueName();
405   unsigned Len = ValName->getKeyLength();
406   const char *Name = ValName->getKeyData();
407
408 #define GET_FUNCTION_RECOGNIZER
409 #include "llvm/IR/Intrinsics.gen"
410 #undef GET_FUNCTION_RECOGNIZER
411
412   return 0;
413 }
414
415 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
416   assert(id < num_intrinsics && "Invalid intrinsic ID!");
417   static const char * const Table[] = {
418     "not_intrinsic",
419 #define GET_INTRINSIC_NAME_TABLE
420 #include "llvm/IR/Intrinsics.gen"
421 #undef GET_INTRINSIC_NAME_TABLE
422   };
423   if (Tys.empty())
424     return Table[id];
425   std::string Result(Table[id]);
426   for (unsigned i = 0; i < Tys.size(); ++i) {
427     if (PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
428       Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
429                 EVT::getEVT(PTyp->getElementType()).getEVTString();
430     }
431     else if (Tys[i])
432       Result += "." + EVT::getEVT(Tys[i]).getEVTString();
433   }
434   return Result;
435 }
436
437
438 /// IIT_Info - These are enumerators that describe the entries returned by the
439 /// getIntrinsicInfoTableEntries function.
440 ///
441 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
442 enum IIT_Info {
443   // Common values should be encoded with 0-15.
444   IIT_Done = 0,
445   IIT_I1   = 1,
446   IIT_I8   = 2,
447   IIT_I16  = 3,
448   IIT_I32  = 4,
449   IIT_I64  = 5,
450   IIT_F16  = 6,
451   IIT_F32  = 7,
452   IIT_F64  = 8,
453   IIT_V2   = 9,
454   IIT_V4   = 10,
455   IIT_V8   = 11,
456   IIT_V16  = 12,
457   IIT_V32  = 13,
458   IIT_PTR  = 14,
459   IIT_ARG  = 15,
460
461   // Values from 16+ are only encodable with the inefficient encoding.
462   IIT_MMX  = 16,
463   IIT_METADATA = 17,
464   IIT_EMPTYSTRUCT = 18,
465   IIT_STRUCT2 = 19,
466   IIT_STRUCT3 = 20,
467   IIT_STRUCT4 = 21,
468   IIT_STRUCT5 = 22,
469   IIT_EXTEND_VEC_ARG = 23,
470   IIT_TRUNC_VEC_ARG = 24,
471   IIT_ANYPTR = 25,
472   IIT_V1   = 26,
473   IIT_VARARG = 27
474 };
475
476
477 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
478                       SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
479   IIT_Info Info = IIT_Info(Infos[NextElt++]);
480   unsigned StructElts = 2;
481   using namespace Intrinsic;
482
483   switch (Info) {
484   case IIT_Done:
485     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
486     return;
487   case IIT_VARARG:
488     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
489     return;
490   case IIT_MMX:
491     OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
492     return;
493   case IIT_METADATA:
494     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
495     return;
496   case IIT_F16:
497     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
498     return;
499   case IIT_F32:
500     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
501     return;
502   case IIT_F64:
503     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
504     return;
505   case IIT_I1:
506     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
507     return;
508   case IIT_I8:
509     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
510     return;
511   case IIT_I16:
512     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
513     return;
514   case IIT_I32:
515     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
516     return;
517   case IIT_I64:
518     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
519     return;
520   case IIT_V1:
521     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
522     DecodeIITType(NextElt, Infos, OutputTable);
523     return;
524   case IIT_V2:
525     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
526     DecodeIITType(NextElt, Infos, OutputTable);
527     return;
528   case IIT_V4:
529     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
530     DecodeIITType(NextElt, Infos, OutputTable);
531     return;
532   case IIT_V8:
533     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
534     DecodeIITType(NextElt, Infos, OutputTable);
535     return;
536   case IIT_V16:
537     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
538     DecodeIITType(NextElt, Infos, OutputTable);
539     return;
540   case IIT_V32:
541     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
542     DecodeIITType(NextElt, Infos, OutputTable);
543     return;
544   case IIT_PTR:
545     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
546     DecodeIITType(NextElt, Infos, OutputTable);
547     return;
548   case IIT_ANYPTR: {  // [ANYPTR addrspace, subtype]
549     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
550                                              Infos[NextElt++]));
551     DecodeIITType(NextElt, Infos, OutputTable);
552     return;
553   }
554   case IIT_ARG: {
555     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
556     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
557     return;
558   }
559   case IIT_EXTEND_VEC_ARG: {
560     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
561     OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendVecArgument,
562                                              ArgInfo));
563     return;
564   }
565   case IIT_TRUNC_VEC_ARG: {
566     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
567     OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncVecArgument,
568                                              ArgInfo));
569     return;
570   }
571   case IIT_EMPTYSTRUCT:
572     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
573     return;
574   case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
575   case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
576   case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
577   case IIT_STRUCT2: {
578     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
579
580     for (unsigned i = 0; i != StructElts; ++i)
581       DecodeIITType(NextElt, Infos, OutputTable);
582     return;
583   }
584   }
585   llvm_unreachable("unhandled");
586 }
587
588
589 #define GET_INTRINSIC_GENERATOR_GLOBAL
590 #include "llvm/IR/Intrinsics.gen"
591 #undef GET_INTRINSIC_GENERATOR_GLOBAL
592
593 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
594                                              SmallVectorImpl<IITDescriptor> &T){
595   // Check to see if the intrinsic's type was expressible by the table.
596   unsigned TableVal = IIT_Table[id-1];
597
598   // Decode the TableVal into an array of IITValues.
599   SmallVector<unsigned char, 8> IITValues;
600   ArrayRef<unsigned char> IITEntries;
601   unsigned NextElt = 0;
602   if ((TableVal >> 31) != 0) {
603     // This is an offset into the IIT_LongEncodingTable.
604     IITEntries = IIT_LongEncodingTable;
605
606     // Strip sentinel bit.
607     NextElt = (TableVal << 1) >> 1;
608   } else {
609     // Decode the TableVal into an array of IITValues.  If the entry was encoded
610     // into a single word in the table itself, decode it now.
611     do {
612       IITValues.push_back(TableVal & 0xF);
613       TableVal >>= 4;
614     } while (TableVal);
615
616     IITEntries = IITValues;
617     NextElt = 0;
618   }
619
620   // Okay, decode the table into the output vector of IITDescriptors.
621   DecodeIITType(NextElt, IITEntries, T);
622   while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
623     DecodeIITType(NextElt, IITEntries, T);
624 }
625
626
627 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
628                              ArrayRef<Type*> Tys, LLVMContext &Context) {
629   using namespace Intrinsic;
630   IITDescriptor D = Infos.front();
631   Infos = Infos.slice(1);
632
633   switch (D.Kind) {
634   case IITDescriptor::Void: return Type::getVoidTy(Context);
635   case IITDescriptor::VarArg: return Type::getVoidTy(Context);
636   case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
637   case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
638   case IITDescriptor::Half: return Type::getHalfTy(Context);
639   case IITDescriptor::Float: return Type::getFloatTy(Context);
640   case IITDescriptor::Double: return Type::getDoubleTy(Context);
641
642   case IITDescriptor::Integer:
643     return IntegerType::get(Context, D.Integer_Width);
644   case IITDescriptor::Vector:
645     return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
646   case IITDescriptor::Pointer:
647     return PointerType::get(DecodeFixedType(Infos, Tys, Context),
648                             D.Pointer_AddressSpace);
649   case IITDescriptor::Struct: {
650     Type *Elts[5];
651     assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
652     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
653       Elts[i] = DecodeFixedType(Infos, Tys, Context);
654     return StructType::get(Context, ArrayRef<Type*>(Elts,D.Struct_NumElements));
655   }
656
657   case IITDescriptor::Argument:
658     return Tys[D.getArgumentNumber()];
659   case IITDescriptor::ExtendVecArgument:
660     return VectorType::getExtendedElementVectorType(cast<VectorType>(
661                                                   Tys[D.getArgumentNumber()]));
662
663   case IITDescriptor::TruncVecArgument:
664     return VectorType::getTruncatedElementVectorType(cast<VectorType>(
665                                                   Tys[D.getArgumentNumber()]));
666   }
667   llvm_unreachable("unhandled");
668 }
669
670
671
672 FunctionType *Intrinsic::getType(LLVMContext &Context,
673                                  ID id, ArrayRef<Type*> Tys) {
674   SmallVector<IITDescriptor, 8> Table;
675   getIntrinsicInfoTableEntries(id, Table);
676
677   ArrayRef<IITDescriptor> TableRef = Table;
678   Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
679
680   SmallVector<Type*, 8> ArgTys;
681   while (!TableRef.empty())
682     ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
683
684   return FunctionType::get(ResultTy, ArgTys, false);
685 }
686
687 bool Intrinsic::isOverloaded(ID id) {
688 #define GET_INTRINSIC_OVERLOAD_TABLE
689 #include "llvm/IR/Intrinsics.gen"
690 #undef GET_INTRINSIC_OVERLOAD_TABLE
691 }
692
693 /// This defines the "Intrinsic::getAttributes(ID id)" method.
694 #define GET_INTRINSIC_ATTRIBUTES
695 #include "llvm/IR/Intrinsics.gen"
696 #undef GET_INTRINSIC_ATTRIBUTES
697
698 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
699   // There can never be multiple globals with the same name of different types,
700   // because intrinsics must be a specific type.
701   return
702     cast<Function>(M->getOrInsertFunction(getName(id, Tys),
703                                           getType(M->getContext(), id, Tys)));
704 }
705
706 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
707 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
708 #include "llvm/IR/Intrinsics.gen"
709 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
710
711 /// hasAddressTaken - returns true if there are any uses of this function
712 /// other than direct calls or invokes to it.
713 bool Function::hasAddressTaken(const User* *PutOffender) const {
714   for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
715     const User *U = *I;
716     if (isa<BlockAddress>(U))
717       continue;
718     if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
719       return PutOffender ? (*PutOffender = U, true) : true;
720     ImmutableCallSite CS(cast<Instruction>(U));
721     if (!CS.isCallee(I))
722       return PutOffender ? (*PutOffender = U, true) : true;
723   }
724   return false;
725 }
726
727 bool Function::isDefTriviallyDead() const {
728   // Check the linkage
729   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
730       !hasAvailableExternallyLinkage())
731     return false;
732
733   // Check if the function is used by anything other than a blockaddress.
734   for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I)
735     if (!isa<BlockAddress>(*I))
736       return false;
737
738   return true;
739 }
740
741 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
742 /// setjmp or other function that gcc recognizes as "returning twice".
743 bool Function::callsFunctionThatReturnsTwice() const {
744   for (const_inst_iterator
745          I = inst_begin(this), E = inst_end(this); I != E; ++I) {
746     ImmutableCallSite CS(&*I);
747     if (CS && CS.hasFnAttr(Attribute::ReturnsTwice))
748       return true;
749   }
750
751   return false;
752 }
753
754 Constant *Function::getPrefixData() const {
755   assert(hasPrefixData());
756   const LLVMContextImpl::PrefixDataMapTy &PDMap =
757       getContext().pImpl->PrefixDataMap;
758   assert(PDMap.find(this) != PDMap.end());
759   return cast<Constant>(PDMap.find(this)->second->getReturnValue());
760 }
761
762 void Function::setPrefixData(Constant *PrefixData) {
763   if (!PrefixData && !hasPrefixData())
764     return;
765
766   unsigned SCData = getSubclassDataFromValue();
767   LLVMContextImpl::PrefixDataMapTy &PDMap = getContext().pImpl->PrefixDataMap;
768   ReturnInst *&PDHolder = PDMap[this];
769   if (PrefixData) {
770     if (PDHolder)
771       PDHolder->setOperand(0, PrefixData);
772     else
773       PDHolder = ReturnInst::Create(getContext(), PrefixData);
774     SCData |= 2;
775   } else {
776     delete PDHolder;
777     PDMap.erase(this);
778     SCData &= ~2;
779   }
780   setValueSubclassData(SCData);
781 }