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