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