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