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