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