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