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