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 assert(!STyp->isLiteral() && "TODO: implement literal types"); 510 Result += STyp->getName(); 511 } else if (FunctionType* FT = dyn_cast<FunctionType>(Ty)) { 512 Result += "f_" + getMangledTypeStr(FT->getReturnType()); 513 for (size_t i = 0; i < FT->getNumParams(); i++) 514 Result += getMangledTypeStr(FT->getParamType(i)); 515 if (FT->isVarArg()) 516 Result += "vararg"; 517 // Ensure nested function types are distinguishable. 518 Result += "f"; 519 } else if (isa<VectorType>(Ty)) 520 Result += "v" + utostr(Ty->getVectorNumElements()) + 521 getMangledTypeStr(Ty->getVectorElementType()); 522 else if (Ty) 523 Result += EVT::getEVT(Ty).getEVTString(); 524 return Result; 525 } 526 527 StringRef Intrinsic::getName(ID id) { 528 assert(id < num_intrinsics && "Invalid intrinsic ID!"); 529 assert(!isOverloaded(id) && 530 "This version of getName does not support overloading"); 531 return IntrinsicNameTable[id]; 532 } 533 534 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) { 535 assert(id < num_intrinsics && "Invalid intrinsic ID!"); 536 std::string Result(IntrinsicNameTable[id]); 537 for (Type *Ty : Tys) { 538 Result += "." + getMangledTypeStr(Ty); 539 } 540 return Result; 541 } 542 543 544 /// IIT_Info - These are enumerators that describe the entries returned by the 545 /// getIntrinsicInfoTableEntries function. 546 /// 547 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter! 548 enum IIT_Info { 549 // Common values should be encoded with 0-15. 550 IIT_Done = 0, 551 IIT_I1 = 1, 552 IIT_I8 = 2, 553 IIT_I16 = 3, 554 IIT_I32 = 4, 555 IIT_I64 = 5, 556 IIT_F16 = 6, 557 IIT_F32 = 7, 558 IIT_F64 = 8, 559 IIT_V2 = 9, 560 IIT_V4 = 10, 561 IIT_V8 = 11, 562 IIT_V16 = 12, 563 IIT_V32 = 13, 564 IIT_PTR = 14, 565 IIT_ARG = 15, 566 567 // Values from 16+ are only encodable with the inefficient encoding. 568 IIT_V64 = 16, 569 IIT_MMX = 17, 570 IIT_TOKEN = 18, 571 IIT_METADATA = 19, 572 IIT_EMPTYSTRUCT = 20, 573 IIT_STRUCT2 = 21, 574 IIT_STRUCT3 = 22, 575 IIT_STRUCT4 = 23, 576 IIT_STRUCT5 = 24, 577 IIT_EXTEND_ARG = 25, 578 IIT_TRUNC_ARG = 26, 579 IIT_ANYPTR = 27, 580 IIT_V1 = 28, 581 IIT_VARARG = 29, 582 IIT_HALF_VEC_ARG = 30, 583 IIT_SAME_VEC_WIDTH_ARG = 31, 584 IIT_PTR_TO_ARG = 32, 585 IIT_PTR_TO_ELT = 33, 586 IIT_VEC_OF_PTRS_TO_ELT = 34, 587 IIT_I128 = 35, 588 IIT_V512 = 36, 589 IIT_V1024 = 37 590 }; 591 592 593 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos, 594 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) { 595 IIT_Info Info = IIT_Info(Infos[NextElt++]); 596 unsigned StructElts = 2; 597 using namespace Intrinsic; 598 599 switch (Info) { 600 case IIT_Done: 601 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0)); 602 return; 603 case IIT_VARARG: 604 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0)); 605 return; 606 case IIT_MMX: 607 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0)); 608 return; 609 case IIT_TOKEN: 610 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0)); 611 return; 612 case IIT_METADATA: 613 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0)); 614 return; 615 case IIT_F16: 616 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0)); 617 return; 618 case IIT_F32: 619 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0)); 620 return; 621 case IIT_F64: 622 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0)); 623 return; 624 case IIT_I1: 625 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1)); 626 return; 627 case IIT_I8: 628 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8)); 629 return; 630 case IIT_I16: 631 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16)); 632 return; 633 case IIT_I32: 634 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32)); 635 return; 636 case IIT_I64: 637 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64)); 638 return; 639 case IIT_I128: 640 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128)); 641 return; 642 case IIT_V1: 643 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1)); 644 DecodeIITType(NextElt, Infos, OutputTable); 645 return; 646 case IIT_V2: 647 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2)); 648 DecodeIITType(NextElt, Infos, OutputTable); 649 return; 650 case IIT_V4: 651 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4)); 652 DecodeIITType(NextElt, Infos, OutputTable); 653 return; 654 case IIT_V8: 655 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8)); 656 DecodeIITType(NextElt, Infos, OutputTable); 657 return; 658 case IIT_V16: 659 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16)); 660 DecodeIITType(NextElt, Infos, OutputTable); 661 return; 662 case IIT_V32: 663 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32)); 664 DecodeIITType(NextElt, Infos, OutputTable); 665 return; 666 case IIT_V64: 667 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64)); 668 DecodeIITType(NextElt, Infos, OutputTable); 669 return; 670 case IIT_V512: 671 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 512)); 672 DecodeIITType(NextElt, Infos, OutputTable); 673 return; 674 case IIT_V1024: 675 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1024)); 676 DecodeIITType(NextElt, Infos, OutputTable); 677 return; 678 case IIT_PTR: 679 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0)); 680 DecodeIITType(NextElt, Infos, OutputTable); 681 return; 682 case IIT_ANYPTR: { // [ANYPTR addrspace, subtype] 683 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 684 Infos[NextElt++])); 685 DecodeIITType(NextElt, Infos, OutputTable); 686 return; 687 } 688 case IIT_ARG: { 689 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 690 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo)); 691 return; 692 } 693 case IIT_EXTEND_ARG: { 694 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 695 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument, 696 ArgInfo)); 697 return; 698 } 699 case IIT_TRUNC_ARG: { 700 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 701 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument, 702 ArgInfo)); 703 return; 704 } 705 case IIT_HALF_VEC_ARG: { 706 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 707 OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument, 708 ArgInfo)); 709 return; 710 } 711 case IIT_SAME_VEC_WIDTH_ARG: { 712 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 713 OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument, 714 ArgInfo)); 715 return; 716 } 717 case IIT_PTR_TO_ARG: { 718 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 719 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument, 720 ArgInfo)); 721 return; 722 } 723 case IIT_PTR_TO_ELT: { 724 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 725 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo)); 726 return; 727 } 728 case IIT_VEC_OF_PTRS_TO_ELT: { 729 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 730 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfPtrsToElt, 731 ArgInfo)); 732 return; 733 } 734 case IIT_EMPTYSTRUCT: 735 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0)); 736 return; 737 case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH; 738 case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH; 739 case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH; 740 case IIT_STRUCT2: { 741 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts)); 742 743 for (unsigned i = 0; i != StructElts; ++i) 744 DecodeIITType(NextElt, Infos, OutputTable); 745 return; 746 } 747 } 748 llvm_unreachable("unhandled"); 749 } 750 751 752 #define GET_INTRINSIC_GENERATOR_GLOBAL 753 #include "llvm/IR/Intrinsics.gen" 754 #undef GET_INTRINSIC_GENERATOR_GLOBAL 755 756 void Intrinsic::getIntrinsicInfoTableEntries(ID id, 757 SmallVectorImpl<IITDescriptor> &T){ 758 // Check to see if the intrinsic's type was expressible by the table. 759 unsigned TableVal = IIT_Table[id-1]; 760 761 // Decode the TableVal into an array of IITValues. 762 SmallVector<unsigned char, 8> IITValues; 763 ArrayRef<unsigned char> IITEntries; 764 unsigned NextElt = 0; 765 if ((TableVal >> 31) != 0) { 766 // This is an offset into the IIT_LongEncodingTable. 767 IITEntries = IIT_LongEncodingTable; 768 769 // Strip sentinel bit. 770 NextElt = (TableVal << 1) >> 1; 771 } else { 772 // Decode the TableVal into an array of IITValues. If the entry was encoded 773 // into a single word in the table itself, decode it now. 774 do { 775 IITValues.push_back(TableVal & 0xF); 776 TableVal >>= 4; 777 } while (TableVal); 778 779 IITEntries = IITValues; 780 NextElt = 0; 781 } 782 783 // Okay, decode the table into the output vector of IITDescriptors. 784 DecodeIITType(NextElt, IITEntries, T); 785 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0) 786 DecodeIITType(NextElt, IITEntries, T); 787 } 788 789 790 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos, 791 ArrayRef<Type*> Tys, LLVMContext &Context) { 792 using namespace Intrinsic; 793 IITDescriptor D = Infos.front(); 794 Infos = Infos.slice(1); 795 796 switch (D.Kind) { 797 case IITDescriptor::Void: return Type::getVoidTy(Context); 798 case IITDescriptor::VarArg: return Type::getVoidTy(Context); 799 case IITDescriptor::MMX: return Type::getX86_MMXTy(Context); 800 case IITDescriptor::Token: return Type::getTokenTy(Context); 801 case IITDescriptor::Metadata: return Type::getMetadataTy(Context); 802 case IITDescriptor::Half: return Type::getHalfTy(Context); 803 case IITDescriptor::Float: return Type::getFloatTy(Context); 804 case IITDescriptor::Double: return Type::getDoubleTy(Context); 805 806 case IITDescriptor::Integer: 807 return IntegerType::get(Context, D.Integer_Width); 808 case IITDescriptor::Vector: 809 return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width); 810 case IITDescriptor::Pointer: 811 return PointerType::get(DecodeFixedType(Infos, Tys, Context), 812 D.Pointer_AddressSpace); 813 case IITDescriptor::Struct: { 814 Type *Elts[5]; 815 assert(D.Struct_NumElements <= 5 && "Can't handle this yet"); 816 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 817 Elts[i] = DecodeFixedType(Infos, Tys, Context); 818 return StructType::get(Context, makeArrayRef(Elts,D.Struct_NumElements)); 819 } 820 821 case IITDescriptor::Argument: 822 return Tys[D.getArgumentNumber()]; 823 case IITDescriptor::ExtendArgument: { 824 Type *Ty = Tys[D.getArgumentNumber()]; 825 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 826 return VectorType::getExtendedElementVectorType(VTy); 827 828 return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth()); 829 } 830 case IITDescriptor::TruncArgument: { 831 Type *Ty = Tys[D.getArgumentNumber()]; 832 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 833 return VectorType::getTruncatedElementVectorType(VTy); 834 835 IntegerType *ITy = cast<IntegerType>(Ty); 836 assert(ITy->getBitWidth() % 2 == 0); 837 return IntegerType::get(Context, ITy->getBitWidth() / 2); 838 } 839 case IITDescriptor::HalfVecArgument: 840 return VectorType::getHalfElementsVectorType(cast<VectorType>( 841 Tys[D.getArgumentNumber()])); 842 case IITDescriptor::SameVecWidthArgument: { 843 Type *EltTy = DecodeFixedType(Infos, Tys, Context); 844 Type *Ty = Tys[D.getArgumentNumber()]; 845 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 846 return VectorType::get(EltTy, VTy->getNumElements()); 847 } 848 llvm_unreachable("unhandled"); 849 } 850 case IITDescriptor::PtrToArgument: { 851 Type *Ty = Tys[D.getArgumentNumber()]; 852 return PointerType::getUnqual(Ty); 853 } 854 case IITDescriptor::PtrToElt: { 855 Type *Ty = Tys[D.getArgumentNumber()]; 856 VectorType *VTy = dyn_cast<VectorType>(Ty); 857 if (!VTy) 858 llvm_unreachable("Expected an argument of Vector Type"); 859 Type *EltTy = VTy->getVectorElementType(); 860 return PointerType::getUnqual(EltTy); 861 } 862 case IITDescriptor::VecOfPtrsToElt: { 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 VectorType::get(PointerType::getUnqual(EltTy), 869 VTy->getNumElements()); 870 } 871 } 872 llvm_unreachable("unhandled"); 873 } 874 875 876 877 FunctionType *Intrinsic::getType(LLVMContext &Context, 878 ID id, ArrayRef<Type*> Tys) { 879 SmallVector<IITDescriptor, 8> Table; 880 getIntrinsicInfoTableEntries(id, Table); 881 882 ArrayRef<IITDescriptor> TableRef = Table; 883 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context); 884 885 SmallVector<Type*, 8> ArgTys; 886 while (!TableRef.empty()) 887 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context)); 888 889 // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg 890 // If we see void type as the type of the last argument, it is vararg intrinsic 891 if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) { 892 ArgTys.pop_back(); 893 return FunctionType::get(ResultTy, ArgTys, true); 894 } 895 return FunctionType::get(ResultTy, ArgTys, false); 896 } 897 898 bool Intrinsic::isOverloaded(ID id) { 899 #define GET_INTRINSIC_OVERLOAD_TABLE 900 #include "llvm/IR/Intrinsics.gen" 901 #undef GET_INTRINSIC_OVERLOAD_TABLE 902 } 903 904 bool Intrinsic::isLeaf(ID id) { 905 switch (id) { 906 default: 907 return true; 908 909 case Intrinsic::experimental_gc_statepoint: 910 case Intrinsic::experimental_patchpoint_void: 911 case Intrinsic::experimental_patchpoint_i64: 912 return false; 913 } 914 } 915 916 /// This defines the "Intrinsic::getAttributes(ID id)" method. 917 #define GET_INTRINSIC_ATTRIBUTES 918 #include "llvm/IR/Intrinsics.gen" 919 #undef GET_INTRINSIC_ATTRIBUTES 920 921 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) { 922 // There can never be multiple globals with the same name of different types, 923 // because intrinsics must be a specific type. 924 return 925 cast<Function>(M->getOrInsertFunction(getName(id, Tys), 926 getType(M->getContext(), id, Tys))); 927 } 928 929 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method. 930 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 931 #include "llvm/IR/Intrinsics.gen" 932 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 933 934 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method. 935 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 936 #include "llvm/IR/Intrinsics.gen" 937 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 938 939 bool Intrinsic::matchIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos, 940 SmallVectorImpl<Type*> &ArgTys) { 941 using namespace Intrinsic; 942 943 // If we ran out of descriptors, there are too many arguments. 944 if (Infos.empty()) return true; 945 IITDescriptor D = Infos.front(); 946 Infos = Infos.slice(1); 947 948 switch (D.Kind) { 949 case IITDescriptor::Void: return !Ty->isVoidTy(); 950 case IITDescriptor::VarArg: return true; 951 case IITDescriptor::MMX: return !Ty->isX86_MMXTy(); 952 case IITDescriptor::Token: return !Ty->isTokenTy(); 953 case IITDescriptor::Metadata: return !Ty->isMetadataTy(); 954 case IITDescriptor::Half: return !Ty->isHalfTy(); 955 case IITDescriptor::Float: return !Ty->isFloatTy(); 956 case IITDescriptor::Double: return !Ty->isDoubleTy(); 957 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width); 958 case IITDescriptor::Vector: { 959 VectorType *VT = dyn_cast<VectorType>(Ty); 960 return !VT || VT->getNumElements() != D.Vector_Width || 961 matchIntrinsicType(VT->getElementType(), Infos, ArgTys); 962 } 963 case IITDescriptor::Pointer: { 964 PointerType *PT = dyn_cast<PointerType>(Ty); 965 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace || 966 matchIntrinsicType(PT->getElementType(), Infos, ArgTys); 967 } 968 969 case IITDescriptor::Struct: { 970 StructType *ST = dyn_cast<StructType>(Ty); 971 if (!ST || ST->getNumElements() != D.Struct_NumElements) 972 return true; 973 974 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 975 if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys)) 976 return true; 977 return false; 978 } 979 980 case IITDescriptor::Argument: 981 // Two cases here - If this is the second occurrence of an argument, verify 982 // that the later instance matches the previous instance. 983 if (D.getArgumentNumber() < ArgTys.size()) 984 return Ty != ArgTys[D.getArgumentNumber()]; 985 986 // Otherwise, if this is the first instance of an argument, record it and 987 // verify the "Any" kind. 988 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error"); 989 ArgTys.push_back(Ty); 990 991 switch (D.getArgumentKind()) { 992 case IITDescriptor::AK_Any: return false; // Success 993 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy(); 994 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy(); 995 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty); 996 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty); 997 } 998 llvm_unreachable("all argument kinds not covered"); 999 1000 case IITDescriptor::ExtendArgument: { 1001 // This may only be used when referring to a previous vector argument. 1002 if (D.getArgumentNumber() >= ArgTys.size()) 1003 return true; 1004 1005 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1006 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 1007 NewTy = VectorType::getExtendedElementVectorType(VTy); 1008 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 1009 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth()); 1010 else 1011 return true; 1012 1013 return Ty != NewTy; 1014 } 1015 case IITDescriptor::TruncArgument: { 1016 // This may only be used when referring to a previous vector argument. 1017 if (D.getArgumentNumber() >= ArgTys.size()) 1018 return true; 1019 1020 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1021 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 1022 NewTy = VectorType::getTruncatedElementVectorType(VTy); 1023 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 1024 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2); 1025 else 1026 return true; 1027 1028 return Ty != NewTy; 1029 } 1030 case IITDescriptor::HalfVecArgument: 1031 // This may only be used when referring to a previous vector argument. 1032 return D.getArgumentNumber() >= ArgTys.size() || 1033 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) || 1034 VectorType::getHalfElementsVectorType( 1035 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty; 1036 case IITDescriptor::SameVecWidthArgument: { 1037 if (D.getArgumentNumber() >= ArgTys.size()) 1038 return true; 1039 VectorType * ReferenceType = 1040 dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1041 VectorType *ThisArgType = dyn_cast<VectorType>(Ty); 1042 if (!ThisArgType || !ReferenceType || 1043 (ReferenceType->getVectorNumElements() != 1044 ThisArgType->getVectorNumElements())) 1045 return true; 1046 return matchIntrinsicType(ThisArgType->getVectorElementType(), 1047 Infos, ArgTys); 1048 } 1049 case IITDescriptor::PtrToArgument: { 1050 if (D.getArgumentNumber() >= ArgTys.size()) 1051 return true; 1052 Type * ReferenceType = ArgTys[D.getArgumentNumber()]; 1053 PointerType *ThisArgType = dyn_cast<PointerType>(Ty); 1054 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType); 1055 } 1056 case IITDescriptor::PtrToElt: { 1057 if (D.getArgumentNumber() >= ArgTys.size()) 1058 return true; 1059 VectorType * ReferenceType = 1060 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]); 1061 PointerType *ThisArgType = dyn_cast<PointerType>(Ty); 1062 1063 return (!ThisArgType || !ReferenceType || 1064 ThisArgType->getElementType() != ReferenceType->getElementType()); 1065 } 1066 case IITDescriptor::VecOfPtrsToElt: { 1067 if (D.getArgumentNumber() >= ArgTys.size()) 1068 return true; 1069 VectorType * ReferenceType = 1070 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]); 1071 VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty); 1072 if (!ThisArgVecTy || !ReferenceType || 1073 (ReferenceType->getVectorNumElements() != 1074 ThisArgVecTy->getVectorNumElements())) 1075 return true; 1076 PointerType *ThisArgEltTy = 1077 dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType()); 1078 if (!ThisArgEltTy) 1079 return true; 1080 return ThisArgEltTy->getElementType() != 1081 ReferenceType->getVectorElementType(); 1082 } 1083 } 1084 llvm_unreachable("unhandled"); 1085 } 1086 1087 bool 1088 Intrinsic::matchIntrinsicVarArg(bool isVarArg, 1089 ArrayRef<Intrinsic::IITDescriptor> &Infos) { 1090 // If there are no descriptors left, then it can't be a vararg. 1091 if (Infos.empty()) 1092 return isVarArg; 1093 1094 // There should be only one descriptor remaining at this point. 1095 if (Infos.size() != 1) 1096 return true; 1097 1098 // Check and verify the descriptor. 1099 IITDescriptor D = Infos.front(); 1100 Infos = Infos.slice(1); 1101 if (D.Kind == IITDescriptor::VarArg) 1102 return !isVarArg; 1103 1104 return true; 1105 } 1106 1107 Optional<Function*> Intrinsic::remangleIntrinsicFunction(Function *F) { 1108 Intrinsic::ID ID = F->getIntrinsicID(); 1109 if (!ID) 1110 return None; 1111 1112 FunctionType *FTy = F->getFunctionType(); 1113 // Accumulate an array of overloaded types for the given intrinsic 1114 SmallVector<Type *, 4> ArgTys; 1115 { 1116 SmallVector<Intrinsic::IITDescriptor, 8> Table; 1117 getIntrinsicInfoTableEntries(ID, Table); 1118 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table; 1119 1120 // If we encounter any problems matching the signature with the descriptor 1121 // just give up remangling. It's up to verifier to report the discrepancy. 1122 if (Intrinsic::matchIntrinsicType(FTy->getReturnType(), TableRef, ArgTys)) 1123 return None; 1124 for (auto Ty : FTy->params()) 1125 if (Intrinsic::matchIntrinsicType(Ty, TableRef, ArgTys)) 1126 return None; 1127 if (Intrinsic::matchIntrinsicVarArg(FTy->isVarArg(), TableRef)) 1128 return None; 1129 } 1130 1131 StringRef Name = F->getName(); 1132 if (Name == Intrinsic::getName(ID, ArgTys)) 1133 return None; 1134 1135 auto NewDecl = Intrinsic::getDeclaration(F->getParent(), ID, ArgTys); 1136 NewDecl->setCallingConv(F->getCallingConv()); 1137 assert(NewDecl->getFunctionType() == FTy && "Shouldn't change the signature"); 1138 return NewDecl; 1139 } 1140 1141 /// hasAddressTaken - returns true if there are any uses of this function 1142 /// other than direct calls or invokes to it. 1143 bool Function::hasAddressTaken(const User* *PutOffender) const { 1144 for (const Use &U : uses()) { 1145 const User *FU = U.getUser(); 1146 if (isa<BlockAddress>(FU)) 1147 continue; 1148 if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU)) { 1149 if (PutOffender) 1150 *PutOffender = FU; 1151 return true; 1152 } 1153 ImmutableCallSite CS(cast<Instruction>(FU)); 1154 if (!CS.isCallee(&U)) { 1155 if (PutOffender) 1156 *PutOffender = FU; 1157 return true; 1158 } 1159 } 1160 return false; 1161 } 1162 1163 bool Function::isDefTriviallyDead() const { 1164 // Check the linkage 1165 if (!hasLinkOnceLinkage() && !hasLocalLinkage() && 1166 !hasAvailableExternallyLinkage()) 1167 return false; 1168 1169 // Check if the function is used by anything other than a blockaddress. 1170 for (const User *U : users()) 1171 if (!isa<BlockAddress>(U)) 1172 return false; 1173 1174 return true; 1175 } 1176 1177 /// callsFunctionThatReturnsTwice - Return true if the function has a call to 1178 /// setjmp or other function that gcc recognizes as "returning twice". 1179 bool Function::callsFunctionThatReturnsTwice() const { 1180 for (const_inst_iterator 1181 I = inst_begin(this), E = inst_end(this); I != E; ++I) { 1182 ImmutableCallSite CS(&*I); 1183 if (CS && CS.hasFnAttr(Attribute::ReturnsTwice)) 1184 return true; 1185 } 1186 1187 return false; 1188 } 1189 1190 Constant *Function::getPersonalityFn() const { 1191 assert(hasPersonalityFn() && getNumOperands()); 1192 return cast<Constant>(Op<0>()); 1193 } 1194 1195 void Function::setPersonalityFn(Constant *Fn) { 1196 setHungoffOperand<0>(Fn); 1197 setValueSubclassDataBit(3, Fn != nullptr); 1198 } 1199 1200 Constant *Function::getPrefixData() const { 1201 assert(hasPrefixData() && getNumOperands()); 1202 return cast<Constant>(Op<1>()); 1203 } 1204 1205 void Function::setPrefixData(Constant *PrefixData) { 1206 setHungoffOperand<1>(PrefixData); 1207 setValueSubclassDataBit(1, PrefixData != nullptr); 1208 } 1209 1210 Constant *Function::getPrologueData() const { 1211 assert(hasPrologueData() && getNumOperands()); 1212 return cast<Constant>(Op<2>()); 1213 } 1214 1215 void Function::setPrologueData(Constant *PrologueData) { 1216 setHungoffOperand<2>(PrologueData); 1217 setValueSubclassDataBit(2, PrologueData != nullptr); 1218 } 1219 1220 void Function::allocHungoffUselist() { 1221 // If we've already allocated a uselist, stop here. 1222 if (getNumOperands()) 1223 return; 1224 1225 allocHungoffUses(3, /*IsPhi=*/ false); 1226 setNumHungOffUseOperands(3); 1227 1228 // Initialize the uselist with placeholder operands to allow traversal. 1229 auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)); 1230 Op<0>().set(CPN); 1231 Op<1>().set(CPN); 1232 Op<2>().set(CPN); 1233 } 1234 1235 template <int Idx> 1236 void Function::setHungoffOperand(Constant *C) { 1237 if (C) { 1238 allocHungoffUselist(); 1239 Op<Idx>().set(C); 1240 } else if (getNumOperands()) { 1241 Op<Idx>().set( 1242 ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0))); 1243 } 1244 } 1245 1246 void Function::setValueSubclassDataBit(unsigned Bit, bool On) { 1247 assert(Bit < 16 && "SubclassData contains only 16 bits"); 1248 if (On) 1249 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit)); 1250 else 1251 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit)); 1252 } 1253 1254 void Function::setEntryCount(uint64_t Count) { 1255 MDBuilder MDB(getContext()); 1256 setMetadata(LLVMContext::MD_prof, MDB.createFunctionEntryCount(Count)); 1257 } 1258 1259 Optional<uint64_t> Function::getEntryCount() const { 1260 MDNode *MD = getMetadata(LLVMContext::MD_prof); 1261 if (MD && MD->getOperand(0)) 1262 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) 1263 if (MDS->getString().equals("function_entry_count")) { 1264 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1)); 1265 uint64_t Count = CI->getValue().getZExtValue(); 1266 if (Count == 0) 1267 return None; 1268 return Count; 1269 } 1270 return None; 1271 } 1272 1273 void Function::setSectionPrefix(StringRef Prefix) { 1274 MDBuilder MDB(getContext()); 1275 setMetadata(LLVMContext::MD_section_prefix, 1276 MDB.createFunctionSectionPrefix(Prefix)); 1277 } 1278 1279 Optional<StringRef> Function::getSectionPrefix() const { 1280 if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) { 1281 assert(dyn_cast<MDString>(MD->getOperand(0)) 1282 ->getString() 1283 .equals("function_section_prefix") && 1284 "Metadata not match"); 1285 return dyn_cast<MDString>(MD->getOperand(1))->getString(); 1286 } 1287 return None; 1288 } 1289