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