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/STLExtras.h" 18 #include "llvm/ADT/StringExtras.h" 19 #include "llvm/CodeGen/ValueTypes.h" 20 #include "llvm/IR/CallSite.h" 21 #include "llvm/IR/Constants.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/MDBuilder.h" 27 #include "llvm/IR/Metadata.h" 28 #include "llvm/IR/Module.h" 29 #include "llvm/Support/ManagedStatic.h" 30 #include "llvm/Support/RWMutex.h" 31 #include "llvm/Support/StringPool.h" 32 #include "llvm/Support/Threading.h" 33 using namespace llvm; 34 35 // Explicit instantiations of SymbolTableListTraits since some of the methods 36 // are not in the public header file... 37 template class llvm::SymbolTableListTraits<Argument>; 38 template class llvm::SymbolTableListTraits<BasicBlock>; 39 40 //===----------------------------------------------------------------------===// 41 // Argument Implementation 42 //===----------------------------------------------------------------------===// 43 44 void Argument::anchor() { } 45 46 Argument::Argument(Type *Ty, const Twine &Name, Function *Par) 47 : Value(Ty, Value::ArgumentVal) { 48 Parent = nullptr; 49 50 if (Par) 51 Par->getArgumentList().push_back(this); 52 setName(Name); 53 } 54 55 void Argument::setParent(Function *parent) { 56 Parent = parent; 57 } 58 59 /// getArgNo - Return the index of this formal argument in its containing 60 /// function. For example in "void foo(int a, float b)" a is 0 and b is 1. 61 unsigned Argument::getArgNo() const { 62 const Function *F = getParent(); 63 assert(F && "Argument is not in a function"); 64 65 Function::const_arg_iterator AI = F->arg_begin(); 66 unsigned ArgIdx = 0; 67 for (; &*AI != this; ++AI) 68 ++ArgIdx; 69 70 return ArgIdx; 71 } 72 73 /// hasNonNullAttr - Return true if this argument has the nonnull attribute on 74 /// it in its containing function. Also returns true if at least one byte is 75 /// known to be dereferenceable and the pointer is in addrspace(0). 76 bool Argument::hasNonNullAttr() const { 77 if (!getType()->isPointerTy()) return false; 78 if (getParent()->getAttributes(). 79 hasAttribute(getArgNo()+1, Attribute::NonNull)) 80 return true; 81 else if (getDereferenceableBytes() > 0 && 82 getType()->getPointerAddressSpace() == 0) 83 return true; 84 return false; 85 } 86 87 /// hasByValAttr - Return true if this argument has the byval attribute on it 88 /// in its containing function. 89 bool Argument::hasByValAttr() const { 90 if (!getType()->isPointerTy()) return false; 91 return hasAttribute(Attribute::ByVal); 92 } 93 94 bool Argument::hasSwiftSelfAttr() const { 95 return getParent()->getAttributes(). 96 hasAttribute(getArgNo()+1, Attribute::SwiftSelf); 97 } 98 99 bool Argument::hasSwiftErrorAttr() const { 100 return getParent()->getAttributes(). 101 hasAttribute(getArgNo()+1, Attribute::SwiftError); 102 } 103 104 /// \brief Return true if this argument has the inalloca attribute on it in 105 /// its containing function. 106 bool Argument::hasInAllocaAttr() const { 107 if (!getType()->isPointerTy()) return false; 108 return hasAttribute(Attribute::InAlloca); 109 } 110 111 bool Argument::hasByValOrInAllocaAttr() const { 112 if (!getType()->isPointerTy()) return false; 113 AttributeSet Attrs = getParent()->getAttributes(); 114 return Attrs.hasAttribute(getArgNo() + 1, Attribute::ByVal) || 115 Attrs.hasAttribute(getArgNo() + 1, Attribute::InAlloca); 116 } 117 118 unsigned Argument::getParamAlignment() const { 119 assert(getType()->isPointerTy() && "Only pointers have alignments"); 120 return getParent()->getParamAlignment(getArgNo()+1); 121 122 } 123 124 uint64_t Argument::getDereferenceableBytes() const { 125 assert(getType()->isPointerTy() && 126 "Only pointers have dereferenceable bytes"); 127 return getParent()->getDereferenceableBytes(getArgNo()+1); 128 } 129 130 uint64_t Argument::getDereferenceableOrNullBytes() const { 131 assert(getType()->isPointerTy() && 132 "Only pointers have dereferenceable bytes"); 133 return getParent()->getDereferenceableOrNullBytes(getArgNo()+1); 134 } 135 136 /// hasNestAttr - Return true if this argument has the nest attribute on 137 /// it in its containing function. 138 bool Argument::hasNestAttr() const { 139 if (!getType()->isPointerTy()) return false; 140 return hasAttribute(Attribute::Nest); 141 } 142 143 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on 144 /// it in its containing function. 145 bool Argument::hasNoAliasAttr() const { 146 if (!getType()->isPointerTy()) return false; 147 return hasAttribute(Attribute::NoAlias); 148 } 149 150 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute 151 /// on it in its containing function. 152 bool Argument::hasNoCaptureAttr() const { 153 if (!getType()->isPointerTy()) return false; 154 return hasAttribute(Attribute::NoCapture); 155 } 156 157 /// hasSRetAttr - Return true if this argument has the sret attribute on 158 /// it in its containing function. 159 bool Argument::hasStructRetAttr() const { 160 if (!getType()->isPointerTy()) return false; 161 return hasAttribute(Attribute::StructRet); 162 } 163 164 /// hasReturnedAttr - Return true if this argument has the returned attribute on 165 /// it in its containing function. 166 bool Argument::hasReturnedAttr() const { 167 return hasAttribute(Attribute::Returned); 168 } 169 170 /// hasZExtAttr - Return true if this argument has the zext attribute on it in 171 /// its containing function. 172 bool Argument::hasZExtAttr() const { 173 return hasAttribute(Attribute::ZExt); 174 } 175 176 /// hasSExtAttr Return true if this argument has the sext attribute on it in its 177 /// containing function. 178 bool Argument::hasSExtAttr() const { 179 return hasAttribute(Attribute::SExt); 180 } 181 182 /// Return true if this argument has the readonly or readnone attribute on it 183 /// in its containing function. 184 bool Argument::onlyReadsMemory() const { 185 return getParent()->getAttributes(). 186 hasAttribute(getArgNo()+1, Attribute::ReadOnly) || 187 getParent()->getAttributes(). 188 hasAttribute(getArgNo()+1, Attribute::ReadNone); 189 } 190 191 /// addAttr - Add attributes to an argument. 192 void Argument::addAttr(AttributeSet AS) { 193 assert(AS.getNumSlots() <= 1 && 194 "Trying to add more than one attribute set to an argument!"); 195 AttrBuilder B(AS, AS.getSlotIndex(0)); 196 getParent()->addAttributes(getArgNo() + 1, 197 AttributeSet::get(Parent->getContext(), 198 getArgNo() + 1, B)); 199 } 200 201 /// removeAttr - Remove attributes from an argument. 202 void Argument::removeAttr(AttributeSet AS) { 203 assert(AS.getNumSlots() <= 1 && 204 "Trying to remove more than one attribute set from an argument!"); 205 AttrBuilder B(AS, AS.getSlotIndex(0)); 206 getParent()->removeAttributes(getArgNo() + 1, 207 AttributeSet::get(Parent->getContext(), 208 getArgNo() + 1, B)); 209 } 210 211 /// hasAttribute - Checks if an argument has a given attribute. 212 bool Argument::hasAttribute(Attribute::AttrKind Kind) const { 213 return getParent()->hasAttribute(getArgNo() + 1, Kind); 214 } 215 216 //===----------------------------------------------------------------------===// 217 // Helper Methods in Function 218 //===----------------------------------------------------------------------===// 219 220 bool Function::isMaterializable() const { 221 return getGlobalObjectSubClassData() & (1 << IsMaterializableBit); 222 } 223 224 void Function::setIsMaterializable(bool V) { 225 unsigned Mask = 1 << IsMaterializableBit; 226 setGlobalObjectSubClassData((~Mask & getGlobalObjectSubClassData()) | 227 (V ? Mask : 0u)); 228 } 229 230 LLVMContext &Function::getContext() const { 231 return getType()->getContext(); 232 } 233 234 FunctionType *Function::getFunctionType() const { 235 return cast<FunctionType>(getValueType()); 236 } 237 238 bool Function::isVarArg() const { 239 return getFunctionType()->isVarArg(); 240 } 241 242 Type *Function::getReturnType() const { 243 return getFunctionType()->getReturnType(); 244 } 245 246 void Function::removeFromParent() { 247 getParent()->getFunctionList().remove(getIterator()); 248 } 249 250 void Function::eraseFromParent() { 251 getParent()->getFunctionList().erase(getIterator()); 252 } 253 254 //===----------------------------------------------------------------------===// 255 // Function Implementation 256 //===----------------------------------------------------------------------===// 257 258 Function::Function(FunctionType *Ty, LinkageTypes Linkage, const Twine &name, 259 Module *ParentModule) 260 : GlobalObject(Ty, Value::FunctionVal, 261 OperandTraits<Function>::op_begin(this), 0, Linkage, name) { 262 assert(FunctionType::isValidReturnType(getReturnType()) && 263 "invalid return type"); 264 setGlobalObjectSubClassData(0); 265 SymTab = new ValueSymbolTable(); 266 267 // If the function has arguments, mark them as lazily built. 268 if (Ty->getNumParams()) 269 setValueSubclassData(1); // Set the "has lazy arguments" bit. 270 271 if (ParentModule) 272 ParentModule->getFunctionList().push_back(this); 273 274 // Ensure intrinsics have the right parameter attributes. 275 // Note, the IntID field will have been set in Value::setName if this function 276 // name is a valid intrinsic ID. 277 if (IntID) 278 setAttributes(Intrinsic::getAttributes(getContext(), IntID)); 279 } 280 281 Function::~Function() { 282 dropAllReferences(); // After this it is safe to delete instructions. 283 284 // Delete all of the method arguments and unlink from symbol table... 285 ArgumentList.clear(); 286 delete SymTab; 287 288 // Remove the function from the on-the-side GC table. 289 clearGC(); 290 } 291 292 void Function::BuildLazyArguments() const { 293 // Create the arguments vector, all arguments start out unnamed. 294 FunctionType *FT = getFunctionType(); 295 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 296 assert(!FT->getParamType(i)->isVoidTy() && 297 "Cannot have void typed arguments!"); 298 ArgumentList.push_back(new Argument(FT->getParamType(i))); 299 } 300 301 // Clear the lazy arguments bit. 302 unsigned SDC = getSubclassDataFromValue(); 303 const_cast<Function*>(this)->setValueSubclassData(SDC &= ~(1<<0)); 304 } 305 306 void Function::stealArgumentListFrom(Function &Src) { 307 assert(isDeclaration() && "Expected no references to current arguments"); 308 309 // Drop the current arguments, if any, and set the lazy argument bit. 310 if (!hasLazyArguments()) { 311 assert(llvm::all_of(ArgumentList, 312 [](const Argument &A) { return A.use_empty(); }) && 313 "Expected arguments to be unused in declaration"); 314 ArgumentList.clear(); 315 setValueSubclassData(getSubclassDataFromValue() | (1 << 0)); 316 } 317 318 // Nothing to steal if Src has lazy arguments. 319 if (Src.hasLazyArguments()) 320 return; 321 322 // Steal arguments from Src, and fix the lazy argument bits. 323 ArgumentList.splice(ArgumentList.end(), Src.ArgumentList); 324 setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0)); 325 Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0)); 326 } 327 328 size_t Function::arg_size() const { 329 return getFunctionType()->getNumParams(); 330 } 331 bool Function::arg_empty() const { 332 return getFunctionType()->getNumParams() == 0; 333 } 334 335 void Function::setParent(Module *parent) { 336 Parent = parent; 337 } 338 339 // dropAllReferences() - This function causes all the subinstructions to "let 340 // go" of all references that they are maintaining. This allows one to 341 // 'delete' a whole class at a time, even though there may be circular 342 // references... first all references are dropped, and all use counts go to 343 // zero. Then everything is deleted for real. Note that no operations are 344 // valid on an object that has "dropped all references", except operator 345 // delete. 346 // 347 void Function::dropAllReferences() { 348 setIsMaterializable(false); 349 350 for (iterator I = begin(), E = end(); I != E; ++I) 351 I->dropAllReferences(); 352 353 // Delete all basic blocks. They are now unused, except possibly by 354 // blockaddresses, but BasicBlock's destructor takes care of those. 355 while (!BasicBlocks.empty()) 356 BasicBlocks.begin()->eraseFromParent(); 357 358 // Drop uses of any optional data (real or placeholder). 359 if (getNumOperands()) { 360 User::dropAllReferences(); 361 setNumHungOffUseOperands(0); 362 setValueSubclassData(getSubclassDataFromValue() & ~0xe); 363 } 364 365 // Metadata is stored in a side-table. 366 clearMetadata(); 367 } 368 369 void Function::addAttribute(unsigned i, Attribute::AttrKind attr) { 370 AttributeSet PAL = getAttributes(); 371 PAL = PAL.addAttribute(getContext(), i, attr); 372 setAttributes(PAL); 373 } 374 375 void Function::addAttributes(unsigned i, AttributeSet attrs) { 376 AttributeSet PAL = getAttributes(); 377 PAL = PAL.addAttributes(getContext(), i, attrs); 378 setAttributes(PAL); 379 } 380 381 void Function::removeAttribute(unsigned i, Attribute::AttrKind attr) { 382 AttributeSet PAL = getAttributes(); 383 PAL = PAL.removeAttribute(getContext(), i, attr); 384 setAttributes(PAL); 385 } 386 387 void Function::removeAttributes(unsigned i, AttributeSet attrs) { 388 AttributeSet PAL = getAttributes(); 389 PAL = PAL.removeAttributes(getContext(), i, attrs); 390 setAttributes(PAL); 391 } 392 393 void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) { 394 AttributeSet PAL = getAttributes(); 395 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes); 396 setAttributes(PAL); 397 } 398 399 void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) { 400 AttributeSet PAL = getAttributes(); 401 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes); 402 setAttributes(PAL); 403 } 404 405 const std::string &Function::getGC() const { 406 assert(hasGC() && "Function has no collector"); 407 return getContext().getGC(*this); 408 } 409 410 void Function::setGC(std::string Str) { 411 setValueSubclassDataBit(14, !Str.empty()); 412 getContext().setGC(*this, std::move(Str)); 413 } 414 415 void Function::clearGC() { 416 if (!hasGC()) 417 return; 418 getContext().deleteGC(*this); 419 setValueSubclassDataBit(14, false); 420 } 421 422 /// Copy all additional attributes (those not needed to create a Function) from 423 /// the Function Src to this one. 424 void Function::copyAttributesFrom(const GlobalValue *Src) { 425 GlobalObject::copyAttributesFrom(Src); 426 const Function *SrcF = dyn_cast<Function>(Src); 427 if (!SrcF) 428 return; 429 430 setCallingConv(SrcF->getCallingConv()); 431 setAttributes(SrcF->getAttributes()); 432 if (SrcF->hasGC()) 433 setGC(SrcF->getGC()); 434 else 435 clearGC(); 436 if (SrcF->hasPersonalityFn()) 437 setPersonalityFn(SrcF->getPersonalityFn()); 438 if (SrcF->hasPrefixData()) 439 setPrefixData(SrcF->getPrefixData()); 440 if (SrcF->hasPrologueData()) 441 setPrologueData(SrcF->getPrologueData()); 442 } 443 444 /// Table of string intrinsic names indexed by enum value. 445 static const char * const IntrinsicNameTable[] = { 446 "not_intrinsic", 447 #define GET_INTRINSIC_NAME_TABLE 448 #include "llvm/IR/Intrinsics.gen" 449 #undef GET_INTRINSIC_NAME_TABLE 450 }; 451 452 /// \brief This does the actual lookup of an intrinsic ID which 453 /// matches the given function name. 454 static Intrinsic::ID lookupIntrinsicID(const ValueName *ValName) { 455 StringRef Name = ValName->getKey(); 456 457 ArrayRef<const char *> NameTable(&IntrinsicNameTable[1], 458 std::end(IntrinsicNameTable)); 459 int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name); 460 Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + 1); 461 if (ID == Intrinsic::not_intrinsic) 462 return ID; 463 464 // If the intrinsic is not overloaded, require an exact match. If it is 465 // overloaded, require a prefix match. 466 bool IsPrefixMatch = Name.size() > strlen(NameTable[Idx]); 467 return IsPrefixMatch == isOverloaded(ID) ? ID : Intrinsic::not_intrinsic; 468 } 469 470 void Function::recalculateIntrinsicID() { 471 const ValueName *ValName = this->getValueName(); 472 if (!ValName || !isIntrinsic()) { 473 IntID = Intrinsic::not_intrinsic; 474 return; 475 } 476 IntID = lookupIntrinsicID(ValName); 477 } 478 479 /// Returns a stable mangling for the type specified for use in the name 480 /// mangling scheme used by 'any' types in intrinsic signatures. The mangling 481 /// of named types is simply their name. Manglings for unnamed types consist 482 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions) 483 /// combined with the mangling of their component types. A vararg function 484 /// type will have a suffix of 'vararg'. Since function types can contain 485 /// other function types, we close a function type mangling with suffix 'f' 486 /// which can't be confused with it's prefix. This ensures we don't have 487 /// collisions between two unrelated function types. Otherwise, you might 488 /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.) 489 /// Manglings of integers, floats, and vectors ('i', 'f', and 'v' prefix in most 490 /// cases) fall back to the MVT codepath, where they could be mangled to 491 /// 'x86mmx', for example; matching on derived types is not sufficient to mangle 492 /// everything. 493 static std::string getMangledTypeStr(Type* Ty) { 494 std::string Result; 495 if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) { 496 Result += "p" + llvm::utostr(PTyp->getAddressSpace()) + 497 getMangledTypeStr(PTyp->getElementType()); 498 } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) { 499 Result += "a" + llvm::utostr(ATyp->getNumElements()) + 500 getMangledTypeStr(ATyp->getElementType()); 501 } else if (StructType* STyp = dyn_cast<StructType>(Ty)) { 502 assert(!STyp->isLiteral() && "TODO: implement literal types"); 503 Result += STyp->getName(); 504 } else if (FunctionType* FT = dyn_cast<FunctionType>(Ty)) { 505 Result += "f_" + getMangledTypeStr(FT->getReturnType()); 506 for (size_t i = 0; i < FT->getNumParams(); i++) 507 Result += getMangledTypeStr(FT->getParamType(i)); 508 if (FT->isVarArg()) 509 Result += "vararg"; 510 // Ensure nested function types are distinguishable. 511 Result += "f"; 512 } else if (isa<VectorType>(Ty)) 513 Result += "v" + utostr(Ty->getVectorNumElements()) + 514 getMangledTypeStr(Ty->getVectorElementType()); 515 else if (Ty) 516 Result += EVT::getEVT(Ty).getEVTString(); 517 return Result; 518 } 519 520 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) { 521 assert(id < num_intrinsics && "Invalid intrinsic ID!"); 522 if (Tys.empty()) 523 return IntrinsicNameTable[id]; 524 std::string Result(IntrinsicNameTable[id]); 525 for (unsigned i = 0; i < Tys.size(); ++i) { 526 Result += "." + getMangledTypeStr(Tys[i]); 527 } 528 return Result; 529 } 530 531 532 /// IIT_Info - These are enumerators that describe the entries returned by the 533 /// getIntrinsicInfoTableEntries function. 534 /// 535 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter! 536 enum IIT_Info { 537 // Common values should be encoded with 0-15. 538 IIT_Done = 0, 539 IIT_I1 = 1, 540 IIT_I8 = 2, 541 IIT_I16 = 3, 542 IIT_I32 = 4, 543 IIT_I64 = 5, 544 IIT_F16 = 6, 545 IIT_F32 = 7, 546 IIT_F64 = 8, 547 IIT_V2 = 9, 548 IIT_V4 = 10, 549 IIT_V8 = 11, 550 IIT_V16 = 12, 551 IIT_V32 = 13, 552 IIT_PTR = 14, 553 IIT_ARG = 15, 554 555 // Values from 16+ are only encodable with the inefficient encoding. 556 IIT_V64 = 16, 557 IIT_MMX = 17, 558 IIT_TOKEN = 18, 559 IIT_METADATA = 19, 560 IIT_EMPTYSTRUCT = 20, 561 IIT_STRUCT2 = 21, 562 IIT_STRUCT3 = 22, 563 IIT_STRUCT4 = 23, 564 IIT_STRUCT5 = 24, 565 IIT_EXTEND_ARG = 25, 566 IIT_TRUNC_ARG = 26, 567 IIT_ANYPTR = 27, 568 IIT_V1 = 28, 569 IIT_VARARG = 29, 570 IIT_HALF_VEC_ARG = 30, 571 IIT_SAME_VEC_WIDTH_ARG = 31, 572 IIT_PTR_TO_ARG = 32, 573 IIT_VEC_OF_PTRS_TO_ELT = 33, 574 IIT_I128 = 34, 575 IIT_V512 = 35, 576 IIT_V1024 = 36 577 }; 578 579 580 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos, 581 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) { 582 IIT_Info Info = IIT_Info(Infos[NextElt++]); 583 unsigned StructElts = 2; 584 using namespace Intrinsic; 585 586 switch (Info) { 587 case IIT_Done: 588 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0)); 589 return; 590 case IIT_VARARG: 591 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0)); 592 return; 593 case IIT_MMX: 594 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0)); 595 return; 596 case IIT_TOKEN: 597 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0)); 598 return; 599 case IIT_METADATA: 600 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0)); 601 return; 602 case IIT_F16: 603 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0)); 604 return; 605 case IIT_F32: 606 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0)); 607 return; 608 case IIT_F64: 609 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0)); 610 return; 611 case IIT_I1: 612 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1)); 613 return; 614 case IIT_I8: 615 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8)); 616 return; 617 case IIT_I16: 618 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16)); 619 return; 620 case IIT_I32: 621 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32)); 622 return; 623 case IIT_I64: 624 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64)); 625 return; 626 case IIT_I128: 627 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128)); 628 return; 629 case IIT_V1: 630 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1)); 631 DecodeIITType(NextElt, Infos, OutputTable); 632 return; 633 case IIT_V2: 634 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2)); 635 DecodeIITType(NextElt, Infos, OutputTable); 636 return; 637 case IIT_V4: 638 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4)); 639 DecodeIITType(NextElt, Infos, OutputTable); 640 return; 641 case IIT_V8: 642 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8)); 643 DecodeIITType(NextElt, Infos, OutputTable); 644 return; 645 case IIT_V16: 646 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16)); 647 DecodeIITType(NextElt, Infos, OutputTable); 648 return; 649 case IIT_V32: 650 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32)); 651 DecodeIITType(NextElt, Infos, OutputTable); 652 return; 653 case IIT_V64: 654 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64)); 655 DecodeIITType(NextElt, Infos, OutputTable); 656 return; 657 case IIT_V512: 658 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 512)); 659 DecodeIITType(NextElt, Infos, OutputTable); 660 return; 661 case IIT_V1024: 662 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1024)); 663 DecodeIITType(NextElt, Infos, OutputTable); 664 return; 665 case IIT_PTR: 666 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0)); 667 DecodeIITType(NextElt, Infos, OutputTable); 668 return; 669 case IIT_ANYPTR: { // [ANYPTR addrspace, subtype] 670 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 671 Infos[NextElt++])); 672 DecodeIITType(NextElt, Infos, OutputTable); 673 return; 674 } 675 case IIT_ARG: { 676 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 677 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo)); 678 return; 679 } 680 case IIT_EXTEND_ARG: { 681 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 682 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument, 683 ArgInfo)); 684 return; 685 } 686 case IIT_TRUNC_ARG: { 687 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 688 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument, 689 ArgInfo)); 690 return; 691 } 692 case IIT_HALF_VEC_ARG: { 693 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 694 OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument, 695 ArgInfo)); 696 return; 697 } 698 case IIT_SAME_VEC_WIDTH_ARG: { 699 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 700 OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument, 701 ArgInfo)); 702 return; 703 } 704 case IIT_PTR_TO_ARG: { 705 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 706 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument, 707 ArgInfo)); 708 return; 709 } 710 case IIT_VEC_OF_PTRS_TO_ELT: { 711 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 712 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfPtrsToElt, 713 ArgInfo)); 714 return; 715 } 716 case IIT_EMPTYSTRUCT: 717 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0)); 718 return; 719 case IIT_STRUCT5: ++StructElts; // FALL THROUGH. 720 case IIT_STRUCT4: ++StructElts; // FALL THROUGH. 721 case IIT_STRUCT3: ++StructElts; // FALL THROUGH. 722 case IIT_STRUCT2: { 723 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts)); 724 725 for (unsigned i = 0; i != StructElts; ++i) 726 DecodeIITType(NextElt, Infos, OutputTable); 727 return; 728 } 729 } 730 llvm_unreachable("unhandled"); 731 } 732 733 734 #define GET_INTRINSIC_GENERATOR_GLOBAL 735 #include "llvm/IR/Intrinsics.gen" 736 #undef GET_INTRINSIC_GENERATOR_GLOBAL 737 738 void Intrinsic::getIntrinsicInfoTableEntries(ID id, 739 SmallVectorImpl<IITDescriptor> &T){ 740 // Check to see if the intrinsic's type was expressible by the table. 741 unsigned TableVal = IIT_Table[id-1]; 742 743 // Decode the TableVal into an array of IITValues. 744 SmallVector<unsigned char, 8> IITValues; 745 ArrayRef<unsigned char> IITEntries; 746 unsigned NextElt = 0; 747 if ((TableVal >> 31) != 0) { 748 // This is an offset into the IIT_LongEncodingTable. 749 IITEntries = IIT_LongEncodingTable; 750 751 // Strip sentinel bit. 752 NextElt = (TableVal << 1) >> 1; 753 } else { 754 // Decode the TableVal into an array of IITValues. If the entry was encoded 755 // into a single word in the table itself, decode it now. 756 do { 757 IITValues.push_back(TableVal & 0xF); 758 TableVal >>= 4; 759 } while (TableVal); 760 761 IITEntries = IITValues; 762 NextElt = 0; 763 } 764 765 // Okay, decode the table into the output vector of IITDescriptors. 766 DecodeIITType(NextElt, IITEntries, T); 767 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0) 768 DecodeIITType(NextElt, IITEntries, T); 769 } 770 771 772 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos, 773 ArrayRef<Type*> Tys, LLVMContext &Context) { 774 using namespace Intrinsic; 775 IITDescriptor D = Infos.front(); 776 Infos = Infos.slice(1); 777 778 switch (D.Kind) { 779 case IITDescriptor::Void: return Type::getVoidTy(Context); 780 case IITDescriptor::VarArg: return Type::getVoidTy(Context); 781 case IITDescriptor::MMX: return Type::getX86_MMXTy(Context); 782 case IITDescriptor::Token: return Type::getTokenTy(Context); 783 case IITDescriptor::Metadata: return Type::getMetadataTy(Context); 784 case IITDescriptor::Half: return Type::getHalfTy(Context); 785 case IITDescriptor::Float: return Type::getFloatTy(Context); 786 case IITDescriptor::Double: return Type::getDoubleTy(Context); 787 788 case IITDescriptor::Integer: 789 return IntegerType::get(Context, D.Integer_Width); 790 case IITDescriptor::Vector: 791 return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width); 792 case IITDescriptor::Pointer: 793 return PointerType::get(DecodeFixedType(Infos, Tys, Context), 794 D.Pointer_AddressSpace); 795 case IITDescriptor::Struct: { 796 Type *Elts[5]; 797 assert(D.Struct_NumElements <= 5 && "Can't handle this yet"); 798 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 799 Elts[i] = DecodeFixedType(Infos, Tys, Context); 800 return StructType::get(Context, makeArrayRef(Elts,D.Struct_NumElements)); 801 } 802 803 case IITDescriptor::Argument: 804 return Tys[D.getArgumentNumber()]; 805 case IITDescriptor::ExtendArgument: { 806 Type *Ty = Tys[D.getArgumentNumber()]; 807 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 808 return VectorType::getExtendedElementVectorType(VTy); 809 810 return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth()); 811 } 812 case IITDescriptor::TruncArgument: { 813 Type *Ty = Tys[D.getArgumentNumber()]; 814 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 815 return VectorType::getTruncatedElementVectorType(VTy); 816 817 IntegerType *ITy = cast<IntegerType>(Ty); 818 assert(ITy->getBitWidth() % 2 == 0); 819 return IntegerType::get(Context, ITy->getBitWidth() / 2); 820 } 821 case IITDescriptor::HalfVecArgument: 822 return VectorType::getHalfElementsVectorType(cast<VectorType>( 823 Tys[D.getArgumentNumber()])); 824 case IITDescriptor::SameVecWidthArgument: { 825 Type *EltTy = DecodeFixedType(Infos, Tys, Context); 826 Type *Ty = Tys[D.getArgumentNumber()]; 827 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 828 return VectorType::get(EltTy, VTy->getNumElements()); 829 } 830 llvm_unreachable("unhandled"); 831 } 832 case IITDescriptor::PtrToArgument: { 833 Type *Ty = Tys[D.getArgumentNumber()]; 834 return PointerType::getUnqual(Ty); 835 } 836 case IITDescriptor::VecOfPtrsToElt: { 837 Type *Ty = Tys[D.getArgumentNumber()]; 838 VectorType *VTy = dyn_cast<VectorType>(Ty); 839 if (!VTy) 840 llvm_unreachable("Expected an argument of Vector Type"); 841 Type *EltTy = VTy->getVectorElementType(); 842 return VectorType::get(PointerType::getUnqual(EltTy), 843 VTy->getNumElements()); 844 } 845 } 846 llvm_unreachable("unhandled"); 847 } 848 849 850 851 FunctionType *Intrinsic::getType(LLVMContext &Context, 852 ID id, ArrayRef<Type*> Tys) { 853 SmallVector<IITDescriptor, 8> Table; 854 getIntrinsicInfoTableEntries(id, Table); 855 856 ArrayRef<IITDescriptor> TableRef = Table; 857 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context); 858 859 SmallVector<Type*, 8> ArgTys; 860 while (!TableRef.empty()) 861 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context)); 862 863 // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg 864 // If we see void type as the type of the last argument, it is vararg intrinsic 865 if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) { 866 ArgTys.pop_back(); 867 return FunctionType::get(ResultTy, ArgTys, true); 868 } 869 return FunctionType::get(ResultTy, ArgTys, false); 870 } 871 872 bool Intrinsic::isOverloaded(ID id) { 873 #define GET_INTRINSIC_OVERLOAD_TABLE 874 #include "llvm/IR/Intrinsics.gen" 875 #undef GET_INTRINSIC_OVERLOAD_TABLE 876 } 877 878 bool Intrinsic::isLeaf(ID id) { 879 switch (id) { 880 default: 881 return true; 882 883 case Intrinsic::experimental_gc_statepoint: 884 case Intrinsic::experimental_patchpoint_void: 885 case Intrinsic::experimental_patchpoint_i64: 886 return false; 887 } 888 } 889 890 /// This defines the "Intrinsic::getAttributes(ID id)" method. 891 #define GET_INTRINSIC_ATTRIBUTES 892 #include "llvm/IR/Intrinsics.gen" 893 #undef GET_INTRINSIC_ATTRIBUTES 894 895 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) { 896 // There can never be multiple globals with the same name of different types, 897 // because intrinsics must be a specific type. 898 return 899 cast<Function>(M->getOrInsertFunction(getName(id, Tys), 900 getType(M->getContext(), id, Tys))); 901 } 902 903 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method. 904 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 905 #include "llvm/IR/Intrinsics.gen" 906 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 907 908 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method. 909 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 910 #include "llvm/IR/Intrinsics.gen" 911 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 912 913 /// hasAddressTaken - returns true if there are any uses of this function 914 /// other than direct calls or invokes to it. 915 bool Function::hasAddressTaken(const User* *PutOffender) const { 916 for (const Use &U : uses()) { 917 const User *FU = U.getUser(); 918 if (isa<BlockAddress>(FU)) 919 continue; 920 if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU)) { 921 if (PutOffender) 922 *PutOffender = FU; 923 return true; 924 } 925 ImmutableCallSite CS(cast<Instruction>(FU)); 926 if (!CS.isCallee(&U)) { 927 if (PutOffender) 928 *PutOffender = FU; 929 return true; 930 } 931 } 932 return false; 933 } 934 935 bool Function::isDefTriviallyDead() const { 936 // Check the linkage 937 if (!hasLinkOnceLinkage() && !hasLocalLinkage() && 938 !hasAvailableExternallyLinkage()) 939 return false; 940 941 // Check if the function is used by anything other than a blockaddress. 942 for (const User *U : users()) 943 if (!isa<BlockAddress>(U)) 944 return false; 945 946 return true; 947 } 948 949 /// callsFunctionThatReturnsTwice - Return true if the function has a call to 950 /// setjmp or other function that gcc recognizes as "returning twice". 951 bool Function::callsFunctionThatReturnsTwice() const { 952 for (const_inst_iterator 953 I = inst_begin(this), E = inst_end(this); I != E; ++I) { 954 ImmutableCallSite CS(&*I); 955 if (CS && CS.hasFnAttr(Attribute::ReturnsTwice)) 956 return true; 957 } 958 959 return false; 960 } 961 962 Constant *Function::getPersonalityFn() const { 963 assert(hasPersonalityFn() && getNumOperands()); 964 return cast<Constant>(Op<0>()); 965 } 966 967 void Function::setPersonalityFn(Constant *Fn) { 968 setHungoffOperand<0>(Fn); 969 setValueSubclassDataBit(3, Fn != nullptr); 970 } 971 972 Constant *Function::getPrefixData() const { 973 assert(hasPrefixData() && getNumOperands()); 974 return cast<Constant>(Op<1>()); 975 } 976 977 void Function::setPrefixData(Constant *PrefixData) { 978 setHungoffOperand<1>(PrefixData); 979 setValueSubclassDataBit(1, PrefixData != nullptr); 980 } 981 982 Constant *Function::getPrologueData() const { 983 assert(hasPrologueData() && getNumOperands()); 984 return cast<Constant>(Op<2>()); 985 } 986 987 void Function::setPrologueData(Constant *PrologueData) { 988 setHungoffOperand<2>(PrologueData); 989 setValueSubclassDataBit(2, PrologueData != nullptr); 990 } 991 992 void Function::allocHungoffUselist() { 993 // If we've already allocated a uselist, stop here. 994 if (getNumOperands()) 995 return; 996 997 allocHungoffUses(3, /*IsPhi=*/ false); 998 setNumHungOffUseOperands(3); 999 1000 // Initialize the uselist with placeholder operands to allow traversal. 1001 auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)); 1002 Op<0>().set(CPN); 1003 Op<1>().set(CPN); 1004 Op<2>().set(CPN); 1005 } 1006 1007 template <int Idx> 1008 void Function::setHungoffOperand(Constant *C) { 1009 if (C) { 1010 allocHungoffUselist(); 1011 Op<Idx>().set(C); 1012 } else if (getNumOperands()) { 1013 Op<Idx>().set( 1014 ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0))); 1015 } 1016 } 1017 1018 void Function::setValueSubclassDataBit(unsigned Bit, bool On) { 1019 assert(Bit < 16 && "SubclassData contains only 16 bits"); 1020 if (On) 1021 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit)); 1022 else 1023 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit)); 1024 } 1025 1026 void Function::setEntryCount(uint64_t Count) { 1027 MDBuilder MDB(getContext()); 1028 setMetadata(LLVMContext::MD_prof, MDB.createFunctionEntryCount(Count)); 1029 } 1030 1031 Optional<uint64_t> Function::getEntryCount() const { 1032 MDNode *MD = getMetadata(LLVMContext::MD_prof); 1033 if (MD && MD->getOperand(0)) 1034 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) 1035 if (MDS->getString().equals("function_entry_count")) { 1036 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1)); 1037 return CI->getValue().getZExtValue(); 1038 } 1039 return None; 1040 } 1041