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