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