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