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/BitVector.h" 17 #include "llvm/ADT/DenseSet.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/ConstantRange.h" 29 #include "llvm/IR/Constants.h" 30 #include "llvm/IR/DerivedTypes.h" 31 #include "llvm/IR/GlobalValue.h" 32 #include "llvm/IR/InstIterator.h" 33 #include "llvm/IR/Instruction.h" 34 #include "llvm/IR/IntrinsicInst.h" 35 #include "llvm/IR/Intrinsics.h" 36 #include "llvm/IR/IntrinsicsAArch64.h" 37 #include "llvm/IR/IntrinsicsAMDGPU.h" 38 #include "llvm/IR/IntrinsicsARM.h" 39 #include "llvm/IR/IntrinsicsBPF.h" 40 #include "llvm/IR/IntrinsicsDirectX.h" 41 #include "llvm/IR/IntrinsicsHexagon.h" 42 #include "llvm/IR/IntrinsicsLoongArch.h" 43 #include "llvm/IR/IntrinsicsMips.h" 44 #include "llvm/IR/IntrinsicsNVPTX.h" 45 #include "llvm/IR/IntrinsicsPowerPC.h" 46 #include "llvm/IR/IntrinsicsR600.h" 47 #include "llvm/IR/IntrinsicsRISCV.h" 48 #include "llvm/IR/IntrinsicsS390.h" 49 #include "llvm/IR/IntrinsicsSPIRV.h" 50 #include "llvm/IR/IntrinsicsVE.h" 51 #include "llvm/IR/IntrinsicsWebAssembly.h" 52 #include "llvm/IR/IntrinsicsX86.h" 53 #include "llvm/IR/IntrinsicsXCore.h" 54 #include "llvm/IR/LLVMContext.h" 55 #include "llvm/IR/MDBuilder.h" 56 #include "llvm/IR/Metadata.h" 57 #include "llvm/IR/Module.h" 58 #include "llvm/IR/Operator.h" 59 #include "llvm/IR/SymbolTableListTraits.h" 60 #include "llvm/IR/Type.h" 61 #include "llvm/IR/Use.h" 62 #include "llvm/IR/User.h" 63 #include "llvm/IR/Value.h" 64 #include "llvm/IR/ValueSymbolTable.h" 65 #include "llvm/Support/Casting.h" 66 #include "llvm/Support/CommandLine.h" 67 #include "llvm/Support/Compiler.h" 68 #include "llvm/Support/ErrorHandling.h" 69 #include "llvm/Support/ModRef.h" 70 #include <cassert> 71 #include <cstddef> 72 #include <cstdint> 73 #include <cstring> 74 #include <string> 75 76 using namespace llvm; 77 using ProfileCount = Function::ProfileCount; 78 79 // Explicit instantiations of SymbolTableListTraits since some of the methods 80 // are not in the public header file... 81 template class llvm::SymbolTableListTraits<BasicBlock>; 82 83 static cl::opt<int> NonGlobalValueMaxNameSize( 84 "non-global-value-max-name-size", cl::Hidden, cl::init(1024), 85 cl::desc("Maximum size for the name of non-global values.")); 86 87 extern cl::opt<bool> UseNewDbgInfoFormat; 88 89 void Function::renumberBlocks() { 90 validateBlockNumbers(); 91 92 NextBlockNum = 0; 93 for (auto &BB : *this) 94 BB.Number = NextBlockNum++; 95 BlockNumEpoch++; 96 } 97 98 void Function::validateBlockNumbers() const { 99 #ifndef NDEBUG 100 BitVector Numbers(NextBlockNum); 101 for (const auto &BB : *this) { 102 unsigned Num = BB.getNumber(); 103 assert(Num < NextBlockNum && "out of range block number"); 104 assert(!Numbers[Num] && "duplicate block numbers"); 105 Numbers.set(Num); 106 } 107 #endif 108 } 109 110 void Function::convertToNewDbgValues() { 111 IsNewDbgInfoFormat = true; 112 for (auto &BB : *this) { 113 BB.convertToNewDbgValues(); 114 } 115 } 116 117 void Function::convertFromNewDbgValues() { 118 IsNewDbgInfoFormat = false; 119 for (auto &BB : *this) { 120 BB.convertFromNewDbgValues(); 121 } 122 } 123 124 void Function::setIsNewDbgInfoFormat(bool NewFlag) { 125 if (NewFlag && !IsNewDbgInfoFormat) 126 convertToNewDbgValues(); 127 else if (!NewFlag && IsNewDbgInfoFormat) 128 convertFromNewDbgValues(); 129 } 130 void Function::setNewDbgInfoFormatFlag(bool NewFlag) { 131 for (auto &BB : *this) { 132 BB.setNewDbgInfoFormatFlag(NewFlag); 133 } 134 IsNewDbgInfoFormat = NewFlag; 135 } 136 137 //===----------------------------------------------------------------------===// 138 // Argument Implementation 139 //===----------------------------------------------------------------------===// 140 141 Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo) 142 : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) { 143 setName(Name); 144 } 145 146 void Argument::setParent(Function *parent) { 147 Parent = parent; 148 } 149 150 bool Argument::hasNonNullAttr(bool AllowUndefOrPoison) const { 151 if (!getType()->isPointerTy()) return false; 152 if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull) && 153 (AllowUndefOrPoison || 154 getParent()->hasParamAttribute(getArgNo(), Attribute::NoUndef))) 155 return true; 156 else if (getDereferenceableBytes() > 0 && 157 !NullPointerIsDefined(getParent(), 158 getType()->getPointerAddressSpace())) 159 return true; 160 return false; 161 } 162 163 bool Argument::hasByValAttr() const { 164 if (!getType()->isPointerTy()) return false; 165 return hasAttribute(Attribute::ByVal); 166 } 167 168 bool Argument::hasByRefAttr() const { 169 if (!getType()->isPointerTy()) 170 return false; 171 return hasAttribute(Attribute::ByRef); 172 } 173 174 bool Argument::hasSwiftSelfAttr() const { 175 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf); 176 } 177 178 bool Argument::hasSwiftErrorAttr() const { 179 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError); 180 } 181 182 bool Argument::hasInAllocaAttr() const { 183 if (!getType()->isPointerTy()) return false; 184 return hasAttribute(Attribute::InAlloca); 185 } 186 187 bool Argument::hasPreallocatedAttr() const { 188 if (!getType()->isPointerTy()) 189 return false; 190 return hasAttribute(Attribute::Preallocated); 191 } 192 193 bool Argument::hasPassPointeeByValueCopyAttr() const { 194 if (!getType()->isPointerTy()) return false; 195 AttributeList Attrs = getParent()->getAttributes(); 196 return Attrs.hasParamAttr(getArgNo(), Attribute::ByVal) || 197 Attrs.hasParamAttr(getArgNo(), Attribute::InAlloca) || 198 Attrs.hasParamAttr(getArgNo(), Attribute::Preallocated); 199 } 200 201 bool Argument::hasPointeeInMemoryValueAttr() const { 202 if (!getType()->isPointerTy()) 203 return false; 204 AttributeList Attrs = getParent()->getAttributes(); 205 return Attrs.hasParamAttr(getArgNo(), Attribute::ByVal) || 206 Attrs.hasParamAttr(getArgNo(), Attribute::StructRet) || 207 Attrs.hasParamAttr(getArgNo(), Attribute::InAlloca) || 208 Attrs.hasParamAttr(getArgNo(), Attribute::Preallocated) || 209 Attrs.hasParamAttr(getArgNo(), Attribute::ByRef); 210 } 211 212 /// For a byval, sret, inalloca, or preallocated parameter, get the in-memory 213 /// parameter type. 214 static Type *getMemoryParamAllocType(AttributeSet ParamAttrs) { 215 // FIXME: All the type carrying attributes are mutually exclusive, so there 216 // should be a single query to get the stored type that handles any of them. 217 if (Type *ByValTy = ParamAttrs.getByValType()) 218 return ByValTy; 219 if (Type *ByRefTy = ParamAttrs.getByRefType()) 220 return ByRefTy; 221 if (Type *PreAllocTy = ParamAttrs.getPreallocatedType()) 222 return PreAllocTy; 223 if (Type *InAllocaTy = ParamAttrs.getInAllocaType()) 224 return InAllocaTy; 225 if (Type *SRetTy = ParamAttrs.getStructRetType()) 226 return SRetTy; 227 228 return nullptr; 229 } 230 231 uint64_t Argument::getPassPointeeByValueCopySize(const DataLayout &DL) const { 232 AttributeSet ParamAttrs = 233 getParent()->getAttributes().getParamAttrs(getArgNo()); 234 if (Type *MemTy = getMemoryParamAllocType(ParamAttrs)) 235 return DL.getTypeAllocSize(MemTy); 236 return 0; 237 } 238 239 Type *Argument::getPointeeInMemoryValueType() const { 240 AttributeSet ParamAttrs = 241 getParent()->getAttributes().getParamAttrs(getArgNo()); 242 return getMemoryParamAllocType(ParamAttrs); 243 } 244 245 MaybeAlign Argument::getParamAlign() const { 246 assert(getType()->isPointerTy() && "Only pointers have alignments"); 247 return getParent()->getParamAlign(getArgNo()); 248 } 249 250 MaybeAlign Argument::getParamStackAlign() const { 251 return getParent()->getParamStackAlign(getArgNo()); 252 } 253 254 Type *Argument::getParamByValType() const { 255 assert(getType()->isPointerTy() && "Only pointers have byval types"); 256 return getParent()->getParamByValType(getArgNo()); 257 } 258 259 Type *Argument::getParamStructRetType() const { 260 assert(getType()->isPointerTy() && "Only pointers have sret types"); 261 return getParent()->getParamStructRetType(getArgNo()); 262 } 263 264 Type *Argument::getParamByRefType() const { 265 assert(getType()->isPointerTy() && "Only pointers have byref types"); 266 return getParent()->getParamByRefType(getArgNo()); 267 } 268 269 Type *Argument::getParamInAllocaType() const { 270 assert(getType()->isPointerTy() && "Only pointers have inalloca types"); 271 return getParent()->getParamInAllocaType(getArgNo()); 272 } 273 274 uint64_t Argument::getDereferenceableBytes() const { 275 assert(getType()->isPointerTy() && 276 "Only pointers have dereferenceable bytes"); 277 return getParent()->getParamDereferenceableBytes(getArgNo()); 278 } 279 280 uint64_t Argument::getDereferenceableOrNullBytes() const { 281 assert(getType()->isPointerTy() && 282 "Only pointers have dereferenceable bytes"); 283 return getParent()->getParamDereferenceableOrNullBytes(getArgNo()); 284 } 285 286 FPClassTest Argument::getNoFPClass() const { 287 return getParent()->getParamNoFPClass(getArgNo()); 288 } 289 290 std::optional<ConstantRange> Argument::getRange() const { 291 const Attribute RangeAttr = getAttribute(llvm::Attribute::Range); 292 if (RangeAttr.isValid()) 293 return RangeAttr.getRange(); 294 return std::nullopt; 295 } 296 297 bool Argument::hasNestAttr() const { 298 if (!getType()->isPointerTy()) return false; 299 return hasAttribute(Attribute::Nest); 300 } 301 302 bool Argument::hasNoAliasAttr() const { 303 if (!getType()->isPointerTy()) return false; 304 return hasAttribute(Attribute::NoAlias); 305 } 306 307 bool Argument::hasNoCaptureAttr() const { 308 if (!getType()->isPointerTy()) return false; 309 return hasAttribute(Attribute::NoCapture); 310 } 311 312 bool Argument::hasNoFreeAttr() const { 313 if (!getType()->isPointerTy()) return false; 314 return hasAttribute(Attribute::NoFree); 315 } 316 317 bool Argument::hasStructRetAttr() const { 318 if (!getType()->isPointerTy()) return false; 319 return hasAttribute(Attribute::StructRet); 320 } 321 322 bool Argument::hasInRegAttr() const { 323 return hasAttribute(Attribute::InReg); 324 } 325 326 bool Argument::hasReturnedAttr() const { 327 return hasAttribute(Attribute::Returned); 328 } 329 330 bool Argument::hasZExtAttr() const { 331 return hasAttribute(Attribute::ZExt); 332 } 333 334 bool Argument::hasSExtAttr() const { 335 return hasAttribute(Attribute::SExt); 336 } 337 338 bool Argument::onlyReadsMemory() const { 339 AttributeList Attrs = getParent()->getAttributes(); 340 return Attrs.hasParamAttr(getArgNo(), Attribute::ReadOnly) || 341 Attrs.hasParamAttr(getArgNo(), Attribute::ReadNone); 342 } 343 344 void Argument::addAttrs(AttrBuilder &B) { 345 AttributeList AL = getParent()->getAttributes(); 346 AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B); 347 getParent()->setAttributes(AL); 348 } 349 350 void Argument::addAttr(Attribute::AttrKind Kind) { 351 getParent()->addParamAttr(getArgNo(), Kind); 352 } 353 354 void Argument::addAttr(Attribute Attr) { 355 getParent()->addParamAttr(getArgNo(), Attr); 356 } 357 358 void Argument::removeAttr(Attribute::AttrKind Kind) { 359 getParent()->removeParamAttr(getArgNo(), Kind); 360 } 361 362 void Argument::removeAttrs(const AttributeMask &AM) { 363 AttributeList AL = getParent()->getAttributes(); 364 AL = AL.removeParamAttributes(Parent->getContext(), getArgNo(), AM); 365 getParent()->setAttributes(AL); 366 } 367 368 bool Argument::hasAttribute(Attribute::AttrKind Kind) const { 369 return getParent()->hasParamAttribute(getArgNo(), Kind); 370 } 371 372 Attribute Argument::getAttribute(Attribute::AttrKind Kind) const { 373 return getParent()->getParamAttribute(getArgNo(), Kind); 374 } 375 376 //===----------------------------------------------------------------------===// 377 // Helper Methods in Function 378 //===----------------------------------------------------------------------===// 379 380 LLVMContext &Function::getContext() const { 381 return getType()->getContext(); 382 } 383 384 const DataLayout &Function::getDataLayout() const { 385 return getParent()->getDataLayout(); 386 } 387 388 unsigned Function::getInstructionCount() const { 389 unsigned NumInstrs = 0; 390 for (const BasicBlock &BB : BasicBlocks) 391 NumInstrs += std::distance(BB.instructionsWithoutDebug().begin(), 392 BB.instructionsWithoutDebug().end()); 393 return NumInstrs; 394 } 395 396 Function *Function::Create(FunctionType *Ty, LinkageTypes Linkage, 397 const Twine &N, Module &M) { 398 return Create(Ty, Linkage, M.getDataLayout().getProgramAddressSpace(), N, &M); 399 } 400 401 Function *Function::createWithDefaultAttr(FunctionType *Ty, 402 LinkageTypes Linkage, 403 unsigned AddrSpace, const Twine &N, 404 Module *M) { 405 auto *F = new (AllocMarker) Function(Ty, Linkage, AddrSpace, N, M); 406 AttrBuilder B(F->getContext()); 407 UWTableKind UWTable = M->getUwtable(); 408 if (UWTable != UWTableKind::None) 409 B.addUWTableAttr(UWTable); 410 switch (M->getFramePointer()) { 411 case FramePointerKind::None: 412 // 0 ("none") is the default. 413 break; 414 case FramePointerKind::Reserved: 415 B.addAttribute("frame-pointer", "reserved"); 416 break; 417 case FramePointerKind::NonLeaf: 418 B.addAttribute("frame-pointer", "non-leaf"); 419 break; 420 case FramePointerKind::All: 421 B.addAttribute("frame-pointer", "all"); 422 break; 423 } 424 if (M->getModuleFlag("function_return_thunk_extern")) 425 B.addAttribute(Attribute::FnRetThunkExtern); 426 StringRef DefaultCPU = F->getContext().getDefaultTargetCPU(); 427 if (!DefaultCPU.empty()) 428 B.addAttribute("target-cpu", DefaultCPU); 429 StringRef DefaultFeatures = F->getContext().getDefaultTargetFeatures(); 430 if (!DefaultFeatures.empty()) 431 B.addAttribute("target-features", DefaultFeatures); 432 433 // Check if the module attribute is present and not zero. 434 auto isModuleAttributeSet = [&](const StringRef &ModAttr) -> bool { 435 const auto *Attr = 436 mdconst::extract_or_null<ConstantInt>(M->getModuleFlag(ModAttr)); 437 return Attr && !Attr->isZero(); 438 }; 439 440 auto AddAttributeIfSet = [&](const StringRef &ModAttr) { 441 if (isModuleAttributeSet(ModAttr)) 442 B.addAttribute(ModAttr); 443 }; 444 445 StringRef SignType = "none"; 446 if (isModuleAttributeSet("sign-return-address")) 447 SignType = "non-leaf"; 448 if (isModuleAttributeSet("sign-return-address-all")) 449 SignType = "all"; 450 if (SignType != "none") { 451 B.addAttribute("sign-return-address", SignType); 452 B.addAttribute("sign-return-address-key", 453 isModuleAttributeSet("sign-return-address-with-bkey") 454 ? "b_key" 455 : "a_key"); 456 } 457 AddAttributeIfSet("branch-target-enforcement"); 458 AddAttributeIfSet("branch-protection-pauth-lr"); 459 AddAttributeIfSet("guarded-control-stack"); 460 461 F->addFnAttrs(B); 462 return F; 463 } 464 465 void Function::removeFromParent() { 466 getParent()->getFunctionList().remove(getIterator()); 467 } 468 469 void Function::eraseFromParent() { 470 getParent()->getFunctionList().erase(getIterator()); 471 } 472 473 void Function::splice(Function::iterator ToIt, Function *FromF, 474 Function::iterator FromBeginIt, 475 Function::iterator FromEndIt) { 476 #ifdef EXPENSIVE_CHECKS 477 // Check that FromBeginIt is before FromEndIt. 478 auto FromFEnd = FromF->end(); 479 for (auto It = FromBeginIt; It != FromEndIt; ++It) 480 assert(It != FromFEnd && "FromBeginIt not before FromEndIt!"); 481 #endif // EXPENSIVE_CHECKS 482 BasicBlocks.splice(ToIt, FromF->BasicBlocks, FromBeginIt, FromEndIt); 483 } 484 485 Function::iterator Function::erase(Function::iterator FromIt, 486 Function::iterator ToIt) { 487 return BasicBlocks.erase(FromIt, ToIt); 488 } 489 490 //===----------------------------------------------------------------------===// 491 // Function Implementation 492 //===----------------------------------------------------------------------===// 493 494 static unsigned computeAddrSpace(unsigned AddrSpace, Module *M) { 495 // If AS == -1 and we are passed a valid module pointer we place the function 496 // in the program address space. Otherwise we default to AS0. 497 if (AddrSpace == static_cast<unsigned>(-1)) 498 return M ? M->getDataLayout().getProgramAddressSpace() : 0; 499 return AddrSpace; 500 } 501 502 Function::Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, 503 const Twine &name, Module *ParentModule) 504 : GlobalObject(Ty, Value::FunctionVal, AllocMarker, Linkage, name, 505 computeAddrSpace(AddrSpace, ParentModule)), 506 NumArgs(Ty->getNumParams()), IsNewDbgInfoFormat(UseNewDbgInfoFormat) { 507 assert(FunctionType::isValidReturnType(getReturnType()) && 508 "invalid return type"); 509 setGlobalObjectSubClassData(0); 510 511 // We only need a symbol table for a function if the context keeps value names 512 if (!getContext().shouldDiscardValueNames()) 513 SymTab = std::make_unique<ValueSymbolTable>(NonGlobalValueMaxNameSize); 514 515 // If the function has arguments, mark them as lazily built. 516 if (Ty->getNumParams()) 517 setValueSubclassData(1); // Set the "has lazy arguments" bit. 518 519 if (ParentModule) { 520 ParentModule->getFunctionList().push_back(this); 521 IsNewDbgInfoFormat = ParentModule->IsNewDbgInfoFormat; 522 } 523 524 HasLLVMReservedName = getName().starts_with("llvm."); 525 // Ensure intrinsics have the right parameter attributes. 526 // Note, the IntID field will have been set in Value::setName if this function 527 // name is a valid intrinsic ID. 528 if (IntID) 529 setAttributes(Intrinsic::getAttributes(getContext(), IntID)); 530 } 531 532 Function::~Function() { 533 validateBlockNumbers(); 534 535 dropAllReferences(); // After this it is safe to delete instructions. 536 537 // Delete all of the method arguments and unlink from symbol table... 538 if (Arguments) 539 clearArguments(); 540 541 // Remove the function from the on-the-side GC table. 542 clearGC(); 543 } 544 545 void Function::BuildLazyArguments() const { 546 // Create the arguments vector, all arguments start out unnamed. 547 auto *FT = getFunctionType(); 548 if (NumArgs > 0) { 549 Arguments = std::allocator<Argument>().allocate(NumArgs); 550 for (unsigned i = 0, e = NumArgs; i != e; ++i) { 551 Type *ArgTy = FT->getParamType(i); 552 assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!"); 553 new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i); 554 } 555 } 556 557 // Clear the lazy arguments bit. 558 unsigned SDC = getSubclassDataFromValue(); 559 SDC &= ~(1 << 0); 560 const_cast<Function*>(this)->setValueSubclassData(SDC); 561 assert(!hasLazyArguments()); 562 } 563 564 static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) { 565 return MutableArrayRef<Argument>(Args, Count); 566 } 567 568 bool Function::isConstrainedFPIntrinsic() const { 569 return Intrinsic::isConstrainedFPIntrinsic(getIntrinsicID()); 570 } 571 572 void Function::clearArguments() { 573 for (Argument &A : makeArgArray(Arguments, NumArgs)) { 574 A.setName(""); 575 A.~Argument(); 576 } 577 std::allocator<Argument>().deallocate(Arguments, NumArgs); 578 Arguments = nullptr; 579 } 580 581 void Function::stealArgumentListFrom(Function &Src) { 582 assert(isDeclaration() && "Expected no references to current arguments"); 583 584 // Drop the current arguments, if any, and set the lazy argument bit. 585 if (!hasLazyArguments()) { 586 assert(llvm::all_of(makeArgArray(Arguments, NumArgs), 587 [](const Argument &A) { return A.use_empty(); }) && 588 "Expected arguments to be unused in declaration"); 589 clearArguments(); 590 setValueSubclassData(getSubclassDataFromValue() | (1 << 0)); 591 } 592 593 // Nothing to steal if Src has lazy arguments. 594 if (Src.hasLazyArguments()) 595 return; 596 597 // Steal arguments from Src, and fix the lazy argument bits. 598 assert(arg_size() == Src.arg_size()); 599 Arguments = Src.Arguments; 600 Src.Arguments = nullptr; 601 for (Argument &A : makeArgArray(Arguments, NumArgs)) { 602 // FIXME: This does the work of transferNodesFromList inefficiently. 603 SmallString<128> Name; 604 if (A.hasName()) 605 Name = A.getName(); 606 if (!Name.empty()) 607 A.setName(""); 608 A.setParent(this); 609 if (!Name.empty()) 610 A.setName(Name); 611 } 612 613 setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0)); 614 assert(!hasLazyArguments()); 615 Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0)); 616 } 617 618 void Function::deleteBodyImpl(bool ShouldDrop) { 619 setIsMaterializable(false); 620 621 for (BasicBlock &BB : *this) 622 BB.dropAllReferences(); 623 624 // Delete all basic blocks. They are now unused, except possibly by 625 // blockaddresses, but BasicBlock's destructor takes care of those. 626 while (!BasicBlocks.empty()) 627 BasicBlocks.begin()->eraseFromParent(); 628 629 if (getNumOperands()) { 630 if (ShouldDrop) { 631 // Drop uses of any optional data (real or placeholder). 632 User::dropAllReferences(); 633 setNumHungOffUseOperands(0); 634 } else { 635 // The code needs to match Function::allocHungoffUselist(). 636 auto *CPN = ConstantPointerNull::get(PointerType::get(getContext(), 0)); 637 Op<0>().set(CPN); 638 Op<1>().set(CPN); 639 Op<2>().set(CPN); 640 } 641 setValueSubclassData(getSubclassDataFromValue() & ~0xe); 642 } 643 644 // Metadata is stored in a side-table. 645 clearMetadata(); 646 } 647 648 void Function::addAttributeAtIndex(unsigned i, Attribute Attr) { 649 AttributeSets = AttributeSets.addAttributeAtIndex(getContext(), i, Attr); 650 } 651 652 void Function::addFnAttr(Attribute::AttrKind Kind) { 653 AttributeSets = AttributeSets.addFnAttribute(getContext(), Kind); 654 } 655 656 void Function::addFnAttr(StringRef Kind, StringRef Val) { 657 AttributeSets = AttributeSets.addFnAttribute(getContext(), Kind, Val); 658 } 659 660 void Function::addFnAttr(Attribute Attr) { 661 AttributeSets = AttributeSets.addFnAttribute(getContext(), Attr); 662 } 663 664 void Function::addFnAttrs(const AttrBuilder &Attrs) { 665 AttributeSets = AttributeSets.addFnAttributes(getContext(), Attrs); 666 } 667 668 void Function::addRetAttr(Attribute::AttrKind Kind) { 669 AttributeSets = AttributeSets.addRetAttribute(getContext(), Kind); 670 } 671 672 void Function::addRetAttr(Attribute Attr) { 673 AttributeSets = AttributeSets.addRetAttribute(getContext(), Attr); 674 } 675 676 void Function::addRetAttrs(const AttrBuilder &Attrs) { 677 AttributeSets = AttributeSets.addRetAttributes(getContext(), Attrs); 678 } 679 680 void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) { 681 AttributeSets = AttributeSets.addParamAttribute(getContext(), ArgNo, Kind); 682 } 683 684 void Function::addParamAttr(unsigned ArgNo, Attribute Attr) { 685 AttributeSets = AttributeSets.addParamAttribute(getContext(), ArgNo, Attr); 686 } 687 688 void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) { 689 AttributeSets = AttributeSets.addParamAttributes(getContext(), ArgNo, Attrs); 690 } 691 692 void Function::removeAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) { 693 AttributeSets = AttributeSets.removeAttributeAtIndex(getContext(), i, Kind); 694 } 695 696 void Function::removeAttributeAtIndex(unsigned i, StringRef Kind) { 697 AttributeSets = AttributeSets.removeAttributeAtIndex(getContext(), i, Kind); 698 } 699 700 void Function::removeFnAttr(Attribute::AttrKind Kind) { 701 AttributeSets = AttributeSets.removeFnAttribute(getContext(), Kind); 702 } 703 704 void Function::removeFnAttr(StringRef Kind) { 705 AttributeSets = AttributeSets.removeFnAttribute(getContext(), Kind); 706 } 707 708 void Function::removeFnAttrs(const AttributeMask &AM) { 709 AttributeSets = AttributeSets.removeFnAttributes(getContext(), AM); 710 } 711 712 void Function::removeRetAttr(Attribute::AttrKind Kind) { 713 AttributeSets = AttributeSets.removeRetAttribute(getContext(), Kind); 714 } 715 716 void Function::removeRetAttr(StringRef Kind) { 717 AttributeSets = AttributeSets.removeRetAttribute(getContext(), Kind); 718 } 719 720 void Function::removeRetAttrs(const AttributeMask &Attrs) { 721 AttributeSets = AttributeSets.removeRetAttributes(getContext(), Attrs); 722 } 723 724 void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) { 725 AttributeSets = AttributeSets.removeParamAttribute(getContext(), ArgNo, Kind); 726 } 727 728 void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) { 729 AttributeSets = AttributeSets.removeParamAttribute(getContext(), ArgNo, Kind); 730 } 731 732 void Function::removeParamAttrs(unsigned ArgNo, const AttributeMask &Attrs) { 733 AttributeSets = 734 AttributeSets.removeParamAttributes(getContext(), ArgNo, Attrs); 735 } 736 737 void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) { 738 AttributeSets = 739 AttributeSets.addDereferenceableParamAttr(getContext(), ArgNo, Bytes); 740 } 741 742 bool Function::hasFnAttribute(Attribute::AttrKind Kind) const { 743 return AttributeSets.hasFnAttr(Kind); 744 } 745 746 bool Function::hasFnAttribute(StringRef Kind) const { 747 return AttributeSets.hasFnAttr(Kind); 748 } 749 750 bool Function::hasRetAttribute(Attribute::AttrKind Kind) const { 751 return AttributeSets.hasRetAttr(Kind); 752 } 753 754 bool Function::hasParamAttribute(unsigned ArgNo, 755 Attribute::AttrKind Kind) const { 756 return AttributeSets.hasParamAttr(ArgNo, Kind); 757 } 758 759 Attribute Function::getAttributeAtIndex(unsigned i, 760 Attribute::AttrKind Kind) const { 761 return AttributeSets.getAttributeAtIndex(i, Kind); 762 } 763 764 Attribute Function::getAttributeAtIndex(unsigned i, StringRef Kind) const { 765 return AttributeSets.getAttributeAtIndex(i, Kind); 766 } 767 768 bool Function::hasAttributeAtIndex(unsigned Idx, 769 Attribute::AttrKind Kind) const { 770 return AttributeSets.hasAttributeAtIndex(Idx, Kind); 771 } 772 773 Attribute Function::getFnAttribute(Attribute::AttrKind Kind) const { 774 return AttributeSets.getFnAttr(Kind); 775 } 776 777 Attribute Function::getFnAttribute(StringRef Kind) const { 778 return AttributeSets.getFnAttr(Kind); 779 } 780 781 Attribute Function::getRetAttribute(Attribute::AttrKind Kind) const { 782 return AttributeSets.getRetAttr(Kind); 783 } 784 785 uint64_t Function::getFnAttributeAsParsedInteger(StringRef Name, 786 uint64_t Default) const { 787 Attribute A = getFnAttribute(Name); 788 uint64_t Result = Default; 789 if (A.isStringAttribute()) { 790 StringRef Str = A.getValueAsString(); 791 if (Str.getAsInteger(0, Result)) 792 getContext().emitError("cannot parse integer attribute " + Name); 793 } 794 795 return Result; 796 } 797 798 /// gets the specified attribute from the list of attributes. 799 Attribute Function::getParamAttribute(unsigned ArgNo, 800 Attribute::AttrKind Kind) const { 801 return AttributeSets.getParamAttr(ArgNo, Kind); 802 } 803 804 void Function::addDereferenceableOrNullParamAttr(unsigned ArgNo, 805 uint64_t Bytes) { 806 AttributeSets = AttributeSets.addDereferenceableOrNullParamAttr(getContext(), 807 ArgNo, Bytes); 808 } 809 810 void Function::addRangeRetAttr(const ConstantRange &CR) { 811 AttributeSets = AttributeSets.addRangeRetAttr(getContext(), CR); 812 } 813 814 DenormalMode Function::getDenormalMode(const fltSemantics &FPType) const { 815 if (&FPType == &APFloat::IEEEsingle()) { 816 DenormalMode Mode = getDenormalModeF32Raw(); 817 // If the f32 variant of the attribute isn't specified, try to use the 818 // generic one. 819 if (Mode.isValid()) 820 return Mode; 821 } 822 823 return getDenormalModeRaw(); 824 } 825 826 DenormalMode Function::getDenormalModeRaw() const { 827 Attribute Attr = getFnAttribute("denormal-fp-math"); 828 StringRef Val = Attr.getValueAsString(); 829 return parseDenormalFPAttribute(Val); 830 } 831 832 DenormalMode Function::getDenormalModeF32Raw() const { 833 Attribute Attr = getFnAttribute("denormal-fp-math-f32"); 834 if (Attr.isValid()) { 835 StringRef Val = Attr.getValueAsString(); 836 return parseDenormalFPAttribute(Val); 837 } 838 839 return DenormalMode::getInvalid(); 840 } 841 842 const std::string &Function::getGC() const { 843 assert(hasGC() && "Function has no collector"); 844 return getContext().getGC(*this); 845 } 846 847 void Function::setGC(std::string Str) { 848 setValueSubclassDataBit(14, !Str.empty()); 849 getContext().setGC(*this, std::move(Str)); 850 } 851 852 void Function::clearGC() { 853 if (!hasGC()) 854 return; 855 getContext().deleteGC(*this); 856 setValueSubclassDataBit(14, false); 857 } 858 859 bool Function::hasStackProtectorFnAttr() const { 860 return hasFnAttribute(Attribute::StackProtect) || 861 hasFnAttribute(Attribute::StackProtectStrong) || 862 hasFnAttribute(Attribute::StackProtectReq); 863 } 864 865 /// Copy all additional attributes (those not needed to create a Function) from 866 /// the Function Src to this one. 867 void Function::copyAttributesFrom(const Function *Src) { 868 GlobalObject::copyAttributesFrom(Src); 869 setCallingConv(Src->getCallingConv()); 870 setAttributes(Src->getAttributes()); 871 if (Src->hasGC()) 872 setGC(Src->getGC()); 873 else 874 clearGC(); 875 if (Src->hasPersonalityFn()) 876 setPersonalityFn(Src->getPersonalityFn()); 877 if (Src->hasPrefixData()) 878 setPrefixData(Src->getPrefixData()); 879 if (Src->hasPrologueData()) 880 setPrologueData(Src->getPrologueData()); 881 } 882 883 MemoryEffects Function::getMemoryEffects() const { 884 return getAttributes().getMemoryEffects(); 885 } 886 void Function::setMemoryEffects(MemoryEffects ME) { 887 addFnAttr(Attribute::getWithMemoryEffects(getContext(), ME)); 888 } 889 890 /// Determine if the function does not access memory. 891 bool Function::doesNotAccessMemory() const { 892 return getMemoryEffects().doesNotAccessMemory(); 893 } 894 void Function::setDoesNotAccessMemory() { 895 setMemoryEffects(MemoryEffects::none()); 896 } 897 898 /// Determine if the function does not access or only reads memory. 899 bool Function::onlyReadsMemory() const { 900 return getMemoryEffects().onlyReadsMemory(); 901 } 902 void Function::setOnlyReadsMemory() { 903 setMemoryEffects(getMemoryEffects() & MemoryEffects::readOnly()); 904 } 905 906 /// Determine if the function does not access or only writes memory. 907 bool Function::onlyWritesMemory() const { 908 return getMemoryEffects().onlyWritesMemory(); 909 } 910 void Function::setOnlyWritesMemory() { 911 setMemoryEffects(getMemoryEffects() & MemoryEffects::writeOnly()); 912 } 913 914 /// Determine if the call can access memmory only using pointers based 915 /// on its arguments. 916 bool Function::onlyAccessesArgMemory() const { 917 return getMemoryEffects().onlyAccessesArgPointees(); 918 } 919 void Function::setOnlyAccessesArgMemory() { 920 setMemoryEffects(getMemoryEffects() & MemoryEffects::argMemOnly()); 921 } 922 923 /// Determine if the function may only access memory that is 924 /// inaccessible from the IR. 925 bool Function::onlyAccessesInaccessibleMemory() const { 926 return getMemoryEffects().onlyAccessesInaccessibleMem(); 927 } 928 void Function::setOnlyAccessesInaccessibleMemory() { 929 setMemoryEffects(getMemoryEffects() & MemoryEffects::inaccessibleMemOnly()); 930 } 931 932 /// Determine if the function may only access memory that is 933 /// either inaccessible from the IR or pointed to by its arguments. 934 bool Function::onlyAccessesInaccessibleMemOrArgMem() const { 935 return getMemoryEffects().onlyAccessesInaccessibleOrArgMem(); 936 } 937 void Function::setOnlyAccessesInaccessibleMemOrArgMem() { 938 setMemoryEffects(getMemoryEffects() & 939 MemoryEffects::inaccessibleOrArgMemOnly()); 940 } 941 942 /// Table of string intrinsic names indexed by enum value. 943 static const char * const IntrinsicNameTable[] = { 944 "not_intrinsic", 945 #define GET_INTRINSIC_NAME_TABLE 946 #include "llvm/IR/IntrinsicImpl.inc" 947 #undef GET_INTRINSIC_NAME_TABLE 948 }; 949 950 /// Table of per-target intrinsic name tables. 951 #define GET_INTRINSIC_TARGET_DATA 952 #include "llvm/IR/IntrinsicImpl.inc" 953 #undef GET_INTRINSIC_TARGET_DATA 954 955 bool Function::isTargetIntrinsic(Intrinsic::ID IID) { 956 return IID > TargetInfos[0].Count; 957 } 958 959 bool Function::isTargetIntrinsic() const { 960 return isTargetIntrinsic(IntID); 961 } 962 963 /// Find the segment of \c IntrinsicNameTable for intrinsics with the same 964 /// target as \c Name, or the generic table if \c Name is not target specific. 965 /// 966 /// Returns the relevant slice of \c IntrinsicNameTable 967 static ArrayRef<const char *> findTargetSubtable(StringRef Name) { 968 assert(Name.starts_with("llvm.")); 969 970 ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos); 971 // Drop "llvm." and take the first dotted component. That will be the target 972 // if this is target specific. 973 StringRef Target = Name.drop_front(5).split('.').first; 974 auto It = partition_point( 975 Targets, [=](const IntrinsicTargetInfo &TI) { return TI.Name < Target; }); 976 // We've either found the target or just fall back to the generic set, which 977 // is always first. 978 const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0]; 979 return ArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count); 980 } 981 982 /// This does the actual lookup of an intrinsic ID which 983 /// matches the given function name. 984 Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) { 985 ArrayRef<const char *> NameTable = findTargetSubtable(Name); 986 int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name); 987 if (Idx == -1) 988 return Intrinsic::not_intrinsic; 989 990 // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have 991 // an index into a sub-table. 992 int Adjust = NameTable.data() - IntrinsicNameTable; 993 Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust); 994 995 // If the intrinsic is not overloaded, require an exact match. If it is 996 // overloaded, require either exact or prefix match. 997 const auto MatchSize = strlen(NameTable[Idx]); 998 assert(Name.size() >= MatchSize && "Expected either exact or prefix match"); 999 bool IsExactMatch = Name.size() == MatchSize; 1000 return IsExactMatch || Intrinsic::isOverloaded(ID) ? ID 1001 : Intrinsic::not_intrinsic; 1002 } 1003 1004 void Function::updateAfterNameChange() { 1005 LibFuncCache = UnknownLibFunc; 1006 StringRef Name = getName(); 1007 if (!Name.starts_with("llvm.")) { 1008 HasLLVMReservedName = false; 1009 IntID = Intrinsic::not_intrinsic; 1010 return; 1011 } 1012 HasLLVMReservedName = true; 1013 IntID = lookupIntrinsicID(Name); 1014 } 1015 1016 /// Returns a stable mangling for the type specified for use in the name 1017 /// mangling scheme used by 'any' types in intrinsic signatures. The mangling 1018 /// of named types is simply their name. Manglings for unnamed types consist 1019 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions) 1020 /// combined with the mangling of their component types. A vararg function 1021 /// type will have a suffix of 'vararg'. Since function types can contain 1022 /// other function types, we close a function type mangling with suffix 'f' 1023 /// which can't be confused with it's prefix. This ensures we don't have 1024 /// collisions between two unrelated function types. Otherwise, you might 1025 /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.) 1026 /// The HasUnnamedType boolean is set if an unnamed type was encountered, 1027 /// indicating that extra care must be taken to ensure a unique name. 1028 static std::string getMangledTypeStr(Type *Ty, bool &HasUnnamedType) { 1029 std::string Result; 1030 if (PointerType *PTyp = dyn_cast<PointerType>(Ty)) { 1031 Result += "p" + utostr(PTyp->getAddressSpace()); 1032 } else if (ArrayType *ATyp = dyn_cast<ArrayType>(Ty)) { 1033 Result += "a" + utostr(ATyp->getNumElements()) + 1034 getMangledTypeStr(ATyp->getElementType(), HasUnnamedType); 1035 } else if (StructType *STyp = dyn_cast<StructType>(Ty)) { 1036 if (!STyp->isLiteral()) { 1037 Result += "s_"; 1038 if (STyp->hasName()) 1039 Result += STyp->getName(); 1040 else 1041 HasUnnamedType = true; 1042 } else { 1043 Result += "sl_"; 1044 for (auto *Elem : STyp->elements()) 1045 Result += getMangledTypeStr(Elem, HasUnnamedType); 1046 } 1047 // Ensure nested structs are distinguishable. 1048 Result += "s"; 1049 } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) { 1050 Result += "f_" + getMangledTypeStr(FT->getReturnType(), HasUnnamedType); 1051 for (size_t i = 0; i < FT->getNumParams(); i++) 1052 Result += getMangledTypeStr(FT->getParamType(i), HasUnnamedType); 1053 if (FT->isVarArg()) 1054 Result += "vararg"; 1055 // Ensure nested function types are distinguishable. 1056 Result += "f"; 1057 } else if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1058 ElementCount EC = VTy->getElementCount(); 1059 if (EC.isScalable()) 1060 Result += "nx"; 1061 Result += "v" + utostr(EC.getKnownMinValue()) + 1062 getMangledTypeStr(VTy->getElementType(), HasUnnamedType); 1063 } else if (TargetExtType *TETy = dyn_cast<TargetExtType>(Ty)) { 1064 Result += "t"; 1065 Result += TETy->getName(); 1066 for (Type *ParamTy : TETy->type_params()) 1067 Result += "_" + getMangledTypeStr(ParamTy, HasUnnamedType); 1068 for (unsigned IntParam : TETy->int_params()) 1069 Result += "_" + utostr(IntParam); 1070 // Ensure nested target extension types are distinguishable. 1071 Result += "t"; 1072 } else if (Ty) { 1073 switch (Ty->getTypeID()) { 1074 default: llvm_unreachable("Unhandled type"); 1075 case Type::VoidTyID: Result += "isVoid"; break; 1076 case Type::MetadataTyID: Result += "Metadata"; break; 1077 case Type::HalfTyID: Result += "f16"; break; 1078 case Type::BFloatTyID: Result += "bf16"; break; 1079 case Type::FloatTyID: Result += "f32"; break; 1080 case Type::DoubleTyID: Result += "f64"; break; 1081 case Type::X86_FP80TyID: Result += "f80"; break; 1082 case Type::FP128TyID: Result += "f128"; break; 1083 case Type::PPC_FP128TyID: 1084 Result += "ppcf128"; 1085 break; 1086 case Type::X86_AMXTyID: Result += "x86amx"; break; 1087 case Type::IntegerTyID: 1088 Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth()); 1089 break; 1090 } 1091 } 1092 return Result; 1093 } 1094 1095 StringRef Intrinsic::getBaseName(ID id) { 1096 assert(id < num_intrinsics && "Invalid intrinsic ID!"); 1097 return IntrinsicNameTable[id]; 1098 } 1099 1100 StringRef Intrinsic::getName(ID id) { 1101 assert(id < num_intrinsics && "Invalid intrinsic ID!"); 1102 assert(!Intrinsic::isOverloaded(id) && 1103 "This version of getName does not support overloading"); 1104 return getBaseName(id); 1105 } 1106 1107 static std::string getIntrinsicNameImpl(Intrinsic::ID Id, ArrayRef<Type *> Tys, 1108 Module *M, FunctionType *FT, 1109 bool EarlyModuleCheck) { 1110 1111 assert(Id < Intrinsic::num_intrinsics && "Invalid intrinsic ID!"); 1112 assert((Tys.empty() || Intrinsic::isOverloaded(Id)) && 1113 "This version of getName is for overloaded intrinsics only"); 1114 (void)EarlyModuleCheck; 1115 assert((!EarlyModuleCheck || M || 1116 !any_of(Tys, [](Type *T) { return isa<PointerType>(T); })) && 1117 "Intrinsic overloading on pointer types need to provide a Module"); 1118 bool HasUnnamedType = false; 1119 std::string Result(Intrinsic::getBaseName(Id)); 1120 for (Type *Ty : Tys) 1121 Result += "." + getMangledTypeStr(Ty, HasUnnamedType); 1122 if (HasUnnamedType) { 1123 assert(M && "unnamed types need a module"); 1124 if (!FT) 1125 FT = Intrinsic::getType(M->getContext(), Id, Tys); 1126 else 1127 assert((FT == Intrinsic::getType(M->getContext(), Id, Tys)) && 1128 "Provided FunctionType must match arguments"); 1129 return M->getUniqueIntrinsicName(Result, Id, FT); 1130 } 1131 return Result; 1132 } 1133 1134 std::string Intrinsic::getName(ID Id, ArrayRef<Type *> Tys, Module *M, 1135 FunctionType *FT) { 1136 assert(M && "We need to have a Module"); 1137 return getIntrinsicNameImpl(Id, Tys, M, FT, true); 1138 } 1139 1140 std::string Intrinsic::getNameNoUnnamedTypes(ID Id, ArrayRef<Type *> Tys) { 1141 return getIntrinsicNameImpl(Id, Tys, nullptr, nullptr, false); 1142 } 1143 1144 /// IIT_Info - These are enumerators that describe the entries returned by the 1145 /// getIntrinsicInfoTableEntries function. 1146 /// 1147 /// Defined in Intrinsics.td. 1148 enum IIT_Info { 1149 #define GET_INTRINSIC_IITINFO 1150 #include "llvm/IR/IntrinsicImpl.inc" 1151 #undef GET_INTRINSIC_IITINFO 1152 }; 1153 1154 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos, 1155 IIT_Info LastInfo, 1156 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) { 1157 using namespace Intrinsic; 1158 1159 bool IsScalableVector = (LastInfo == IIT_SCALABLE_VEC); 1160 1161 IIT_Info Info = IIT_Info(Infos[NextElt++]); 1162 unsigned StructElts = 2; 1163 1164 switch (Info) { 1165 case IIT_Done: 1166 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0)); 1167 return; 1168 case IIT_VARARG: 1169 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0)); 1170 return; 1171 case IIT_MMX: 1172 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0)); 1173 return; 1174 case IIT_AMX: 1175 OutputTable.push_back(IITDescriptor::get(IITDescriptor::AMX, 0)); 1176 return; 1177 case IIT_TOKEN: 1178 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0)); 1179 return; 1180 case IIT_METADATA: 1181 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0)); 1182 return; 1183 case IIT_F16: 1184 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0)); 1185 return; 1186 case IIT_BF16: 1187 OutputTable.push_back(IITDescriptor::get(IITDescriptor::BFloat, 0)); 1188 return; 1189 case IIT_F32: 1190 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0)); 1191 return; 1192 case IIT_F64: 1193 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0)); 1194 return; 1195 case IIT_F128: 1196 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0)); 1197 return; 1198 case IIT_PPCF128: 1199 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PPCQuad, 0)); 1200 return; 1201 case IIT_I1: 1202 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1)); 1203 return; 1204 case IIT_I2: 1205 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 2)); 1206 return; 1207 case IIT_I4: 1208 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 4)); 1209 return; 1210 case IIT_AARCH64_SVCOUNT: 1211 OutputTable.push_back(IITDescriptor::get(IITDescriptor::AArch64Svcount, 0)); 1212 return; 1213 case IIT_I8: 1214 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8)); 1215 return; 1216 case IIT_I16: 1217 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16)); 1218 return; 1219 case IIT_I32: 1220 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32)); 1221 return; 1222 case IIT_I64: 1223 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64)); 1224 return; 1225 case IIT_I128: 1226 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128)); 1227 return; 1228 case IIT_V1: 1229 OutputTable.push_back(IITDescriptor::getVector(1, IsScalableVector)); 1230 DecodeIITType(NextElt, Infos, Info, OutputTable); 1231 return; 1232 case IIT_V2: 1233 OutputTable.push_back(IITDescriptor::getVector(2, IsScalableVector)); 1234 DecodeIITType(NextElt, Infos, Info, OutputTable); 1235 return; 1236 case IIT_V3: 1237 OutputTable.push_back(IITDescriptor::getVector(3, IsScalableVector)); 1238 DecodeIITType(NextElt, Infos, Info, OutputTable); 1239 return; 1240 case IIT_V4: 1241 OutputTable.push_back(IITDescriptor::getVector(4, IsScalableVector)); 1242 DecodeIITType(NextElt, Infos, Info, OutputTable); 1243 return; 1244 case IIT_V6: 1245 OutputTable.push_back(IITDescriptor::getVector(6, IsScalableVector)); 1246 DecodeIITType(NextElt, Infos, Info, OutputTable); 1247 return; 1248 case IIT_V8: 1249 OutputTable.push_back(IITDescriptor::getVector(8, IsScalableVector)); 1250 DecodeIITType(NextElt, Infos, Info, OutputTable); 1251 return; 1252 case IIT_V10: 1253 OutputTable.push_back(IITDescriptor::getVector(10, IsScalableVector)); 1254 DecodeIITType(NextElt, Infos, Info, OutputTable); 1255 return; 1256 case IIT_V16: 1257 OutputTable.push_back(IITDescriptor::getVector(16, IsScalableVector)); 1258 DecodeIITType(NextElt, Infos, Info, OutputTable); 1259 return; 1260 case IIT_V32: 1261 OutputTable.push_back(IITDescriptor::getVector(32, IsScalableVector)); 1262 DecodeIITType(NextElt, Infos, Info, OutputTable); 1263 return; 1264 case IIT_V64: 1265 OutputTable.push_back(IITDescriptor::getVector(64, IsScalableVector)); 1266 DecodeIITType(NextElt, Infos, Info, OutputTable); 1267 return; 1268 case IIT_V128: 1269 OutputTable.push_back(IITDescriptor::getVector(128, IsScalableVector)); 1270 DecodeIITType(NextElt, Infos, Info, OutputTable); 1271 return; 1272 case IIT_V256: 1273 OutputTable.push_back(IITDescriptor::getVector(256, IsScalableVector)); 1274 DecodeIITType(NextElt, Infos, Info, OutputTable); 1275 return; 1276 case IIT_V512: 1277 OutputTable.push_back(IITDescriptor::getVector(512, IsScalableVector)); 1278 DecodeIITType(NextElt, Infos, Info, OutputTable); 1279 return; 1280 case IIT_V1024: 1281 OutputTable.push_back(IITDescriptor::getVector(1024, IsScalableVector)); 1282 DecodeIITType(NextElt, Infos, Info, OutputTable); 1283 return; 1284 case IIT_EXTERNREF: 1285 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 10)); 1286 return; 1287 case IIT_FUNCREF: 1288 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 20)); 1289 return; 1290 case IIT_PTR: 1291 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0)); 1292 return; 1293 case IIT_ANYPTR: // [ANYPTR addrspace] 1294 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 1295 Infos[NextElt++])); 1296 return; 1297 case IIT_ARG: { 1298 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1299 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo)); 1300 return; 1301 } 1302 case IIT_EXTEND_ARG: { 1303 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1304 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument, 1305 ArgInfo)); 1306 return; 1307 } 1308 case IIT_TRUNC_ARG: { 1309 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1310 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument, 1311 ArgInfo)); 1312 return; 1313 } 1314 case IIT_HALF_VEC_ARG: { 1315 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1316 OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument, 1317 ArgInfo)); 1318 return; 1319 } 1320 case IIT_SAME_VEC_WIDTH_ARG: { 1321 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1322 OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument, 1323 ArgInfo)); 1324 return; 1325 } 1326 case IIT_VEC_OF_ANYPTRS_TO_ELT: { 1327 unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1328 unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1329 OutputTable.push_back( 1330 IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo)); 1331 return; 1332 } 1333 case IIT_EMPTYSTRUCT: 1334 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0)); 1335 return; 1336 case IIT_STRUCT9: ++StructElts; [[fallthrough]]; 1337 case IIT_STRUCT8: ++StructElts; [[fallthrough]]; 1338 case IIT_STRUCT7: ++StructElts; [[fallthrough]]; 1339 case IIT_STRUCT6: ++StructElts; [[fallthrough]]; 1340 case IIT_STRUCT5: ++StructElts; [[fallthrough]]; 1341 case IIT_STRUCT4: ++StructElts; [[fallthrough]]; 1342 case IIT_STRUCT3: ++StructElts; [[fallthrough]]; 1343 case IIT_STRUCT2: { 1344 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts)); 1345 1346 for (unsigned i = 0; i != StructElts; ++i) 1347 DecodeIITType(NextElt, Infos, Info, OutputTable); 1348 return; 1349 } 1350 case IIT_SUBDIVIDE2_ARG: { 1351 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1352 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide2Argument, 1353 ArgInfo)); 1354 return; 1355 } 1356 case IIT_SUBDIVIDE4_ARG: { 1357 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1358 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide4Argument, 1359 ArgInfo)); 1360 return; 1361 } 1362 case IIT_VEC_ELEMENT: { 1363 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1364 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecElementArgument, 1365 ArgInfo)); 1366 return; 1367 } 1368 case IIT_SCALABLE_VEC: { 1369 DecodeIITType(NextElt, Infos, Info, OutputTable); 1370 return; 1371 } 1372 case IIT_VEC_OF_BITCASTS_TO_INT: { 1373 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1374 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfBitcastsToInt, 1375 ArgInfo)); 1376 return; 1377 } 1378 } 1379 llvm_unreachable("unhandled"); 1380 } 1381 1382 #define GET_INTRINSIC_GENERATOR_GLOBAL 1383 #include "llvm/IR/IntrinsicImpl.inc" 1384 #undef GET_INTRINSIC_GENERATOR_GLOBAL 1385 1386 void Intrinsic::getIntrinsicInfoTableEntries(ID id, 1387 SmallVectorImpl<IITDescriptor> &T){ 1388 static_assert(sizeof(IIT_Table[0]) == 2, 1389 "Expect 16-bit entries in IIT_Table"); 1390 // Check to see if the intrinsic's type was expressible by the table. 1391 uint16_t TableVal = IIT_Table[id - 1]; 1392 1393 // Decode the TableVal into an array of IITValues. 1394 SmallVector<unsigned char> IITValues; 1395 ArrayRef<unsigned char> IITEntries; 1396 unsigned NextElt = 0; 1397 if (TableVal >> 15) { 1398 // This is an offset into the IIT_LongEncodingTable. 1399 IITEntries = IIT_LongEncodingTable; 1400 1401 // Strip sentinel bit. 1402 NextElt = TableVal & 0x7fff; 1403 } else { 1404 // If the entry was encoded into a single word in the table itself, decode 1405 // it from an array of nibbles to an array of bytes. 1406 do { 1407 IITValues.push_back(TableVal & 0xF); 1408 TableVal >>= 4; 1409 } while (TableVal); 1410 1411 IITEntries = IITValues; 1412 NextElt = 0; 1413 } 1414 1415 // Okay, decode the table into the output vector of IITDescriptors. 1416 DecodeIITType(NextElt, IITEntries, IIT_Done, T); 1417 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0) 1418 DecodeIITType(NextElt, IITEntries, IIT_Done, T); 1419 } 1420 1421 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos, 1422 ArrayRef<Type*> Tys, LLVMContext &Context) { 1423 using namespace Intrinsic; 1424 1425 IITDescriptor D = Infos.front(); 1426 Infos = Infos.slice(1); 1427 1428 switch (D.Kind) { 1429 case IITDescriptor::Void: return Type::getVoidTy(Context); 1430 case IITDescriptor::VarArg: return Type::getVoidTy(Context); 1431 case IITDescriptor::MMX: 1432 return llvm::FixedVectorType::get(llvm::IntegerType::get(Context, 64), 1); 1433 case IITDescriptor::AMX: return Type::getX86_AMXTy(Context); 1434 case IITDescriptor::Token: return Type::getTokenTy(Context); 1435 case IITDescriptor::Metadata: return Type::getMetadataTy(Context); 1436 case IITDescriptor::Half: return Type::getHalfTy(Context); 1437 case IITDescriptor::BFloat: return Type::getBFloatTy(Context); 1438 case IITDescriptor::Float: return Type::getFloatTy(Context); 1439 case IITDescriptor::Double: return Type::getDoubleTy(Context); 1440 case IITDescriptor::Quad: return Type::getFP128Ty(Context); 1441 case IITDescriptor::PPCQuad: return Type::getPPC_FP128Ty(Context); 1442 case IITDescriptor::AArch64Svcount: 1443 return TargetExtType::get(Context, "aarch64.svcount"); 1444 1445 case IITDescriptor::Integer: 1446 return IntegerType::get(Context, D.Integer_Width); 1447 case IITDescriptor::Vector: 1448 return VectorType::get(DecodeFixedType(Infos, Tys, Context), 1449 D.Vector_Width); 1450 case IITDescriptor::Pointer: 1451 return PointerType::get(Context, D.Pointer_AddressSpace); 1452 case IITDescriptor::Struct: { 1453 SmallVector<Type *, 8> Elts; 1454 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 1455 Elts.push_back(DecodeFixedType(Infos, Tys, Context)); 1456 return StructType::get(Context, Elts); 1457 } 1458 case IITDescriptor::Argument: 1459 return Tys[D.getArgumentNumber()]; 1460 case IITDescriptor::ExtendArgument: { 1461 Type *Ty = Tys[D.getArgumentNumber()]; 1462 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1463 return VectorType::getExtendedElementVectorType(VTy); 1464 1465 return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth()); 1466 } 1467 case IITDescriptor::TruncArgument: { 1468 Type *Ty = Tys[D.getArgumentNumber()]; 1469 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1470 return VectorType::getTruncatedElementVectorType(VTy); 1471 1472 IntegerType *ITy = cast<IntegerType>(Ty); 1473 assert(ITy->getBitWidth() % 2 == 0); 1474 return IntegerType::get(Context, ITy->getBitWidth() / 2); 1475 } 1476 case IITDescriptor::Subdivide2Argument: 1477 case IITDescriptor::Subdivide4Argument: { 1478 Type *Ty = Tys[D.getArgumentNumber()]; 1479 VectorType *VTy = dyn_cast<VectorType>(Ty); 1480 assert(VTy && "Expected an argument of Vector Type"); 1481 int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2; 1482 return VectorType::getSubdividedVectorType(VTy, SubDivs); 1483 } 1484 case IITDescriptor::HalfVecArgument: 1485 return VectorType::getHalfElementsVectorType(cast<VectorType>( 1486 Tys[D.getArgumentNumber()])); 1487 case IITDescriptor::SameVecWidthArgument: { 1488 Type *EltTy = DecodeFixedType(Infos, Tys, Context); 1489 Type *Ty = Tys[D.getArgumentNumber()]; 1490 if (auto *VTy = dyn_cast<VectorType>(Ty)) 1491 return VectorType::get(EltTy, VTy->getElementCount()); 1492 return EltTy; 1493 } 1494 case IITDescriptor::VecElementArgument: { 1495 Type *Ty = Tys[D.getArgumentNumber()]; 1496 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1497 return VTy->getElementType(); 1498 llvm_unreachable("Expected an argument of Vector Type"); 1499 } 1500 case IITDescriptor::VecOfBitcastsToInt: { 1501 Type *Ty = Tys[D.getArgumentNumber()]; 1502 VectorType *VTy = dyn_cast<VectorType>(Ty); 1503 assert(VTy && "Expected an argument of Vector Type"); 1504 return VectorType::getInteger(VTy); 1505 } 1506 case IITDescriptor::VecOfAnyPtrsToElt: 1507 // Return the overloaded type (which determines the pointers address space) 1508 return Tys[D.getOverloadArgNumber()]; 1509 } 1510 llvm_unreachable("unhandled"); 1511 } 1512 1513 FunctionType *Intrinsic::getType(LLVMContext &Context, 1514 ID id, ArrayRef<Type*> Tys) { 1515 SmallVector<IITDescriptor, 8> Table; 1516 getIntrinsicInfoTableEntries(id, Table); 1517 1518 ArrayRef<IITDescriptor> TableRef = Table; 1519 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context); 1520 1521 SmallVector<Type*, 8> ArgTys; 1522 while (!TableRef.empty()) 1523 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context)); 1524 1525 // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg 1526 // If we see void type as the type of the last argument, it is vararg intrinsic 1527 if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) { 1528 ArgTys.pop_back(); 1529 return FunctionType::get(ResultTy, ArgTys, true); 1530 } 1531 return FunctionType::get(ResultTy, ArgTys, false); 1532 } 1533 1534 bool Intrinsic::isOverloaded(ID id) { 1535 #define GET_INTRINSIC_OVERLOAD_TABLE 1536 #include "llvm/IR/IntrinsicImpl.inc" 1537 #undef GET_INTRINSIC_OVERLOAD_TABLE 1538 } 1539 1540 /// This defines the "Intrinsic::getAttributes(ID id)" method. 1541 #define GET_INTRINSIC_ATTRIBUTES 1542 #include "llvm/IR/IntrinsicImpl.inc" 1543 #undef GET_INTRINSIC_ATTRIBUTES 1544 1545 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) { 1546 // There can never be multiple globals with the same name of different types, 1547 // because intrinsics must be a specific type. 1548 auto *FT = getType(M->getContext(), id, Tys); 1549 return cast<Function>( 1550 M->getOrInsertFunction( 1551 Tys.empty() ? getName(id) : getName(id, Tys, M, FT), FT) 1552 .getCallee()); 1553 } 1554 1555 // This defines the "Intrinsic::getIntrinsicForClangBuiltin()" method. 1556 #define GET_LLVM_INTRINSIC_FOR_CLANG_BUILTIN 1557 #include "llvm/IR/IntrinsicImpl.inc" 1558 #undef GET_LLVM_INTRINSIC_FOR_CLANG_BUILTIN 1559 1560 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method. 1561 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 1562 #include "llvm/IR/IntrinsicImpl.inc" 1563 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 1564 1565 bool Intrinsic::isConstrainedFPIntrinsic(ID QID) { 1566 switch (QID) { 1567 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 1568 case Intrinsic::INTRINSIC: 1569 #include "llvm/IR/ConstrainedOps.def" 1570 #undef INSTRUCTION 1571 return true; 1572 default: 1573 return false; 1574 } 1575 } 1576 1577 bool Intrinsic::hasConstrainedFPRoundingModeOperand(Intrinsic::ID QID) { 1578 switch (QID) { 1579 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 1580 case Intrinsic::INTRINSIC: \ 1581 return ROUND_MODE == 1; 1582 #include "llvm/IR/ConstrainedOps.def" 1583 #undef INSTRUCTION 1584 default: 1585 return false; 1586 } 1587 } 1588 1589 using DeferredIntrinsicMatchPair = 1590 std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>; 1591 1592 static bool matchIntrinsicType( 1593 Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos, 1594 SmallVectorImpl<Type *> &ArgTys, 1595 SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks, 1596 bool IsDeferredCheck) { 1597 using namespace Intrinsic; 1598 1599 // If we ran out of descriptors, there are too many arguments. 1600 if (Infos.empty()) return true; 1601 1602 // Do this before slicing off the 'front' part 1603 auto InfosRef = Infos; 1604 auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) { 1605 DeferredChecks.emplace_back(T, InfosRef); 1606 return false; 1607 }; 1608 1609 IITDescriptor D = Infos.front(); 1610 Infos = Infos.slice(1); 1611 1612 switch (D.Kind) { 1613 case IITDescriptor::Void: return !Ty->isVoidTy(); 1614 case IITDescriptor::VarArg: return true; 1615 case IITDescriptor::MMX: { 1616 FixedVectorType *VT = dyn_cast<FixedVectorType>(Ty); 1617 return !VT || VT->getNumElements() != 1 || 1618 !VT->getElementType()->isIntegerTy(64); 1619 } 1620 case IITDescriptor::AMX: return !Ty->isX86_AMXTy(); 1621 case IITDescriptor::Token: return !Ty->isTokenTy(); 1622 case IITDescriptor::Metadata: return !Ty->isMetadataTy(); 1623 case IITDescriptor::Half: return !Ty->isHalfTy(); 1624 case IITDescriptor::BFloat: return !Ty->isBFloatTy(); 1625 case IITDescriptor::Float: return !Ty->isFloatTy(); 1626 case IITDescriptor::Double: return !Ty->isDoubleTy(); 1627 case IITDescriptor::Quad: return !Ty->isFP128Ty(); 1628 case IITDescriptor::PPCQuad: return !Ty->isPPC_FP128Ty(); 1629 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width); 1630 case IITDescriptor::AArch64Svcount: 1631 return !isa<TargetExtType>(Ty) || 1632 cast<TargetExtType>(Ty)->getName() != "aarch64.svcount"; 1633 case IITDescriptor::Vector: { 1634 VectorType *VT = dyn_cast<VectorType>(Ty); 1635 return !VT || VT->getElementCount() != D.Vector_Width || 1636 matchIntrinsicType(VT->getElementType(), Infos, ArgTys, 1637 DeferredChecks, IsDeferredCheck); 1638 } 1639 case IITDescriptor::Pointer: { 1640 PointerType *PT = dyn_cast<PointerType>(Ty); 1641 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace; 1642 } 1643 1644 case IITDescriptor::Struct: { 1645 StructType *ST = dyn_cast<StructType>(Ty); 1646 if (!ST || !ST->isLiteral() || ST->isPacked() || 1647 ST->getNumElements() != D.Struct_NumElements) 1648 return true; 1649 1650 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 1651 if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys, 1652 DeferredChecks, IsDeferredCheck)) 1653 return true; 1654 return false; 1655 } 1656 1657 case IITDescriptor::Argument: 1658 // If this is the second occurrence of an argument, 1659 // verify that the later instance matches the previous instance. 1660 if (D.getArgumentNumber() < ArgTys.size()) 1661 return Ty != ArgTys[D.getArgumentNumber()]; 1662 1663 if (D.getArgumentNumber() > ArgTys.size() || 1664 D.getArgumentKind() == IITDescriptor::AK_MatchType) 1665 return IsDeferredCheck || DeferCheck(Ty); 1666 1667 assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck && 1668 "Table consistency error"); 1669 ArgTys.push_back(Ty); 1670 1671 switch (D.getArgumentKind()) { 1672 case IITDescriptor::AK_Any: return false; // Success 1673 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy(); 1674 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy(); 1675 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty); 1676 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty); 1677 default: break; 1678 } 1679 llvm_unreachable("all argument kinds not covered"); 1680 1681 case IITDescriptor::ExtendArgument: { 1682 // If this is a forward reference, defer the check for later. 1683 if (D.getArgumentNumber() >= ArgTys.size()) 1684 return IsDeferredCheck || DeferCheck(Ty); 1685 1686 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1687 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 1688 NewTy = VectorType::getExtendedElementVectorType(VTy); 1689 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 1690 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth()); 1691 else 1692 return true; 1693 1694 return Ty != NewTy; 1695 } 1696 case IITDescriptor::TruncArgument: { 1697 // If this is a forward reference, defer the check for later. 1698 if (D.getArgumentNumber() >= ArgTys.size()) 1699 return IsDeferredCheck || DeferCheck(Ty); 1700 1701 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1702 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 1703 NewTy = VectorType::getTruncatedElementVectorType(VTy); 1704 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 1705 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2); 1706 else 1707 return true; 1708 1709 return Ty != NewTy; 1710 } 1711 case IITDescriptor::HalfVecArgument: 1712 // If this is a forward reference, defer the check for later. 1713 if (D.getArgumentNumber() >= ArgTys.size()) 1714 return IsDeferredCheck || DeferCheck(Ty); 1715 return !isa<VectorType>(ArgTys[D.getArgumentNumber()]) || 1716 VectorType::getHalfElementsVectorType( 1717 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty; 1718 case IITDescriptor::SameVecWidthArgument: { 1719 if (D.getArgumentNumber() >= ArgTys.size()) { 1720 // Defer check and subsequent check for the vector element type. 1721 Infos = Infos.slice(1); 1722 return IsDeferredCheck || DeferCheck(Ty); 1723 } 1724 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1725 auto *ThisArgType = dyn_cast<VectorType>(Ty); 1726 // Both must be vectors of the same number of elements or neither. 1727 if ((ReferenceType != nullptr) != (ThisArgType != nullptr)) 1728 return true; 1729 Type *EltTy = Ty; 1730 if (ThisArgType) { 1731 if (ReferenceType->getElementCount() != 1732 ThisArgType->getElementCount()) 1733 return true; 1734 EltTy = ThisArgType->getElementType(); 1735 } 1736 return matchIntrinsicType(EltTy, Infos, ArgTys, DeferredChecks, 1737 IsDeferredCheck); 1738 } 1739 case IITDescriptor::VecOfAnyPtrsToElt: { 1740 unsigned RefArgNumber = D.getRefArgNumber(); 1741 if (RefArgNumber >= ArgTys.size()) { 1742 if (IsDeferredCheck) 1743 return true; 1744 // If forward referencing, already add the pointer-vector type and 1745 // defer the checks for later. 1746 ArgTys.push_back(Ty); 1747 return DeferCheck(Ty); 1748 } 1749 1750 if (!IsDeferredCheck){ 1751 assert(D.getOverloadArgNumber() == ArgTys.size() && 1752 "Table consistency error"); 1753 ArgTys.push_back(Ty); 1754 } 1755 1756 // Verify the overloaded type "matches" the Ref type. 1757 // i.e. Ty is a vector with the same width as Ref. 1758 // Composed of pointers to the same element type as Ref. 1759 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]); 1760 auto *ThisArgVecTy = dyn_cast<VectorType>(Ty); 1761 if (!ThisArgVecTy || !ReferenceType || 1762 (ReferenceType->getElementCount() != ThisArgVecTy->getElementCount())) 1763 return true; 1764 return !ThisArgVecTy->getElementType()->isPointerTy(); 1765 } 1766 case IITDescriptor::VecElementArgument: { 1767 if (D.getArgumentNumber() >= ArgTys.size()) 1768 return IsDeferredCheck ? true : DeferCheck(Ty); 1769 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1770 return !ReferenceType || Ty != ReferenceType->getElementType(); 1771 } 1772 case IITDescriptor::Subdivide2Argument: 1773 case IITDescriptor::Subdivide4Argument: { 1774 // If this is a forward reference, defer the check for later. 1775 if (D.getArgumentNumber() >= ArgTys.size()) 1776 return IsDeferredCheck || DeferCheck(Ty); 1777 1778 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1779 if (auto *VTy = dyn_cast<VectorType>(NewTy)) { 1780 int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2; 1781 NewTy = VectorType::getSubdividedVectorType(VTy, SubDivs); 1782 return Ty != NewTy; 1783 } 1784 return true; 1785 } 1786 case IITDescriptor::VecOfBitcastsToInt: { 1787 if (D.getArgumentNumber() >= ArgTys.size()) 1788 return IsDeferredCheck || DeferCheck(Ty); 1789 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1790 auto *ThisArgVecTy = dyn_cast<VectorType>(Ty); 1791 if (!ThisArgVecTy || !ReferenceType) 1792 return true; 1793 return ThisArgVecTy != VectorType::getInteger(ReferenceType); 1794 } 1795 } 1796 llvm_unreachable("unhandled"); 1797 } 1798 1799 Intrinsic::MatchIntrinsicTypesResult 1800 Intrinsic::matchIntrinsicSignature(FunctionType *FTy, 1801 ArrayRef<Intrinsic::IITDescriptor> &Infos, 1802 SmallVectorImpl<Type *> &ArgTys) { 1803 SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks; 1804 if (matchIntrinsicType(FTy->getReturnType(), Infos, ArgTys, DeferredChecks, 1805 false)) 1806 return MatchIntrinsicTypes_NoMatchRet; 1807 1808 unsigned NumDeferredReturnChecks = DeferredChecks.size(); 1809 1810 for (auto *Ty : FTy->params()) 1811 if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, false)) 1812 return MatchIntrinsicTypes_NoMatchArg; 1813 1814 for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) { 1815 DeferredIntrinsicMatchPair &Check = DeferredChecks[I]; 1816 if (matchIntrinsicType(Check.first, Check.second, ArgTys, DeferredChecks, 1817 true)) 1818 return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet 1819 : MatchIntrinsicTypes_NoMatchArg; 1820 } 1821 1822 return MatchIntrinsicTypes_Match; 1823 } 1824 1825 bool 1826 Intrinsic::matchIntrinsicVarArg(bool isVarArg, 1827 ArrayRef<Intrinsic::IITDescriptor> &Infos) { 1828 // If there are no descriptors left, then it can't be a vararg. 1829 if (Infos.empty()) 1830 return isVarArg; 1831 1832 // There should be only one descriptor remaining at this point. 1833 if (Infos.size() != 1) 1834 return true; 1835 1836 // Check and verify the descriptor. 1837 IITDescriptor D = Infos.front(); 1838 Infos = Infos.slice(1); 1839 if (D.Kind == IITDescriptor::VarArg) 1840 return !isVarArg; 1841 1842 return true; 1843 } 1844 1845 bool Intrinsic::getIntrinsicSignature(Intrinsic::ID ID, FunctionType *FT, 1846 SmallVectorImpl<Type *> &ArgTys) { 1847 if (!ID) 1848 return false; 1849 1850 SmallVector<Intrinsic::IITDescriptor, 8> Table; 1851 getIntrinsicInfoTableEntries(ID, Table); 1852 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table; 1853 1854 if (Intrinsic::matchIntrinsicSignature(FT, TableRef, ArgTys) != 1855 Intrinsic::MatchIntrinsicTypesResult::MatchIntrinsicTypes_Match) { 1856 return false; 1857 } 1858 if (Intrinsic::matchIntrinsicVarArg(FT->isVarArg(), TableRef)) 1859 return false; 1860 return true; 1861 } 1862 1863 bool Intrinsic::getIntrinsicSignature(Function *F, 1864 SmallVectorImpl<Type *> &ArgTys) { 1865 return getIntrinsicSignature(F->getIntrinsicID(), F->getFunctionType(), 1866 ArgTys); 1867 } 1868 1869 std::optional<Function *> Intrinsic::remangleIntrinsicFunction(Function *F) { 1870 SmallVector<Type *, 4> ArgTys; 1871 if (!getIntrinsicSignature(F, ArgTys)) 1872 return std::nullopt; 1873 1874 Intrinsic::ID ID = F->getIntrinsicID(); 1875 StringRef Name = F->getName(); 1876 std::string WantedName = 1877 Intrinsic::getName(ID, ArgTys, F->getParent(), F->getFunctionType()); 1878 if (Name == WantedName) 1879 return std::nullopt; 1880 1881 Function *NewDecl = [&] { 1882 if (auto *ExistingGV = F->getParent()->getNamedValue(WantedName)) { 1883 if (auto *ExistingF = dyn_cast<Function>(ExistingGV)) 1884 if (ExistingF->getFunctionType() == F->getFunctionType()) 1885 return ExistingF; 1886 1887 // The name already exists, but is not a function or has the wrong 1888 // prototype. Make place for the new one by renaming the old version. 1889 // Either this old version will be removed later on or the module is 1890 // invalid and we'll get an error. 1891 ExistingGV->setName(WantedName + ".renamed"); 1892 } 1893 return Intrinsic::getDeclaration(F->getParent(), ID, ArgTys); 1894 }(); 1895 1896 NewDecl->setCallingConv(F->getCallingConv()); 1897 assert(NewDecl->getFunctionType() == F->getFunctionType() && 1898 "Shouldn't change the signature"); 1899 return NewDecl; 1900 } 1901 1902 /// hasAddressTaken - returns true if there are any uses of this function 1903 /// other than direct calls or invokes to it. Optionally ignores callback 1904 /// uses, assume like pointer annotation calls, and references in llvm.used 1905 /// and llvm.compiler.used variables. 1906 bool Function::hasAddressTaken(const User **PutOffender, 1907 bool IgnoreCallbackUses, 1908 bool IgnoreAssumeLikeCalls, bool IgnoreLLVMUsed, 1909 bool IgnoreARCAttachedCall, 1910 bool IgnoreCastedDirectCall) const { 1911 for (const Use &U : uses()) { 1912 const User *FU = U.getUser(); 1913 if (isa<BlockAddress>(FU)) 1914 continue; 1915 1916 if (IgnoreCallbackUses) { 1917 AbstractCallSite ACS(&U); 1918 if (ACS && ACS.isCallbackCall()) 1919 continue; 1920 } 1921 1922 const auto *Call = dyn_cast<CallBase>(FU); 1923 if (!Call) { 1924 if (IgnoreAssumeLikeCalls && 1925 isa<BitCastOperator, AddrSpaceCastOperator>(FU) && 1926 all_of(FU->users(), [](const User *U) { 1927 if (const auto *I = dyn_cast<IntrinsicInst>(U)) 1928 return I->isAssumeLikeIntrinsic(); 1929 return false; 1930 })) { 1931 continue; 1932 } 1933 1934 if (IgnoreLLVMUsed && !FU->user_empty()) { 1935 const User *FUU = FU; 1936 if (isa<BitCastOperator, AddrSpaceCastOperator>(FU) && 1937 FU->hasOneUse() && !FU->user_begin()->user_empty()) 1938 FUU = *FU->user_begin(); 1939 if (llvm::all_of(FUU->users(), [](const User *U) { 1940 if (const auto *GV = dyn_cast<GlobalVariable>(U)) 1941 return GV->hasName() && 1942 (GV->getName() == "llvm.compiler.used" || 1943 GV->getName() == "llvm.used"); 1944 return false; 1945 })) 1946 continue; 1947 } 1948 if (PutOffender) 1949 *PutOffender = FU; 1950 return true; 1951 } 1952 1953 if (IgnoreAssumeLikeCalls) { 1954 if (const auto *I = dyn_cast<IntrinsicInst>(Call)) 1955 if (I->isAssumeLikeIntrinsic()) 1956 continue; 1957 } 1958 1959 if (!Call->isCallee(&U) || (!IgnoreCastedDirectCall && 1960 Call->getFunctionType() != getFunctionType())) { 1961 if (IgnoreARCAttachedCall && 1962 Call->isOperandBundleOfType(LLVMContext::OB_clang_arc_attachedcall, 1963 U.getOperandNo())) 1964 continue; 1965 1966 if (PutOffender) 1967 *PutOffender = FU; 1968 return true; 1969 } 1970 } 1971 return false; 1972 } 1973 1974 bool Function::isDefTriviallyDead() const { 1975 // Check the linkage 1976 if (!hasLinkOnceLinkage() && !hasLocalLinkage() && 1977 !hasAvailableExternallyLinkage()) 1978 return false; 1979 1980 // Check if the function is used by anything other than a blockaddress. 1981 for (const User *U : users()) 1982 if (!isa<BlockAddress>(U)) 1983 return false; 1984 1985 return true; 1986 } 1987 1988 /// callsFunctionThatReturnsTwice - Return true if the function has a call to 1989 /// setjmp or other function that gcc recognizes as "returning twice". 1990 bool Function::callsFunctionThatReturnsTwice() const { 1991 for (const Instruction &I : instructions(this)) 1992 if (const auto *Call = dyn_cast<CallBase>(&I)) 1993 if (Call->hasFnAttr(Attribute::ReturnsTwice)) 1994 return true; 1995 1996 return false; 1997 } 1998 1999 Constant *Function::getPersonalityFn() const { 2000 assert(hasPersonalityFn() && getNumOperands()); 2001 return cast<Constant>(Op<0>()); 2002 } 2003 2004 void Function::setPersonalityFn(Constant *Fn) { 2005 setHungoffOperand<0>(Fn); 2006 setValueSubclassDataBit(3, Fn != nullptr); 2007 } 2008 2009 Constant *Function::getPrefixData() const { 2010 assert(hasPrefixData() && getNumOperands()); 2011 return cast<Constant>(Op<1>()); 2012 } 2013 2014 void Function::setPrefixData(Constant *PrefixData) { 2015 setHungoffOperand<1>(PrefixData); 2016 setValueSubclassDataBit(1, PrefixData != nullptr); 2017 } 2018 2019 Constant *Function::getPrologueData() const { 2020 assert(hasPrologueData() && getNumOperands()); 2021 return cast<Constant>(Op<2>()); 2022 } 2023 2024 void Function::setPrologueData(Constant *PrologueData) { 2025 setHungoffOperand<2>(PrologueData); 2026 setValueSubclassDataBit(2, PrologueData != nullptr); 2027 } 2028 2029 void Function::allocHungoffUselist() { 2030 // If we've already allocated a uselist, stop here. 2031 if (getNumOperands()) 2032 return; 2033 2034 allocHungoffUses(3, /*IsPhi=*/ false); 2035 setNumHungOffUseOperands(3); 2036 2037 // Initialize the uselist with placeholder operands to allow traversal. 2038 auto *CPN = ConstantPointerNull::get(PointerType::get(getContext(), 0)); 2039 Op<0>().set(CPN); 2040 Op<1>().set(CPN); 2041 Op<2>().set(CPN); 2042 } 2043 2044 template <int Idx> 2045 void Function::setHungoffOperand(Constant *C) { 2046 if (C) { 2047 allocHungoffUselist(); 2048 Op<Idx>().set(C); 2049 } else if (getNumOperands()) { 2050 Op<Idx>().set(ConstantPointerNull::get(PointerType::get(getContext(), 0))); 2051 } 2052 } 2053 2054 void Function::setValueSubclassDataBit(unsigned Bit, bool On) { 2055 assert(Bit < 16 && "SubclassData contains only 16 bits"); 2056 if (On) 2057 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit)); 2058 else 2059 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit)); 2060 } 2061 2062 void Function::setEntryCount(ProfileCount Count, 2063 const DenseSet<GlobalValue::GUID> *S) { 2064 #if !defined(NDEBUG) 2065 auto PrevCount = getEntryCount(); 2066 assert(!PrevCount || PrevCount->getType() == Count.getType()); 2067 #endif 2068 2069 auto ImportGUIDs = getImportGUIDs(); 2070 if (S == nullptr && ImportGUIDs.size()) 2071 S = &ImportGUIDs; 2072 2073 MDBuilder MDB(getContext()); 2074 setMetadata( 2075 LLVMContext::MD_prof, 2076 MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S)); 2077 } 2078 2079 void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type, 2080 const DenseSet<GlobalValue::GUID> *Imports) { 2081 setEntryCount(ProfileCount(Count, Type), Imports); 2082 } 2083 2084 std::optional<ProfileCount> Function::getEntryCount(bool AllowSynthetic) const { 2085 MDNode *MD = getMetadata(LLVMContext::MD_prof); 2086 if (MD && MD->getOperand(0)) 2087 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) { 2088 if (MDS->getString() == "function_entry_count") { 2089 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1)); 2090 uint64_t Count = CI->getValue().getZExtValue(); 2091 // A value of -1 is used for SamplePGO when there were no samples. 2092 // Treat this the same as unknown. 2093 if (Count == (uint64_t)-1) 2094 return std::nullopt; 2095 return ProfileCount(Count, PCT_Real); 2096 } else if (AllowSynthetic && 2097 MDS->getString() == "synthetic_function_entry_count") { 2098 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1)); 2099 uint64_t Count = CI->getValue().getZExtValue(); 2100 return ProfileCount(Count, PCT_Synthetic); 2101 } 2102 } 2103 return std::nullopt; 2104 } 2105 2106 DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const { 2107 DenseSet<GlobalValue::GUID> R; 2108 if (MDNode *MD = getMetadata(LLVMContext::MD_prof)) 2109 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) 2110 if (MDS->getString() == "function_entry_count") 2111 for (unsigned i = 2; i < MD->getNumOperands(); i++) 2112 R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i)) 2113 ->getValue() 2114 .getZExtValue()); 2115 return R; 2116 } 2117 2118 void Function::setSectionPrefix(StringRef Prefix) { 2119 MDBuilder MDB(getContext()); 2120 setMetadata(LLVMContext::MD_section_prefix, 2121 MDB.createFunctionSectionPrefix(Prefix)); 2122 } 2123 2124 std::optional<StringRef> Function::getSectionPrefix() const { 2125 if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) { 2126 assert(cast<MDString>(MD->getOperand(0))->getString() == 2127 "function_section_prefix" && 2128 "Metadata not match"); 2129 return cast<MDString>(MD->getOperand(1))->getString(); 2130 } 2131 return std::nullopt; 2132 } 2133 2134 bool Function::nullPointerIsDefined() const { 2135 return hasFnAttribute(Attribute::NullPointerIsValid); 2136 } 2137 2138 bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) { 2139 if (F && F->nullPointerIsDefined()) 2140 return true; 2141 2142 if (AS != 0) 2143 return true; 2144 2145 return false; 2146 } 2147