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 // Opaque pointer doesn't have pointee type information, so we just mangle 921 // address space for opaque pointer. 922 if (!PTyp->isOpaque()) 923 Result += getMangledTypeStr(PTyp->getNonOpaquePointerElementType(), 924 HasUnnamedType); 925 } else if (ArrayType *ATyp = dyn_cast<ArrayType>(Ty)) { 926 Result += "a" + utostr(ATyp->getNumElements()) + 927 getMangledTypeStr(ATyp->getElementType(), HasUnnamedType); 928 } else if (StructType *STyp = dyn_cast<StructType>(Ty)) { 929 if (!STyp->isLiteral()) { 930 Result += "s_"; 931 if (STyp->hasName()) 932 Result += STyp->getName(); 933 else 934 HasUnnamedType = true; 935 } else { 936 Result += "sl_"; 937 for (auto *Elem : STyp->elements()) 938 Result += getMangledTypeStr(Elem, HasUnnamedType); 939 } 940 // Ensure nested structs are distinguishable. 941 Result += "s"; 942 } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) { 943 Result += "f_" + getMangledTypeStr(FT->getReturnType(), HasUnnamedType); 944 for (size_t i = 0; i < FT->getNumParams(); i++) 945 Result += getMangledTypeStr(FT->getParamType(i), HasUnnamedType); 946 if (FT->isVarArg()) 947 Result += "vararg"; 948 // Ensure nested function types are distinguishable. 949 Result += "f"; 950 } else if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 951 ElementCount EC = VTy->getElementCount(); 952 if (EC.isScalable()) 953 Result += "nx"; 954 Result += "v" + utostr(EC.getKnownMinValue()) + 955 getMangledTypeStr(VTy->getElementType(), HasUnnamedType); 956 } else if (TargetExtType *TETy = dyn_cast<TargetExtType>(Ty)) { 957 Result += "t"; 958 Result += TETy->getName(); 959 for (Type *ParamTy : TETy->type_params()) 960 Result += "_" + getMangledTypeStr(ParamTy, HasUnnamedType); 961 for (unsigned IntParam : TETy->int_params()) 962 Result += "_" + utostr(IntParam); 963 // Ensure nested target extension types are distinguishable. 964 Result += "t"; 965 } else if (Ty) { 966 switch (Ty->getTypeID()) { 967 default: llvm_unreachable("Unhandled type"); 968 case Type::VoidTyID: Result += "isVoid"; break; 969 case Type::MetadataTyID: Result += "Metadata"; break; 970 case Type::HalfTyID: Result += "f16"; break; 971 case Type::BFloatTyID: Result += "bf16"; break; 972 case Type::FloatTyID: Result += "f32"; break; 973 case Type::DoubleTyID: Result += "f64"; break; 974 case Type::X86_FP80TyID: Result += "f80"; break; 975 case Type::FP128TyID: Result += "f128"; break; 976 case Type::PPC_FP128TyID: Result += "ppcf128"; break; 977 case Type::X86_MMXTyID: Result += "x86mmx"; break; 978 case Type::X86_AMXTyID: Result += "x86amx"; break; 979 case Type::IntegerTyID: 980 Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth()); 981 break; 982 } 983 } 984 return Result; 985 } 986 987 StringRef Intrinsic::getBaseName(ID id) { 988 assert(id < num_intrinsics && "Invalid intrinsic ID!"); 989 return IntrinsicNameTable[id]; 990 } 991 992 StringRef Intrinsic::getName(ID id) { 993 assert(id < num_intrinsics && "Invalid intrinsic ID!"); 994 assert(!Intrinsic::isOverloaded(id) && 995 "This version of getName does not support overloading"); 996 return getBaseName(id); 997 } 998 999 static std::string getIntrinsicNameImpl(Intrinsic::ID Id, ArrayRef<Type *> Tys, 1000 Module *M, FunctionType *FT, 1001 bool EarlyModuleCheck) { 1002 1003 assert(Id < Intrinsic::num_intrinsics && "Invalid intrinsic ID!"); 1004 assert((Tys.empty() || Intrinsic::isOverloaded(Id)) && 1005 "This version of getName is for overloaded intrinsics only"); 1006 (void)EarlyModuleCheck; 1007 assert((!EarlyModuleCheck || M || 1008 !any_of(Tys, [](Type *T) { return isa<PointerType>(T); })) && 1009 "Intrinsic overloading on pointer types need to provide a Module"); 1010 bool HasUnnamedType = false; 1011 std::string Result(Intrinsic::getBaseName(Id)); 1012 for (Type *Ty : Tys) 1013 Result += "." + getMangledTypeStr(Ty, HasUnnamedType); 1014 if (HasUnnamedType) { 1015 assert(M && "unnamed types need a module"); 1016 if (!FT) 1017 FT = Intrinsic::getType(M->getContext(), Id, Tys); 1018 else 1019 assert((FT == Intrinsic::getType(M->getContext(), Id, Tys)) && 1020 "Provided FunctionType must match arguments"); 1021 return M->getUniqueIntrinsicName(Result, Id, FT); 1022 } 1023 return Result; 1024 } 1025 1026 std::string Intrinsic::getName(ID Id, ArrayRef<Type *> Tys, Module *M, 1027 FunctionType *FT) { 1028 assert(M && "We need to have a Module"); 1029 return getIntrinsicNameImpl(Id, Tys, M, FT, true); 1030 } 1031 1032 std::string Intrinsic::getNameNoUnnamedTypes(ID Id, ArrayRef<Type *> Tys) { 1033 return getIntrinsicNameImpl(Id, Tys, nullptr, nullptr, false); 1034 } 1035 1036 /// IIT_Info - These are enumerators that describe the entries returned by the 1037 /// getIntrinsicInfoTableEntries function. 1038 /// 1039 /// Defined in Intrinsics.td. 1040 enum IIT_Info { 1041 #define GET_INTRINSIC_IITINFO 1042 #include "llvm/IR/IntrinsicImpl.inc" 1043 #undef GET_INTRINSIC_IITINFO 1044 }; 1045 1046 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos, 1047 IIT_Info LastInfo, 1048 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) { 1049 using namespace Intrinsic; 1050 1051 bool IsScalableVector = (LastInfo == IIT_SCALABLE_VEC); 1052 1053 IIT_Info Info = IIT_Info(Infos[NextElt++]); 1054 unsigned StructElts = 2; 1055 1056 switch (Info) { 1057 case IIT_Done: 1058 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0)); 1059 return; 1060 case IIT_VARARG: 1061 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0)); 1062 return; 1063 case IIT_MMX: 1064 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0)); 1065 return; 1066 case IIT_AMX: 1067 OutputTable.push_back(IITDescriptor::get(IITDescriptor::AMX, 0)); 1068 return; 1069 case IIT_TOKEN: 1070 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0)); 1071 return; 1072 case IIT_METADATA: 1073 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0)); 1074 return; 1075 case IIT_F16: 1076 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0)); 1077 return; 1078 case IIT_BF16: 1079 OutputTable.push_back(IITDescriptor::get(IITDescriptor::BFloat, 0)); 1080 return; 1081 case IIT_F32: 1082 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0)); 1083 return; 1084 case IIT_F64: 1085 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0)); 1086 return; 1087 case IIT_F128: 1088 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0)); 1089 return; 1090 case IIT_PPCF128: 1091 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PPCQuad, 0)); 1092 return; 1093 case IIT_I1: 1094 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1)); 1095 return; 1096 case IIT_I2: 1097 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 2)); 1098 return; 1099 case IIT_I4: 1100 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 4)); 1101 return; 1102 case IIT_AARCH64_SVCOUNT: 1103 OutputTable.push_back(IITDescriptor::get(IITDescriptor::AArch64Svcount, 0)); 1104 return; 1105 case IIT_I8: 1106 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8)); 1107 return; 1108 case IIT_I16: 1109 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16)); 1110 return; 1111 case IIT_I32: 1112 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32)); 1113 return; 1114 case IIT_I64: 1115 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64)); 1116 return; 1117 case IIT_I128: 1118 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128)); 1119 return; 1120 case IIT_V1: 1121 OutputTable.push_back(IITDescriptor::getVector(1, IsScalableVector)); 1122 DecodeIITType(NextElt, Infos, Info, OutputTable); 1123 return; 1124 case IIT_V2: 1125 OutputTable.push_back(IITDescriptor::getVector(2, IsScalableVector)); 1126 DecodeIITType(NextElt, Infos, Info, OutputTable); 1127 return; 1128 case IIT_V3: 1129 OutputTable.push_back(IITDescriptor::getVector(3, IsScalableVector)); 1130 DecodeIITType(NextElt, Infos, Info, OutputTable); 1131 return; 1132 case IIT_V4: 1133 OutputTable.push_back(IITDescriptor::getVector(4, IsScalableVector)); 1134 DecodeIITType(NextElt, Infos, Info, OutputTable); 1135 return; 1136 case IIT_V8: 1137 OutputTable.push_back(IITDescriptor::getVector(8, IsScalableVector)); 1138 DecodeIITType(NextElt, Infos, Info, OutputTable); 1139 return; 1140 case IIT_V16: 1141 OutputTable.push_back(IITDescriptor::getVector(16, IsScalableVector)); 1142 DecodeIITType(NextElt, Infos, Info, OutputTable); 1143 return; 1144 case IIT_V32: 1145 OutputTable.push_back(IITDescriptor::getVector(32, IsScalableVector)); 1146 DecodeIITType(NextElt, Infos, Info, OutputTable); 1147 return; 1148 case IIT_V64: 1149 OutputTable.push_back(IITDescriptor::getVector(64, IsScalableVector)); 1150 DecodeIITType(NextElt, Infos, Info, OutputTable); 1151 return; 1152 case IIT_V128: 1153 OutputTable.push_back(IITDescriptor::getVector(128, IsScalableVector)); 1154 DecodeIITType(NextElt, Infos, Info, OutputTable); 1155 return; 1156 case IIT_V256: 1157 OutputTable.push_back(IITDescriptor::getVector(256, IsScalableVector)); 1158 DecodeIITType(NextElt, Infos, Info, OutputTable); 1159 return; 1160 case IIT_V512: 1161 OutputTable.push_back(IITDescriptor::getVector(512, IsScalableVector)); 1162 DecodeIITType(NextElt, Infos, Info, OutputTable); 1163 return; 1164 case IIT_V1024: 1165 OutputTable.push_back(IITDescriptor::getVector(1024, IsScalableVector)); 1166 DecodeIITType(NextElt, Infos, Info, OutputTable); 1167 return; 1168 case IIT_EXTERNREF: 1169 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 10)); 1170 return; 1171 case IIT_FUNCREF: 1172 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 20)); 1173 return; 1174 case IIT_PTR: 1175 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0)); 1176 return; 1177 case IIT_ANYPTR: // [ANYPTR addrspace] 1178 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 1179 Infos[NextElt++])); 1180 return; 1181 case IIT_ARG: { 1182 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1183 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo)); 1184 return; 1185 } 1186 case IIT_EXTEND_ARG: { 1187 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1188 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument, 1189 ArgInfo)); 1190 return; 1191 } 1192 case IIT_TRUNC_ARG: { 1193 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1194 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument, 1195 ArgInfo)); 1196 return; 1197 } 1198 case IIT_HALF_VEC_ARG: { 1199 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1200 OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument, 1201 ArgInfo)); 1202 return; 1203 } 1204 case IIT_SAME_VEC_WIDTH_ARG: { 1205 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1206 OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument, 1207 ArgInfo)); 1208 return; 1209 } 1210 case IIT_VEC_OF_ANYPTRS_TO_ELT: { 1211 unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1212 unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1213 OutputTable.push_back( 1214 IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo)); 1215 return; 1216 } 1217 case IIT_EMPTYSTRUCT: 1218 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0)); 1219 return; 1220 case IIT_STRUCT9: ++StructElts; [[fallthrough]]; 1221 case IIT_STRUCT8: ++StructElts; [[fallthrough]]; 1222 case IIT_STRUCT7: ++StructElts; [[fallthrough]]; 1223 case IIT_STRUCT6: ++StructElts; [[fallthrough]]; 1224 case IIT_STRUCT5: ++StructElts; [[fallthrough]]; 1225 case IIT_STRUCT4: ++StructElts; [[fallthrough]]; 1226 case IIT_STRUCT3: ++StructElts; [[fallthrough]]; 1227 case IIT_STRUCT2: { 1228 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts)); 1229 1230 for (unsigned i = 0; i != StructElts; ++i) 1231 DecodeIITType(NextElt, Infos, Info, OutputTable); 1232 return; 1233 } 1234 case IIT_SUBDIVIDE2_ARG: { 1235 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1236 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide2Argument, 1237 ArgInfo)); 1238 return; 1239 } 1240 case IIT_SUBDIVIDE4_ARG: { 1241 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1242 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide4Argument, 1243 ArgInfo)); 1244 return; 1245 } 1246 case IIT_VEC_ELEMENT: { 1247 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1248 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecElementArgument, 1249 ArgInfo)); 1250 return; 1251 } 1252 case IIT_SCALABLE_VEC: { 1253 DecodeIITType(NextElt, Infos, Info, OutputTable); 1254 return; 1255 } 1256 case IIT_VEC_OF_BITCASTS_TO_INT: { 1257 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1258 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfBitcastsToInt, 1259 ArgInfo)); 1260 return; 1261 } 1262 } 1263 llvm_unreachable("unhandled"); 1264 } 1265 1266 #define GET_INTRINSIC_GENERATOR_GLOBAL 1267 #include "llvm/IR/IntrinsicImpl.inc" 1268 #undef GET_INTRINSIC_GENERATOR_GLOBAL 1269 1270 void Intrinsic::getIntrinsicInfoTableEntries(ID id, 1271 SmallVectorImpl<IITDescriptor> &T){ 1272 // Check to see if the intrinsic's type was expressible by the table. 1273 unsigned TableVal = IIT_Table[id-1]; 1274 1275 // Decode the TableVal into an array of IITValues. 1276 SmallVector<unsigned char, 8> IITValues; 1277 ArrayRef<unsigned char> IITEntries; 1278 unsigned NextElt = 0; 1279 if ((TableVal >> 31) != 0) { 1280 // This is an offset into the IIT_LongEncodingTable. 1281 IITEntries = IIT_LongEncodingTable; 1282 1283 // Strip sentinel bit. 1284 NextElt = (TableVal << 1) >> 1; 1285 } else { 1286 // Decode the TableVal into an array of IITValues. If the entry was encoded 1287 // into a single word in the table itself, decode it now. 1288 do { 1289 IITValues.push_back(TableVal & 0xF); 1290 TableVal >>= 4; 1291 } while (TableVal); 1292 1293 IITEntries = IITValues; 1294 NextElt = 0; 1295 } 1296 1297 // Okay, decode the table into the output vector of IITDescriptors. 1298 DecodeIITType(NextElt, IITEntries, IIT_Done, T); 1299 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0) 1300 DecodeIITType(NextElt, IITEntries, IIT_Done, T); 1301 } 1302 1303 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos, 1304 ArrayRef<Type*> Tys, LLVMContext &Context) { 1305 using namespace Intrinsic; 1306 1307 IITDescriptor D = Infos.front(); 1308 Infos = Infos.slice(1); 1309 1310 switch (D.Kind) { 1311 case IITDescriptor::Void: return Type::getVoidTy(Context); 1312 case IITDescriptor::VarArg: return Type::getVoidTy(Context); 1313 case IITDescriptor::MMX: return Type::getX86_MMXTy(Context); 1314 case IITDescriptor::AMX: return Type::getX86_AMXTy(Context); 1315 case IITDescriptor::Token: return Type::getTokenTy(Context); 1316 case IITDescriptor::Metadata: return Type::getMetadataTy(Context); 1317 case IITDescriptor::Half: return Type::getHalfTy(Context); 1318 case IITDescriptor::BFloat: return Type::getBFloatTy(Context); 1319 case IITDescriptor::Float: return Type::getFloatTy(Context); 1320 case IITDescriptor::Double: return Type::getDoubleTy(Context); 1321 case IITDescriptor::Quad: return Type::getFP128Ty(Context); 1322 case IITDescriptor::PPCQuad: return Type::getPPC_FP128Ty(Context); 1323 case IITDescriptor::AArch64Svcount: 1324 return TargetExtType::get(Context, "aarch64.svcount"); 1325 1326 case IITDescriptor::Integer: 1327 return IntegerType::get(Context, D.Integer_Width); 1328 case IITDescriptor::Vector: 1329 return VectorType::get(DecodeFixedType(Infos, Tys, Context), 1330 D.Vector_Width); 1331 case IITDescriptor::Pointer: 1332 return PointerType::get(Context, D.Pointer_AddressSpace); 1333 case IITDescriptor::Struct: { 1334 SmallVector<Type *, 8> Elts; 1335 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 1336 Elts.push_back(DecodeFixedType(Infos, Tys, Context)); 1337 return StructType::get(Context, Elts); 1338 } 1339 case IITDescriptor::Argument: 1340 return Tys[D.getArgumentNumber()]; 1341 case IITDescriptor::ExtendArgument: { 1342 Type *Ty = Tys[D.getArgumentNumber()]; 1343 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1344 return VectorType::getExtendedElementVectorType(VTy); 1345 1346 return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth()); 1347 } 1348 case IITDescriptor::TruncArgument: { 1349 Type *Ty = Tys[D.getArgumentNumber()]; 1350 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1351 return VectorType::getTruncatedElementVectorType(VTy); 1352 1353 IntegerType *ITy = cast<IntegerType>(Ty); 1354 assert(ITy->getBitWidth() % 2 == 0); 1355 return IntegerType::get(Context, ITy->getBitWidth() / 2); 1356 } 1357 case IITDescriptor::Subdivide2Argument: 1358 case IITDescriptor::Subdivide4Argument: { 1359 Type *Ty = Tys[D.getArgumentNumber()]; 1360 VectorType *VTy = dyn_cast<VectorType>(Ty); 1361 assert(VTy && "Expected an argument of Vector Type"); 1362 int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2; 1363 return VectorType::getSubdividedVectorType(VTy, SubDivs); 1364 } 1365 case IITDescriptor::HalfVecArgument: 1366 return VectorType::getHalfElementsVectorType(cast<VectorType>( 1367 Tys[D.getArgumentNumber()])); 1368 case IITDescriptor::SameVecWidthArgument: { 1369 Type *EltTy = DecodeFixedType(Infos, Tys, Context); 1370 Type *Ty = Tys[D.getArgumentNumber()]; 1371 if (auto *VTy = dyn_cast<VectorType>(Ty)) 1372 return VectorType::get(EltTy, VTy->getElementCount()); 1373 return EltTy; 1374 } 1375 case IITDescriptor::VecElementArgument: { 1376 Type *Ty = Tys[D.getArgumentNumber()]; 1377 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1378 return VTy->getElementType(); 1379 llvm_unreachable("Expected an argument of Vector Type"); 1380 } 1381 case IITDescriptor::VecOfBitcastsToInt: { 1382 Type *Ty = Tys[D.getArgumentNumber()]; 1383 VectorType *VTy = dyn_cast<VectorType>(Ty); 1384 assert(VTy && "Expected an argument of Vector Type"); 1385 return VectorType::getInteger(VTy); 1386 } 1387 case IITDescriptor::VecOfAnyPtrsToElt: 1388 // Return the overloaded type (which determines the pointers address space) 1389 return Tys[D.getOverloadArgNumber()]; 1390 } 1391 llvm_unreachable("unhandled"); 1392 } 1393 1394 FunctionType *Intrinsic::getType(LLVMContext &Context, 1395 ID id, ArrayRef<Type*> Tys) { 1396 SmallVector<IITDescriptor, 8> Table; 1397 getIntrinsicInfoTableEntries(id, Table); 1398 1399 ArrayRef<IITDescriptor> TableRef = Table; 1400 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context); 1401 1402 SmallVector<Type*, 8> ArgTys; 1403 while (!TableRef.empty()) 1404 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context)); 1405 1406 // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg 1407 // If we see void type as the type of the last argument, it is vararg intrinsic 1408 if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) { 1409 ArgTys.pop_back(); 1410 return FunctionType::get(ResultTy, ArgTys, true); 1411 } 1412 return FunctionType::get(ResultTy, ArgTys, false); 1413 } 1414 1415 bool Intrinsic::isOverloaded(ID id) { 1416 #define GET_INTRINSIC_OVERLOAD_TABLE 1417 #include "llvm/IR/IntrinsicImpl.inc" 1418 #undef GET_INTRINSIC_OVERLOAD_TABLE 1419 } 1420 1421 /// This defines the "Intrinsic::getAttributes(ID id)" method. 1422 #define GET_INTRINSIC_ATTRIBUTES 1423 #include "llvm/IR/IntrinsicImpl.inc" 1424 #undef GET_INTRINSIC_ATTRIBUTES 1425 1426 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) { 1427 // There can never be multiple globals with the same name of different types, 1428 // because intrinsics must be a specific type. 1429 auto *FT = getType(M->getContext(), id, Tys); 1430 return cast<Function>( 1431 M->getOrInsertFunction( 1432 Tys.empty() ? getName(id) : getName(id, Tys, M, FT), FT) 1433 .getCallee()); 1434 } 1435 1436 // This defines the "Intrinsic::getIntrinsicForClangBuiltin()" method. 1437 #define GET_LLVM_INTRINSIC_FOR_CLANG_BUILTIN 1438 #include "llvm/IR/IntrinsicImpl.inc" 1439 #undef GET_LLVM_INTRINSIC_FOR_CLANG_BUILTIN 1440 1441 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method. 1442 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 1443 #include "llvm/IR/IntrinsicImpl.inc" 1444 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 1445 1446 using DeferredIntrinsicMatchPair = 1447 std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>; 1448 1449 static bool matchIntrinsicType( 1450 Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos, 1451 SmallVectorImpl<Type *> &ArgTys, 1452 SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks, 1453 bool IsDeferredCheck) { 1454 using namespace Intrinsic; 1455 1456 // If we ran out of descriptors, there are too many arguments. 1457 if (Infos.empty()) return true; 1458 1459 // Do this before slicing off the 'front' part 1460 auto InfosRef = Infos; 1461 auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) { 1462 DeferredChecks.emplace_back(T, InfosRef); 1463 return false; 1464 }; 1465 1466 IITDescriptor D = Infos.front(); 1467 Infos = Infos.slice(1); 1468 1469 switch (D.Kind) { 1470 case IITDescriptor::Void: return !Ty->isVoidTy(); 1471 case IITDescriptor::VarArg: return true; 1472 case IITDescriptor::MMX: return !Ty->isX86_MMXTy(); 1473 case IITDescriptor::AMX: return !Ty->isX86_AMXTy(); 1474 case IITDescriptor::Token: return !Ty->isTokenTy(); 1475 case IITDescriptor::Metadata: return !Ty->isMetadataTy(); 1476 case IITDescriptor::Half: return !Ty->isHalfTy(); 1477 case IITDescriptor::BFloat: return !Ty->isBFloatTy(); 1478 case IITDescriptor::Float: return !Ty->isFloatTy(); 1479 case IITDescriptor::Double: return !Ty->isDoubleTy(); 1480 case IITDescriptor::Quad: return !Ty->isFP128Ty(); 1481 case IITDescriptor::PPCQuad: return !Ty->isPPC_FP128Ty(); 1482 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width); 1483 case IITDescriptor::AArch64Svcount: 1484 return !isa<TargetExtType>(Ty) || 1485 cast<TargetExtType>(Ty)->getName() != "aarch64.svcount"; 1486 case IITDescriptor::Vector: { 1487 VectorType *VT = dyn_cast<VectorType>(Ty); 1488 return !VT || VT->getElementCount() != D.Vector_Width || 1489 matchIntrinsicType(VT->getElementType(), Infos, ArgTys, 1490 DeferredChecks, IsDeferredCheck); 1491 } 1492 case IITDescriptor::Pointer: { 1493 PointerType *PT = dyn_cast<PointerType>(Ty); 1494 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace; 1495 } 1496 1497 case IITDescriptor::Struct: { 1498 StructType *ST = dyn_cast<StructType>(Ty); 1499 if (!ST || !ST->isLiteral() || ST->isPacked() || 1500 ST->getNumElements() != D.Struct_NumElements) 1501 return true; 1502 1503 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 1504 if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys, 1505 DeferredChecks, IsDeferredCheck)) 1506 return true; 1507 return false; 1508 } 1509 1510 case IITDescriptor::Argument: 1511 // If this is the second occurrence of an argument, 1512 // verify that the later instance matches the previous instance. 1513 if (D.getArgumentNumber() < ArgTys.size()) 1514 return Ty != ArgTys[D.getArgumentNumber()]; 1515 1516 if (D.getArgumentNumber() > ArgTys.size() || 1517 D.getArgumentKind() == IITDescriptor::AK_MatchType) 1518 return IsDeferredCheck || DeferCheck(Ty); 1519 1520 assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck && 1521 "Table consistency error"); 1522 ArgTys.push_back(Ty); 1523 1524 switch (D.getArgumentKind()) { 1525 case IITDescriptor::AK_Any: return false; // Success 1526 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy(); 1527 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy(); 1528 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty); 1529 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty); 1530 default: break; 1531 } 1532 llvm_unreachable("all argument kinds not covered"); 1533 1534 case IITDescriptor::ExtendArgument: { 1535 // If this is a forward reference, defer the check for later. 1536 if (D.getArgumentNumber() >= ArgTys.size()) 1537 return IsDeferredCheck || DeferCheck(Ty); 1538 1539 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1540 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 1541 NewTy = VectorType::getExtendedElementVectorType(VTy); 1542 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 1543 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth()); 1544 else 1545 return true; 1546 1547 return Ty != NewTy; 1548 } 1549 case IITDescriptor::TruncArgument: { 1550 // If this is a forward reference, defer the check for later. 1551 if (D.getArgumentNumber() >= ArgTys.size()) 1552 return IsDeferredCheck || DeferCheck(Ty); 1553 1554 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1555 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 1556 NewTy = VectorType::getTruncatedElementVectorType(VTy); 1557 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 1558 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2); 1559 else 1560 return true; 1561 1562 return Ty != NewTy; 1563 } 1564 case IITDescriptor::HalfVecArgument: 1565 // If this is a forward reference, defer the check for later. 1566 if (D.getArgumentNumber() >= ArgTys.size()) 1567 return IsDeferredCheck || DeferCheck(Ty); 1568 return !isa<VectorType>(ArgTys[D.getArgumentNumber()]) || 1569 VectorType::getHalfElementsVectorType( 1570 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty; 1571 case IITDescriptor::SameVecWidthArgument: { 1572 if (D.getArgumentNumber() >= ArgTys.size()) { 1573 // Defer check and subsequent check for the vector element type. 1574 Infos = Infos.slice(1); 1575 return IsDeferredCheck || DeferCheck(Ty); 1576 } 1577 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1578 auto *ThisArgType = dyn_cast<VectorType>(Ty); 1579 // Both must be vectors of the same number of elements or neither. 1580 if ((ReferenceType != nullptr) != (ThisArgType != nullptr)) 1581 return true; 1582 Type *EltTy = Ty; 1583 if (ThisArgType) { 1584 if (ReferenceType->getElementCount() != 1585 ThisArgType->getElementCount()) 1586 return true; 1587 EltTy = ThisArgType->getElementType(); 1588 } 1589 return matchIntrinsicType(EltTy, Infos, ArgTys, DeferredChecks, 1590 IsDeferredCheck); 1591 } 1592 case IITDescriptor::VecOfAnyPtrsToElt: { 1593 unsigned RefArgNumber = D.getRefArgNumber(); 1594 if (RefArgNumber >= ArgTys.size()) { 1595 if (IsDeferredCheck) 1596 return true; 1597 // If forward referencing, already add the pointer-vector type and 1598 // defer the checks for later. 1599 ArgTys.push_back(Ty); 1600 return DeferCheck(Ty); 1601 } 1602 1603 if (!IsDeferredCheck){ 1604 assert(D.getOverloadArgNumber() == ArgTys.size() && 1605 "Table consistency error"); 1606 ArgTys.push_back(Ty); 1607 } 1608 1609 // Verify the overloaded type "matches" the Ref type. 1610 // i.e. Ty is a vector with the same width as Ref. 1611 // Composed of pointers to the same element type as Ref. 1612 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]); 1613 auto *ThisArgVecTy = dyn_cast<VectorType>(Ty); 1614 if (!ThisArgVecTy || !ReferenceType || 1615 (ReferenceType->getElementCount() != ThisArgVecTy->getElementCount())) 1616 return true; 1617 PointerType *ThisArgEltTy = 1618 dyn_cast<PointerType>(ThisArgVecTy->getElementType()); 1619 if (!ThisArgEltTy) 1620 return true; 1621 return !ThisArgEltTy->isOpaqueOrPointeeTypeMatches( 1622 ReferenceType->getElementType()); 1623 } 1624 case IITDescriptor::VecElementArgument: { 1625 if (D.getArgumentNumber() >= ArgTys.size()) 1626 return IsDeferredCheck ? true : DeferCheck(Ty); 1627 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1628 return !ReferenceType || Ty != ReferenceType->getElementType(); 1629 } 1630 case IITDescriptor::Subdivide2Argument: 1631 case IITDescriptor::Subdivide4Argument: { 1632 // If this is a forward reference, defer the check for later. 1633 if (D.getArgumentNumber() >= ArgTys.size()) 1634 return IsDeferredCheck || DeferCheck(Ty); 1635 1636 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1637 if (auto *VTy = dyn_cast<VectorType>(NewTy)) { 1638 int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2; 1639 NewTy = VectorType::getSubdividedVectorType(VTy, SubDivs); 1640 return Ty != NewTy; 1641 } 1642 return true; 1643 } 1644 case IITDescriptor::VecOfBitcastsToInt: { 1645 if (D.getArgumentNumber() >= ArgTys.size()) 1646 return IsDeferredCheck || DeferCheck(Ty); 1647 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1648 auto *ThisArgVecTy = dyn_cast<VectorType>(Ty); 1649 if (!ThisArgVecTy || !ReferenceType) 1650 return true; 1651 return ThisArgVecTy != VectorType::getInteger(ReferenceType); 1652 } 1653 } 1654 llvm_unreachable("unhandled"); 1655 } 1656 1657 Intrinsic::MatchIntrinsicTypesResult 1658 Intrinsic::matchIntrinsicSignature(FunctionType *FTy, 1659 ArrayRef<Intrinsic::IITDescriptor> &Infos, 1660 SmallVectorImpl<Type *> &ArgTys) { 1661 SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks; 1662 if (matchIntrinsicType(FTy->getReturnType(), Infos, ArgTys, DeferredChecks, 1663 false)) 1664 return MatchIntrinsicTypes_NoMatchRet; 1665 1666 unsigned NumDeferredReturnChecks = DeferredChecks.size(); 1667 1668 for (auto *Ty : FTy->params()) 1669 if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, false)) 1670 return MatchIntrinsicTypes_NoMatchArg; 1671 1672 for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) { 1673 DeferredIntrinsicMatchPair &Check = DeferredChecks[I]; 1674 if (matchIntrinsicType(Check.first, Check.second, ArgTys, DeferredChecks, 1675 true)) 1676 return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet 1677 : MatchIntrinsicTypes_NoMatchArg; 1678 } 1679 1680 return MatchIntrinsicTypes_Match; 1681 } 1682 1683 bool 1684 Intrinsic::matchIntrinsicVarArg(bool isVarArg, 1685 ArrayRef<Intrinsic::IITDescriptor> &Infos) { 1686 // If there are no descriptors left, then it can't be a vararg. 1687 if (Infos.empty()) 1688 return isVarArg; 1689 1690 // There should be only one descriptor remaining at this point. 1691 if (Infos.size() != 1) 1692 return true; 1693 1694 // Check and verify the descriptor. 1695 IITDescriptor D = Infos.front(); 1696 Infos = Infos.slice(1); 1697 if (D.Kind == IITDescriptor::VarArg) 1698 return !isVarArg; 1699 1700 return true; 1701 } 1702 1703 bool Intrinsic::getIntrinsicSignature(Function *F, 1704 SmallVectorImpl<Type *> &ArgTys) { 1705 Intrinsic::ID ID = F->getIntrinsicID(); 1706 if (!ID) 1707 return false; 1708 1709 SmallVector<Intrinsic::IITDescriptor, 8> Table; 1710 getIntrinsicInfoTableEntries(ID, Table); 1711 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table; 1712 1713 if (Intrinsic::matchIntrinsicSignature(F->getFunctionType(), TableRef, 1714 ArgTys) != 1715 Intrinsic::MatchIntrinsicTypesResult::MatchIntrinsicTypes_Match) { 1716 return false; 1717 } 1718 if (Intrinsic::matchIntrinsicVarArg(F->getFunctionType()->isVarArg(), 1719 TableRef)) 1720 return false; 1721 return true; 1722 } 1723 1724 std::optional<Function *> Intrinsic::remangleIntrinsicFunction(Function *F) { 1725 SmallVector<Type *, 4> ArgTys; 1726 if (!getIntrinsicSignature(F, ArgTys)) 1727 return std::nullopt; 1728 1729 Intrinsic::ID ID = F->getIntrinsicID(); 1730 StringRef Name = F->getName(); 1731 std::string WantedName = 1732 Intrinsic::getName(ID, ArgTys, F->getParent(), F->getFunctionType()); 1733 if (Name == WantedName) 1734 return std::nullopt; 1735 1736 Function *NewDecl = [&] { 1737 if (auto *ExistingGV = F->getParent()->getNamedValue(WantedName)) { 1738 if (auto *ExistingF = dyn_cast<Function>(ExistingGV)) 1739 if (ExistingF->getFunctionType() == F->getFunctionType()) 1740 return ExistingF; 1741 1742 // The name already exists, but is not a function or has the wrong 1743 // prototype. Make place for the new one by renaming the old version. 1744 // Either this old version will be removed later on or the module is 1745 // invalid and we'll get an error. 1746 ExistingGV->setName(WantedName + ".renamed"); 1747 } 1748 return Intrinsic::getDeclaration(F->getParent(), ID, ArgTys); 1749 }(); 1750 1751 NewDecl->setCallingConv(F->getCallingConv()); 1752 assert(NewDecl->getFunctionType() == F->getFunctionType() && 1753 "Shouldn't change the signature"); 1754 return NewDecl; 1755 } 1756 1757 /// hasAddressTaken - returns true if there are any uses of this function 1758 /// other than direct calls or invokes to it. Optionally ignores callback 1759 /// uses, assume like pointer annotation calls, and references in llvm.used 1760 /// and llvm.compiler.used variables. 1761 bool Function::hasAddressTaken(const User **PutOffender, 1762 bool IgnoreCallbackUses, 1763 bool IgnoreAssumeLikeCalls, bool IgnoreLLVMUsed, 1764 bool IgnoreARCAttachedCall) const { 1765 for (const Use &U : uses()) { 1766 const User *FU = U.getUser(); 1767 if (isa<BlockAddress>(FU)) 1768 continue; 1769 1770 if (IgnoreCallbackUses) { 1771 AbstractCallSite ACS(&U); 1772 if (ACS && ACS.isCallbackCall()) 1773 continue; 1774 } 1775 1776 const auto *Call = dyn_cast<CallBase>(FU); 1777 if (!Call) { 1778 if (IgnoreAssumeLikeCalls && 1779 isa<BitCastOperator, AddrSpaceCastOperator>(FU) && 1780 all_of(FU->users(), [](const User *U) { 1781 if (const auto *I = dyn_cast<IntrinsicInst>(U)) 1782 return I->isAssumeLikeIntrinsic(); 1783 return false; 1784 })) { 1785 continue; 1786 } 1787 1788 if (IgnoreLLVMUsed && !FU->user_empty()) { 1789 const User *FUU = FU; 1790 if (isa<BitCastOperator, AddrSpaceCastOperator>(FU) && 1791 FU->hasOneUse() && !FU->user_begin()->user_empty()) 1792 FUU = *FU->user_begin(); 1793 if (llvm::all_of(FUU->users(), [](const User *U) { 1794 if (const auto *GV = dyn_cast<GlobalVariable>(U)) 1795 return GV->hasName() && 1796 (GV->getName().equals("llvm.compiler.used") || 1797 GV->getName().equals("llvm.used")); 1798 return false; 1799 })) 1800 continue; 1801 } 1802 if (PutOffender) 1803 *PutOffender = FU; 1804 return true; 1805 } 1806 1807 if (IgnoreAssumeLikeCalls) { 1808 if (const auto *I = dyn_cast<IntrinsicInst>(Call)) 1809 if (I->isAssumeLikeIntrinsic()) 1810 continue; 1811 } 1812 1813 if (!Call->isCallee(&U) || Call->getFunctionType() != getFunctionType()) { 1814 if (IgnoreARCAttachedCall && 1815 Call->isOperandBundleOfType(LLVMContext::OB_clang_arc_attachedcall, 1816 U.getOperandNo())) 1817 continue; 1818 1819 if (PutOffender) 1820 *PutOffender = FU; 1821 return true; 1822 } 1823 } 1824 return false; 1825 } 1826 1827 bool Function::isDefTriviallyDead() const { 1828 // Check the linkage 1829 if (!hasLinkOnceLinkage() && !hasLocalLinkage() && 1830 !hasAvailableExternallyLinkage()) 1831 return false; 1832 1833 // Check if the function is used by anything other than a blockaddress. 1834 for (const User *U : users()) 1835 if (!isa<BlockAddress>(U)) 1836 return false; 1837 1838 return true; 1839 } 1840 1841 /// callsFunctionThatReturnsTwice - Return true if the function has a call to 1842 /// setjmp or other function that gcc recognizes as "returning twice". 1843 bool Function::callsFunctionThatReturnsTwice() const { 1844 for (const Instruction &I : instructions(this)) 1845 if (const auto *Call = dyn_cast<CallBase>(&I)) 1846 if (Call->hasFnAttr(Attribute::ReturnsTwice)) 1847 return true; 1848 1849 return false; 1850 } 1851 1852 Constant *Function::getPersonalityFn() const { 1853 assert(hasPersonalityFn() && getNumOperands()); 1854 return cast<Constant>(Op<0>()); 1855 } 1856 1857 void Function::setPersonalityFn(Constant *Fn) { 1858 setHungoffOperand<0>(Fn); 1859 setValueSubclassDataBit(3, Fn != nullptr); 1860 } 1861 1862 Constant *Function::getPrefixData() const { 1863 assert(hasPrefixData() && getNumOperands()); 1864 return cast<Constant>(Op<1>()); 1865 } 1866 1867 void Function::setPrefixData(Constant *PrefixData) { 1868 setHungoffOperand<1>(PrefixData); 1869 setValueSubclassDataBit(1, PrefixData != nullptr); 1870 } 1871 1872 Constant *Function::getPrologueData() const { 1873 assert(hasPrologueData() && getNumOperands()); 1874 return cast<Constant>(Op<2>()); 1875 } 1876 1877 void Function::setPrologueData(Constant *PrologueData) { 1878 setHungoffOperand<2>(PrologueData); 1879 setValueSubclassDataBit(2, PrologueData != nullptr); 1880 } 1881 1882 void Function::allocHungoffUselist() { 1883 // If we've already allocated a uselist, stop here. 1884 if (getNumOperands()) 1885 return; 1886 1887 allocHungoffUses(3, /*IsPhi=*/ false); 1888 setNumHungOffUseOperands(3); 1889 1890 // Initialize the uselist with placeholder operands to allow traversal. 1891 auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)); 1892 Op<0>().set(CPN); 1893 Op<1>().set(CPN); 1894 Op<2>().set(CPN); 1895 } 1896 1897 template <int Idx> 1898 void Function::setHungoffOperand(Constant *C) { 1899 if (C) { 1900 allocHungoffUselist(); 1901 Op<Idx>().set(C); 1902 } else if (getNumOperands()) { 1903 Op<Idx>().set( 1904 ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0))); 1905 } 1906 } 1907 1908 void Function::setValueSubclassDataBit(unsigned Bit, bool On) { 1909 assert(Bit < 16 && "SubclassData contains only 16 bits"); 1910 if (On) 1911 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit)); 1912 else 1913 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit)); 1914 } 1915 1916 void Function::setEntryCount(ProfileCount Count, 1917 const DenseSet<GlobalValue::GUID> *S) { 1918 #if !defined(NDEBUG) 1919 auto PrevCount = getEntryCount(); 1920 assert(!PrevCount || PrevCount->getType() == Count.getType()); 1921 #endif 1922 1923 auto ImportGUIDs = getImportGUIDs(); 1924 if (S == nullptr && ImportGUIDs.size()) 1925 S = &ImportGUIDs; 1926 1927 MDBuilder MDB(getContext()); 1928 setMetadata( 1929 LLVMContext::MD_prof, 1930 MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S)); 1931 } 1932 1933 void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type, 1934 const DenseSet<GlobalValue::GUID> *Imports) { 1935 setEntryCount(ProfileCount(Count, Type), Imports); 1936 } 1937 1938 std::optional<ProfileCount> Function::getEntryCount(bool AllowSynthetic) const { 1939 MDNode *MD = getMetadata(LLVMContext::MD_prof); 1940 if (MD && MD->getOperand(0)) 1941 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) { 1942 if (MDS->getString().equals("function_entry_count")) { 1943 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1)); 1944 uint64_t Count = CI->getValue().getZExtValue(); 1945 // A value of -1 is used for SamplePGO when there were no samples. 1946 // Treat this the same as unknown. 1947 if (Count == (uint64_t)-1) 1948 return std::nullopt; 1949 return ProfileCount(Count, PCT_Real); 1950 } else if (AllowSynthetic && 1951 MDS->getString().equals("synthetic_function_entry_count")) { 1952 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1)); 1953 uint64_t Count = CI->getValue().getZExtValue(); 1954 return ProfileCount(Count, PCT_Synthetic); 1955 } 1956 } 1957 return std::nullopt; 1958 } 1959 1960 DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const { 1961 DenseSet<GlobalValue::GUID> R; 1962 if (MDNode *MD = getMetadata(LLVMContext::MD_prof)) 1963 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) 1964 if (MDS->getString().equals("function_entry_count")) 1965 for (unsigned i = 2; i < MD->getNumOperands(); i++) 1966 R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i)) 1967 ->getValue() 1968 .getZExtValue()); 1969 return R; 1970 } 1971 1972 void Function::setSectionPrefix(StringRef Prefix) { 1973 MDBuilder MDB(getContext()); 1974 setMetadata(LLVMContext::MD_section_prefix, 1975 MDB.createFunctionSectionPrefix(Prefix)); 1976 } 1977 1978 std::optional<StringRef> Function::getSectionPrefix() const { 1979 if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) { 1980 assert(cast<MDString>(MD->getOperand(0)) 1981 ->getString() 1982 .equals("function_section_prefix") && 1983 "Metadata not match"); 1984 return cast<MDString>(MD->getOperand(1))->getString(); 1985 } 1986 return std::nullopt; 1987 } 1988 1989 bool Function::nullPointerIsDefined() const { 1990 return hasFnAttribute(Attribute::NullPointerIsValid); 1991 } 1992 1993 bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) { 1994 if (F && F->nullPointerIsDefined()) 1995 return true; 1996 1997 if (AS != 0) 1998 return true; 1999 2000 return false; 2001 } 2002