1 //===- Function.cpp - Implement the Global object classes -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Function class for the IR library. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/IR/Function.h" 14 #include "SymbolTableListTraitsImpl.h" 15 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/DenseSet.h" 17 #include "llvm/ADT/None.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallString.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/StringExtras.h" 22 #include "llvm/ADT/StringRef.h" 23 #include "llvm/IR/AbstractCallSite.h" 24 #include "llvm/IR/Argument.h" 25 #include "llvm/IR/Attributes.h" 26 #include "llvm/IR/BasicBlock.h" 27 #include "llvm/IR/Constant.h" 28 #include "llvm/IR/Constants.h" 29 #include "llvm/IR/DerivedTypes.h" 30 #include "llvm/IR/GlobalValue.h" 31 #include "llvm/IR/InstIterator.h" 32 #include "llvm/IR/Instruction.h" 33 #include "llvm/IR/Instructions.h" 34 #include "llvm/IR/Intrinsics.h" 35 #include "llvm/IR/IntrinsicsAArch64.h" 36 #include "llvm/IR/IntrinsicsAMDGPU.h" 37 #include "llvm/IR/IntrinsicsARM.h" 38 #include "llvm/IR/IntrinsicsBPF.h" 39 #include "llvm/IR/IntrinsicsHexagon.h" 40 #include "llvm/IR/IntrinsicsMips.h" 41 #include "llvm/IR/IntrinsicsNVPTX.h" 42 #include "llvm/IR/IntrinsicsPowerPC.h" 43 #include "llvm/IR/IntrinsicsR600.h" 44 #include "llvm/IR/IntrinsicsRISCV.h" 45 #include "llvm/IR/IntrinsicsS390.h" 46 #include "llvm/IR/IntrinsicsWebAssembly.h" 47 #include "llvm/IR/IntrinsicsX86.h" 48 #include "llvm/IR/IntrinsicsXCore.h" 49 #include "llvm/IR/LLVMContext.h" 50 #include "llvm/IR/MDBuilder.h" 51 #include "llvm/IR/Metadata.h" 52 #include "llvm/IR/Module.h" 53 #include "llvm/IR/SymbolTableListTraits.h" 54 #include "llvm/IR/Type.h" 55 #include "llvm/IR/Use.h" 56 #include "llvm/IR/User.h" 57 #include "llvm/IR/Value.h" 58 #include "llvm/IR/ValueSymbolTable.h" 59 #include "llvm/Support/Casting.h" 60 #include "llvm/Support/Compiler.h" 61 #include "llvm/Support/ErrorHandling.h" 62 #include <algorithm> 63 #include <cassert> 64 #include <cstddef> 65 #include <cstdint> 66 #include <cstring> 67 #include <string> 68 69 using namespace llvm; 70 using ProfileCount = Function::ProfileCount; 71 72 // Explicit instantiations of SymbolTableListTraits since some of the methods 73 // are not in the public header file... 74 template class llvm::SymbolTableListTraits<BasicBlock>; 75 76 //===----------------------------------------------------------------------===// 77 // Argument Implementation 78 //===----------------------------------------------------------------------===// 79 80 Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo) 81 : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) { 82 setName(Name); 83 } 84 85 void Argument::setParent(Function *parent) { 86 Parent = parent; 87 } 88 89 bool Argument::hasNonNullAttr() const { 90 if (!getType()->isPointerTy()) return false; 91 if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull)) 92 return true; 93 else if (getDereferenceableBytes() > 0 && 94 !NullPointerIsDefined(getParent(), 95 getType()->getPointerAddressSpace())) 96 return true; 97 return false; 98 } 99 100 bool Argument::hasByValAttr() const { 101 if (!getType()->isPointerTy()) return false; 102 return hasAttribute(Attribute::ByVal); 103 } 104 105 bool Argument::hasByRefAttr() const { 106 if (!getType()->isPointerTy()) 107 return false; 108 return hasAttribute(Attribute::ByRef); 109 } 110 111 bool Argument::hasSwiftSelfAttr() const { 112 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf); 113 } 114 115 bool Argument::hasSwiftErrorAttr() const { 116 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError); 117 } 118 119 bool Argument::hasInAllocaAttr() const { 120 if (!getType()->isPointerTy()) return false; 121 return hasAttribute(Attribute::InAlloca); 122 } 123 124 bool Argument::hasPreallocatedAttr() const { 125 if (!getType()->isPointerTy()) 126 return false; 127 return hasAttribute(Attribute::Preallocated); 128 } 129 130 bool Argument::hasPassPointeeByValueCopyAttr() const { 131 if (!getType()->isPointerTy()) return false; 132 AttributeList Attrs = getParent()->getAttributes(); 133 return Attrs.hasParamAttribute(getArgNo(), Attribute::ByVal) || 134 Attrs.hasParamAttribute(getArgNo(), Attribute::InAlloca) || 135 Attrs.hasParamAttribute(getArgNo(), Attribute::Preallocated); 136 } 137 138 bool Argument::hasPointeeInMemoryValueAttr() const { 139 if (!getType()->isPointerTy()) 140 return false; 141 AttributeList Attrs = getParent()->getAttributes(); 142 return Attrs.hasParamAttribute(getArgNo(), Attribute::ByVal) || 143 Attrs.hasParamAttribute(getArgNo(), Attribute::InAlloca) || 144 Attrs.hasParamAttribute(getArgNo(), Attribute::Preallocated) || 145 Attrs.hasParamAttribute(getArgNo(), Attribute::ByRef); 146 } 147 148 /// For a byval, inalloca, or preallocated parameter, get the in-memory 149 /// parameter type. 150 static Type *getMemoryParamAllocType(AttributeSet ParamAttrs, Type *ArgTy) { 151 // FIXME: All the type carrying attributes are mutually exclusive, so there 152 // should be a single query to get the stored type that handles any of them. 153 if (Type *ByValTy = ParamAttrs.getByValType()) 154 return ByValTy; 155 if (Type *ByRefTy = ParamAttrs.getByRefType()) 156 return ByRefTy; 157 if (Type *PreAllocTy = ParamAttrs.getPreallocatedType()) 158 return PreAllocTy; 159 160 // FIXME: inalloca always depends on pointee element type. It's also possible 161 // for byval to miss it. 162 if (ParamAttrs.hasAttribute(Attribute::InAlloca) || 163 ParamAttrs.hasAttribute(Attribute::ByVal) || 164 ParamAttrs.hasAttribute(Attribute::Preallocated)) 165 return cast<PointerType>(ArgTy)->getElementType(); 166 167 return nullptr; 168 } 169 170 uint64_t Argument::getPassPointeeByValueCopySize(const DataLayout &DL) const { 171 AttributeSet ParamAttrs = 172 getParent()->getAttributes().getParamAttributes(getArgNo()); 173 if (Type *MemTy = getMemoryParamAllocType(ParamAttrs, getType())) 174 return DL.getTypeAllocSize(MemTy); 175 return 0; 176 } 177 178 Type *Argument::getPointeeInMemoryValueType() const { 179 AttributeSet ParamAttrs = 180 getParent()->getAttributes().getParamAttributes(getArgNo()); 181 return getMemoryParamAllocType(ParamAttrs, getType()); 182 } 183 184 unsigned Argument::getParamAlignment() const { 185 assert(getType()->isPointerTy() && "Only pointers have alignments"); 186 return getParent()->getParamAlignment(getArgNo()); 187 } 188 189 MaybeAlign Argument::getParamAlign() const { 190 assert(getType()->isPointerTy() && "Only pointers have alignments"); 191 return getParent()->getParamAlign(getArgNo()); 192 } 193 194 Type *Argument::getParamByValType() const { 195 assert(getType()->isPointerTy() && "Only pointers have byval types"); 196 return getParent()->getParamByValType(getArgNo()); 197 } 198 199 Type *Argument::getParamByRefType() const { 200 assert(getType()->isPointerTy() && "Only pointers have byval types"); 201 return getParent()->getParamByRefType(getArgNo()); 202 } 203 204 uint64_t Argument::getDereferenceableBytes() const { 205 assert(getType()->isPointerTy() && 206 "Only pointers have dereferenceable bytes"); 207 return getParent()->getParamDereferenceableBytes(getArgNo()); 208 } 209 210 uint64_t Argument::getDereferenceableOrNullBytes() const { 211 assert(getType()->isPointerTy() && 212 "Only pointers have dereferenceable bytes"); 213 return getParent()->getParamDereferenceableOrNullBytes(getArgNo()); 214 } 215 216 bool Argument::hasNestAttr() const { 217 if (!getType()->isPointerTy()) return false; 218 return hasAttribute(Attribute::Nest); 219 } 220 221 bool Argument::hasNoAliasAttr() const { 222 if (!getType()->isPointerTy()) return false; 223 return hasAttribute(Attribute::NoAlias); 224 } 225 226 bool Argument::hasNoCaptureAttr() const { 227 if (!getType()->isPointerTy()) return false; 228 return hasAttribute(Attribute::NoCapture); 229 } 230 231 bool Argument::hasStructRetAttr() const { 232 if (!getType()->isPointerTy()) return false; 233 return hasAttribute(Attribute::StructRet); 234 } 235 236 bool Argument::hasInRegAttr() const { 237 return hasAttribute(Attribute::InReg); 238 } 239 240 bool Argument::hasReturnedAttr() const { 241 return hasAttribute(Attribute::Returned); 242 } 243 244 bool Argument::hasZExtAttr() const { 245 return hasAttribute(Attribute::ZExt); 246 } 247 248 bool Argument::hasSExtAttr() const { 249 return hasAttribute(Attribute::SExt); 250 } 251 252 bool Argument::onlyReadsMemory() const { 253 AttributeList Attrs = getParent()->getAttributes(); 254 return Attrs.hasParamAttribute(getArgNo(), Attribute::ReadOnly) || 255 Attrs.hasParamAttribute(getArgNo(), Attribute::ReadNone); 256 } 257 258 void Argument::addAttrs(AttrBuilder &B) { 259 AttributeList AL = getParent()->getAttributes(); 260 AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B); 261 getParent()->setAttributes(AL); 262 } 263 264 void Argument::addAttr(Attribute::AttrKind Kind) { 265 getParent()->addParamAttr(getArgNo(), Kind); 266 } 267 268 void Argument::addAttr(Attribute Attr) { 269 getParent()->addParamAttr(getArgNo(), Attr); 270 } 271 272 void Argument::removeAttr(Attribute::AttrKind Kind) { 273 getParent()->removeParamAttr(getArgNo(), Kind); 274 } 275 276 bool Argument::hasAttribute(Attribute::AttrKind Kind) const { 277 return getParent()->hasParamAttribute(getArgNo(), Kind); 278 } 279 280 Attribute Argument::getAttribute(Attribute::AttrKind Kind) const { 281 return getParent()->getParamAttribute(getArgNo(), Kind); 282 } 283 284 //===----------------------------------------------------------------------===// 285 // Helper Methods in Function 286 //===----------------------------------------------------------------------===// 287 288 LLVMContext &Function::getContext() const { 289 return getType()->getContext(); 290 } 291 292 unsigned Function::getInstructionCount() const { 293 unsigned NumInstrs = 0; 294 for (const BasicBlock &BB : BasicBlocks) 295 NumInstrs += std::distance(BB.instructionsWithoutDebug().begin(), 296 BB.instructionsWithoutDebug().end()); 297 return NumInstrs; 298 } 299 300 Function *Function::Create(FunctionType *Ty, LinkageTypes Linkage, 301 const Twine &N, Module &M) { 302 return Create(Ty, Linkage, M.getDataLayout().getProgramAddressSpace(), N, &M); 303 } 304 305 void Function::removeFromParent() { 306 getParent()->getFunctionList().remove(getIterator()); 307 } 308 309 void Function::eraseFromParent() { 310 getParent()->getFunctionList().erase(getIterator()); 311 } 312 313 //===----------------------------------------------------------------------===// 314 // Function Implementation 315 //===----------------------------------------------------------------------===// 316 317 static unsigned computeAddrSpace(unsigned AddrSpace, Module *M) { 318 // If AS == -1 and we are passed a valid module pointer we place the function 319 // in the program address space. Otherwise we default to AS0. 320 if (AddrSpace == static_cast<unsigned>(-1)) 321 return M ? M->getDataLayout().getProgramAddressSpace() : 0; 322 return AddrSpace; 323 } 324 325 Function::Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, 326 const Twine &name, Module *ParentModule) 327 : GlobalObject(Ty, Value::FunctionVal, 328 OperandTraits<Function>::op_begin(this), 0, Linkage, name, 329 computeAddrSpace(AddrSpace, ParentModule)), 330 NumArgs(Ty->getNumParams()) { 331 assert(FunctionType::isValidReturnType(getReturnType()) && 332 "invalid return type"); 333 setGlobalObjectSubClassData(0); 334 335 // We only need a symbol table for a function if the context keeps value names 336 if (!getContext().shouldDiscardValueNames()) 337 SymTab = std::make_unique<ValueSymbolTable>(); 338 339 // If the function has arguments, mark them as lazily built. 340 if (Ty->getNumParams()) 341 setValueSubclassData(1); // Set the "has lazy arguments" bit. 342 343 if (ParentModule) 344 ParentModule->getFunctionList().push_back(this); 345 346 HasLLVMReservedName = getName().startswith("llvm."); 347 // Ensure intrinsics have the right parameter attributes. 348 // Note, the IntID field will have been set in Value::setName if this function 349 // name is a valid intrinsic ID. 350 if (IntID) 351 setAttributes(Intrinsic::getAttributes(getContext(), IntID)); 352 } 353 354 Function::~Function() { 355 dropAllReferences(); // After this it is safe to delete instructions. 356 357 // Delete all of the method arguments and unlink from symbol table... 358 if (Arguments) 359 clearArguments(); 360 361 // Remove the function from the on-the-side GC table. 362 clearGC(); 363 } 364 365 void Function::BuildLazyArguments() const { 366 // Create the arguments vector, all arguments start out unnamed. 367 auto *FT = getFunctionType(); 368 if (NumArgs > 0) { 369 Arguments = std::allocator<Argument>().allocate(NumArgs); 370 for (unsigned i = 0, e = NumArgs; i != e; ++i) { 371 Type *ArgTy = FT->getParamType(i); 372 assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!"); 373 new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i); 374 } 375 } 376 377 // Clear the lazy arguments bit. 378 unsigned SDC = getSubclassDataFromValue(); 379 SDC &= ~(1 << 0); 380 const_cast<Function*>(this)->setValueSubclassData(SDC); 381 assert(!hasLazyArguments()); 382 } 383 384 static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) { 385 return MutableArrayRef<Argument>(Args, Count); 386 } 387 388 bool Function::isConstrainedFPIntrinsic() const { 389 switch (getIntrinsicID()) { 390 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 391 case Intrinsic::INTRINSIC: 392 #include "llvm/IR/ConstrainedOps.def" 393 return true; 394 #undef INSTRUCTION 395 default: 396 return false; 397 } 398 } 399 400 void Function::clearArguments() { 401 for (Argument &A : makeArgArray(Arguments, NumArgs)) { 402 A.setName(""); 403 A.~Argument(); 404 } 405 std::allocator<Argument>().deallocate(Arguments, NumArgs); 406 Arguments = nullptr; 407 } 408 409 void Function::stealArgumentListFrom(Function &Src) { 410 assert(isDeclaration() && "Expected no references to current arguments"); 411 412 // Drop the current arguments, if any, and set the lazy argument bit. 413 if (!hasLazyArguments()) { 414 assert(llvm::all_of(makeArgArray(Arguments, NumArgs), 415 [](const Argument &A) { return A.use_empty(); }) && 416 "Expected arguments to be unused in declaration"); 417 clearArguments(); 418 setValueSubclassData(getSubclassDataFromValue() | (1 << 0)); 419 } 420 421 // Nothing to steal if Src has lazy arguments. 422 if (Src.hasLazyArguments()) 423 return; 424 425 // Steal arguments from Src, and fix the lazy argument bits. 426 assert(arg_size() == Src.arg_size()); 427 Arguments = Src.Arguments; 428 Src.Arguments = nullptr; 429 for (Argument &A : makeArgArray(Arguments, NumArgs)) { 430 // FIXME: This does the work of transferNodesFromList inefficiently. 431 SmallString<128> Name; 432 if (A.hasName()) 433 Name = A.getName(); 434 if (!Name.empty()) 435 A.setName(""); 436 A.setParent(this); 437 if (!Name.empty()) 438 A.setName(Name); 439 } 440 441 setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0)); 442 assert(!hasLazyArguments()); 443 Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0)); 444 } 445 446 // dropAllReferences() - This function causes all the subinstructions to "let 447 // go" of all references that they are maintaining. This allows one to 448 // 'delete' a whole class at a time, even though there may be circular 449 // references... first all references are dropped, and all use counts go to 450 // zero. Then everything is deleted for real. Note that no operations are 451 // valid on an object that has "dropped all references", except operator 452 // delete. 453 // 454 void Function::dropAllReferences() { 455 setIsMaterializable(false); 456 457 for (BasicBlock &BB : *this) 458 BB.dropAllReferences(); 459 460 // Delete all basic blocks. They are now unused, except possibly by 461 // blockaddresses, but BasicBlock's destructor takes care of those. 462 while (!BasicBlocks.empty()) 463 BasicBlocks.begin()->eraseFromParent(); 464 465 // Drop uses of any optional data (real or placeholder). 466 if (getNumOperands()) { 467 User::dropAllReferences(); 468 setNumHungOffUseOperands(0); 469 setValueSubclassData(getSubclassDataFromValue() & ~0xe); 470 } 471 472 // Metadata is stored in a side-table. 473 clearMetadata(); 474 } 475 476 void Function::addAttribute(unsigned i, Attribute::AttrKind Kind) { 477 AttributeList PAL = getAttributes(); 478 PAL = PAL.addAttribute(getContext(), i, Kind); 479 setAttributes(PAL); 480 } 481 482 void Function::addAttribute(unsigned i, Attribute Attr) { 483 AttributeList PAL = getAttributes(); 484 PAL = PAL.addAttribute(getContext(), i, Attr); 485 setAttributes(PAL); 486 } 487 488 void Function::addAttributes(unsigned i, const AttrBuilder &Attrs) { 489 AttributeList PAL = getAttributes(); 490 PAL = PAL.addAttributes(getContext(), i, Attrs); 491 setAttributes(PAL); 492 } 493 494 void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) { 495 AttributeList PAL = getAttributes(); 496 PAL = PAL.addParamAttribute(getContext(), ArgNo, Kind); 497 setAttributes(PAL); 498 } 499 500 void Function::addParamAttr(unsigned ArgNo, Attribute Attr) { 501 AttributeList PAL = getAttributes(); 502 PAL = PAL.addParamAttribute(getContext(), ArgNo, Attr); 503 setAttributes(PAL); 504 } 505 506 void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) { 507 AttributeList PAL = getAttributes(); 508 PAL = PAL.addParamAttributes(getContext(), ArgNo, Attrs); 509 setAttributes(PAL); 510 } 511 512 void Function::removeAttribute(unsigned i, Attribute::AttrKind Kind) { 513 AttributeList PAL = getAttributes(); 514 PAL = PAL.removeAttribute(getContext(), i, Kind); 515 setAttributes(PAL); 516 } 517 518 void Function::removeAttribute(unsigned i, StringRef Kind) { 519 AttributeList PAL = getAttributes(); 520 PAL = PAL.removeAttribute(getContext(), i, Kind); 521 setAttributes(PAL); 522 } 523 524 void Function::removeAttributes(unsigned i, const AttrBuilder &Attrs) { 525 AttributeList PAL = getAttributes(); 526 PAL = PAL.removeAttributes(getContext(), i, Attrs); 527 setAttributes(PAL); 528 } 529 530 void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) { 531 AttributeList PAL = getAttributes(); 532 PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind); 533 setAttributes(PAL); 534 } 535 536 void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) { 537 AttributeList PAL = getAttributes(); 538 PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind); 539 setAttributes(PAL); 540 } 541 542 void Function::removeParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) { 543 AttributeList PAL = getAttributes(); 544 PAL = PAL.removeParamAttributes(getContext(), ArgNo, Attrs); 545 setAttributes(PAL); 546 } 547 548 void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) { 549 AttributeList PAL = getAttributes(); 550 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes); 551 setAttributes(PAL); 552 } 553 554 void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) { 555 AttributeList PAL = getAttributes(); 556 PAL = PAL.addDereferenceableParamAttr(getContext(), ArgNo, Bytes); 557 setAttributes(PAL); 558 } 559 560 void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) { 561 AttributeList PAL = getAttributes(); 562 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes); 563 setAttributes(PAL); 564 } 565 566 void Function::addDereferenceableOrNullParamAttr(unsigned ArgNo, 567 uint64_t Bytes) { 568 AttributeList PAL = getAttributes(); 569 PAL = PAL.addDereferenceableOrNullParamAttr(getContext(), ArgNo, Bytes); 570 setAttributes(PAL); 571 } 572 573 const std::string &Function::getGC() const { 574 assert(hasGC() && "Function has no collector"); 575 return getContext().getGC(*this); 576 } 577 578 void Function::setGC(std::string Str) { 579 setValueSubclassDataBit(14, !Str.empty()); 580 getContext().setGC(*this, std::move(Str)); 581 } 582 583 void Function::clearGC() { 584 if (!hasGC()) 585 return; 586 getContext().deleteGC(*this); 587 setValueSubclassDataBit(14, false); 588 } 589 590 /// Copy all additional attributes (those not needed to create a Function) from 591 /// the Function Src to this one. 592 void Function::copyAttributesFrom(const Function *Src) { 593 GlobalObject::copyAttributesFrom(Src); 594 setCallingConv(Src->getCallingConv()); 595 setAttributes(Src->getAttributes()); 596 if (Src->hasGC()) 597 setGC(Src->getGC()); 598 else 599 clearGC(); 600 if (Src->hasPersonalityFn()) 601 setPersonalityFn(Src->getPersonalityFn()); 602 if (Src->hasPrefixData()) 603 setPrefixData(Src->getPrefixData()); 604 if (Src->hasPrologueData()) 605 setPrologueData(Src->getPrologueData()); 606 } 607 608 /// Table of string intrinsic names indexed by enum value. 609 static const char * const IntrinsicNameTable[] = { 610 "not_intrinsic", 611 #define GET_INTRINSIC_NAME_TABLE 612 #include "llvm/IR/IntrinsicImpl.inc" 613 #undef GET_INTRINSIC_NAME_TABLE 614 }; 615 616 /// Table of per-target intrinsic name tables. 617 #define GET_INTRINSIC_TARGET_DATA 618 #include "llvm/IR/IntrinsicImpl.inc" 619 #undef GET_INTRINSIC_TARGET_DATA 620 621 /// Find the segment of \c IntrinsicNameTable for intrinsics with the same 622 /// target as \c Name, or the generic table if \c Name is not target specific. 623 /// 624 /// Returns the relevant slice of \c IntrinsicNameTable 625 static ArrayRef<const char *> findTargetSubtable(StringRef Name) { 626 assert(Name.startswith("llvm.")); 627 628 ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos); 629 // Drop "llvm." and take the first dotted component. That will be the target 630 // if this is target specific. 631 StringRef Target = Name.drop_front(5).split('.').first; 632 auto It = partition_point( 633 Targets, [=](const IntrinsicTargetInfo &TI) { return TI.Name < Target; }); 634 // We've either found the target or just fall back to the generic set, which 635 // is always first. 636 const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0]; 637 return makeArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count); 638 } 639 640 /// This does the actual lookup of an intrinsic ID which 641 /// matches the given function name. 642 Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) { 643 ArrayRef<const char *> NameTable = findTargetSubtable(Name); 644 int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name); 645 if (Idx == -1) 646 return Intrinsic::not_intrinsic; 647 648 // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have 649 // an index into a sub-table. 650 int Adjust = NameTable.data() - IntrinsicNameTable; 651 Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust); 652 653 // If the intrinsic is not overloaded, require an exact match. If it is 654 // overloaded, require either exact or prefix match. 655 const auto MatchSize = strlen(NameTable[Idx]); 656 assert(Name.size() >= MatchSize && "Expected either exact or prefix match"); 657 bool IsExactMatch = Name.size() == MatchSize; 658 return IsExactMatch || Intrinsic::isOverloaded(ID) ? ID 659 : Intrinsic::not_intrinsic; 660 } 661 662 void Function::recalculateIntrinsicID() { 663 StringRef Name = getName(); 664 if (!Name.startswith("llvm.")) { 665 HasLLVMReservedName = false; 666 IntID = Intrinsic::not_intrinsic; 667 return; 668 } 669 HasLLVMReservedName = true; 670 IntID = lookupIntrinsicID(Name); 671 } 672 673 /// Returns a stable mangling for the type specified for use in the name 674 /// mangling scheme used by 'any' types in intrinsic signatures. The mangling 675 /// of named types is simply their name. Manglings for unnamed types consist 676 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions) 677 /// combined with the mangling of their component types. A vararg function 678 /// type will have a suffix of 'vararg'. Since function types can contain 679 /// other function types, we close a function type mangling with suffix 'f' 680 /// which can't be confused with it's prefix. This ensures we don't have 681 /// collisions between two unrelated function types. Otherwise, you might 682 /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.) 683 /// 684 static std::string getMangledTypeStr(Type* Ty) { 685 std::string Result; 686 if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) { 687 Result += "p" + utostr(PTyp->getAddressSpace()) + 688 getMangledTypeStr(PTyp->getElementType()); 689 } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) { 690 Result += "a" + utostr(ATyp->getNumElements()) + 691 getMangledTypeStr(ATyp->getElementType()); 692 } else if (StructType *STyp = dyn_cast<StructType>(Ty)) { 693 if (!STyp->isLiteral()) { 694 Result += "s_"; 695 Result += STyp->getName(); 696 } else { 697 Result += "sl_"; 698 for (auto Elem : STyp->elements()) 699 Result += getMangledTypeStr(Elem); 700 } 701 // Ensure nested structs are distinguishable. 702 Result += "s"; 703 } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) { 704 Result += "f_" + getMangledTypeStr(FT->getReturnType()); 705 for (size_t i = 0; i < FT->getNumParams(); i++) 706 Result += getMangledTypeStr(FT->getParamType(i)); 707 if (FT->isVarArg()) 708 Result += "vararg"; 709 // Ensure nested function types are distinguishable. 710 Result += "f"; 711 } else if (VectorType* VTy = dyn_cast<VectorType>(Ty)) { 712 ElementCount EC = VTy->getElementCount(); 713 if (EC.Scalable) 714 Result += "nx"; 715 Result += "v" + utostr(EC.Min) + getMangledTypeStr(VTy->getElementType()); 716 } else if (Ty) { 717 switch (Ty->getTypeID()) { 718 default: llvm_unreachable("Unhandled type"); 719 case Type::VoidTyID: Result += "isVoid"; break; 720 case Type::MetadataTyID: Result += "Metadata"; break; 721 case Type::HalfTyID: Result += "f16"; break; 722 case Type::BFloatTyID: Result += "bf16"; break; 723 case Type::FloatTyID: Result += "f32"; break; 724 case Type::DoubleTyID: Result += "f64"; break; 725 case Type::X86_FP80TyID: Result += "f80"; break; 726 case Type::FP128TyID: Result += "f128"; break; 727 case Type::PPC_FP128TyID: Result += "ppcf128"; break; 728 case Type::X86_MMXTyID: Result += "x86mmx"; break; 729 case Type::IntegerTyID: 730 Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth()); 731 break; 732 } 733 } 734 return Result; 735 } 736 737 StringRef Intrinsic::getName(ID id) { 738 assert(id < num_intrinsics && "Invalid intrinsic ID!"); 739 assert(!Intrinsic::isOverloaded(id) && 740 "This version of getName does not support overloading"); 741 return IntrinsicNameTable[id]; 742 } 743 744 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) { 745 assert(id < num_intrinsics && "Invalid intrinsic ID!"); 746 std::string Result(IntrinsicNameTable[id]); 747 for (Type *Ty : Tys) { 748 Result += "." + getMangledTypeStr(Ty); 749 } 750 return Result; 751 } 752 753 /// IIT_Info - These are enumerators that describe the entries returned by the 754 /// getIntrinsicInfoTableEntries function. 755 /// 756 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter! 757 enum IIT_Info { 758 // Common values should be encoded with 0-15. 759 IIT_Done = 0, 760 IIT_I1 = 1, 761 IIT_I8 = 2, 762 IIT_I16 = 3, 763 IIT_I32 = 4, 764 IIT_I64 = 5, 765 IIT_F16 = 6, 766 IIT_F32 = 7, 767 IIT_F64 = 8, 768 IIT_V2 = 9, 769 IIT_V4 = 10, 770 IIT_V8 = 11, 771 IIT_V16 = 12, 772 IIT_V32 = 13, 773 IIT_PTR = 14, 774 IIT_ARG = 15, 775 776 // Values from 16+ are only encodable with the inefficient encoding. 777 IIT_V64 = 16, 778 IIT_MMX = 17, 779 IIT_TOKEN = 18, 780 IIT_METADATA = 19, 781 IIT_EMPTYSTRUCT = 20, 782 IIT_STRUCT2 = 21, 783 IIT_STRUCT3 = 22, 784 IIT_STRUCT4 = 23, 785 IIT_STRUCT5 = 24, 786 IIT_EXTEND_ARG = 25, 787 IIT_TRUNC_ARG = 26, 788 IIT_ANYPTR = 27, 789 IIT_V1 = 28, 790 IIT_VARARG = 29, 791 IIT_HALF_VEC_ARG = 30, 792 IIT_SAME_VEC_WIDTH_ARG = 31, 793 IIT_PTR_TO_ARG = 32, 794 IIT_PTR_TO_ELT = 33, 795 IIT_VEC_OF_ANYPTRS_TO_ELT = 34, 796 IIT_I128 = 35, 797 IIT_V512 = 36, 798 IIT_V1024 = 37, 799 IIT_STRUCT6 = 38, 800 IIT_STRUCT7 = 39, 801 IIT_STRUCT8 = 40, 802 IIT_F128 = 41, 803 IIT_VEC_ELEMENT = 42, 804 IIT_SCALABLE_VEC = 43, 805 IIT_SUBDIVIDE2_ARG = 44, 806 IIT_SUBDIVIDE4_ARG = 45, 807 IIT_VEC_OF_BITCASTS_TO_INT = 46, 808 IIT_V128 = 47, 809 IIT_BF16 = 48 810 }; 811 812 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos, 813 IIT_Info LastInfo, 814 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) { 815 using namespace Intrinsic; 816 817 bool IsScalableVector = (LastInfo == IIT_SCALABLE_VEC); 818 819 IIT_Info Info = IIT_Info(Infos[NextElt++]); 820 unsigned StructElts = 2; 821 822 switch (Info) { 823 case IIT_Done: 824 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0)); 825 return; 826 case IIT_VARARG: 827 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0)); 828 return; 829 case IIT_MMX: 830 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0)); 831 return; 832 case IIT_TOKEN: 833 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0)); 834 return; 835 case IIT_METADATA: 836 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0)); 837 return; 838 case IIT_F16: 839 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0)); 840 return; 841 case IIT_BF16: 842 OutputTable.push_back(IITDescriptor::get(IITDescriptor::BFloat, 0)); 843 return; 844 case IIT_F32: 845 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0)); 846 return; 847 case IIT_F64: 848 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0)); 849 return; 850 case IIT_F128: 851 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0)); 852 return; 853 case IIT_I1: 854 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1)); 855 return; 856 case IIT_I8: 857 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8)); 858 return; 859 case IIT_I16: 860 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16)); 861 return; 862 case IIT_I32: 863 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32)); 864 return; 865 case IIT_I64: 866 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64)); 867 return; 868 case IIT_I128: 869 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128)); 870 return; 871 case IIT_V1: 872 OutputTable.push_back(IITDescriptor::getVector(1, IsScalableVector)); 873 DecodeIITType(NextElt, Infos, Info, OutputTable); 874 return; 875 case IIT_V2: 876 OutputTable.push_back(IITDescriptor::getVector(2, IsScalableVector)); 877 DecodeIITType(NextElt, Infos, Info, OutputTable); 878 return; 879 case IIT_V4: 880 OutputTable.push_back(IITDescriptor::getVector(4, IsScalableVector)); 881 DecodeIITType(NextElt, Infos, Info, OutputTable); 882 return; 883 case IIT_V8: 884 OutputTable.push_back(IITDescriptor::getVector(8, IsScalableVector)); 885 DecodeIITType(NextElt, Infos, Info, OutputTable); 886 return; 887 case IIT_V16: 888 OutputTable.push_back(IITDescriptor::getVector(16, IsScalableVector)); 889 DecodeIITType(NextElt, Infos, Info, OutputTable); 890 return; 891 case IIT_V32: 892 OutputTable.push_back(IITDescriptor::getVector(32, IsScalableVector)); 893 DecodeIITType(NextElt, Infos, Info, OutputTable); 894 return; 895 case IIT_V64: 896 OutputTable.push_back(IITDescriptor::getVector(64, IsScalableVector)); 897 DecodeIITType(NextElt, Infos, Info, OutputTable); 898 return; 899 case IIT_V128: 900 OutputTable.push_back(IITDescriptor::getVector(128, IsScalableVector)); 901 DecodeIITType(NextElt, Infos, Info, OutputTable); 902 return; 903 case IIT_V512: 904 OutputTable.push_back(IITDescriptor::getVector(512, IsScalableVector)); 905 DecodeIITType(NextElt, Infos, Info, OutputTable); 906 return; 907 case IIT_V1024: 908 OutputTable.push_back(IITDescriptor::getVector(1024, IsScalableVector)); 909 DecodeIITType(NextElt, Infos, Info, OutputTable); 910 return; 911 case IIT_PTR: 912 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0)); 913 DecodeIITType(NextElt, Infos, Info, OutputTable); 914 return; 915 case IIT_ANYPTR: { // [ANYPTR addrspace, subtype] 916 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 917 Infos[NextElt++])); 918 DecodeIITType(NextElt, Infos, Info, OutputTable); 919 return; 920 } 921 case IIT_ARG: { 922 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 923 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo)); 924 return; 925 } 926 case IIT_EXTEND_ARG: { 927 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 928 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument, 929 ArgInfo)); 930 return; 931 } 932 case IIT_TRUNC_ARG: { 933 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 934 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument, 935 ArgInfo)); 936 return; 937 } 938 case IIT_HALF_VEC_ARG: { 939 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 940 OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument, 941 ArgInfo)); 942 return; 943 } 944 case IIT_SAME_VEC_WIDTH_ARG: { 945 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 946 OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument, 947 ArgInfo)); 948 return; 949 } 950 case IIT_PTR_TO_ARG: { 951 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 952 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument, 953 ArgInfo)); 954 return; 955 } 956 case IIT_PTR_TO_ELT: { 957 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 958 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo)); 959 return; 960 } 961 case IIT_VEC_OF_ANYPTRS_TO_ELT: { 962 unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 963 unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 964 OutputTable.push_back( 965 IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo)); 966 return; 967 } 968 case IIT_EMPTYSTRUCT: 969 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0)); 970 return; 971 case IIT_STRUCT8: ++StructElts; LLVM_FALLTHROUGH; 972 case IIT_STRUCT7: ++StructElts; LLVM_FALLTHROUGH; 973 case IIT_STRUCT6: ++StructElts; LLVM_FALLTHROUGH; 974 case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH; 975 case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH; 976 case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH; 977 case IIT_STRUCT2: { 978 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts)); 979 980 for (unsigned i = 0; i != StructElts; ++i) 981 DecodeIITType(NextElt, Infos, Info, OutputTable); 982 return; 983 } 984 case IIT_SUBDIVIDE2_ARG: { 985 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 986 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide2Argument, 987 ArgInfo)); 988 return; 989 } 990 case IIT_SUBDIVIDE4_ARG: { 991 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 992 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide4Argument, 993 ArgInfo)); 994 return; 995 } 996 case IIT_VEC_ELEMENT: { 997 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 998 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecElementArgument, 999 ArgInfo)); 1000 return; 1001 } 1002 case IIT_SCALABLE_VEC: { 1003 DecodeIITType(NextElt, Infos, Info, OutputTable); 1004 return; 1005 } 1006 case IIT_VEC_OF_BITCASTS_TO_INT: { 1007 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1008 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfBitcastsToInt, 1009 ArgInfo)); 1010 return; 1011 } 1012 } 1013 llvm_unreachable("unhandled"); 1014 } 1015 1016 #define GET_INTRINSIC_GENERATOR_GLOBAL 1017 #include "llvm/IR/IntrinsicImpl.inc" 1018 #undef GET_INTRINSIC_GENERATOR_GLOBAL 1019 1020 void Intrinsic::getIntrinsicInfoTableEntries(ID id, 1021 SmallVectorImpl<IITDescriptor> &T){ 1022 // Check to see if the intrinsic's type was expressible by the table. 1023 unsigned TableVal = IIT_Table[id-1]; 1024 1025 // Decode the TableVal into an array of IITValues. 1026 SmallVector<unsigned char, 8> IITValues; 1027 ArrayRef<unsigned char> IITEntries; 1028 unsigned NextElt = 0; 1029 if ((TableVal >> 31) != 0) { 1030 // This is an offset into the IIT_LongEncodingTable. 1031 IITEntries = IIT_LongEncodingTable; 1032 1033 // Strip sentinel bit. 1034 NextElt = (TableVal << 1) >> 1; 1035 } else { 1036 // Decode the TableVal into an array of IITValues. If the entry was encoded 1037 // into a single word in the table itself, decode it now. 1038 do { 1039 IITValues.push_back(TableVal & 0xF); 1040 TableVal >>= 4; 1041 } while (TableVal); 1042 1043 IITEntries = IITValues; 1044 NextElt = 0; 1045 } 1046 1047 // Okay, decode the table into the output vector of IITDescriptors. 1048 DecodeIITType(NextElt, IITEntries, IIT_Done, T); 1049 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0) 1050 DecodeIITType(NextElt, IITEntries, IIT_Done, T); 1051 } 1052 1053 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos, 1054 ArrayRef<Type*> Tys, LLVMContext &Context) { 1055 using namespace Intrinsic; 1056 1057 IITDescriptor D = Infos.front(); 1058 Infos = Infos.slice(1); 1059 1060 switch (D.Kind) { 1061 case IITDescriptor::Void: return Type::getVoidTy(Context); 1062 case IITDescriptor::VarArg: return Type::getVoidTy(Context); 1063 case IITDescriptor::MMX: return Type::getX86_MMXTy(Context); 1064 case IITDescriptor::Token: return Type::getTokenTy(Context); 1065 case IITDescriptor::Metadata: return Type::getMetadataTy(Context); 1066 case IITDescriptor::Half: return Type::getHalfTy(Context); 1067 case IITDescriptor::BFloat: return Type::getBFloatTy(Context); 1068 case IITDescriptor::Float: return Type::getFloatTy(Context); 1069 case IITDescriptor::Double: return Type::getDoubleTy(Context); 1070 case IITDescriptor::Quad: return Type::getFP128Ty(Context); 1071 1072 case IITDescriptor::Integer: 1073 return IntegerType::get(Context, D.Integer_Width); 1074 case IITDescriptor::Vector: 1075 return VectorType::get(DecodeFixedType(Infos, Tys, Context), 1076 D.Vector_Width); 1077 case IITDescriptor::Pointer: 1078 return PointerType::get(DecodeFixedType(Infos, Tys, Context), 1079 D.Pointer_AddressSpace); 1080 case IITDescriptor::Struct: { 1081 SmallVector<Type *, 8> Elts; 1082 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 1083 Elts.push_back(DecodeFixedType(Infos, Tys, Context)); 1084 return StructType::get(Context, Elts); 1085 } 1086 case IITDescriptor::Argument: 1087 return Tys[D.getArgumentNumber()]; 1088 case IITDescriptor::ExtendArgument: { 1089 Type *Ty = Tys[D.getArgumentNumber()]; 1090 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1091 return VectorType::getExtendedElementVectorType(VTy); 1092 1093 return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth()); 1094 } 1095 case IITDescriptor::TruncArgument: { 1096 Type *Ty = Tys[D.getArgumentNumber()]; 1097 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1098 return VectorType::getTruncatedElementVectorType(VTy); 1099 1100 IntegerType *ITy = cast<IntegerType>(Ty); 1101 assert(ITy->getBitWidth() % 2 == 0); 1102 return IntegerType::get(Context, ITy->getBitWidth() / 2); 1103 } 1104 case IITDescriptor::Subdivide2Argument: 1105 case IITDescriptor::Subdivide4Argument: { 1106 Type *Ty = Tys[D.getArgumentNumber()]; 1107 VectorType *VTy = dyn_cast<VectorType>(Ty); 1108 assert(VTy && "Expected an argument of Vector Type"); 1109 int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2; 1110 return VectorType::getSubdividedVectorType(VTy, SubDivs); 1111 } 1112 case IITDescriptor::HalfVecArgument: 1113 return VectorType::getHalfElementsVectorType(cast<VectorType>( 1114 Tys[D.getArgumentNumber()])); 1115 case IITDescriptor::SameVecWidthArgument: { 1116 Type *EltTy = DecodeFixedType(Infos, Tys, Context); 1117 Type *Ty = Tys[D.getArgumentNumber()]; 1118 if (auto *VTy = dyn_cast<VectorType>(Ty)) 1119 return VectorType::get(EltTy, VTy->getElementCount()); 1120 return EltTy; 1121 } 1122 case IITDescriptor::PtrToArgument: { 1123 Type *Ty = Tys[D.getArgumentNumber()]; 1124 return PointerType::getUnqual(Ty); 1125 } 1126 case IITDescriptor::PtrToElt: { 1127 Type *Ty = Tys[D.getArgumentNumber()]; 1128 VectorType *VTy = dyn_cast<VectorType>(Ty); 1129 if (!VTy) 1130 llvm_unreachable("Expected an argument of Vector Type"); 1131 Type *EltTy = VTy->getElementType(); 1132 return PointerType::getUnqual(EltTy); 1133 } 1134 case IITDescriptor::VecElementArgument: { 1135 Type *Ty = Tys[D.getArgumentNumber()]; 1136 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1137 return VTy->getElementType(); 1138 llvm_unreachable("Expected an argument of Vector Type"); 1139 } 1140 case IITDescriptor::VecOfBitcastsToInt: { 1141 Type *Ty = Tys[D.getArgumentNumber()]; 1142 VectorType *VTy = dyn_cast<VectorType>(Ty); 1143 assert(VTy && "Expected an argument of Vector Type"); 1144 return VectorType::getInteger(VTy); 1145 } 1146 case IITDescriptor::VecOfAnyPtrsToElt: 1147 // Return the overloaded type (which determines the pointers address space) 1148 return Tys[D.getOverloadArgNumber()]; 1149 } 1150 llvm_unreachable("unhandled"); 1151 } 1152 1153 FunctionType *Intrinsic::getType(LLVMContext &Context, 1154 ID id, ArrayRef<Type*> Tys) { 1155 SmallVector<IITDescriptor, 8> Table; 1156 getIntrinsicInfoTableEntries(id, Table); 1157 1158 ArrayRef<IITDescriptor> TableRef = Table; 1159 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context); 1160 1161 SmallVector<Type*, 8> ArgTys; 1162 while (!TableRef.empty()) 1163 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context)); 1164 1165 // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg 1166 // If we see void type as the type of the last argument, it is vararg intrinsic 1167 if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) { 1168 ArgTys.pop_back(); 1169 return FunctionType::get(ResultTy, ArgTys, true); 1170 } 1171 return FunctionType::get(ResultTy, ArgTys, false); 1172 } 1173 1174 bool Intrinsic::isOverloaded(ID id) { 1175 #define GET_INTRINSIC_OVERLOAD_TABLE 1176 #include "llvm/IR/IntrinsicImpl.inc" 1177 #undef GET_INTRINSIC_OVERLOAD_TABLE 1178 } 1179 1180 bool Intrinsic::isLeaf(ID id) { 1181 switch (id) { 1182 default: 1183 return true; 1184 1185 case Intrinsic::experimental_gc_statepoint: 1186 case Intrinsic::experimental_patchpoint_void: 1187 case Intrinsic::experimental_patchpoint_i64: 1188 return false; 1189 } 1190 } 1191 1192 /// This defines the "Intrinsic::getAttributes(ID id)" method. 1193 #define GET_INTRINSIC_ATTRIBUTES 1194 #include "llvm/IR/IntrinsicImpl.inc" 1195 #undef GET_INTRINSIC_ATTRIBUTES 1196 1197 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) { 1198 // There can never be multiple globals with the same name of different types, 1199 // because intrinsics must be a specific type. 1200 return cast<Function>( 1201 M->getOrInsertFunction(getName(id, Tys), 1202 getType(M->getContext(), id, Tys)) 1203 .getCallee()); 1204 } 1205 1206 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method. 1207 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 1208 #include "llvm/IR/IntrinsicImpl.inc" 1209 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 1210 1211 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method. 1212 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 1213 #include "llvm/IR/IntrinsicImpl.inc" 1214 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 1215 1216 using DeferredIntrinsicMatchPair = 1217 std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>; 1218 1219 static bool matchIntrinsicType( 1220 Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos, 1221 SmallVectorImpl<Type *> &ArgTys, 1222 SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks, 1223 bool IsDeferredCheck) { 1224 using namespace Intrinsic; 1225 1226 // If we ran out of descriptors, there are too many arguments. 1227 if (Infos.empty()) return true; 1228 1229 // Do this before slicing off the 'front' part 1230 auto InfosRef = Infos; 1231 auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) { 1232 DeferredChecks.emplace_back(T, InfosRef); 1233 return false; 1234 }; 1235 1236 IITDescriptor D = Infos.front(); 1237 Infos = Infos.slice(1); 1238 1239 switch (D.Kind) { 1240 case IITDescriptor::Void: return !Ty->isVoidTy(); 1241 case IITDescriptor::VarArg: return true; 1242 case IITDescriptor::MMX: return !Ty->isX86_MMXTy(); 1243 case IITDescriptor::Token: return !Ty->isTokenTy(); 1244 case IITDescriptor::Metadata: return !Ty->isMetadataTy(); 1245 case IITDescriptor::Half: return !Ty->isHalfTy(); 1246 case IITDescriptor::BFloat: return !Ty->isBFloatTy(); 1247 case IITDescriptor::Float: return !Ty->isFloatTy(); 1248 case IITDescriptor::Double: return !Ty->isDoubleTy(); 1249 case IITDescriptor::Quad: return !Ty->isFP128Ty(); 1250 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width); 1251 case IITDescriptor::Vector: { 1252 VectorType *VT = dyn_cast<VectorType>(Ty); 1253 return !VT || VT->getElementCount() != D.Vector_Width || 1254 matchIntrinsicType(VT->getElementType(), Infos, ArgTys, 1255 DeferredChecks, IsDeferredCheck); 1256 } 1257 case IITDescriptor::Pointer: { 1258 PointerType *PT = dyn_cast<PointerType>(Ty); 1259 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace || 1260 matchIntrinsicType(PT->getElementType(), Infos, ArgTys, 1261 DeferredChecks, IsDeferredCheck); 1262 } 1263 1264 case IITDescriptor::Struct: { 1265 StructType *ST = dyn_cast<StructType>(Ty); 1266 if (!ST || ST->getNumElements() != D.Struct_NumElements) 1267 return true; 1268 1269 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 1270 if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys, 1271 DeferredChecks, IsDeferredCheck)) 1272 return true; 1273 return false; 1274 } 1275 1276 case IITDescriptor::Argument: 1277 // If this is the second occurrence of an argument, 1278 // verify that the later instance matches the previous instance. 1279 if (D.getArgumentNumber() < ArgTys.size()) 1280 return Ty != ArgTys[D.getArgumentNumber()]; 1281 1282 if (D.getArgumentNumber() > ArgTys.size() || 1283 D.getArgumentKind() == IITDescriptor::AK_MatchType) 1284 return IsDeferredCheck || DeferCheck(Ty); 1285 1286 assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck && 1287 "Table consistency error"); 1288 ArgTys.push_back(Ty); 1289 1290 switch (D.getArgumentKind()) { 1291 case IITDescriptor::AK_Any: return false; // Success 1292 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy(); 1293 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy(); 1294 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty); 1295 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty); 1296 default: break; 1297 } 1298 llvm_unreachable("all argument kinds not covered"); 1299 1300 case IITDescriptor::ExtendArgument: { 1301 // If this is a forward reference, defer the check for later. 1302 if (D.getArgumentNumber() >= ArgTys.size()) 1303 return IsDeferredCheck || DeferCheck(Ty); 1304 1305 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1306 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 1307 NewTy = VectorType::getExtendedElementVectorType(VTy); 1308 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 1309 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth()); 1310 else 1311 return true; 1312 1313 return Ty != NewTy; 1314 } 1315 case IITDescriptor::TruncArgument: { 1316 // If this is a forward reference, defer the check for later. 1317 if (D.getArgumentNumber() >= ArgTys.size()) 1318 return IsDeferredCheck || DeferCheck(Ty); 1319 1320 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1321 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 1322 NewTy = VectorType::getTruncatedElementVectorType(VTy); 1323 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 1324 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2); 1325 else 1326 return true; 1327 1328 return Ty != NewTy; 1329 } 1330 case IITDescriptor::HalfVecArgument: 1331 // If this is a forward reference, defer the check for later. 1332 if (D.getArgumentNumber() >= ArgTys.size()) 1333 return IsDeferredCheck || DeferCheck(Ty); 1334 return !isa<VectorType>(ArgTys[D.getArgumentNumber()]) || 1335 VectorType::getHalfElementsVectorType( 1336 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty; 1337 case IITDescriptor::SameVecWidthArgument: { 1338 if (D.getArgumentNumber() >= ArgTys.size()) { 1339 // Defer check and subsequent check for the vector element type. 1340 Infos = Infos.slice(1); 1341 return IsDeferredCheck || DeferCheck(Ty); 1342 } 1343 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1344 auto *ThisArgType = dyn_cast<VectorType>(Ty); 1345 // Both must be vectors of the same number of elements or neither. 1346 if ((ReferenceType != nullptr) != (ThisArgType != nullptr)) 1347 return true; 1348 Type *EltTy = Ty; 1349 if (ThisArgType) { 1350 if (ReferenceType->getElementCount() != 1351 ThisArgType->getElementCount()) 1352 return true; 1353 EltTy = ThisArgType->getElementType(); 1354 } 1355 return matchIntrinsicType(EltTy, Infos, ArgTys, DeferredChecks, 1356 IsDeferredCheck); 1357 } 1358 case IITDescriptor::PtrToArgument: { 1359 if (D.getArgumentNumber() >= ArgTys.size()) 1360 return IsDeferredCheck || DeferCheck(Ty); 1361 Type * ReferenceType = ArgTys[D.getArgumentNumber()]; 1362 PointerType *ThisArgType = dyn_cast<PointerType>(Ty); 1363 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType); 1364 } 1365 case IITDescriptor::PtrToElt: { 1366 if (D.getArgumentNumber() >= ArgTys.size()) 1367 return IsDeferredCheck || DeferCheck(Ty); 1368 VectorType * ReferenceType = 1369 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]); 1370 PointerType *ThisArgType = dyn_cast<PointerType>(Ty); 1371 1372 return (!ThisArgType || !ReferenceType || 1373 ThisArgType->getElementType() != ReferenceType->getElementType()); 1374 } 1375 case IITDescriptor::VecOfAnyPtrsToElt: { 1376 unsigned RefArgNumber = D.getRefArgNumber(); 1377 if (RefArgNumber >= ArgTys.size()) { 1378 if (IsDeferredCheck) 1379 return true; 1380 // If forward referencing, already add the pointer-vector type and 1381 // defer the checks for later. 1382 ArgTys.push_back(Ty); 1383 return DeferCheck(Ty); 1384 } 1385 1386 if (!IsDeferredCheck){ 1387 assert(D.getOverloadArgNumber() == ArgTys.size() && 1388 "Table consistency error"); 1389 ArgTys.push_back(Ty); 1390 } 1391 1392 // Verify the overloaded type "matches" the Ref type. 1393 // i.e. Ty is a vector with the same width as Ref. 1394 // Composed of pointers to the same element type as Ref. 1395 VectorType *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]); 1396 VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty); 1397 if (!ThisArgVecTy || !ReferenceType || 1398 (ReferenceType->getNumElements() != ThisArgVecTy->getNumElements())) 1399 return true; 1400 PointerType *ThisArgEltTy = 1401 dyn_cast<PointerType>(ThisArgVecTy->getElementType()); 1402 if (!ThisArgEltTy) 1403 return true; 1404 return ThisArgEltTy->getElementType() != ReferenceType->getElementType(); 1405 } 1406 case IITDescriptor::VecElementArgument: { 1407 if (D.getArgumentNumber() >= ArgTys.size()) 1408 return IsDeferredCheck ? true : DeferCheck(Ty); 1409 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1410 return !ReferenceType || Ty != ReferenceType->getElementType(); 1411 } 1412 case IITDescriptor::Subdivide2Argument: 1413 case IITDescriptor::Subdivide4Argument: { 1414 // If this is a forward reference, defer the check for later. 1415 if (D.getArgumentNumber() >= ArgTys.size()) 1416 return IsDeferredCheck || DeferCheck(Ty); 1417 1418 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1419 if (auto *VTy = dyn_cast<VectorType>(NewTy)) { 1420 int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2; 1421 NewTy = VectorType::getSubdividedVectorType(VTy, SubDivs); 1422 return Ty != NewTy; 1423 } 1424 return true; 1425 } 1426 case IITDescriptor::VecOfBitcastsToInt: { 1427 if (D.getArgumentNumber() >= ArgTys.size()) 1428 return IsDeferredCheck || DeferCheck(Ty); 1429 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1430 auto *ThisArgVecTy = dyn_cast<VectorType>(Ty); 1431 if (!ThisArgVecTy || !ReferenceType) 1432 return true; 1433 return ThisArgVecTy != VectorType::getInteger(ReferenceType); 1434 } 1435 } 1436 llvm_unreachable("unhandled"); 1437 } 1438 1439 Intrinsic::MatchIntrinsicTypesResult 1440 Intrinsic::matchIntrinsicSignature(FunctionType *FTy, 1441 ArrayRef<Intrinsic::IITDescriptor> &Infos, 1442 SmallVectorImpl<Type *> &ArgTys) { 1443 SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks; 1444 if (matchIntrinsicType(FTy->getReturnType(), Infos, ArgTys, DeferredChecks, 1445 false)) 1446 return MatchIntrinsicTypes_NoMatchRet; 1447 1448 unsigned NumDeferredReturnChecks = DeferredChecks.size(); 1449 1450 for (auto Ty : FTy->params()) 1451 if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, false)) 1452 return MatchIntrinsicTypes_NoMatchArg; 1453 1454 for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) { 1455 DeferredIntrinsicMatchPair &Check = DeferredChecks[I]; 1456 if (matchIntrinsicType(Check.first, Check.second, ArgTys, DeferredChecks, 1457 true)) 1458 return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet 1459 : MatchIntrinsicTypes_NoMatchArg; 1460 } 1461 1462 return MatchIntrinsicTypes_Match; 1463 } 1464 1465 bool 1466 Intrinsic::matchIntrinsicVarArg(bool isVarArg, 1467 ArrayRef<Intrinsic::IITDescriptor> &Infos) { 1468 // If there are no descriptors left, then it can't be a vararg. 1469 if (Infos.empty()) 1470 return isVarArg; 1471 1472 // There should be only one descriptor remaining at this point. 1473 if (Infos.size() != 1) 1474 return true; 1475 1476 // Check and verify the descriptor. 1477 IITDescriptor D = Infos.front(); 1478 Infos = Infos.slice(1); 1479 if (D.Kind == IITDescriptor::VarArg) 1480 return !isVarArg; 1481 1482 return true; 1483 } 1484 1485 bool Intrinsic::getIntrinsicSignature(Function *F, 1486 SmallVectorImpl<Type *> &ArgTys) { 1487 Intrinsic::ID ID = F->getIntrinsicID(); 1488 if (!ID) 1489 return false; 1490 1491 SmallVector<Intrinsic::IITDescriptor, 8> Table; 1492 getIntrinsicInfoTableEntries(ID, Table); 1493 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table; 1494 1495 if (Intrinsic::matchIntrinsicSignature(F->getFunctionType(), TableRef, 1496 ArgTys) != 1497 Intrinsic::MatchIntrinsicTypesResult::MatchIntrinsicTypes_Match) { 1498 return false; 1499 } 1500 if (Intrinsic::matchIntrinsicVarArg(F->getFunctionType()->isVarArg(), 1501 TableRef)) 1502 return false; 1503 return true; 1504 } 1505 1506 Optional<Function *> Intrinsic::remangleIntrinsicFunction(Function *F) { 1507 SmallVector<Type *, 4> ArgTys; 1508 if (!getIntrinsicSignature(F, ArgTys)) 1509 return None; 1510 1511 Intrinsic::ID ID = F->getIntrinsicID(); 1512 StringRef Name = F->getName(); 1513 if (Name == Intrinsic::getName(ID, ArgTys)) 1514 return None; 1515 1516 auto NewDecl = Intrinsic::getDeclaration(F->getParent(), ID, ArgTys); 1517 NewDecl->setCallingConv(F->getCallingConv()); 1518 assert(NewDecl->getFunctionType() == F->getFunctionType() && 1519 "Shouldn't change the signature"); 1520 return NewDecl; 1521 } 1522 1523 /// hasAddressTaken - returns true if there are any uses of this function 1524 /// other than direct calls or invokes to it. Optionally ignores callback 1525 /// uses. 1526 bool Function::hasAddressTaken(const User **PutOffender, 1527 bool IgnoreCallbackUses) const { 1528 for (const Use &U : uses()) { 1529 const User *FU = U.getUser(); 1530 if (isa<BlockAddress>(FU)) 1531 continue; 1532 1533 if (IgnoreCallbackUses) { 1534 AbstractCallSite ACS(&U); 1535 if (ACS && ACS.isCallbackCall()) 1536 continue; 1537 } 1538 1539 const auto *Call = dyn_cast<CallBase>(FU); 1540 if (!Call) { 1541 if (PutOffender) 1542 *PutOffender = FU; 1543 return true; 1544 } 1545 if (!Call->isCallee(&U)) { 1546 if (PutOffender) 1547 *PutOffender = FU; 1548 return true; 1549 } 1550 } 1551 return false; 1552 } 1553 1554 bool Function::isDefTriviallyDead() const { 1555 // Check the linkage 1556 if (!hasLinkOnceLinkage() && !hasLocalLinkage() && 1557 !hasAvailableExternallyLinkage()) 1558 return false; 1559 1560 // Check if the function is used by anything other than a blockaddress. 1561 for (const User *U : users()) 1562 if (!isa<BlockAddress>(U)) 1563 return false; 1564 1565 return true; 1566 } 1567 1568 /// callsFunctionThatReturnsTwice - Return true if the function has a call to 1569 /// setjmp or other function that gcc recognizes as "returning twice". 1570 bool Function::callsFunctionThatReturnsTwice() const { 1571 for (const Instruction &I : instructions(this)) 1572 if (const auto *Call = dyn_cast<CallBase>(&I)) 1573 if (Call->hasFnAttr(Attribute::ReturnsTwice)) 1574 return true; 1575 1576 return false; 1577 } 1578 1579 Constant *Function::getPersonalityFn() const { 1580 assert(hasPersonalityFn() && getNumOperands()); 1581 return cast<Constant>(Op<0>()); 1582 } 1583 1584 void Function::setPersonalityFn(Constant *Fn) { 1585 setHungoffOperand<0>(Fn); 1586 setValueSubclassDataBit(3, Fn != nullptr); 1587 } 1588 1589 Constant *Function::getPrefixData() const { 1590 assert(hasPrefixData() && getNumOperands()); 1591 return cast<Constant>(Op<1>()); 1592 } 1593 1594 void Function::setPrefixData(Constant *PrefixData) { 1595 setHungoffOperand<1>(PrefixData); 1596 setValueSubclassDataBit(1, PrefixData != nullptr); 1597 } 1598 1599 Constant *Function::getPrologueData() const { 1600 assert(hasPrologueData() && getNumOperands()); 1601 return cast<Constant>(Op<2>()); 1602 } 1603 1604 void Function::setPrologueData(Constant *PrologueData) { 1605 setHungoffOperand<2>(PrologueData); 1606 setValueSubclassDataBit(2, PrologueData != nullptr); 1607 } 1608 1609 void Function::allocHungoffUselist() { 1610 // If we've already allocated a uselist, stop here. 1611 if (getNumOperands()) 1612 return; 1613 1614 allocHungoffUses(3, /*IsPhi=*/ false); 1615 setNumHungOffUseOperands(3); 1616 1617 // Initialize the uselist with placeholder operands to allow traversal. 1618 auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)); 1619 Op<0>().set(CPN); 1620 Op<1>().set(CPN); 1621 Op<2>().set(CPN); 1622 } 1623 1624 template <int Idx> 1625 void Function::setHungoffOperand(Constant *C) { 1626 if (C) { 1627 allocHungoffUselist(); 1628 Op<Idx>().set(C); 1629 } else if (getNumOperands()) { 1630 Op<Idx>().set( 1631 ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0))); 1632 } 1633 } 1634 1635 void Function::setValueSubclassDataBit(unsigned Bit, bool On) { 1636 assert(Bit < 16 && "SubclassData contains only 16 bits"); 1637 if (On) 1638 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit)); 1639 else 1640 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit)); 1641 } 1642 1643 void Function::setEntryCount(ProfileCount Count, 1644 const DenseSet<GlobalValue::GUID> *S) { 1645 assert(Count.hasValue()); 1646 #if !defined(NDEBUG) 1647 auto PrevCount = getEntryCount(); 1648 assert(!PrevCount.hasValue() || PrevCount.getType() == Count.getType()); 1649 #endif 1650 1651 auto ImportGUIDs = getImportGUIDs(); 1652 if (S == nullptr && ImportGUIDs.size()) 1653 S = &ImportGUIDs; 1654 1655 MDBuilder MDB(getContext()); 1656 setMetadata( 1657 LLVMContext::MD_prof, 1658 MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S)); 1659 } 1660 1661 void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type, 1662 const DenseSet<GlobalValue::GUID> *Imports) { 1663 setEntryCount(ProfileCount(Count, Type), Imports); 1664 } 1665 1666 ProfileCount Function::getEntryCount(bool AllowSynthetic) const { 1667 MDNode *MD = getMetadata(LLVMContext::MD_prof); 1668 if (MD && MD->getOperand(0)) 1669 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) { 1670 if (MDS->getString().equals("function_entry_count")) { 1671 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1)); 1672 uint64_t Count = CI->getValue().getZExtValue(); 1673 // A value of -1 is used for SamplePGO when there were no samples. 1674 // Treat this the same as unknown. 1675 if (Count == (uint64_t)-1) 1676 return ProfileCount::getInvalid(); 1677 return ProfileCount(Count, PCT_Real); 1678 } else if (AllowSynthetic && 1679 MDS->getString().equals("synthetic_function_entry_count")) { 1680 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1)); 1681 uint64_t Count = CI->getValue().getZExtValue(); 1682 return ProfileCount(Count, PCT_Synthetic); 1683 } 1684 } 1685 return ProfileCount::getInvalid(); 1686 } 1687 1688 DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const { 1689 DenseSet<GlobalValue::GUID> R; 1690 if (MDNode *MD = getMetadata(LLVMContext::MD_prof)) 1691 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) 1692 if (MDS->getString().equals("function_entry_count")) 1693 for (unsigned i = 2; i < MD->getNumOperands(); i++) 1694 R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i)) 1695 ->getValue() 1696 .getZExtValue()); 1697 return R; 1698 } 1699 1700 void Function::setSectionPrefix(StringRef Prefix) { 1701 MDBuilder MDB(getContext()); 1702 setMetadata(LLVMContext::MD_section_prefix, 1703 MDB.createFunctionSectionPrefix(Prefix)); 1704 } 1705 1706 Optional<StringRef> Function::getSectionPrefix() const { 1707 if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) { 1708 assert(cast<MDString>(MD->getOperand(0)) 1709 ->getString() 1710 .equals("function_section_prefix") && 1711 "Metadata not match"); 1712 return cast<MDString>(MD->getOperand(1))->getString(); 1713 } 1714 return None; 1715 } 1716 1717 bool Function::nullPointerIsDefined() const { 1718 return hasFnAttribute(Attribute::NullPointerIsValid); 1719 } 1720 1721 bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) { 1722 if (F && F->nullPointerIsDefined()) 1723 return true; 1724 1725 if (AS != 0) 1726 return true; 1727 1728 return false; 1729 } 1730