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