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