Run clang-format in small sections of code to make a patch easier to read.
[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/LeakDetector.h"
27 #include "llvm/IR/Module.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 = nullptr;
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, const Twine &name,
211                    Module *ParentModule)
212     : GlobalValue(PointerType::getUnqual(Ty), Value::FunctionVal, nullptr, 0,
213                   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(nullptr);
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 = nullptr;
352       if (GCNamePool->empty()) {
353         delete GCNamePool;
354         GCNamePool = nullptr;
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(nullptr);
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_ARG = 23,
470   IIT_TRUNC_ARG = 24,
471   IIT_ANYPTR = 25,
472   IIT_V1   = 26,
473   IIT_VARARG = 27,
474   IIT_HALF_VEC_ARG = 28
475 };
476
477
478 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
479                       SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
480   IIT_Info Info = IIT_Info(Infos[NextElt++]);
481   unsigned StructElts = 2;
482   using namespace Intrinsic;
483
484   switch (Info) {
485   case IIT_Done:
486     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
487     return;
488   case IIT_VARARG:
489     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
490     return;
491   case IIT_MMX:
492     OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
493     return;
494   case IIT_METADATA:
495     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
496     return;
497   case IIT_F16:
498     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
499     return;
500   case IIT_F32:
501     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
502     return;
503   case IIT_F64:
504     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
505     return;
506   case IIT_I1:
507     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
508     return;
509   case IIT_I8:
510     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
511     return;
512   case IIT_I16:
513     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
514     return;
515   case IIT_I32:
516     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
517     return;
518   case IIT_I64:
519     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
520     return;
521   case IIT_V1:
522     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
523     DecodeIITType(NextElt, Infos, OutputTable);
524     return;
525   case IIT_V2:
526     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
527     DecodeIITType(NextElt, Infos, OutputTable);
528     return;
529   case IIT_V4:
530     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
531     DecodeIITType(NextElt, Infos, OutputTable);
532     return;
533   case IIT_V8:
534     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
535     DecodeIITType(NextElt, Infos, OutputTable);
536     return;
537   case IIT_V16:
538     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
539     DecodeIITType(NextElt, Infos, OutputTable);
540     return;
541   case IIT_V32:
542     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
543     DecodeIITType(NextElt, Infos, OutputTable);
544     return;
545   case IIT_PTR:
546     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
547     DecodeIITType(NextElt, Infos, OutputTable);
548     return;
549   case IIT_ANYPTR: {  // [ANYPTR addrspace, subtype]
550     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
551                                              Infos[NextElt++]));
552     DecodeIITType(NextElt, Infos, OutputTable);
553     return;
554   }
555   case IIT_ARG: {
556     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
557     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
558     return;
559   }
560   case IIT_EXTEND_ARG: {
561     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
562     OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
563                                              ArgInfo));
564     return;
565   }
566   case IIT_TRUNC_ARG: {
567     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
568     OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
569                                              ArgInfo));
570     return;
571   }
572   case IIT_HALF_VEC_ARG: {
573     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
574     OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
575                                              ArgInfo));
576     return;
577   }
578   case IIT_EMPTYSTRUCT:
579     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
580     return;
581   case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
582   case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
583   case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
584   case IIT_STRUCT2: {
585     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
586
587     for (unsigned i = 0; i != StructElts; ++i)
588       DecodeIITType(NextElt, Infos, OutputTable);
589     return;
590   }
591   }
592   llvm_unreachable("unhandled");
593 }
594
595
596 #define GET_INTRINSIC_GENERATOR_GLOBAL
597 #include "llvm/IR/Intrinsics.gen"
598 #undef GET_INTRINSIC_GENERATOR_GLOBAL
599
600 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
601                                              SmallVectorImpl<IITDescriptor> &T){
602   // Check to see if the intrinsic's type was expressible by the table.
603   unsigned TableVal = IIT_Table[id-1];
604
605   // Decode the TableVal into an array of IITValues.
606   SmallVector<unsigned char, 8> IITValues;
607   ArrayRef<unsigned char> IITEntries;
608   unsigned NextElt = 0;
609   if ((TableVal >> 31) != 0) {
610     // This is an offset into the IIT_LongEncodingTable.
611     IITEntries = IIT_LongEncodingTable;
612
613     // Strip sentinel bit.
614     NextElt = (TableVal << 1) >> 1;
615   } else {
616     // Decode the TableVal into an array of IITValues.  If the entry was encoded
617     // into a single word in the table itself, decode it now.
618     do {
619       IITValues.push_back(TableVal & 0xF);
620       TableVal >>= 4;
621     } while (TableVal);
622
623     IITEntries = IITValues;
624     NextElt = 0;
625   }
626
627   // Okay, decode the table into the output vector of IITDescriptors.
628   DecodeIITType(NextElt, IITEntries, T);
629   while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
630     DecodeIITType(NextElt, IITEntries, T);
631 }
632
633
634 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
635                              ArrayRef<Type*> Tys, LLVMContext &Context) {
636   using namespace Intrinsic;
637   IITDescriptor D = Infos.front();
638   Infos = Infos.slice(1);
639
640   switch (D.Kind) {
641   case IITDescriptor::Void: return Type::getVoidTy(Context);
642   case IITDescriptor::VarArg: return Type::getVoidTy(Context);
643   case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
644   case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
645   case IITDescriptor::Half: return Type::getHalfTy(Context);
646   case IITDescriptor::Float: return Type::getFloatTy(Context);
647   case IITDescriptor::Double: return Type::getDoubleTy(Context);
648
649   case IITDescriptor::Integer:
650     return IntegerType::get(Context, D.Integer_Width);
651   case IITDescriptor::Vector:
652     return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
653   case IITDescriptor::Pointer:
654     return PointerType::get(DecodeFixedType(Infos, Tys, Context),
655                             D.Pointer_AddressSpace);
656   case IITDescriptor::Struct: {
657     Type *Elts[5];
658     assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
659     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
660       Elts[i] = DecodeFixedType(Infos, Tys, Context);
661     return StructType::get(Context, ArrayRef<Type*>(Elts,D.Struct_NumElements));
662   }
663
664   case IITDescriptor::Argument:
665     return Tys[D.getArgumentNumber()];
666   case IITDescriptor::ExtendArgument: {
667     Type *Ty = Tys[D.getArgumentNumber()];
668     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
669       return VectorType::getExtendedElementVectorType(VTy);
670
671     return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
672   }
673   case IITDescriptor::TruncArgument: {
674     Type *Ty = Tys[D.getArgumentNumber()];
675     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
676       return VectorType::getTruncatedElementVectorType(VTy);
677
678     IntegerType *ITy = cast<IntegerType>(Ty);
679     assert(ITy->getBitWidth() % 2 == 0);
680     return IntegerType::get(Context, ITy->getBitWidth() / 2);
681   }
682   case IITDescriptor::HalfVecArgument:
683     return VectorType::getHalfElementsVectorType(cast<VectorType>(
684                                                   Tys[D.getArgumentNumber()]));
685   }
686   llvm_unreachable("unhandled");
687 }
688
689
690
691 FunctionType *Intrinsic::getType(LLVMContext &Context,
692                                  ID id, ArrayRef<Type*> Tys) {
693   SmallVector<IITDescriptor, 8> Table;
694   getIntrinsicInfoTableEntries(id, Table);
695
696   ArrayRef<IITDescriptor> TableRef = Table;
697   Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
698
699   SmallVector<Type*, 8> ArgTys;
700   while (!TableRef.empty())
701     ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
702
703   return FunctionType::get(ResultTy, ArgTys, false);
704 }
705
706 bool Intrinsic::isOverloaded(ID id) {
707 #define GET_INTRINSIC_OVERLOAD_TABLE
708 #include "llvm/IR/Intrinsics.gen"
709 #undef GET_INTRINSIC_OVERLOAD_TABLE
710 }
711
712 /// This defines the "Intrinsic::getAttributes(ID id)" method.
713 #define GET_INTRINSIC_ATTRIBUTES
714 #include "llvm/IR/Intrinsics.gen"
715 #undef GET_INTRINSIC_ATTRIBUTES
716
717 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
718   // There can never be multiple globals with the same name of different types,
719   // because intrinsics must be a specific type.
720   return
721     cast<Function>(M->getOrInsertFunction(getName(id, Tys),
722                                           getType(M->getContext(), id, Tys)));
723 }
724
725 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
726 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
727 #include "llvm/IR/Intrinsics.gen"
728 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
729
730 /// hasAddressTaken - returns true if there are any uses of this function
731 /// other than direct calls or invokes to it.
732 bool Function::hasAddressTaken(const User* *PutOffender) const {
733   for (const Use &U : uses()) {
734     const User *FU = U.getUser();
735     if (isa<BlockAddress>(FU))
736       continue;
737     if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU))
738       return PutOffender ? (*PutOffender = FU, true) : true;
739     ImmutableCallSite CS(cast<Instruction>(FU));
740     if (!CS.isCallee(&U))
741       return PutOffender ? (*PutOffender = FU, true) : true;
742   }
743   return false;
744 }
745
746 bool Function::isDefTriviallyDead() const {
747   // Check the linkage
748   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
749       !hasAvailableExternallyLinkage())
750     return false;
751
752   // Check if the function is used by anything other than a blockaddress.
753   for (const User *U : users())
754     if (!isa<BlockAddress>(U))
755       return false;
756
757   return true;
758 }
759
760 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
761 /// setjmp or other function that gcc recognizes as "returning twice".
762 bool Function::callsFunctionThatReturnsTwice() const {
763   for (const_inst_iterator
764          I = inst_begin(this), E = inst_end(this); I != E; ++I) {
765     ImmutableCallSite CS(&*I);
766     if (CS && CS.hasFnAttr(Attribute::ReturnsTwice))
767       return true;
768   }
769
770   return false;
771 }
772
773 Constant *Function::getPrefixData() const {
774   assert(hasPrefixData());
775   const LLVMContextImpl::PrefixDataMapTy &PDMap =
776       getContext().pImpl->PrefixDataMap;
777   assert(PDMap.find(this) != PDMap.end());
778   return cast<Constant>(PDMap.find(this)->second->getReturnValue());
779 }
780
781 void Function::setPrefixData(Constant *PrefixData) {
782   if (!PrefixData && !hasPrefixData())
783     return;
784
785   unsigned SCData = getSubclassDataFromValue();
786   LLVMContextImpl::PrefixDataMapTy &PDMap = getContext().pImpl->PrefixDataMap;
787   ReturnInst *&PDHolder = PDMap[this];
788   if (PrefixData) {
789     if (PDHolder)
790       PDHolder->setOperand(0, PrefixData);
791     else
792       PDHolder = ReturnInst::Create(getContext(), PrefixData);
793     SCData |= 2;
794   } else {
795     delete PDHolder;
796     PDMap.erase(this);
797     SCData &= ~2;
798   }
799   setValueSubclassData(SCData);
800 }