1 //===- AsmWriter.cpp - Printing LLVM as an assembly file ------------------===// 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 library implements `print` family of functions in classes like 10 // Module, Function, Value, etc. In-memory representation of those classes is 11 // converted to IR strings. 12 // 13 // Note that these routines must be extremely tolerant of various errors in the 14 // LLVM code, because it can be used for debugging transformations. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/ADT/APFloat.h" 19 #include "llvm/ADT/APInt.h" 20 #include "llvm/ADT/ArrayRef.h" 21 #include "llvm/ADT/DenseMap.h" 22 #include "llvm/ADT/None.h" 23 #include "llvm/ADT/Optional.h" 24 #include "llvm/ADT/STLExtras.h" 25 #include "llvm/ADT/SetVector.h" 26 #include "llvm/ADT/SmallString.h" 27 #include "llvm/ADT/SmallVector.h" 28 #include "llvm/ADT/StringExtras.h" 29 #include "llvm/ADT/StringRef.h" 30 #include "llvm/ADT/iterator_range.h" 31 #include "llvm/BinaryFormat/Dwarf.h" 32 #include "llvm/Config/llvm-config.h" 33 #include "llvm/IR/Argument.h" 34 #include "llvm/IR/AssemblyAnnotationWriter.h" 35 #include "llvm/IR/Attributes.h" 36 #include "llvm/IR/BasicBlock.h" 37 #include "llvm/IR/CFG.h" 38 #include "llvm/IR/CallingConv.h" 39 #include "llvm/IR/Comdat.h" 40 #include "llvm/IR/Constant.h" 41 #include "llvm/IR/Constants.h" 42 #include "llvm/IR/DebugInfoMetadata.h" 43 #include "llvm/IR/DerivedTypes.h" 44 #include "llvm/IR/Function.h" 45 #include "llvm/IR/GlobalAlias.h" 46 #include "llvm/IR/GlobalIFunc.h" 47 #include "llvm/IR/GlobalIndirectSymbol.h" 48 #include "llvm/IR/GlobalObject.h" 49 #include "llvm/IR/GlobalValue.h" 50 #include "llvm/IR/GlobalVariable.h" 51 #include "llvm/IR/IRPrintingPasses.h" 52 #include "llvm/IR/InlineAsm.h" 53 #include "llvm/IR/InstrTypes.h" 54 #include "llvm/IR/Instruction.h" 55 #include "llvm/IR/Instructions.h" 56 #include "llvm/IR/IntrinsicInst.h" 57 #include "llvm/IR/LLVMContext.h" 58 #include "llvm/IR/Metadata.h" 59 #include "llvm/IR/Module.h" 60 #include "llvm/IR/ModuleSlotTracker.h" 61 #include "llvm/IR/ModuleSummaryIndex.h" 62 #include "llvm/IR/Operator.h" 63 #include "llvm/IR/Type.h" 64 #include "llvm/IR/TypeFinder.h" 65 #include "llvm/IR/Use.h" 66 #include "llvm/IR/User.h" 67 #include "llvm/IR/Value.h" 68 #include "llvm/Support/AtomicOrdering.h" 69 #include "llvm/Support/Casting.h" 70 #include "llvm/Support/Compiler.h" 71 #include "llvm/Support/Debug.h" 72 #include "llvm/Support/ErrorHandling.h" 73 #include "llvm/Support/Format.h" 74 #include "llvm/Support/FormattedStream.h" 75 #include "llvm/Support/raw_ostream.h" 76 #include <algorithm> 77 #include <cassert> 78 #include <cctype> 79 #include <cstddef> 80 #include <cstdint> 81 #include <iterator> 82 #include <memory> 83 #include <string> 84 #include <tuple> 85 #include <utility> 86 #include <vector> 87 88 using namespace llvm; 89 90 // Make virtual table appear in this compilation unit. 91 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() = default; 92 93 //===----------------------------------------------------------------------===// 94 // Helper Functions 95 //===----------------------------------------------------------------------===// 96 97 using OrderMap = MapVector<const Value *, unsigned>; 98 99 using UseListOrderMap = 100 DenseMap<const Function *, MapVector<const Value *, std::vector<unsigned>>>; 101 102 /// Look for a value that might be wrapped as metadata, e.g. a value in a 103 /// metadata operand. Returns the input value as-is if it is not wrapped. 104 static const Value *skipMetadataWrapper(const Value *V) { 105 if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) 106 if (const auto *VAM = dyn_cast<ValueAsMetadata>(MAV->getMetadata())) 107 return VAM->getValue(); 108 return V; 109 } 110 111 static void orderValue(const Value *V, OrderMap &OM) { 112 if (OM.lookup(V)) 113 return; 114 115 if (const Constant *C = dyn_cast<Constant>(V)) 116 if (C->getNumOperands() && !isa<GlobalValue>(C)) 117 for (const Value *Op : C->operands()) 118 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op)) 119 orderValue(Op, OM); 120 121 // Note: we cannot cache this lookup above, since inserting into the map 122 // changes the map's size, and thus affects the other IDs. 123 unsigned ID = OM.size() + 1; 124 OM[V] = ID; 125 } 126 127 static OrderMap orderModule(const Module *M) { 128 OrderMap OM; 129 130 for (const GlobalVariable &G : M->globals()) { 131 if (G.hasInitializer()) 132 if (!isa<GlobalValue>(G.getInitializer())) 133 orderValue(G.getInitializer(), OM); 134 orderValue(&G, OM); 135 } 136 for (const GlobalAlias &A : M->aliases()) { 137 if (!isa<GlobalValue>(A.getAliasee())) 138 orderValue(A.getAliasee(), OM); 139 orderValue(&A, OM); 140 } 141 for (const GlobalIFunc &I : M->ifuncs()) { 142 if (!isa<GlobalValue>(I.getResolver())) 143 orderValue(I.getResolver(), OM); 144 orderValue(&I, OM); 145 } 146 for (const Function &F : *M) { 147 for (const Use &U : F.operands()) 148 if (!isa<GlobalValue>(U.get())) 149 orderValue(U.get(), OM); 150 151 orderValue(&F, OM); 152 153 if (F.isDeclaration()) 154 continue; 155 156 for (const Argument &A : F.args()) 157 orderValue(&A, OM); 158 for (const BasicBlock &BB : F) { 159 orderValue(&BB, OM); 160 for (const Instruction &I : BB) { 161 for (const Value *Op : I.operands()) { 162 Op = skipMetadataWrapper(Op); 163 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) || 164 isa<InlineAsm>(*Op)) 165 orderValue(Op, OM); 166 } 167 orderValue(&I, OM); 168 } 169 } 170 } 171 return OM; 172 } 173 174 static std::vector<unsigned> 175 predictValueUseListOrder(const Value *V, unsigned ID, const OrderMap &OM) { 176 // Predict use-list order for this one. 177 using Entry = std::pair<const Use *, unsigned>; 178 SmallVector<Entry, 64> List; 179 for (const Use &U : V->uses()) 180 // Check if this user will be serialized. 181 if (OM.lookup(U.getUser())) 182 List.push_back(std::make_pair(&U, List.size())); 183 184 if (List.size() < 2) 185 // We may have lost some users. 186 return {}; 187 188 // When referencing a value before its declaration, a temporary value is 189 // created, which will later be RAUWed with the actual value. This reverses 190 // the use list. This happens for all values apart from basic blocks. 191 bool GetsReversed = !isa<BasicBlock>(V); 192 if (auto *BA = dyn_cast<BlockAddress>(V)) 193 ID = OM.lookup(BA->getBasicBlock()); 194 llvm::sort(List, [&](const Entry &L, const Entry &R) { 195 const Use *LU = L.first; 196 const Use *RU = R.first; 197 if (LU == RU) 198 return false; 199 200 auto LID = OM.lookup(LU->getUser()); 201 auto RID = OM.lookup(RU->getUser()); 202 203 // If ID is 4, then expect: 7 6 5 1 2 3. 204 if (LID < RID) { 205 if (GetsReversed) 206 if (RID <= ID) 207 return true; 208 return false; 209 } 210 if (RID < LID) { 211 if (GetsReversed) 212 if (LID <= ID) 213 return false; 214 return true; 215 } 216 217 // LID and RID are equal, so we have different operands of the same user. 218 // Assume operands are added in order for all instructions. 219 if (GetsReversed) 220 if (LID <= ID) 221 return LU->getOperandNo() < RU->getOperandNo(); 222 return LU->getOperandNo() > RU->getOperandNo(); 223 }); 224 225 if (llvm::is_sorted(List, [](const Entry &L, const Entry &R) { 226 return L.second < R.second; 227 })) 228 // Order is already correct. 229 return {}; 230 231 // Store the shuffle. 232 std::vector<unsigned> Shuffle(List.size()); 233 for (size_t I = 0, E = List.size(); I != E; ++I) 234 Shuffle[I] = List[I].second; 235 return Shuffle; 236 } 237 238 static UseListOrderMap predictUseListOrder(const Module *M) { 239 OrderMap OM = orderModule(M); 240 UseListOrderMap ULOM; 241 for (const auto &Pair : OM) { 242 const Value *V = Pair.first; 243 if (V->use_empty() || std::next(V->use_begin()) == V->use_end()) 244 continue; 245 246 std::vector<unsigned> Shuffle = 247 predictValueUseListOrder(V, Pair.second, OM); 248 if (Shuffle.empty()) 249 continue; 250 251 const Function *F = nullptr; 252 if (auto *I = dyn_cast<Instruction>(V)) 253 F = I->getFunction(); 254 if (auto *A = dyn_cast<Argument>(V)) 255 F = A->getParent(); 256 if (auto *BB = dyn_cast<BasicBlock>(V)) 257 F = BB->getParent(); 258 ULOM[F][V] = std::move(Shuffle); 259 } 260 return ULOM; 261 } 262 263 static const Module *getModuleFromVal(const Value *V) { 264 if (const Argument *MA = dyn_cast<Argument>(V)) 265 return MA->getParent() ? MA->getParent()->getParent() : nullptr; 266 267 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) 268 return BB->getParent() ? BB->getParent()->getParent() : nullptr; 269 270 if (const Instruction *I = dyn_cast<Instruction>(V)) { 271 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr; 272 return M ? M->getParent() : nullptr; 273 } 274 275 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) 276 return GV->getParent(); 277 278 if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) { 279 for (const User *U : MAV->users()) 280 if (isa<Instruction>(U)) 281 if (const Module *M = getModuleFromVal(U)) 282 return M; 283 return nullptr; 284 } 285 286 return nullptr; 287 } 288 289 static void PrintCallingConv(unsigned cc, raw_ostream &Out) { 290 switch (cc) { 291 default: Out << "cc" << cc; break; 292 case CallingConv::Fast: Out << "fastcc"; break; 293 case CallingConv::Cold: Out << "coldcc"; break; 294 case CallingConv::WebKit_JS: Out << "webkit_jscc"; break; 295 case CallingConv::AnyReg: Out << "anyregcc"; break; 296 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break; 297 case CallingConv::PreserveAll: Out << "preserve_allcc"; break; 298 case CallingConv::CXX_FAST_TLS: Out << "cxx_fast_tlscc"; break; 299 case CallingConv::GHC: Out << "ghccc"; break; 300 case CallingConv::Tail: Out << "tailcc"; break; 301 case CallingConv::CFGuard_Check: Out << "cfguard_checkcc"; break; 302 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break; 303 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break; 304 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break; 305 case CallingConv::X86_RegCall: Out << "x86_regcallcc"; break; 306 case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break; 307 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break; 308 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break; 309 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break; 310 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break; 311 case CallingConv::AArch64_VectorCall: Out << "aarch64_vector_pcs"; break; 312 case CallingConv::AArch64_SVE_VectorCall: 313 Out << "aarch64_sve_vector_pcs"; 314 break; 315 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break; 316 case CallingConv::AVR_INTR: Out << "avr_intrcc "; break; 317 case CallingConv::AVR_SIGNAL: Out << "avr_signalcc "; break; 318 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break; 319 case CallingConv::PTX_Device: Out << "ptx_device"; break; 320 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break; 321 case CallingConv::Win64: Out << "win64cc"; break; 322 case CallingConv::SPIR_FUNC: Out << "spir_func"; break; 323 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break; 324 case CallingConv::Swift: Out << "swiftcc"; break; 325 case CallingConv::SwiftTail: Out << "swifttailcc"; break; 326 case CallingConv::X86_INTR: Out << "x86_intrcc"; break; 327 case CallingConv::HHVM: Out << "hhvmcc"; break; 328 case CallingConv::HHVM_C: Out << "hhvm_ccc"; break; 329 case CallingConv::AMDGPU_VS: Out << "amdgpu_vs"; break; 330 case CallingConv::AMDGPU_LS: Out << "amdgpu_ls"; break; 331 case CallingConv::AMDGPU_HS: Out << "amdgpu_hs"; break; 332 case CallingConv::AMDGPU_ES: Out << "amdgpu_es"; break; 333 case CallingConv::AMDGPU_GS: Out << "amdgpu_gs"; break; 334 case CallingConv::AMDGPU_PS: Out << "amdgpu_ps"; break; 335 case CallingConv::AMDGPU_CS: Out << "amdgpu_cs"; break; 336 case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break; 337 case CallingConv::AMDGPU_Gfx: Out << "amdgpu_gfx"; break; 338 } 339 } 340 341 enum PrefixType { 342 GlobalPrefix, 343 ComdatPrefix, 344 LabelPrefix, 345 LocalPrefix, 346 NoPrefix 347 }; 348 349 void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) { 350 assert(!Name.empty() && "Cannot get empty name!"); 351 352 // Scan the name to see if it needs quotes first. 353 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0])); 354 if (!NeedsQuotes) { 355 for (unsigned i = 0, e = Name.size(); i != e; ++i) { 356 // By making this unsigned, the value passed in to isalnum will always be 357 // in the range 0-255. This is important when building with MSVC because 358 // its implementation will assert. This situation can arise when dealing 359 // with UTF-8 multibyte characters. 360 unsigned char C = Name[i]; 361 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' && 362 C != '_') { 363 NeedsQuotes = true; 364 break; 365 } 366 } 367 } 368 369 // If we didn't need any quotes, just write out the name in one blast. 370 if (!NeedsQuotes) { 371 OS << Name; 372 return; 373 } 374 375 // Okay, we need quotes. Output the quotes and escape any scary characters as 376 // needed. 377 OS << '"'; 378 printEscapedString(Name, OS); 379 OS << '"'; 380 } 381 382 /// Turn the specified name into an 'LLVM name', which is either prefixed with % 383 /// (if the string only contains simple characters) or is surrounded with ""'s 384 /// (if it has special chars in it). Print it out. 385 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) { 386 switch (Prefix) { 387 case NoPrefix: 388 break; 389 case GlobalPrefix: 390 OS << '@'; 391 break; 392 case ComdatPrefix: 393 OS << '$'; 394 break; 395 case LabelPrefix: 396 break; 397 case LocalPrefix: 398 OS << '%'; 399 break; 400 } 401 printLLVMNameWithoutPrefix(OS, Name); 402 } 403 404 /// Turn the specified name into an 'LLVM name', which is either prefixed with % 405 /// (if the string only contains simple characters) or is surrounded with ""'s 406 /// (if it has special chars in it). Print it out. 407 static void PrintLLVMName(raw_ostream &OS, const Value *V) { 408 PrintLLVMName(OS, V->getName(), 409 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix); 410 } 411 412 static void PrintShuffleMask(raw_ostream &Out, Type *Ty, ArrayRef<int> Mask) { 413 Out << ", <"; 414 if (isa<ScalableVectorType>(Ty)) 415 Out << "vscale x "; 416 Out << Mask.size() << " x i32> "; 417 bool FirstElt = true; 418 if (all_of(Mask, [](int Elt) { return Elt == 0; })) { 419 Out << "zeroinitializer"; 420 } else if (all_of(Mask, [](int Elt) { return Elt == UndefMaskElem; })) { 421 Out << "undef"; 422 } else { 423 Out << "<"; 424 for (int Elt : Mask) { 425 if (FirstElt) 426 FirstElt = false; 427 else 428 Out << ", "; 429 Out << "i32 "; 430 if (Elt == UndefMaskElem) 431 Out << "undef"; 432 else 433 Out << Elt; 434 } 435 Out << ">"; 436 } 437 } 438 439 namespace { 440 441 class TypePrinting { 442 public: 443 TypePrinting(const Module *M = nullptr) : DeferredM(M) {} 444 445 TypePrinting(const TypePrinting &) = delete; 446 TypePrinting &operator=(const TypePrinting &) = delete; 447 448 /// The named types that are used by the current module. 449 TypeFinder &getNamedTypes(); 450 451 /// The numbered types, number to type mapping. 452 std::vector<StructType *> &getNumberedTypes(); 453 454 bool empty(); 455 456 void print(Type *Ty, raw_ostream &OS); 457 458 void printStructBody(StructType *Ty, raw_ostream &OS); 459 460 private: 461 void incorporateTypes(); 462 463 /// A module to process lazily when needed. Set to nullptr as soon as used. 464 const Module *DeferredM; 465 466 TypeFinder NamedTypes; 467 468 // The numbered types, along with their value. 469 DenseMap<StructType *, unsigned> Type2Number; 470 471 std::vector<StructType *> NumberedTypes; 472 }; 473 474 } // end anonymous namespace 475 476 TypeFinder &TypePrinting::getNamedTypes() { 477 incorporateTypes(); 478 return NamedTypes; 479 } 480 481 std::vector<StructType *> &TypePrinting::getNumberedTypes() { 482 incorporateTypes(); 483 484 // We know all the numbers that each type is used and we know that it is a 485 // dense assignment. Convert the map to an index table, if it's not done 486 // already (judging from the sizes): 487 if (NumberedTypes.size() == Type2Number.size()) 488 return NumberedTypes; 489 490 NumberedTypes.resize(Type2Number.size()); 491 for (const auto &P : Type2Number) { 492 assert(P.second < NumberedTypes.size() && "Didn't get a dense numbering?"); 493 assert(!NumberedTypes[P.second] && "Didn't get a unique numbering?"); 494 NumberedTypes[P.second] = P.first; 495 } 496 return NumberedTypes; 497 } 498 499 bool TypePrinting::empty() { 500 incorporateTypes(); 501 return NamedTypes.empty() && Type2Number.empty(); 502 } 503 504 void TypePrinting::incorporateTypes() { 505 if (!DeferredM) 506 return; 507 508 NamedTypes.run(*DeferredM, false); 509 DeferredM = nullptr; 510 511 // The list of struct types we got back includes all the struct types, split 512 // the unnamed ones out to a numbering and remove the anonymous structs. 513 unsigned NextNumber = 0; 514 515 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E; 516 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) { 517 StructType *STy = *I; 518 519 // Ignore anonymous types. 520 if (STy->isLiteral()) 521 continue; 522 523 if (STy->getName().empty()) 524 Type2Number[STy] = NextNumber++; 525 else 526 *NextToUse++ = STy; 527 } 528 529 NamedTypes.erase(NextToUse, NamedTypes.end()); 530 } 531 532 /// Write the specified type to the specified raw_ostream, making use of type 533 /// names or up references to shorten the type name where possible. 534 void TypePrinting::print(Type *Ty, raw_ostream &OS) { 535 switch (Ty->getTypeID()) { 536 case Type::VoidTyID: OS << "void"; return; 537 case Type::HalfTyID: OS << "half"; return; 538 case Type::BFloatTyID: OS << "bfloat"; return; 539 case Type::FloatTyID: OS << "float"; return; 540 case Type::DoubleTyID: OS << "double"; return; 541 case Type::X86_FP80TyID: OS << "x86_fp80"; return; 542 case Type::FP128TyID: OS << "fp128"; return; 543 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return; 544 case Type::LabelTyID: OS << "label"; return; 545 case Type::MetadataTyID: OS << "metadata"; return; 546 case Type::X86_MMXTyID: OS << "x86_mmx"; return; 547 case Type::X86_AMXTyID: OS << "x86_amx"; return; 548 case Type::TokenTyID: OS << "token"; return; 549 case Type::IntegerTyID: 550 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth(); 551 return; 552 553 case Type::FunctionTyID: { 554 FunctionType *FTy = cast<FunctionType>(Ty); 555 print(FTy->getReturnType(), OS); 556 OS << " ("; 557 for (FunctionType::param_iterator I = FTy->param_begin(), 558 E = FTy->param_end(); I != E; ++I) { 559 if (I != FTy->param_begin()) 560 OS << ", "; 561 print(*I, OS); 562 } 563 if (FTy->isVarArg()) { 564 if (FTy->getNumParams()) OS << ", "; 565 OS << "..."; 566 } 567 OS << ')'; 568 return; 569 } 570 case Type::StructTyID: { 571 StructType *STy = cast<StructType>(Ty); 572 573 if (STy->isLiteral()) 574 return printStructBody(STy, OS); 575 576 if (!STy->getName().empty()) 577 return PrintLLVMName(OS, STy->getName(), LocalPrefix); 578 579 incorporateTypes(); 580 const auto I = Type2Number.find(STy); 581 if (I != Type2Number.end()) 582 OS << '%' << I->second; 583 else // Not enumerated, print the hex address. 584 OS << "%\"type " << STy << '\"'; 585 return; 586 } 587 case Type::PointerTyID: { 588 PointerType *PTy = cast<PointerType>(Ty); 589 if (PTy->isOpaque()) { 590 OS << "ptr"; 591 if (unsigned AddressSpace = PTy->getAddressSpace()) 592 OS << " addrspace(" << AddressSpace << ')'; 593 return; 594 } 595 print(PTy->getElementType(), OS); 596 if (unsigned AddressSpace = PTy->getAddressSpace()) 597 OS << " addrspace(" << AddressSpace << ')'; 598 OS << '*'; 599 return; 600 } 601 case Type::ArrayTyID: { 602 ArrayType *ATy = cast<ArrayType>(Ty); 603 OS << '[' << ATy->getNumElements() << " x "; 604 print(ATy->getElementType(), OS); 605 OS << ']'; 606 return; 607 } 608 case Type::FixedVectorTyID: 609 case Type::ScalableVectorTyID: { 610 VectorType *PTy = cast<VectorType>(Ty); 611 ElementCount EC = PTy->getElementCount(); 612 OS << "<"; 613 if (EC.isScalable()) 614 OS << "vscale x "; 615 OS << EC.getKnownMinValue() << " x "; 616 print(PTy->getElementType(), OS); 617 OS << '>'; 618 return; 619 } 620 } 621 llvm_unreachable("Invalid TypeID"); 622 } 623 624 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) { 625 if (STy->isOpaque()) { 626 OS << "opaque"; 627 return; 628 } 629 630 if (STy->isPacked()) 631 OS << '<'; 632 633 if (STy->getNumElements() == 0) { 634 OS << "{}"; 635 } else { 636 StructType::element_iterator I = STy->element_begin(); 637 OS << "{ "; 638 print(*I++, OS); 639 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) { 640 OS << ", "; 641 print(*I, OS); 642 } 643 644 OS << " }"; 645 } 646 if (STy->isPacked()) 647 OS << '>'; 648 } 649 650 AbstractSlotTrackerStorage::~AbstractSlotTrackerStorage() {} 651 652 namespace llvm { 653 654 //===----------------------------------------------------------------------===// 655 // SlotTracker Class: Enumerate slot numbers for unnamed values 656 //===----------------------------------------------------------------------===// 657 /// This class provides computation of slot numbers for LLVM Assembly writing. 658 /// 659 class SlotTracker : public AbstractSlotTrackerStorage { 660 public: 661 /// ValueMap - A mapping of Values to slot numbers. 662 using ValueMap = DenseMap<const Value *, unsigned>; 663 664 private: 665 /// TheModule - The module for which we are holding slot numbers. 666 const Module* TheModule; 667 668 /// TheFunction - The function for which we are holding slot numbers. 669 const Function* TheFunction = nullptr; 670 bool FunctionProcessed = false; 671 bool ShouldInitializeAllMetadata; 672 673 std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)> 674 ProcessModuleHookFn; 675 std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)> 676 ProcessFunctionHookFn; 677 678 /// The summary index for which we are holding slot numbers. 679 const ModuleSummaryIndex *TheIndex = nullptr; 680 681 /// mMap - The slot map for the module level data. 682 ValueMap mMap; 683 unsigned mNext = 0; 684 685 /// fMap - The slot map for the function level data. 686 ValueMap fMap; 687 unsigned fNext = 0; 688 689 /// mdnMap - Map for MDNodes. 690 DenseMap<const MDNode*, unsigned> mdnMap; 691 unsigned mdnNext = 0; 692 693 /// asMap - The slot map for attribute sets. 694 DenseMap<AttributeSet, unsigned> asMap; 695 unsigned asNext = 0; 696 697 /// ModulePathMap - The slot map for Module paths used in the summary index. 698 StringMap<unsigned> ModulePathMap; 699 unsigned ModulePathNext = 0; 700 701 /// GUIDMap - The slot map for GUIDs used in the summary index. 702 DenseMap<GlobalValue::GUID, unsigned> GUIDMap; 703 unsigned GUIDNext = 0; 704 705 /// TypeIdMap - The slot map for type ids used in the summary index. 706 StringMap<unsigned> TypeIdMap; 707 unsigned TypeIdNext = 0; 708 709 public: 710 /// Construct from a module. 711 /// 712 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all 713 /// functions, giving correct numbering for metadata referenced only from 714 /// within a function (even if no functions have been initialized). 715 explicit SlotTracker(const Module *M, 716 bool ShouldInitializeAllMetadata = false); 717 718 /// Construct from a function, starting out in incorp state. 719 /// 720 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all 721 /// functions, giving correct numbering for metadata referenced only from 722 /// within a function (even if no functions have been initialized). 723 explicit SlotTracker(const Function *F, 724 bool ShouldInitializeAllMetadata = false); 725 726 /// Construct from a module summary index. 727 explicit SlotTracker(const ModuleSummaryIndex *Index); 728 729 SlotTracker(const SlotTracker &) = delete; 730 SlotTracker &operator=(const SlotTracker &) = delete; 731 732 ~SlotTracker() = default; 733 734 void setProcessHook( 735 std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>); 736 void setProcessHook(std::function<void(AbstractSlotTrackerStorage *, 737 const Function *, bool)>); 738 739 unsigned getNextMetadataSlot() override { return mdnNext; } 740 741 void createMetadataSlot(const MDNode *N) override; 742 743 /// Return the slot number of the specified value in it's type 744 /// plane. If something is not in the SlotTracker, return -1. 745 int getLocalSlot(const Value *V); 746 int getGlobalSlot(const GlobalValue *V); 747 int getMetadataSlot(const MDNode *N) override; 748 int getAttributeGroupSlot(AttributeSet AS); 749 int getModulePathSlot(StringRef Path); 750 int getGUIDSlot(GlobalValue::GUID GUID); 751 int getTypeIdSlot(StringRef Id); 752 753 /// If you'd like to deal with a function instead of just a module, use 754 /// this method to get its data into the SlotTracker. 755 void incorporateFunction(const Function *F) { 756 TheFunction = F; 757 FunctionProcessed = false; 758 } 759 760 const Function *getFunction() const { return TheFunction; } 761 762 /// After calling incorporateFunction, use this method to remove the 763 /// most recently incorporated function from the SlotTracker. This 764 /// will reset the state of the machine back to just the module contents. 765 void purgeFunction(); 766 767 /// MDNode map iterators. 768 using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator; 769 770 mdn_iterator mdn_begin() { return mdnMap.begin(); } 771 mdn_iterator mdn_end() { return mdnMap.end(); } 772 unsigned mdn_size() const { return mdnMap.size(); } 773 bool mdn_empty() const { return mdnMap.empty(); } 774 775 /// AttributeSet map iterators. 776 using as_iterator = DenseMap<AttributeSet, unsigned>::iterator; 777 778 as_iterator as_begin() { return asMap.begin(); } 779 as_iterator as_end() { return asMap.end(); } 780 unsigned as_size() const { return asMap.size(); } 781 bool as_empty() const { return asMap.empty(); } 782 783 /// GUID map iterators. 784 using guid_iterator = DenseMap<GlobalValue::GUID, unsigned>::iterator; 785 786 /// These functions do the actual initialization. 787 inline void initializeIfNeeded(); 788 int initializeIndexIfNeeded(); 789 790 // Implementation Details 791 private: 792 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table. 793 void CreateModuleSlot(const GlobalValue *V); 794 795 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table. 796 void CreateMetadataSlot(const MDNode *N); 797 798 /// CreateFunctionSlot - Insert the specified Value* into the slot table. 799 void CreateFunctionSlot(const Value *V); 800 801 /// Insert the specified AttributeSet into the slot table. 802 void CreateAttributeSetSlot(AttributeSet AS); 803 804 inline void CreateModulePathSlot(StringRef Path); 805 void CreateGUIDSlot(GlobalValue::GUID GUID); 806 void CreateTypeIdSlot(StringRef Id); 807 808 /// Add all of the module level global variables (and their initializers) 809 /// and function declarations, but not the contents of those functions. 810 void processModule(); 811 // Returns number of allocated slots 812 int processIndex(); 813 814 /// Add all of the functions arguments, basic blocks, and instructions. 815 void processFunction(); 816 817 /// Add the metadata directly attached to a GlobalObject. 818 void processGlobalObjectMetadata(const GlobalObject &GO); 819 820 /// Add all of the metadata from a function. 821 void processFunctionMetadata(const Function &F); 822 823 /// Add all of the metadata from an instruction. 824 void processInstructionMetadata(const Instruction &I); 825 }; 826 827 } // end namespace llvm 828 829 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M, 830 const Function *F) 831 : M(M), F(F), Machine(&Machine) {} 832 833 ModuleSlotTracker::ModuleSlotTracker(const Module *M, 834 bool ShouldInitializeAllMetadata) 835 : ShouldCreateStorage(M), 836 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {} 837 838 ModuleSlotTracker::~ModuleSlotTracker() = default; 839 840 SlotTracker *ModuleSlotTracker::getMachine() { 841 if (!ShouldCreateStorage) 842 return Machine; 843 844 ShouldCreateStorage = false; 845 MachineStorage = 846 std::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata); 847 Machine = MachineStorage.get(); 848 if (ProcessModuleHookFn) 849 Machine->setProcessHook(ProcessModuleHookFn); 850 if (ProcessFunctionHookFn) 851 Machine->setProcessHook(ProcessFunctionHookFn); 852 return Machine; 853 } 854 855 void ModuleSlotTracker::incorporateFunction(const Function &F) { 856 // Using getMachine() may lazily create the slot tracker. 857 if (!getMachine()) 858 return; 859 860 // Nothing to do if this is the right function already. 861 if (this->F == &F) 862 return; 863 if (this->F) 864 Machine->purgeFunction(); 865 Machine->incorporateFunction(&F); 866 this->F = &F; 867 } 868 869 int ModuleSlotTracker::getLocalSlot(const Value *V) { 870 assert(F && "No function incorporated"); 871 return Machine->getLocalSlot(V); 872 } 873 874 void ModuleSlotTracker::setProcessHook( 875 std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)> 876 Fn) { 877 ProcessModuleHookFn = Fn; 878 } 879 880 void ModuleSlotTracker::setProcessHook( 881 std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)> 882 Fn) { 883 ProcessFunctionHookFn = Fn; 884 } 885 886 static SlotTracker *createSlotTracker(const Value *V) { 887 if (const Argument *FA = dyn_cast<Argument>(V)) 888 return new SlotTracker(FA->getParent()); 889 890 if (const Instruction *I = dyn_cast<Instruction>(V)) 891 if (I->getParent()) 892 return new SlotTracker(I->getParent()->getParent()); 893 894 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) 895 return new SlotTracker(BB->getParent()); 896 897 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) 898 return new SlotTracker(GV->getParent()); 899 900 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 901 return new SlotTracker(GA->getParent()); 902 903 if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V)) 904 return new SlotTracker(GIF->getParent()); 905 906 if (const Function *Func = dyn_cast<Function>(V)) 907 return new SlotTracker(Func); 908 909 return nullptr; 910 } 911 912 #if 0 913 #define ST_DEBUG(X) dbgs() << X 914 #else 915 #define ST_DEBUG(X) 916 #endif 917 918 // Module level constructor. Causes the contents of the Module (sans functions) 919 // to be added to the slot table. 920 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata) 921 : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {} 922 923 // Function level constructor. Causes the contents of the Module and the one 924 // function provided to be added to the slot table. 925 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata) 926 : TheModule(F ? F->getParent() : nullptr), TheFunction(F), 927 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {} 928 929 SlotTracker::SlotTracker(const ModuleSummaryIndex *Index) 930 : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index) {} 931 932 inline void SlotTracker::initializeIfNeeded() { 933 if (TheModule) { 934 processModule(); 935 TheModule = nullptr; ///< Prevent re-processing next time we're called. 936 } 937 938 if (TheFunction && !FunctionProcessed) 939 processFunction(); 940 } 941 942 int SlotTracker::initializeIndexIfNeeded() { 943 if (!TheIndex) 944 return 0; 945 int NumSlots = processIndex(); 946 TheIndex = nullptr; ///< Prevent re-processing next time we're called. 947 return NumSlots; 948 } 949 950 // Iterate through all the global variables, functions, and global 951 // variable initializers and create slots for them. 952 void SlotTracker::processModule() { 953 ST_DEBUG("begin processModule!\n"); 954 955 // Add all of the unnamed global variables to the value table. 956 for (const GlobalVariable &Var : TheModule->globals()) { 957 if (!Var.hasName()) 958 CreateModuleSlot(&Var); 959 processGlobalObjectMetadata(Var); 960 auto Attrs = Var.getAttributes(); 961 if (Attrs.hasAttributes()) 962 CreateAttributeSetSlot(Attrs); 963 } 964 965 for (const GlobalAlias &A : TheModule->aliases()) { 966 if (!A.hasName()) 967 CreateModuleSlot(&A); 968 } 969 970 for (const GlobalIFunc &I : TheModule->ifuncs()) { 971 if (!I.hasName()) 972 CreateModuleSlot(&I); 973 } 974 975 // Add metadata used by named metadata. 976 for (const NamedMDNode &NMD : TheModule->named_metadata()) { 977 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) 978 CreateMetadataSlot(NMD.getOperand(i)); 979 } 980 981 for (const Function &F : *TheModule) { 982 if (!F.hasName()) 983 // Add all the unnamed functions to the table. 984 CreateModuleSlot(&F); 985 986 if (ShouldInitializeAllMetadata) 987 processFunctionMetadata(F); 988 989 // Add all the function attributes to the table. 990 // FIXME: Add attributes of other objects? 991 AttributeSet FnAttrs = F.getAttributes().getFnAttributes(); 992 if (FnAttrs.hasAttributes()) 993 CreateAttributeSetSlot(FnAttrs); 994 } 995 996 if (ProcessModuleHookFn) 997 ProcessModuleHookFn(this, TheModule, ShouldInitializeAllMetadata); 998 999 ST_DEBUG("end processModule!\n"); 1000 } 1001 1002 // Process the arguments, basic blocks, and instructions of a function. 1003 void SlotTracker::processFunction() { 1004 ST_DEBUG("begin processFunction!\n"); 1005 fNext = 0; 1006 1007 // Process function metadata if it wasn't hit at the module-level. 1008 if (!ShouldInitializeAllMetadata) 1009 processFunctionMetadata(*TheFunction); 1010 1011 // Add all the function arguments with no names. 1012 for(Function::const_arg_iterator AI = TheFunction->arg_begin(), 1013 AE = TheFunction->arg_end(); AI != AE; ++AI) 1014 if (!AI->hasName()) 1015 CreateFunctionSlot(&*AI); 1016 1017 ST_DEBUG("Inserting Instructions:\n"); 1018 1019 // Add all of the basic blocks and instructions with no names. 1020 for (auto &BB : *TheFunction) { 1021 if (!BB.hasName()) 1022 CreateFunctionSlot(&BB); 1023 1024 for (auto &I : BB) { 1025 if (!I.getType()->isVoidTy() && !I.hasName()) 1026 CreateFunctionSlot(&I); 1027 1028 // We allow direct calls to any llvm.foo function here, because the 1029 // target may not be linked into the optimizer. 1030 if (const auto *Call = dyn_cast<CallBase>(&I)) { 1031 // Add all the call attributes to the table. 1032 AttributeSet Attrs = Call->getAttributes().getFnAttributes(); 1033 if (Attrs.hasAttributes()) 1034 CreateAttributeSetSlot(Attrs); 1035 } 1036 } 1037 } 1038 1039 if (ProcessFunctionHookFn) 1040 ProcessFunctionHookFn(this, TheFunction, ShouldInitializeAllMetadata); 1041 1042 FunctionProcessed = true; 1043 1044 ST_DEBUG("end processFunction!\n"); 1045 } 1046 1047 // Iterate through all the GUID in the index and create slots for them. 1048 int SlotTracker::processIndex() { 1049 ST_DEBUG("begin processIndex!\n"); 1050 assert(TheIndex); 1051 1052 // The first block of slots are just the module ids, which start at 0 and are 1053 // assigned consecutively. Since the StringMap iteration order isn't 1054 // guaranteed, use a std::map to order by module ID before assigning slots. 1055 std::map<uint64_t, StringRef> ModuleIdToPathMap; 1056 for (auto &ModPath : TheIndex->modulePaths()) 1057 ModuleIdToPathMap[ModPath.second.first] = ModPath.first(); 1058 for (auto &ModPair : ModuleIdToPathMap) 1059 CreateModulePathSlot(ModPair.second); 1060 1061 // Start numbering the GUIDs after the module ids. 1062 GUIDNext = ModulePathNext; 1063 1064 for (auto &GlobalList : *TheIndex) 1065 CreateGUIDSlot(GlobalList.first); 1066 1067 for (auto &TId : TheIndex->typeIdCompatibleVtableMap()) 1068 CreateGUIDSlot(GlobalValue::getGUID(TId.first)); 1069 1070 // Start numbering the TypeIds after the GUIDs. 1071 TypeIdNext = GUIDNext; 1072 for (const auto &TID : TheIndex->typeIds()) 1073 CreateTypeIdSlot(TID.second.first); 1074 1075 ST_DEBUG("end processIndex!\n"); 1076 return TypeIdNext; 1077 } 1078 1079 void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) { 1080 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 1081 GO.getAllMetadata(MDs); 1082 for (auto &MD : MDs) 1083 CreateMetadataSlot(MD.second); 1084 } 1085 1086 void SlotTracker::processFunctionMetadata(const Function &F) { 1087 processGlobalObjectMetadata(F); 1088 for (auto &BB : F) { 1089 for (auto &I : BB) 1090 processInstructionMetadata(I); 1091 } 1092 } 1093 1094 void SlotTracker::processInstructionMetadata(const Instruction &I) { 1095 // Process metadata used directly by intrinsics. 1096 if (const CallInst *CI = dyn_cast<CallInst>(&I)) 1097 if (Function *F = CI->getCalledFunction()) 1098 if (F->isIntrinsic()) 1099 for (auto &Op : I.operands()) 1100 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op)) 1101 if (MDNode *N = dyn_cast<MDNode>(V->getMetadata())) 1102 CreateMetadataSlot(N); 1103 1104 // Process metadata attached to this instruction. 1105 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 1106 I.getAllMetadata(MDs); 1107 for (auto &MD : MDs) 1108 CreateMetadataSlot(MD.second); 1109 } 1110 1111 /// Clean up after incorporating a function. This is the only way to get out of 1112 /// the function incorporation state that affects get*Slot/Create*Slot. Function 1113 /// incorporation state is indicated by TheFunction != 0. 1114 void SlotTracker::purgeFunction() { 1115 ST_DEBUG("begin purgeFunction!\n"); 1116 fMap.clear(); // Simply discard the function level map 1117 TheFunction = nullptr; 1118 FunctionProcessed = false; 1119 ST_DEBUG("end purgeFunction!\n"); 1120 } 1121 1122 /// getGlobalSlot - Get the slot number of a global value. 1123 int SlotTracker::getGlobalSlot(const GlobalValue *V) { 1124 // Check for uninitialized state and do lazy initialization. 1125 initializeIfNeeded(); 1126 1127 // Find the value in the module map 1128 ValueMap::iterator MI = mMap.find(V); 1129 return MI == mMap.end() ? -1 : (int)MI->second; 1130 } 1131 1132 void SlotTracker::setProcessHook( 1133 std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)> 1134 Fn) { 1135 ProcessModuleHookFn = Fn; 1136 } 1137 1138 void SlotTracker::setProcessHook( 1139 std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)> 1140 Fn) { 1141 ProcessFunctionHookFn = Fn; 1142 } 1143 1144 /// getMetadataSlot - Get the slot number of a MDNode. 1145 void SlotTracker::createMetadataSlot(const MDNode *N) { CreateMetadataSlot(N); } 1146 1147 /// getMetadataSlot - Get the slot number of a MDNode. 1148 int SlotTracker::getMetadataSlot(const MDNode *N) { 1149 // Check for uninitialized state and do lazy initialization. 1150 initializeIfNeeded(); 1151 1152 // Find the MDNode in the module map 1153 mdn_iterator MI = mdnMap.find(N); 1154 return MI == mdnMap.end() ? -1 : (int)MI->second; 1155 } 1156 1157 /// getLocalSlot - Get the slot number for a value that is local to a function. 1158 int SlotTracker::getLocalSlot(const Value *V) { 1159 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!"); 1160 1161 // Check for uninitialized state and do lazy initialization. 1162 initializeIfNeeded(); 1163 1164 ValueMap::iterator FI = fMap.find(V); 1165 return FI == fMap.end() ? -1 : (int)FI->second; 1166 } 1167 1168 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) { 1169 // Check for uninitialized state and do lazy initialization. 1170 initializeIfNeeded(); 1171 1172 // Find the AttributeSet in the module map. 1173 as_iterator AI = asMap.find(AS); 1174 return AI == asMap.end() ? -1 : (int)AI->second; 1175 } 1176 1177 int SlotTracker::getModulePathSlot(StringRef Path) { 1178 // Check for uninitialized state and do lazy initialization. 1179 initializeIndexIfNeeded(); 1180 1181 // Find the Module path in the map 1182 auto I = ModulePathMap.find(Path); 1183 return I == ModulePathMap.end() ? -1 : (int)I->second; 1184 } 1185 1186 int SlotTracker::getGUIDSlot(GlobalValue::GUID GUID) { 1187 // Check for uninitialized state and do lazy initialization. 1188 initializeIndexIfNeeded(); 1189 1190 // Find the GUID in the map 1191 guid_iterator I = GUIDMap.find(GUID); 1192 return I == GUIDMap.end() ? -1 : (int)I->second; 1193 } 1194 1195 int SlotTracker::getTypeIdSlot(StringRef Id) { 1196 // Check for uninitialized state and do lazy initialization. 1197 initializeIndexIfNeeded(); 1198 1199 // Find the TypeId string in the map 1200 auto I = TypeIdMap.find(Id); 1201 return I == TypeIdMap.end() ? -1 : (int)I->second; 1202 } 1203 1204 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table. 1205 void SlotTracker::CreateModuleSlot(const GlobalValue *V) { 1206 assert(V && "Can't insert a null Value into SlotTracker!"); 1207 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!"); 1208 assert(!V->hasName() && "Doesn't need a slot!"); 1209 1210 unsigned DestSlot = mNext++; 1211 mMap[V] = DestSlot; 1212 1213 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" << 1214 DestSlot << " ["); 1215 // G = Global, F = Function, A = Alias, I = IFunc, o = other 1216 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' : 1217 (isa<Function>(V) ? 'F' : 1218 (isa<GlobalAlias>(V) ? 'A' : 1219 (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n"); 1220 } 1221 1222 /// CreateSlot - Create a new slot for the specified value if it has no name. 1223 void SlotTracker::CreateFunctionSlot(const Value *V) { 1224 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!"); 1225 1226 unsigned DestSlot = fNext++; 1227 fMap[V] = DestSlot; 1228 1229 // G = Global, F = Function, o = other 1230 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" << 1231 DestSlot << " [o]\n"); 1232 } 1233 1234 /// CreateModuleSlot - Insert the specified MDNode* into the slot table. 1235 void SlotTracker::CreateMetadataSlot(const MDNode *N) { 1236 assert(N && "Can't insert a null Value into SlotTracker!"); 1237 1238 // Don't make slots for DIExpressions or DIArgLists. We just print them inline 1239 // everywhere. 1240 if (isa<DIExpression>(N) || isa<DIArgList>(N)) 1241 return; 1242 1243 unsigned DestSlot = mdnNext; 1244 if (!mdnMap.insert(std::make_pair(N, DestSlot)).second) 1245 return; 1246 ++mdnNext; 1247 1248 // Recursively add any MDNodes referenced by operands. 1249 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1250 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i))) 1251 CreateMetadataSlot(Op); 1252 } 1253 1254 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) { 1255 assert(AS.hasAttributes() && "Doesn't need a slot!"); 1256 1257 as_iterator I = asMap.find(AS); 1258 if (I != asMap.end()) 1259 return; 1260 1261 unsigned DestSlot = asNext++; 1262 asMap[AS] = DestSlot; 1263 } 1264 1265 /// Create a new slot for the specified Module 1266 void SlotTracker::CreateModulePathSlot(StringRef Path) { 1267 ModulePathMap[Path] = ModulePathNext++; 1268 } 1269 1270 /// Create a new slot for the specified GUID 1271 void SlotTracker::CreateGUIDSlot(GlobalValue::GUID GUID) { 1272 GUIDMap[GUID] = GUIDNext++; 1273 } 1274 1275 /// Create a new slot for the specified Id 1276 void SlotTracker::CreateTypeIdSlot(StringRef Id) { 1277 TypeIdMap[Id] = TypeIdNext++; 1278 } 1279 1280 //===----------------------------------------------------------------------===// 1281 // AsmWriter Implementation 1282 //===----------------------------------------------------------------------===// 1283 1284 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, 1285 TypePrinting *TypePrinter, 1286 SlotTracker *Machine, 1287 const Module *Context); 1288 1289 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD, 1290 TypePrinting *TypePrinter, 1291 SlotTracker *Machine, const Module *Context, 1292 bool FromValue = false); 1293 1294 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) { 1295 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) { 1296 // 'Fast' is an abbreviation for all fast-math-flags. 1297 if (FPO->isFast()) 1298 Out << " fast"; 1299 else { 1300 if (FPO->hasAllowReassoc()) 1301 Out << " reassoc"; 1302 if (FPO->hasNoNaNs()) 1303 Out << " nnan"; 1304 if (FPO->hasNoInfs()) 1305 Out << " ninf"; 1306 if (FPO->hasNoSignedZeros()) 1307 Out << " nsz"; 1308 if (FPO->hasAllowReciprocal()) 1309 Out << " arcp"; 1310 if (FPO->hasAllowContract()) 1311 Out << " contract"; 1312 if (FPO->hasApproxFunc()) 1313 Out << " afn"; 1314 } 1315 } 1316 1317 if (const OverflowingBinaryOperator *OBO = 1318 dyn_cast<OverflowingBinaryOperator>(U)) { 1319 if (OBO->hasNoUnsignedWrap()) 1320 Out << " nuw"; 1321 if (OBO->hasNoSignedWrap()) 1322 Out << " nsw"; 1323 } else if (const PossiblyExactOperator *Div = 1324 dyn_cast<PossiblyExactOperator>(U)) { 1325 if (Div->isExact()) 1326 Out << " exact"; 1327 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) { 1328 if (GEP->isInBounds()) 1329 Out << " inbounds"; 1330 } 1331 } 1332 1333 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV, 1334 TypePrinting &TypePrinter, 1335 SlotTracker *Machine, 1336 const Module *Context) { 1337 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 1338 if (CI->getType()->isIntegerTy(1)) { 1339 Out << (CI->getZExtValue() ? "true" : "false"); 1340 return; 1341 } 1342 Out << CI->getValue(); 1343 return; 1344 } 1345 1346 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) { 1347 const APFloat &APF = CFP->getValueAPF(); 1348 if (&APF.getSemantics() == &APFloat::IEEEsingle() || 1349 &APF.getSemantics() == &APFloat::IEEEdouble()) { 1350 // We would like to output the FP constant value in exponential notation, 1351 // but we cannot do this if doing so will lose precision. Check here to 1352 // make sure that we only output it in exponential format if we can parse 1353 // the value back and get the same value. 1354 // 1355 bool ignored; 1356 bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble(); 1357 bool isInf = APF.isInfinity(); 1358 bool isNaN = APF.isNaN(); 1359 if (!isInf && !isNaN) { 1360 double Val = APF.convertToDouble(); 1361 SmallString<128> StrVal; 1362 APF.toString(StrVal, 6, 0, false); 1363 // Check to make sure that the stringized number is not some string like 1364 // "Inf" or NaN, that atof will accept, but the lexer will not. Check 1365 // that the string matches the "[-+]?[0-9]" regex. 1366 // 1367 assert((isDigit(StrVal[0]) || ((StrVal[0] == '-' || StrVal[0] == '+') && 1368 isDigit(StrVal[1]))) && 1369 "[-+]?[0-9] regex does not match!"); 1370 // Reparse stringized version! 1371 if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) { 1372 Out << StrVal; 1373 return; 1374 } 1375 } 1376 // Otherwise we could not reparse it to exactly the same value, so we must 1377 // output the string in hexadecimal format! Note that loading and storing 1378 // floating point types changes the bits of NaNs on some hosts, notably 1379 // x86, so we must not use these types. 1380 static_assert(sizeof(double) == sizeof(uint64_t), 1381 "assuming that double is 64 bits!"); 1382 APFloat apf = APF; 1383 // Floats are represented in ASCII IR as double, convert. 1384 // FIXME: We should allow 32-bit hex float and remove this. 1385 if (!isDouble) { 1386 // A signaling NaN is quieted on conversion, so we need to recreate the 1387 // expected value after convert (quiet bit of the payload is clear). 1388 bool IsSNAN = apf.isSignaling(); 1389 apf.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, 1390 &ignored); 1391 if (IsSNAN) { 1392 APInt Payload = apf.bitcastToAPInt(); 1393 apf = APFloat::getSNaN(APFloat::IEEEdouble(), apf.isNegative(), 1394 &Payload); 1395 } 1396 } 1397 Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true); 1398 return; 1399 } 1400 1401 // Either half, bfloat or some form of long double. 1402 // These appear as a magic letter identifying the type, then a 1403 // fixed number of hex digits. 1404 Out << "0x"; 1405 APInt API = APF.bitcastToAPInt(); 1406 if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) { 1407 Out << 'K'; 1408 Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4, 1409 /*Upper=*/true); 1410 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16, 1411 /*Upper=*/true); 1412 return; 1413 } else if (&APF.getSemantics() == &APFloat::IEEEquad()) { 1414 Out << 'L'; 1415 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16, 1416 /*Upper=*/true); 1417 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16, 1418 /*Upper=*/true); 1419 } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) { 1420 Out << 'M'; 1421 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16, 1422 /*Upper=*/true); 1423 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16, 1424 /*Upper=*/true); 1425 } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) { 1426 Out << 'H'; 1427 Out << format_hex_no_prefix(API.getZExtValue(), 4, 1428 /*Upper=*/true); 1429 } else if (&APF.getSemantics() == &APFloat::BFloat()) { 1430 Out << 'R'; 1431 Out << format_hex_no_prefix(API.getZExtValue(), 4, 1432 /*Upper=*/true); 1433 } else 1434 llvm_unreachable("Unsupported floating point type"); 1435 return; 1436 } 1437 1438 if (isa<ConstantAggregateZero>(CV)) { 1439 Out << "zeroinitializer"; 1440 return; 1441 } 1442 1443 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) { 1444 Out << "blockaddress("; 1445 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine, 1446 Context); 1447 Out << ", "; 1448 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine, 1449 Context); 1450 Out << ")"; 1451 return; 1452 } 1453 1454 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV)) { 1455 Out << "dso_local_equivalent "; 1456 WriteAsOperandInternal(Out, Equiv->getGlobalValue(), &TypePrinter, Machine, 1457 Context); 1458 return; 1459 } 1460 1461 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) { 1462 Type *ETy = CA->getType()->getElementType(); 1463 Out << '['; 1464 TypePrinter.print(ETy, Out); 1465 Out << ' '; 1466 WriteAsOperandInternal(Out, CA->getOperand(0), 1467 &TypePrinter, Machine, 1468 Context); 1469 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) { 1470 Out << ", "; 1471 TypePrinter.print(ETy, Out); 1472 Out << ' '; 1473 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine, 1474 Context); 1475 } 1476 Out << ']'; 1477 return; 1478 } 1479 1480 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) { 1481 // As a special case, print the array as a string if it is an array of 1482 // i8 with ConstantInt values. 1483 if (CA->isString()) { 1484 Out << "c\""; 1485 printEscapedString(CA->getAsString(), Out); 1486 Out << '"'; 1487 return; 1488 } 1489 1490 Type *ETy = CA->getType()->getElementType(); 1491 Out << '['; 1492 TypePrinter.print(ETy, Out); 1493 Out << ' '; 1494 WriteAsOperandInternal(Out, CA->getElementAsConstant(0), 1495 &TypePrinter, Machine, 1496 Context); 1497 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) { 1498 Out << ", "; 1499 TypePrinter.print(ETy, Out); 1500 Out << ' '; 1501 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter, 1502 Machine, Context); 1503 } 1504 Out << ']'; 1505 return; 1506 } 1507 1508 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) { 1509 if (CS->getType()->isPacked()) 1510 Out << '<'; 1511 Out << '{'; 1512 unsigned N = CS->getNumOperands(); 1513 if (N) { 1514 Out << ' '; 1515 TypePrinter.print(CS->getOperand(0)->getType(), Out); 1516 Out << ' '; 1517 1518 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine, 1519 Context); 1520 1521 for (unsigned i = 1; i < N; i++) { 1522 Out << ", "; 1523 TypePrinter.print(CS->getOperand(i)->getType(), Out); 1524 Out << ' '; 1525 1526 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine, 1527 Context); 1528 } 1529 Out << ' '; 1530 } 1531 1532 Out << '}'; 1533 if (CS->getType()->isPacked()) 1534 Out << '>'; 1535 return; 1536 } 1537 1538 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) { 1539 auto *CVVTy = cast<FixedVectorType>(CV->getType()); 1540 Type *ETy = CVVTy->getElementType(); 1541 Out << '<'; 1542 TypePrinter.print(ETy, Out); 1543 Out << ' '; 1544 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter, 1545 Machine, Context); 1546 for (unsigned i = 1, e = CVVTy->getNumElements(); i != e; ++i) { 1547 Out << ", "; 1548 TypePrinter.print(ETy, Out); 1549 Out << ' '; 1550 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter, 1551 Machine, Context); 1552 } 1553 Out << '>'; 1554 return; 1555 } 1556 1557 if (isa<ConstantPointerNull>(CV)) { 1558 Out << "null"; 1559 return; 1560 } 1561 1562 if (isa<ConstantTokenNone>(CV)) { 1563 Out << "none"; 1564 return; 1565 } 1566 1567 if (isa<PoisonValue>(CV)) { 1568 Out << "poison"; 1569 return; 1570 } 1571 1572 if (isa<UndefValue>(CV)) { 1573 Out << "undef"; 1574 return; 1575 } 1576 1577 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 1578 Out << CE->getOpcodeName(); 1579 WriteOptimizationInfo(Out, CE); 1580 if (CE->isCompare()) 1581 Out << ' ' << CmpInst::getPredicateName( 1582 static_cast<CmpInst::Predicate>(CE->getPredicate())); 1583 Out << " ("; 1584 1585 Optional<unsigned> InRangeOp; 1586 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) { 1587 TypePrinter.print(GEP->getSourceElementType(), Out); 1588 Out << ", "; 1589 InRangeOp = GEP->getInRangeIndex(); 1590 if (InRangeOp) 1591 ++*InRangeOp; 1592 } 1593 1594 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) { 1595 if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp) 1596 Out << "inrange "; 1597 TypePrinter.print((*OI)->getType(), Out); 1598 Out << ' '; 1599 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context); 1600 if (OI+1 != CE->op_end()) 1601 Out << ", "; 1602 } 1603 1604 if (CE->hasIndices()) { 1605 ArrayRef<unsigned> Indices = CE->getIndices(); 1606 for (unsigned i = 0, e = Indices.size(); i != e; ++i) 1607 Out << ", " << Indices[i]; 1608 } 1609 1610 if (CE->isCast()) { 1611 Out << " to "; 1612 TypePrinter.print(CE->getType(), Out); 1613 } 1614 1615 if (CE->getOpcode() == Instruction::ShuffleVector) 1616 PrintShuffleMask(Out, CE->getType(), CE->getShuffleMask()); 1617 1618 Out << ')'; 1619 return; 1620 } 1621 1622 Out << "<placeholder or erroneous Constant>"; 1623 } 1624 1625 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node, 1626 TypePrinting *TypePrinter, SlotTracker *Machine, 1627 const Module *Context) { 1628 Out << "!{"; 1629 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) { 1630 const Metadata *MD = Node->getOperand(mi); 1631 if (!MD) 1632 Out << "null"; 1633 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) { 1634 Value *V = MDV->getValue(); 1635 TypePrinter->print(V->getType(), Out); 1636 Out << ' '; 1637 WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context); 1638 } else { 1639 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context); 1640 } 1641 if (mi + 1 != me) 1642 Out << ", "; 1643 } 1644 1645 Out << "}"; 1646 } 1647 1648 namespace { 1649 1650 struct FieldSeparator { 1651 bool Skip = true; 1652 const char *Sep; 1653 1654 FieldSeparator(const char *Sep = ", ") : Sep(Sep) {} 1655 }; 1656 1657 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) { 1658 if (FS.Skip) { 1659 FS.Skip = false; 1660 return OS; 1661 } 1662 return OS << FS.Sep; 1663 } 1664 1665 struct MDFieldPrinter { 1666 raw_ostream &Out; 1667 FieldSeparator FS; 1668 TypePrinting *TypePrinter = nullptr; 1669 SlotTracker *Machine = nullptr; 1670 const Module *Context = nullptr; 1671 1672 explicit MDFieldPrinter(raw_ostream &Out) : Out(Out) {} 1673 MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter, 1674 SlotTracker *Machine, const Module *Context) 1675 : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) { 1676 } 1677 1678 void printTag(const DINode *N); 1679 void printMacinfoType(const DIMacroNode *N); 1680 void printChecksum(const DIFile::ChecksumInfo<StringRef> &N); 1681 void printString(StringRef Name, StringRef Value, 1682 bool ShouldSkipEmpty = true); 1683 void printMetadata(StringRef Name, const Metadata *MD, 1684 bool ShouldSkipNull = true); 1685 template <class IntTy> 1686 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true); 1687 void printAPInt(StringRef Name, const APInt &Int, bool IsUnsigned, 1688 bool ShouldSkipZero); 1689 void printBool(StringRef Name, bool Value, Optional<bool> Default = None); 1690 void printDIFlags(StringRef Name, DINode::DIFlags Flags); 1691 void printDISPFlags(StringRef Name, DISubprogram::DISPFlags Flags); 1692 template <class IntTy, class Stringifier> 1693 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString, 1694 bool ShouldSkipZero = true); 1695 void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK); 1696 void printNameTableKind(StringRef Name, 1697 DICompileUnit::DebugNameTableKind NTK); 1698 }; 1699 1700 } // end anonymous namespace 1701 1702 void MDFieldPrinter::printTag(const DINode *N) { 1703 Out << FS << "tag: "; 1704 auto Tag = dwarf::TagString(N->getTag()); 1705 if (!Tag.empty()) 1706 Out << Tag; 1707 else 1708 Out << N->getTag(); 1709 } 1710 1711 void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) { 1712 Out << FS << "type: "; 1713 auto Type = dwarf::MacinfoString(N->getMacinfoType()); 1714 if (!Type.empty()) 1715 Out << Type; 1716 else 1717 Out << N->getMacinfoType(); 1718 } 1719 1720 void MDFieldPrinter::printChecksum( 1721 const DIFile::ChecksumInfo<StringRef> &Checksum) { 1722 Out << FS << "checksumkind: " << Checksum.getKindAsString(); 1723 printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false); 1724 } 1725 1726 void MDFieldPrinter::printString(StringRef Name, StringRef Value, 1727 bool ShouldSkipEmpty) { 1728 if (ShouldSkipEmpty && Value.empty()) 1729 return; 1730 1731 Out << FS << Name << ": \""; 1732 printEscapedString(Value, Out); 1733 Out << "\""; 1734 } 1735 1736 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD, 1737 TypePrinting *TypePrinter, 1738 SlotTracker *Machine, 1739 const Module *Context) { 1740 if (!MD) { 1741 Out << "null"; 1742 return; 1743 } 1744 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context); 1745 } 1746 1747 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD, 1748 bool ShouldSkipNull) { 1749 if (ShouldSkipNull && !MD) 1750 return; 1751 1752 Out << FS << Name << ": "; 1753 writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context); 1754 } 1755 1756 template <class IntTy> 1757 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) { 1758 if (ShouldSkipZero && !Int) 1759 return; 1760 1761 Out << FS << Name << ": " << Int; 1762 } 1763 1764 void MDFieldPrinter::printAPInt(StringRef Name, const APInt &Int, 1765 bool IsUnsigned, bool ShouldSkipZero) { 1766 if (ShouldSkipZero && Int.isNullValue()) 1767 return; 1768 1769 Out << FS << Name << ": "; 1770 Int.print(Out, !IsUnsigned); 1771 } 1772 1773 void MDFieldPrinter::printBool(StringRef Name, bool Value, 1774 Optional<bool> Default) { 1775 if (Default && Value == *Default) 1776 return; 1777 Out << FS << Name << ": " << (Value ? "true" : "false"); 1778 } 1779 1780 void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) { 1781 if (!Flags) 1782 return; 1783 1784 Out << FS << Name << ": "; 1785 1786 SmallVector<DINode::DIFlags, 8> SplitFlags; 1787 auto Extra = DINode::splitFlags(Flags, SplitFlags); 1788 1789 FieldSeparator FlagsFS(" | "); 1790 for (auto F : SplitFlags) { 1791 auto StringF = DINode::getFlagString(F); 1792 assert(!StringF.empty() && "Expected valid flag"); 1793 Out << FlagsFS << StringF; 1794 } 1795 if (Extra || SplitFlags.empty()) 1796 Out << FlagsFS << Extra; 1797 } 1798 1799 void MDFieldPrinter::printDISPFlags(StringRef Name, 1800 DISubprogram::DISPFlags Flags) { 1801 // Always print this field, because no flags in the IR at all will be 1802 // interpreted as old-style isDefinition: true. 1803 Out << FS << Name << ": "; 1804 1805 if (!Flags) { 1806 Out << 0; 1807 return; 1808 } 1809 1810 SmallVector<DISubprogram::DISPFlags, 8> SplitFlags; 1811 auto Extra = DISubprogram::splitFlags(Flags, SplitFlags); 1812 1813 FieldSeparator FlagsFS(" | "); 1814 for (auto F : SplitFlags) { 1815 auto StringF = DISubprogram::getFlagString(F); 1816 assert(!StringF.empty() && "Expected valid flag"); 1817 Out << FlagsFS << StringF; 1818 } 1819 if (Extra || SplitFlags.empty()) 1820 Out << FlagsFS << Extra; 1821 } 1822 1823 void MDFieldPrinter::printEmissionKind(StringRef Name, 1824 DICompileUnit::DebugEmissionKind EK) { 1825 Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK); 1826 } 1827 1828 void MDFieldPrinter::printNameTableKind(StringRef Name, 1829 DICompileUnit::DebugNameTableKind NTK) { 1830 if (NTK == DICompileUnit::DebugNameTableKind::Default) 1831 return; 1832 Out << FS << Name << ": " << DICompileUnit::nameTableKindString(NTK); 1833 } 1834 1835 template <class IntTy, class Stringifier> 1836 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value, 1837 Stringifier toString, bool ShouldSkipZero) { 1838 if (!Value) 1839 return; 1840 1841 Out << FS << Name << ": "; 1842 auto S = toString(Value); 1843 if (!S.empty()) 1844 Out << S; 1845 else 1846 Out << Value; 1847 } 1848 1849 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N, 1850 TypePrinting *TypePrinter, SlotTracker *Machine, 1851 const Module *Context) { 1852 Out << "!GenericDINode("; 1853 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1854 Printer.printTag(N); 1855 Printer.printString("header", N->getHeader()); 1856 if (N->getNumDwarfOperands()) { 1857 Out << Printer.FS << "operands: {"; 1858 FieldSeparator IFS; 1859 for (auto &I : N->dwarf_operands()) { 1860 Out << IFS; 1861 writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context); 1862 } 1863 Out << "}"; 1864 } 1865 Out << ")"; 1866 } 1867 1868 static void writeDILocation(raw_ostream &Out, const DILocation *DL, 1869 TypePrinting *TypePrinter, SlotTracker *Machine, 1870 const Module *Context) { 1871 Out << "!DILocation("; 1872 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1873 // Always output the line, since 0 is a relevant and important value for it. 1874 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false); 1875 Printer.printInt("column", DL->getColumn()); 1876 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false); 1877 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt()); 1878 Printer.printBool("isImplicitCode", DL->isImplicitCode(), 1879 /* Default */ false); 1880 Out << ")"; 1881 } 1882 1883 static void writeDISubrange(raw_ostream &Out, const DISubrange *N, 1884 TypePrinting *TypePrinter, SlotTracker *Machine, 1885 const Module *Context) { 1886 Out << "!DISubrange("; 1887 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1888 1889 auto *Count = N->getRawCountNode(); 1890 if (auto *CE = dyn_cast_or_null<ConstantAsMetadata>(Count)) { 1891 auto *CV = cast<ConstantInt>(CE->getValue()); 1892 Printer.printInt("count", CV->getSExtValue(), 1893 /* ShouldSkipZero */ false); 1894 } else 1895 Printer.printMetadata("count", Count, /*ShouldSkipNull */ true); 1896 1897 // A lowerBound of constant 0 should not be skipped, since it is different 1898 // from an unspecified lower bound (= nullptr). 1899 auto *LBound = N->getRawLowerBound(); 1900 if (auto *LE = dyn_cast_or_null<ConstantAsMetadata>(LBound)) { 1901 auto *LV = cast<ConstantInt>(LE->getValue()); 1902 Printer.printInt("lowerBound", LV->getSExtValue(), 1903 /* ShouldSkipZero */ false); 1904 } else 1905 Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true); 1906 1907 auto *UBound = N->getRawUpperBound(); 1908 if (auto *UE = dyn_cast_or_null<ConstantAsMetadata>(UBound)) { 1909 auto *UV = cast<ConstantInt>(UE->getValue()); 1910 Printer.printInt("upperBound", UV->getSExtValue(), 1911 /* ShouldSkipZero */ false); 1912 } else 1913 Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true); 1914 1915 auto *Stride = N->getRawStride(); 1916 if (auto *SE = dyn_cast_or_null<ConstantAsMetadata>(Stride)) { 1917 auto *SV = cast<ConstantInt>(SE->getValue()); 1918 Printer.printInt("stride", SV->getSExtValue(), /* ShouldSkipZero */ false); 1919 } else 1920 Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true); 1921 1922 Out << ")"; 1923 } 1924 1925 static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N, 1926 TypePrinting *TypePrinter, 1927 SlotTracker *Machine, 1928 const Module *Context) { 1929 Out << "!DIGenericSubrange("; 1930 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1931 1932 auto IsConstant = [&](Metadata *Bound) -> bool { 1933 if (auto *BE = dyn_cast_or_null<DIExpression>(Bound)) { 1934 return BE->isConstant() 1935 ? DIExpression::SignedOrUnsignedConstant::SignedConstant == 1936 *BE->isConstant() 1937 : false; 1938 } 1939 return false; 1940 }; 1941 1942 auto GetConstant = [&](Metadata *Bound) -> int64_t { 1943 assert(IsConstant(Bound) && "Expected constant"); 1944 auto *BE = dyn_cast_or_null<DIExpression>(Bound); 1945 return static_cast<int64_t>(BE->getElement(1)); 1946 }; 1947 1948 auto *Count = N->getRawCountNode(); 1949 if (IsConstant(Count)) 1950 Printer.printInt("count", GetConstant(Count), 1951 /* ShouldSkipZero */ false); 1952 else 1953 Printer.printMetadata("count", Count, /*ShouldSkipNull */ true); 1954 1955 auto *LBound = N->getRawLowerBound(); 1956 if (IsConstant(LBound)) 1957 Printer.printInt("lowerBound", GetConstant(LBound), 1958 /* ShouldSkipZero */ false); 1959 else 1960 Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true); 1961 1962 auto *UBound = N->getRawUpperBound(); 1963 if (IsConstant(UBound)) 1964 Printer.printInt("upperBound", GetConstant(UBound), 1965 /* ShouldSkipZero */ false); 1966 else 1967 Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true); 1968 1969 auto *Stride = N->getRawStride(); 1970 if (IsConstant(Stride)) 1971 Printer.printInt("stride", GetConstant(Stride), 1972 /* ShouldSkipZero */ false); 1973 else 1974 Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true); 1975 1976 Out << ")"; 1977 } 1978 1979 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N, 1980 TypePrinting *, SlotTracker *, const Module *) { 1981 Out << "!DIEnumerator("; 1982 MDFieldPrinter Printer(Out); 1983 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false); 1984 Printer.printAPInt("value", N->getValue(), N->isUnsigned(), 1985 /*ShouldSkipZero=*/false); 1986 if (N->isUnsigned()) 1987 Printer.printBool("isUnsigned", true); 1988 Out << ")"; 1989 } 1990 1991 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N, 1992 TypePrinting *, SlotTracker *, const Module *) { 1993 Out << "!DIBasicType("; 1994 MDFieldPrinter Printer(Out); 1995 if (N->getTag() != dwarf::DW_TAG_base_type) 1996 Printer.printTag(N); 1997 Printer.printString("name", N->getName()); 1998 Printer.printInt("size", N->getSizeInBits()); 1999 Printer.printInt("align", N->getAlignInBits()); 2000 Printer.printDwarfEnum("encoding", N->getEncoding(), 2001 dwarf::AttributeEncodingString); 2002 Printer.printDIFlags("flags", N->getFlags()); 2003 Out << ")"; 2004 } 2005 2006 static void writeDIStringType(raw_ostream &Out, const DIStringType *N, 2007 TypePrinting *TypePrinter, SlotTracker *Machine, 2008 const Module *Context) { 2009 Out << "!DIStringType("; 2010 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2011 if (N->getTag() != dwarf::DW_TAG_string_type) 2012 Printer.printTag(N); 2013 Printer.printString("name", N->getName()); 2014 Printer.printMetadata("stringLength", N->getRawStringLength()); 2015 Printer.printMetadata("stringLengthExpression", N->getRawStringLengthExp()); 2016 Printer.printInt("size", N->getSizeInBits()); 2017 Printer.printInt("align", N->getAlignInBits()); 2018 Printer.printDwarfEnum("encoding", N->getEncoding(), 2019 dwarf::AttributeEncodingString); 2020 Out << ")"; 2021 } 2022 2023 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N, 2024 TypePrinting *TypePrinter, SlotTracker *Machine, 2025 const Module *Context) { 2026 Out << "!DIDerivedType("; 2027 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2028 Printer.printTag(N); 2029 Printer.printString("name", N->getName()); 2030 Printer.printMetadata("scope", N->getRawScope()); 2031 Printer.printMetadata("file", N->getRawFile()); 2032 Printer.printInt("line", N->getLine()); 2033 Printer.printMetadata("baseType", N->getRawBaseType(), 2034 /* ShouldSkipNull */ false); 2035 Printer.printInt("size", N->getSizeInBits()); 2036 Printer.printInt("align", N->getAlignInBits()); 2037 Printer.printInt("offset", N->getOffsetInBits()); 2038 Printer.printDIFlags("flags", N->getFlags()); 2039 Printer.printMetadata("extraData", N->getRawExtraData()); 2040 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace()) 2041 Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace, 2042 /* ShouldSkipZero */ false); 2043 Out << ")"; 2044 } 2045 2046 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N, 2047 TypePrinting *TypePrinter, 2048 SlotTracker *Machine, const Module *Context) { 2049 Out << "!DICompositeType("; 2050 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2051 Printer.printTag(N); 2052 Printer.printString("name", N->getName()); 2053 Printer.printMetadata("scope", N->getRawScope()); 2054 Printer.printMetadata("file", N->getRawFile()); 2055 Printer.printInt("line", N->getLine()); 2056 Printer.printMetadata("baseType", N->getRawBaseType()); 2057 Printer.printInt("size", N->getSizeInBits()); 2058 Printer.printInt("align", N->getAlignInBits()); 2059 Printer.printInt("offset", N->getOffsetInBits()); 2060 Printer.printDIFlags("flags", N->getFlags()); 2061 Printer.printMetadata("elements", N->getRawElements()); 2062 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(), 2063 dwarf::LanguageString); 2064 Printer.printMetadata("vtableHolder", N->getRawVTableHolder()); 2065 Printer.printMetadata("templateParams", N->getRawTemplateParams()); 2066 Printer.printString("identifier", N->getIdentifier()); 2067 Printer.printMetadata("discriminator", N->getRawDiscriminator()); 2068 Printer.printMetadata("dataLocation", N->getRawDataLocation()); 2069 Printer.printMetadata("associated", N->getRawAssociated()); 2070 Printer.printMetadata("allocated", N->getRawAllocated()); 2071 if (auto *RankConst = N->getRankConst()) 2072 Printer.printInt("rank", RankConst->getSExtValue(), 2073 /* ShouldSkipZero */ false); 2074 else 2075 Printer.printMetadata("rank", N->getRawRank(), /*ShouldSkipNull */ true); 2076 Out << ")"; 2077 } 2078 2079 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N, 2080 TypePrinting *TypePrinter, 2081 SlotTracker *Machine, const Module *Context) { 2082 Out << "!DISubroutineType("; 2083 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2084 Printer.printDIFlags("flags", N->getFlags()); 2085 Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString); 2086 Printer.printMetadata("types", N->getRawTypeArray(), 2087 /* ShouldSkipNull */ false); 2088 Out << ")"; 2089 } 2090 2091 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *, 2092 SlotTracker *, const Module *) { 2093 Out << "!DIFile("; 2094 MDFieldPrinter Printer(Out); 2095 Printer.printString("filename", N->getFilename(), 2096 /* ShouldSkipEmpty */ false); 2097 Printer.printString("directory", N->getDirectory(), 2098 /* ShouldSkipEmpty */ false); 2099 // Print all values for checksum together, or not at all. 2100 if (N->getChecksum()) 2101 Printer.printChecksum(*N->getChecksum()); 2102 Printer.printString("source", N->getSource().getValueOr(StringRef()), 2103 /* ShouldSkipEmpty */ true); 2104 Out << ")"; 2105 } 2106 2107 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N, 2108 TypePrinting *TypePrinter, SlotTracker *Machine, 2109 const Module *Context) { 2110 Out << "!DICompileUnit("; 2111 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2112 Printer.printDwarfEnum("language", N->getSourceLanguage(), 2113 dwarf::LanguageString, /* ShouldSkipZero */ false); 2114 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false); 2115 Printer.printString("producer", N->getProducer()); 2116 Printer.printBool("isOptimized", N->isOptimized()); 2117 Printer.printString("flags", N->getFlags()); 2118 Printer.printInt("runtimeVersion", N->getRuntimeVersion(), 2119 /* ShouldSkipZero */ false); 2120 Printer.printString("splitDebugFilename", N->getSplitDebugFilename()); 2121 Printer.printEmissionKind("emissionKind", N->getEmissionKind()); 2122 Printer.printMetadata("enums", N->getRawEnumTypes()); 2123 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes()); 2124 Printer.printMetadata("globals", N->getRawGlobalVariables()); 2125 Printer.printMetadata("imports", N->getRawImportedEntities()); 2126 Printer.printMetadata("macros", N->getRawMacros()); 2127 Printer.printInt("dwoId", N->getDWOId()); 2128 Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true); 2129 Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(), 2130 false); 2131 Printer.printNameTableKind("nameTableKind", N->getNameTableKind()); 2132 Printer.printBool("rangesBaseAddress", N->getRangesBaseAddress(), false); 2133 Printer.printString("sysroot", N->getSysRoot()); 2134 Printer.printString("sdk", N->getSDK()); 2135 Out << ")"; 2136 } 2137 2138 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N, 2139 TypePrinting *TypePrinter, SlotTracker *Machine, 2140 const Module *Context) { 2141 Out << "!DISubprogram("; 2142 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2143 Printer.printString("name", N->getName()); 2144 Printer.printString("linkageName", N->getLinkageName()); 2145 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2146 Printer.printMetadata("file", N->getRawFile()); 2147 Printer.printInt("line", N->getLine()); 2148 Printer.printMetadata("type", N->getRawType()); 2149 Printer.printInt("scopeLine", N->getScopeLine()); 2150 Printer.printMetadata("containingType", N->getRawContainingType()); 2151 if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none || 2152 N->getVirtualIndex() != 0) 2153 Printer.printInt("virtualIndex", N->getVirtualIndex(), false); 2154 Printer.printInt("thisAdjustment", N->getThisAdjustment()); 2155 Printer.printDIFlags("flags", N->getFlags()); 2156 Printer.printDISPFlags("spFlags", N->getSPFlags()); 2157 Printer.printMetadata("unit", N->getRawUnit()); 2158 Printer.printMetadata("templateParams", N->getRawTemplateParams()); 2159 Printer.printMetadata("declaration", N->getRawDeclaration()); 2160 Printer.printMetadata("retainedNodes", N->getRawRetainedNodes()); 2161 Printer.printMetadata("thrownTypes", N->getRawThrownTypes()); 2162 Out << ")"; 2163 } 2164 2165 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N, 2166 TypePrinting *TypePrinter, SlotTracker *Machine, 2167 const Module *Context) { 2168 Out << "!DILexicalBlock("; 2169 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2170 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2171 Printer.printMetadata("file", N->getRawFile()); 2172 Printer.printInt("line", N->getLine()); 2173 Printer.printInt("column", N->getColumn()); 2174 Out << ")"; 2175 } 2176 2177 static void writeDILexicalBlockFile(raw_ostream &Out, 2178 const DILexicalBlockFile *N, 2179 TypePrinting *TypePrinter, 2180 SlotTracker *Machine, 2181 const Module *Context) { 2182 Out << "!DILexicalBlockFile("; 2183 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2184 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2185 Printer.printMetadata("file", N->getRawFile()); 2186 Printer.printInt("discriminator", N->getDiscriminator(), 2187 /* ShouldSkipZero */ false); 2188 Out << ")"; 2189 } 2190 2191 static void writeDINamespace(raw_ostream &Out, const DINamespace *N, 2192 TypePrinting *TypePrinter, SlotTracker *Machine, 2193 const Module *Context) { 2194 Out << "!DINamespace("; 2195 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2196 Printer.printString("name", N->getName()); 2197 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2198 Printer.printBool("exportSymbols", N->getExportSymbols(), false); 2199 Out << ")"; 2200 } 2201 2202 static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N, 2203 TypePrinting *TypePrinter, SlotTracker *Machine, 2204 const Module *Context) { 2205 Out << "!DICommonBlock("; 2206 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2207 Printer.printMetadata("scope", N->getRawScope(), false); 2208 Printer.printMetadata("declaration", N->getRawDecl(), false); 2209 Printer.printString("name", N->getName()); 2210 Printer.printMetadata("file", N->getRawFile()); 2211 Printer.printInt("line", N->getLineNo()); 2212 Out << ")"; 2213 } 2214 2215 static void writeDIMacro(raw_ostream &Out, const DIMacro *N, 2216 TypePrinting *TypePrinter, SlotTracker *Machine, 2217 const Module *Context) { 2218 Out << "!DIMacro("; 2219 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2220 Printer.printMacinfoType(N); 2221 Printer.printInt("line", N->getLine()); 2222 Printer.printString("name", N->getName()); 2223 Printer.printString("value", N->getValue()); 2224 Out << ")"; 2225 } 2226 2227 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N, 2228 TypePrinting *TypePrinter, SlotTracker *Machine, 2229 const Module *Context) { 2230 Out << "!DIMacroFile("; 2231 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2232 Printer.printInt("line", N->getLine()); 2233 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false); 2234 Printer.printMetadata("nodes", N->getRawElements()); 2235 Out << ")"; 2236 } 2237 2238 static void writeDIModule(raw_ostream &Out, const DIModule *N, 2239 TypePrinting *TypePrinter, SlotTracker *Machine, 2240 const Module *Context) { 2241 Out << "!DIModule("; 2242 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2243 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2244 Printer.printString("name", N->getName()); 2245 Printer.printString("configMacros", N->getConfigurationMacros()); 2246 Printer.printString("includePath", N->getIncludePath()); 2247 Printer.printString("apinotes", N->getAPINotesFile()); 2248 Printer.printMetadata("file", N->getRawFile()); 2249 Printer.printInt("line", N->getLineNo()); 2250 Printer.printBool("isDecl", N->getIsDecl(), /* Default */ false); 2251 Out << ")"; 2252 } 2253 2254 2255 static void writeDITemplateTypeParameter(raw_ostream &Out, 2256 const DITemplateTypeParameter *N, 2257 TypePrinting *TypePrinter, 2258 SlotTracker *Machine, 2259 const Module *Context) { 2260 Out << "!DITemplateTypeParameter("; 2261 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2262 Printer.printString("name", N->getName()); 2263 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false); 2264 Printer.printBool("defaulted", N->isDefault(), /* Default= */ false); 2265 Out << ")"; 2266 } 2267 2268 static void writeDITemplateValueParameter(raw_ostream &Out, 2269 const DITemplateValueParameter *N, 2270 TypePrinting *TypePrinter, 2271 SlotTracker *Machine, 2272 const Module *Context) { 2273 Out << "!DITemplateValueParameter("; 2274 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2275 if (N->getTag() != dwarf::DW_TAG_template_value_parameter) 2276 Printer.printTag(N); 2277 Printer.printString("name", N->getName()); 2278 Printer.printMetadata("type", N->getRawType()); 2279 Printer.printBool("defaulted", N->isDefault(), /* Default= */ false); 2280 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false); 2281 Out << ")"; 2282 } 2283 2284 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N, 2285 TypePrinting *TypePrinter, 2286 SlotTracker *Machine, const Module *Context) { 2287 Out << "!DIGlobalVariable("; 2288 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2289 Printer.printString("name", N->getName()); 2290 Printer.printString("linkageName", N->getLinkageName()); 2291 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2292 Printer.printMetadata("file", N->getRawFile()); 2293 Printer.printInt("line", N->getLine()); 2294 Printer.printMetadata("type", N->getRawType()); 2295 Printer.printBool("isLocal", N->isLocalToUnit()); 2296 Printer.printBool("isDefinition", N->isDefinition()); 2297 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration()); 2298 Printer.printMetadata("templateParams", N->getRawTemplateParams()); 2299 Printer.printInt("align", N->getAlignInBits()); 2300 Out << ")"; 2301 } 2302 2303 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N, 2304 TypePrinting *TypePrinter, 2305 SlotTracker *Machine, const Module *Context) { 2306 Out << "!DILocalVariable("; 2307 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2308 Printer.printString("name", N->getName()); 2309 Printer.printInt("arg", N->getArg()); 2310 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2311 Printer.printMetadata("file", N->getRawFile()); 2312 Printer.printInt("line", N->getLine()); 2313 Printer.printMetadata("type", N->getRawType()); 2314 Printer.printDIFlags("flags", N->getFlags()); 2315 Printer.printInt("align", N->getAlignInBits()); 2316 Out << ")"; 2317 } 2318 2319 static void writeDILabel(raw_ostream &Out, const DILabel *N, 2320 TypePrinting *TypePrinter, 2321 SlotTracker *Machine, const Module *Context) { 2322 Out << "!DILabel("; 2323 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2324 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2325 Printer.printString("name", N->getName()); 2326 Printer.printMetadata("file", N->getRawFile()); 2327 Printer.printInt("line", N->getLine()); 2328 Out << ")"; 2329 } 2330 2331 static void writeDIExpression(raw_ostream &Out, const DIExpression *N, 2332 TypePrinting *TypePrinter, SlotTracker *Machine, 2333 const Module *Context) { 2334 Out << "!DIExpression("; 2335 FieldSeparator FS; 2336 if (N->isValid()) { 2337 for (const DIExpression::ExprOperand &Op : N->expr_ops()) { 2338 auto OpStr = dwarf::OperationEncodingString(Op.getOp()); 2339 assert(!OpStr.empty() && "Expected valid opcode"); 2340 2341 Out << FS << OpStr; 2342 if (Op.getOp() == dwarf::DW_OP_LLVM_convert) { 2343 Out << FS << Op.getArg(0); 2344 Out << FS << dwarf::AttributeEncodingString(Op.getArg(1)); 2345 } else { 2346 for (unsigned A = 0, AE = Op.getNumArgs(); A != AE; ++A) 2347 Out << FS << Op.getArg(A); 2348 } 2349 } 2350 } else { 2351 for (const auto &I : N->getElements()) 2352 Out << FS << I; 2353 } 2354 Out << ")"; 2355 } 2356 2357 static void writeDIArgList(raw_ostream &Out, const DIArgList *N, 2358 TypePrinting *TypePrinter, SlotTracker *Machine, 2359 const Module *Context, bool FromValue = false) { 2360 assert(FromValue && 2361 "Unexpected DIArgList metadata outside of value argument"); 2362 Out << "!DIArgList("; 2363 FieldSeparator FS; 2364 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2365 for (Metadata *Arg : N->getArgs()) { 2366 Out << FS; 2367 WriteAsOperandInternal(Out, Arg, TypePrinter, Machine, Context, true); 2368 } 2369 Out << ")"; 2370 } 2371 2372 static void writeDIGlobalVariableExpression(raw_ostream &Out, 2373 const DIGlobalVariableExpression *N, 2374 TypePrinting *TypePrinter, 2375 SlotTracker *Machine, 2376 const Module *Context) { 2377 Out << "!DIGlobalVariableExpression("; 2378 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2379 Printer.printMetadata("var", N->getVariable()); 2380 Printer.printMetadata("expr", N->getExpression()); 2381 Out << ")"; 2382 } 2383 2384 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N, 2385 TypePrinting *TypePrinter, SlotTracker *Machine, 2386 const Module *Context) { 2387 Out << "!DIObjCProperty("; 2388 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2389 Printer.printString("name", N->getName()); 2390 Printer.printMetadata("file", N->getRawFile()); 2391 Printer.printInt("line", N->getLine()); 2392 Printer.printString("setter", N->getSetterName()); 2393 Printer.printString("getter", N->getGetterName()); 2394 Printer.printInt("attributes", N->getAttributes()); 2395 Printer.printMetadata("type", N->getRawType()); 2396 Out << ")"; 2397 } 2398 2399 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N, 2400 TypePrinting *TypePrinter, 2401 SlotTracker *Machine, const Module *Context) { 2402 Out << "!DIImportedEntity("; 2403 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2404 Printer.printTag(N); 2405 Printer.printString("name", N->getName()); 2406 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2407 Printer.printMetadata("entity", N->getRawEntity()); 2408 Printer.printMetadata("file", N->getRawFile()); 2409 Printer.printInt("line", N->getLine()); 2410 Out << ")"; 2411 } 2412 2413 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node, 2414 TypePrinting *TypePrinter, 2415 SlotTracker *Machine, 2416 const Module *Context) { 2417 if (Node->isDistinct()) 2418 Out << "distinct "; 2419 else if (Node->isTemporary()) 2420 Out << "<temporary!> "; // Handle broken code. 2421 2422 switch (Node->getMetadataID()) { 2423 default: 2424 llvm_unreachable("Expected uniquable MDNode"); 2425 #define HANDLE_MDNODE_LEAF(CLASS) \ 2426 case Metadata::CLASS##Kind: \ 2427 write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \ 2428 break; 2429 #include "llvm/IR/Metadata.def" 2430 } 2431 } 2432 2433 // Full implementation of printing a Value as an operand with support for 2434 // TypePrinting, etc. 2435 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, 2436 TypePrinting *TypePrinter, 2437 SlotTracker *Machine, 2438 const Module *Context) { 2439 if (V->hasName()) { 2440 PrintLLVMName(Out, V); 2441 return; 2442 } 2443 2444 const Constant *CV = dyn_cast<Constant>(V); 2445 if (CV && !isa<GlobalValue>(CV)) { 2446 assert(TypePrinter && "Constants require TypePrinting!"); 2447 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context); 2448 return; 2449 } 2450 2451 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 2452 Out << "asm "; 2453 if (IA->hasSideEffects()) 2454 Out << "sideeffect "; 2455 if (IA->isAlignStack()) 2456 Out << "alignstack "; 2457 // We don't emit the AD_ATT dialect as it's the assumed default. 2458 if (IA->getDialect() == InlineAsm::AD_Intel) 2459 Out << "inteldialect "; 2460 if (IA->canThrow()) 2461 Out << "unwind "; 2462 Out << '"'; 2463 printEscapedString(IA->getAsmString(), Out); 2464 Out << "\", \""; 2465 printEscapedString(IA->getConstraintString(), Out); 2466 Out << '"'; 2467 return; 2468 } 2469 2470 if (auto *MD = dyn_cast<MetadataAsValue>(V)) { 2471 WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine, 2472 Context, /* FromValue */ true); 2473 return; 2474 } 2475 2476 char Prefix = '%'; 2477 int Slot; 2478 // If we have a SlotTracker, use it. 2479 if (Machine) { 2480 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 2481 Slot = Machine->getGlobalSlot(GV); 2482 Prefix = '@'; 2483 } else { 2484 Slot = Machine->getLocalSlot(V); 2485 2486 // If the local value didn't succeed, then we may be referring to a value 2487 // from a different function. Translate it, as this can happen when using 2488 // address of blocks. 2489 if (Slot == -1) 2490 if ((Machine = createSlotTracker(V))) { 2491 Slot = Machine->getLocalSlot(V); 2492 delete Machine; 2493 } 2494 } 2495 } else if ((Machine = createSlotTracker(V))) { 2496 // Otherwise, create one to get the # and then destroy it. 2497 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 2498 Slot = Machine->getGlobalSlot(GV); 2499 Prefix = '@'; 2500 } else { 2501 Slot = Machine->getLocalSlot(V); 2502 } 2503 delete Machine; 2504 Machine = nullptr; 2505 } else { 2506 Slot = -1; 2507 } 2508 2509 if (Slot != -1) 2510 Out << Prefix << Slot; 2511 else 2512 Out << "<badref>"; 2513 } 2514 2515 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD, 2516 TypePrinting *TypePrinter, 2517 SlotTracker *Machine, const Module *Context, 2518 bool FromValue) { 2519 // Write DIExpressions and DIArgLists inline when used as a value. Improves 2520 // readability of debug info intrinsics. 2521 if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) { 2522 writeDIExpression(Out, Expr, TypePrinter, Machine, Context); 2523 return; 2524 } 2525 if (const DIArgList *ArgList = dyn_cast<DIArgList>(MD)) { 2526 writeDIArgList(Out, ArgList, TypePrinter, Machine, Context, FromValue); 2527 return; 2528 } 2529 2530 if (const MDNode *N = dyn_cast<MDNode>(MD)) { 2531 std::unique_ptr<SlotTracker> MachineStorage; 2532 if (!Machine) { 2533 MachineStorage = std::make_unique<SlotTracker>(Context); 2534 Machine = MachineStorage.get(); 2535 } 2536 int Slot = Machine->getMetadataSlot(N); 2537 if (Slot == -1) { 2538 if (const DILocation *Loc = dyn_cast<DILocation>(N)) { 2539 writeDILocation(Out, Loc, TypePrinter, Machine, Context); 2540 return; 2541 } 2542 // Give the pointer value instead of "badref", since this comes up all 2543 // the time when debugging. 2544 Out << "<" << N << ">"; 2545 } else 2546 Out << '!' << Slot; 2547 return; 2548 } 2549 2550 if (const MDString *MDS = dyn_cast<MDString>(MD)) { 2551 Out << "!\""; 2552 printEscapedString(MDS->getString(), Out); 2553 Out << '"'; 2554 return; 2555 } 2556 2557 auto *V = cast<ValueAsMetadata>(MD); 2558 assert(TypePrinter && "TypePrinter required for metadata values"); 2559 assert((FromValue || !isa<LocalAsMetadata>(V)) && 2560 "Unexpected function-local metadata outside of value argument"); 2561 2562 TypePrinter->print(V->getValue()->getType(), Out); 2563 Out << ' '; 2564 WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context); 2565 } 2566 2567 namespace { 2568 2569 class AssemblyWriter { 2570 formatted_raw_ostream &Out; 2571 const Module *TheModule = nullptr; 2572 const ModuleSummaryIndex *TheIndex = nullptr; 2573 std::unique_ptr<SlotTracker> SlotTrackerStorage; 2574 SlotTracker &Machine; 2575 TypePrinting TypePrinter; 2576 AssemblyAnnotationWriter *AnnotationWriter = nullptr; 2577 SetVector<const Comdat *> Comdats; 2578 bool IsForDebug; 2579 bool ShouldPreserveUseListOrder; 2580 UseListOrderMap UseListOrders; 2581 SmallVector<StringRef, 8> MDNames; 2582 /// Synchronization scope names registered with LLVMContext. 2583 SmallVector<StringRef, 8> SSNs; 2584 DenseMap<const GlobalValueSummary *, GlobalValue::GUID> SummaryToGUIDMap; 2585 2586 public: 2587 /// Construct an AssemblyWriter with an external SlotTracker 2588 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M, 2589 AssemblyAnnotationWriter *AAW, bool IsForDebug, 2590 bool ShouldPreserveUseListOrder = false); 2591 2592 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, 2593 const ModuleSummaryIndex *Index, bool IsForDebug); 2594 2595 void printMDNodeBody(const MDNode *MD); 2596 void printNamedMDNode(const NamedMDNode *NMD); 2597 2598 void printModule(const Module *M); 2599 2600 void writeOperand(const Value *Op, bool PrintType); 2601 void writeParamOperand(const Value *Operand, AttributeSet Attrs); 2602 void writeOperandBundles(const CallBase *Call); 2603 void writeSyncScope(const LLVMContext &Context, 2604 SyncScope::ID SSID); 2605 void writeAtomic(const LLVMContext &Context, 2606 AtomicOrdering Ordering, 2607 SyncScope::ID SSID); 2608 void writeAtomicCmpXchg(const LLVMContext &Context, 2609 AtomicOrdering SuccessOrdering, 2610 AtomicOrdering FailureOrdering, 2611 SyncScope::ID SSID); 2612 2613 void writeAllMDNodes(); 2614 void writeMDNode(unsigned Slot, const MDNode *Node); 2615 void writeAttribute(const Attribute &Attr, bool InAttrGroup = false); 2616 void writeAttributeSet(const AttributeSet &AttrSet, bool InAttrGroup = false); 2617 void writeAllAttributeGroups(); 2618 2619 void printTypeIdentities(); 2620 void printGlobal(const GlobalVariable *GV); 2621 void printIndirectSymbol(const GlobalIndirectSymbol *GIS); 2622 void printComdat(const Comdat *C); 2623 void printFunction(const Function *F); 2624 void printArgument(const Argument *FA, AttributeSet Attrs); 2625 void printBasicBlock(const BasicBlock *BB); 2626 void printInstructionLine(const Instruction &I); 2627 void printInstruction(const Instruction &I); 2628 2629 void printUseListOrder(const Value *V, const std::vector<unsigned> &Shuffle); 2630 void printUseLists(const Function *F); 2631 2632 void printModuleSummaryIndex(); 2633 void printSummaryInfo(unsigned Slot, const ValueInfo &VI); 2634 void printSummary(const GlobalValueSummary &Summary); 2635 void printAliasSummary(const AliasSummary *AS); 2636 void printGlobalVarSummary(const GlobalVarSummary *GS); 2637 void printFunctionSummary(const FunctionSummary *FS); 2638 void printTypeIdSummary(const TypeIdSummary &TIS); 2639 void printTypeIdCompatibleVtableSummary(const TypeIdCompatibleVtableInfo &TI); 2640 void printTypeTestResolution(const TypeTestResolution &TTRes); 2641 void printArgs(const std::vector<uint64_t> &Args); 2642 void printWPDRes(const WholeProgramDevirtResolution &WPDRes); 2643 void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo); 2644 void printVFuncId(const FunctionSummary::VFuncId VFId); 2645 void 2646 printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> &VCallList, 2647 const char *Tag); 2648 void 2649 printConstVCalls(const std::vector<FunctionSummary::ConstVCall> &VCallList, 2650 const char *Tag); 2651 2652 private: 2653 /// Print out metadata attachments. 2654 void printMetadataAttachments( 2655 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs, 2656 StringRef Separator); 2657 2658 // printInfoComment - Print a little comment after the instruction indicating 2659 // which slot it occupies. 2660 void printInfoComment(const Value &V); 2661 2662 // printGCRelocateComment - print comment after call to the gc.relocate 2663 // intrinsic indicating base and derived pointer names. 2664 void printGCRelocateComment(const GCRelocateInst &Relocate); 2665 }; 2666 2667 } // end anonymous namespace 2668 2669 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, 2670 const Module *M, AssemblyAnnotationWriter *AAW, 2671 bool IsForDebug, bool ShouldPreserveUseListOrder) 2672 : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW), 2673 IsForDebug(IsForDebug), 2674 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) { 2675 if (!TheModule) 2676 return; 2677 for (const GlobalObject &GO : TheModule->global_objects()) 2678 if (const Comdat *C = GO.getComdat()) 2679 Comdats.insert(C); 2680 } 2681 2682 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, 2683 const ModuleSummaryIndex *Index, bool IsForDebug) 2684 : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr), 2685 IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {} 2686 2687 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) { 2688 if (!Operand) { 2689 Out << "<null operand!>"; 2690 return; 2691 } 2692 if (PrintType) { 2693 TypePrinter.print(Operand->getType(), Out); 2694 Out << ' '; 2695 } 2696 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule); 2697 } 2698 2699 void AssemblyWriter::writeSyncScope(const LLVMContext &Context, 2700 SyncScope::ID SSID) { 2701 switch (SSID) { 2702 case SyncScope::System: { 2703 break; 2704 } 2705 default: { 2706 if (SSNs.empty()) 2707 Context.getSyncScopeNames(SSNs); 2708 2709 Out << " syncscope(\""; 2710 printEscapedString(SSNs[SSID], Out); 2711 Out << "\")"; 2712 break; 2713 } 2714 } 2715 } 2716 2717 void AssemblyWriter::writeAtomic(const LLVMContext &Context, 2718 AtomicOrdering Ordering, 2719 SyncScope::ID SSID) { 2720 if (Ordering == AtomicOrdering::NotAtomic) 2721 return; 2722 2723 writeSyncScope(Context, SSID); 2724 Out << " " << toIRString(Ordering); 2725 } 2726 2727 void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context, 2728 AtomicOrdering SuccessOrdering, 2729 AtomicOrdering FailureOrdering, 2730 SyncScope::ID SSID) { 2731 assert(SuccessOrdering != AtomicOrdering::NotAtomic && 2732 FailureOrdering != AtomicOrdering::NotAtomic); 2733 2734 writeSyncScope(Context, SSID); 2735 Out << " " << toIRString(SuccessOrdering); 2736 Out << " " << toIRString(FailureOrdering); 2737 } 2738 2739 void AssemblyWriter::writeParamOperand(const Value *Operand, 2740 AttributeSet Attrs) { 2741 if (!Operand) { 2742 Out << "<null operand!>"; 2743 return; 2744 } 2745 2746 // Print the type 2747 TypePrinter.print(Operand->getType(), Out); 2748 // Print parameter attributes list 2749 if (Attrs.hasAttributes()) { 2750 Out << ' '; 2751 writeAttributeSet(Attrs); 2752 } 2753 Out << ' '; 2754 // Print the operand 2755 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule); 2756 } 2757 2758 void AssemblyWriter::writeOperandBundles(const CallBase *Call) { 2759 if (!Call->hasOperandBundles()) 2760 return; 2761 2762 Out << " [ "; 2763 2764 bool FirstBundle = true; 2765 for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i) { 2766 OperandBundleUse BU = Call->getOperandBundleAt(i); 2767 2768 if (!FirstBundle) 2769 Out << ", "; 2770 FirstBundle = false; 2771 2772 Out << '"'; 2773 printEscapedString(BU.getTagName(), Out); 2774 Out << '"'; 2775 2776 Out << '('; 2777 2778 bool FirstInput = true; 2779 for (const auto &Input : BU.Inputs) { 2780 if (!FirstInput) 2781 Out << ", "; 2782 FirstInput = false; 2783 2784 TypePrinter.print(Input->getType(), Out); 2785 Out << " "; 2786 WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule); 2787 } 2788 2789 Out << ')'; 2790 } 2791 2792 Out << " ]"; 2793 } 2794 2795 void AssemblyWriter::printModule(const Module *M) { 2796 Machine.initializeIfNeeded(); 2797 2798 if (ShouldPreserveUseListOrder) 2799 UseListOrders = predictUseListOrder(M); 2800 2801 if (!M->getModuleIdentifier().empty() && 2802 // Don't print the ID if it will start a new line (which would 2803 // require a comment char before it). 2804 M->getModuleIdentifier().find('\n') == std::string::npos) 2805 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n"; 2806 2807 if (!M->getSourceFileName().empty()) { 2808 Out << "source_filename = \""; 2809 printEscapedString(M->getSourceFileName(), Out); 2810 Out << "\"\n"; 2811 } 2812 2813 const std::string &DL = M->getDataLayoutStr(); 2814 if (!DL.empty()) 2815 Out << "target datalayout = \"" << DL << "\"\n"; 2816 if (!M->getTargetTriple().empty()) 2817 Out << "target triple = \"" << M->getTargetTriple() << "\"\n"; 2818 2819 if (!M->getModuleInlineAsm().empty()) { 2820 Out << '\n'; 2821 2822 // Split the string into lines, to make it easier to read the .ll file. 2823 StringRef Asm = M->getModuleInlineAsm(); 2824 do { 2825 StringRef Front; 2826 std::tie(Front, Asm) = Asm.split('\n'); 2827 2828 // We found a newline, print the portion of the asm string from the 2829 // last newline up to this newline. 2830 Out << "module asm \""; 2831 printEscapedString(Front, Out); 2832 Out << "\"\n"; 2833 } while (!Asm.empty()); 2834 } 2835 2836 printTypeIdentities(); 2837 2838 // Output all comdats. 2839 if (!Comdats.empty()) 2840 Out << '\n'; 2841 for (const Comdat *C : Comdats) { 2842 printComdat(C); 2843 if (C != Comdats.back()) 2844 Out << '\n'; 2845 } 2846 2847 // Output all globals. 2848 if (!M->global_empty()) Out << '\n'; 2849 for (const GlobalVariable &GV : M->globals()) { 2850 printGlobal(&GV); Out << '\n'; 2851 } 2852 2853 // Output all aliases. 2854 if (!M->alias_empty()) Out << "\n"; 2855 for (const GlobalAlias &GA : M->aliases()) 2856 printIndirectSymbol(&GA); 2857 2858 // Output all ifuncs. 2859 if (!M->ifunc_empty()) Out << "\n"; 2860 for (const GlobalIFunc &GI : M->ifuncs()) 2861 printIndirectSymbol(&GI); 2862 2863 // Output all of the functions. 2864 for (const Function &F : *M) { 2865 Out << '\n'; 2866 printFunction(&F); 2867 } 2868 2869 // Output global use-lists. 2870 printUseLists(nullptr); 2871 2872 // Output all attribute groups. 2873 if (!Machine.as_empty()) { 2874 Out << '\n'; 2875 writeAllAttributeGroups(); 2876 } 2877 2878 // Output named metadata. 2879 if (!M->named_metadata_empty()) Out << '\n'; 2880 2881 for (const NamedMDNode &Node : M->named_metadata()) 2882 printNamedMDNode(&Node); 2883 2884 // Output metadata. 2885 if (!Machine.mdn_empty()) { 2886 Out << '\n'; 2887 writeAllMDNodes(); 2888 } 2889 } 2890 2891 void AssemblyWriter::printModuleSummaryIndex() { 2892 assert(TheIndex); 2893 int NumSlots = Machine.initializeIndexIfNeeded(); 2894 2895 Out << "\n"; 2896 2897 // Print module path entries. To print in order, add paths to a vector 2898 // indexed by module slot. 2899 std::vector<std::pair<std::string, ModuleHash>> moduleVec; 2900 std::string RegularLTOModuleName = 2901 ModuleSummaryIndex::getRegularLTOModuleName(); 2902 moduleVec.resize(TheIndex->modulePaths().size()); 2903 for (auto &ModPath : TheIndex->modulePaths()) 2904 moduleVec[Machine.getModulePathSlot(ModPath.first())] = std::make_pair( 2905 // A module id of -1 is a special entry for a regular LTO module created 2906 // during the thin link. 2907 ModPath.second.first == -1u ? RegularLTOModuleName 2908 : (std::string)std::string(ModPath.first()), 2909 ModPath.second.second); 2910 2911 unsigned i = 0; 2912 for (auto &ModPair : moduleVec) { 2913 Out << "^" << i++ << " = module: ("; 2914 Out << "path: \""; 2915 printEscapedString(ModPair.first, Out); 2916 Out << "\", hash: ("; 2917 FieldSeparator FS; 2918 for (auto Hash : ModPair.second) 2919 Out << FS << Hash; 2920 Out << "))\n"; 2921 } 2922 2923 // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer 2924 // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID). 2925 for (auto &GlobalList : *TheIndex) { 2926 auto GUID = GlobalList.first; 2927 for (auto &Summary : GlobalList.second.SummaryList) 2928 SummaryToGUIDMap[Summary.get()] = GUID; 2929 } 2930 2931 // Print the global value summary entries. 2932 for (auto &GlobalList : *TheIndex) { 2933 auto GUID = GlobalList.first; 2934 auto VI = TheIndex->getValueInfo(GlobalList); 2935 printSummaryInfo(Machine.getGUIDSlot(GUID), VI); 2936 } 2937 2938 // Print the TypeIdMap entries. 2939 for (const auto &TID : TheIndex->typeIds()) { 2940 Out << "^" << Machine.getTypeIdSlot(TID.second.first) 2941 << " = typeid: (name: \"" << TID.second.first << "\""; 2942 printTypeIdSummary(TID.second.second); 2943 Out << ") ; guid = " << TID.first << "\n"; 2944 } 2945 2946 // Print the TypeIdCompatibleVtableMap entries. 2947 for (auto &TId : TheIndex->typeIdCompatibleVtableMap()) { 2948 auto GUID = GlobalValue::getGUID(TId.first); 2949 Out << "^" << Machine.getGUIDSlot(GUID) 2950 << " = typeidCompatibleVTable: (name: \"" << TId.first << "\""; 2951 printTypeIdCompatibleVtableSummary(TId.second); 2952 Out << ") ; guid = " << GUID << "\n"; 2953 } 2954 2955 // Don't emit flags when it's not really needed (value is zero by default). 2956 if (TheIndex->getFlags()) { 2957 Out << "^" << NumSlots << " = flags: " << TheIndex->getFlags() << "\n"; 2958 ++NumSlots; 2959 } 2960 2961 Out << "^" << NumSlots << " = blockcount: " << TheIndex->getBlockCount() 2962 << "\n"; 2963 } 2964 2965 static const char * 2966 getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) { 2967 switch (K) { 2968 case WholeProgramDevirtResolution::Indir: 2969 return "indir"; 2970 case WholeProgramDevirtResolution::SingleImpl: 2971 return "singleImpl"; 2972 case WholeProgramDevirtResolution::BranchFunnel: 2973 return "branchFunnel"; 2974 } 2975 llvm_unreachable("invalid WholeProgramDevirtResolution kind"); 2976 } 2977 2978 static const char *getWholeProgDevirtResByArgKindName( 2979 WholeProgramDevirtResolution::ByArg::Kind K) { 2980 switch (K) { 2981 case WholeProgramDevirtResolution::ByArg::Indir: 2982 return "indir"; 2983 case WholeProgramDevirtResolution::ByArg::UniformRetVal: 2984 return "uniformRetVal"; 2985 case WholeProgramDevirtResolution::ByArg::UniqueRetVal: 2986 return "uniqueRetVal"; 2987 case WholeProgramDevirtResolution::ByArg::VirtualConstProp: 2988 return "virtualConstProp"; 2989 } 2990 llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind"); 2991 } 2992 2993 static const char *getTTResKindName(TypeTestResolution::Kind K) { 2994 switch (K) { 2995 case TypeTestResolution::Unknown: 2996 return "unknown"; 2997 case TypeTestResolution::Unsat: 2998 return "unsat"; 2999 case TypeTestResolution::ByteArray: 3000 return "byteArray"; 3001 case TypeTestResolution::Inline: 3002 return "inline"; 3003 case TypeTestResolution::Single: 3004 return "single"; 3005 case TypeTestResolution::AllOnes: 3006 return "allOnes"; 3007 } 3008 llvm_unreachable("invalid TypeTestResolution kind"); 3009 } 3010 3011 void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) { 3012 Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind) 3013 << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth; 3014 3015 // The following fields are only used if the target does not support the use 3016 // of absolute symbols to store constants. Print only if non-zero. 3017 if (TTRes.AlignLog2) 3018 Out << ", alignLog2: " << TTRes.AlignLog2; 3019 if (TTRes.SizeM1) 3020 Out << ", sizeM1: " << TTRes.SizeM1; 3021 if (TTRes.BitMask) 3022 // BitMask is uint8_t which causes it to print the corresponding char. 3023 Out << ", bitMask: " << (unsigned)TTRes.BitMask; 3024 if (TTRes.InlineBits) 3025 Out << ", inlineBits: " << TTRes.InlineBits; 3026 3027 Out << ")"; 3028 } 3029 3030 void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) { 3031 Out << ", summary: ("; 3032 printTypeTestResolution(TIS.TTRes); 3033 if (!TIS.WPDRes.empty()) { 3034 Out << ", wpdResolutions: ("; 3035 FieldSeparator FS; 3036 for (auto &WPDRes : TIS.WPDRes) { 3037 Out << FS; 3038 Out << "(offset: " << WPDRes.first << ", "; 3039 printWPDRes(WPDRes.second); 3040 Out << ")"; 3041 } 3042 Out << ")"; 3043 } 3044 Out << ")"; 3045 } 3046 3047 void AssemblyWriter::printTypeIdCompatibleVtableSummary( 3048 const TypeIdCompatibleVtableInfo &TI) { 3049 Out << ", summary: ("; 3050 FieldSeparator FS; 3051 for (auto &P : TI) { 3052 Out << FS; 3053 Out << "(offset: " << P.AddressPointOffset << ", "; 3054 Out << "^" << Machine.getGUIDSlot(P.VTableVI.getGUID()); 3055 Out << ")"; 3056 } 3057 Out << ")"; 3058 } 3059 3060 void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) { 3061 Out << "args: ("; 3062 FieldSeparator FS; 3063 for (auto arg : Args) { 3064 Out << FS; 3065 Out << arg; 3066 } 3067 Out << ")"; 3068 } 3069 3070 void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) { 3071 Out << "wpdRes: (kind: "; 3072 Out << getWholeProgDevirtResKindName(WPDRes.TheKind); 3073 3074 if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl) 3075 Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\""; 3076 3077 if (!WPDRes.ResByArg.empty()) { 3078 Out << ", resByArg: ("; 3079 FieldSeparator FS; 3080 for (auto &ResByArg : WPDRes.ResByArg) { 3081 Out << FS; 3082 printArgs(ResByArg.first); 3083 Out << ", byArg: (kind: "; 3084 Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind); 3085 if (ResByArg.second.TheKind == 3086 WholeProgramDevirtResolution::ByArg::UniformRetVal || 3087 ResByArg.second.TheKind == 3088 WholeProgramDevirtResolution::ByArg::UniqueRetVal) 3089 Out << ", info: " << ResByArg.second.Info; 3090 3091 // The following fields are only used if the target does not support the 3092 // use of absolute symbols to store constants. Print only if non-zero. 3093 if (ResByArg.second.Byte || ResByArg.second.Bit) 3094 Out << ", byte: " << ResByArg.second.Byte 3095 << ", bit: " << ResByArg.second.Bit; 3096 3097 Out << ")"; 3098 } 3099 Out << ")"; 3100 } 3101 Out << ")"; 3102 } 3103 3104 static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) { 3105 switch (SK) { 3106 case GlobalValueSummary::AliasKind: 3107 return "alias"; 3108 case GlobalValueSummary::FunctionKind: 3109 return "function"; 3110 case GlobalValueSummary::GlobalVarKind: 3111 return "variable"; 3112 } 3113 llvm_unreachable("invalid summary kind"); 3114 } 3115 3116 void AssemblyWriter::printAliasSummary(const AliasSummary *AS) { 3117 Out << ", aliasee: "; 3118 // The indexes emitted for distributed backends may not include the 3119 // aliasee summary (only if it is being imported directly). Handle 3120 // that case by just emitting "null" as the aliasee. 3121 if (AS->hasAliasee()) 3122 Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]); 3123 else 3124 Out << "null"; 3125 } 3126 3127 void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) { 3128 auto VTableFuncs = GS->vTableFuncs(); 3129 Out << ", varFlags: (readonly: " << GS->VarFlags.MaybeReadOnly << ", " 3130 << "writeonly: " << GS->VarFlags.MaybeWriteOnly << ", " 3131 << "constant: " << GS->VarFlags.Constant; 3132 if (!VTableFuncs.empty()) 3133 Out << ", " 3134 << "vcall_visibility: " << GS->VarFlags.VCallVisibility; 3135 Out << ")"; 3136 3137 if (!VTableFuncs.empty()) { 3138 Out << ", vTableFuncs: ("; 3139 FieldSeparator FS; 3140 for (auto &P : VTableFuncs) { 3141 Out << FS; 3142 Out << "(virtFunc: ^" << Machine.getGUIDSlot(P.FuncVI.getGUID()) 3143 << ", offset: " << P.VTableOffset; 3144 Out << ")"; 3145 } 3146 Out << ")"; 3147 } 3148 } 3149 3150 static std::string getLinkageName(GlobalValue::LinkageTypes LT) { 3151 switch (LT) { 3152 case GlobalValue::ExternalLinkage: 3153 return "external"; 3154 case GlobalValue::PrivateLinkage: 3155 return "private"; 3156 case GlobalValue::InternalLinkage: 3157 return "internal"; 3158 case GlobalValue::LinkOnceAnyLinkage: 3159 return "linkonce"; 3160 case GlobalValue::LinkOnceODRLinkage: 3161 return "linkonce_odr"; 3162 case GlobalValue::WeakAnyLinkage: 3163 return "weak"; 3164 case GlobalValue::WeakODRLinkage: 3165 return "weak_odr"; 3166 case GlobalValue::CommonLinkage: 3167 return "common"; 3168 case GlobalValue::AppendingLinkage: 3169 return "appending"; 3170 case GlobalValue::ExternalWeakLinkage: 3171 return "extern_weak"; 3172 case GlobalValue::AvailableExternallyLinkage: 3173 return "available_externally"; 3174 } 3175 llvm_unreachable("invalid linkage"); 3176 } 3177 3178 // When printing the linkage types in IR where the ExternalLinkage is 3179 // not printed, and other linkage types are expected to be printed with 3180 // a space after the name. 3181 static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) { 3182 if (LT == GlobalValue::ExternalLinkage) 3183 return ""; 3184 return getLinkageName(LT) + " "; 3185 } 3186 3187 static const char *getVisibilityName(GlobalValue::VisibilityTypes Vis) { 3188 switch (Vis) { 3189 case GlobalValue::DefaultVisibility: 3190 return "default"; 3191 case GlobalValue::HiddenVisibility: 3192 return "hidden"; 3193 case GlobalValue::ProtectedVisibility: 3194 return "protected"; 3195 } 3196 llvm_unreachable("invalid visibility"); 3197 } 3198 3199 void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) { 3200 Out << ", insts: " << FS->instCount(); 3201 3202 FunctionSummary::FFlags FFlags = FS->fflags(); 3203 if (FFlags.ReadNone | FFlags.ReadOnly | FFlags.NoRecurse | 3204 FFlags.ReturnDoesNotAlias | FFlags.NoInline | FFlags.AlwaysInline) { 3205 Out << ", funcFlags: ("; 3206 Out << "readNone: " << FFlags.ReadNone; 3207 Out << ", readOnly: " << FFlags.ReadOnly; 3208 Out << ", noRecurse: " << FFlags.NoRecurse; 3209 Out << ", returnDoesNotAlias: " << FFlags.ReturnDoesNotAlias; 3210 Out << ", noInline: " << FFlags.NoInline; 3211 Out << ", alwaysInline: " << FFlags.AlwaysInline; 3212 Out << ")"; 3213 } 3214 if (!FS->calls().empty()) { 3215 Out << ", calls: ("; 3216 FieldSeparator IFS; 3217 for (auto &Call : FS->calls()) { 3218 Out << IFS; 3219 Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID()); 3220 if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown) 3221 Out << ", hotness: " << getHotnessName(Call.second.getHotness()); 3222 else if (Call.second.RelBlockFreq) 3223 Out << ", relbf: " << Call.second.RelBlockFreq; 3224 Out << ")"; 3225 } 3226 Out << ")"; 3227 } 3228 3229 if (const auto *TIdInfo = FS->getTypeIdInfo()) 3230 printTypeIdInfo(*TIdInfo); 3231 3232 auto PrintRange = [&](const ConstantRange &Range) { 3233 Out << "[" << Range.getSignedMin() << ", " << Range.getSignedMax() << "]"; 3234 }; 3235 3236 if (!FS->paramAccesses().empty()) { 3237 Out << ", params: ("; 3238 FieldSeparator IFS; 3239 for (auto &PS : FS->paramAccesses()) { 3240 Out << IFS; 3241 Out << "(param: " << PS.ParamNo; 3242 Out << ", offset: "; 3243 PrintRange(PS.Use); 3244 if (!PS.Calls.empty()) { 3245 Out << ", calls: ("; 3246 FieldSeparator IFS; 3247 for (auto &Call : PS.Calls) { 3248 Out << IFS; 3249 Out << "(callee: ^" << Machine.getGUIDSlot(Call.Callee.getGUID()); 3250 Out << ", param: " << Call.ParamNo; 3251 Out << ", offset: "; 3252 PrintRange(Call.Offsets); 3253 Out << ")"; 3254 } 3255 Out << ")"; 3256 } 3257 Out << ")"; 3258 } 3259 Out << ")"; 3260 } 3261 } 3262 3263 void AssemblyWriter::printTypeIdInfo( 3264 const FunctionSummary::TypeIdInfo &TIDInfo) { 3265 Out << ", typeIdInfo: ("; 3266 FieldSeparator TIDFS; 3267 if (!TIDInfo.TypeTests.empty()) { 3268 Out << TIDFS; 3269 Out << "typeTests: ("; 3270 FieldSeparator FS; 3271 for (auto &GUID : TIDInfo.TypeTests) { 3272 auto TidIter = TheIndex->typeIds().equal_range(GUID); 3273 if (TidIter.first == TidIter.second) { 3274 Out << FS; 3275 Out << GUID; 3276 continue; 3277 } 3278 // Print all type id that correspond to this GUID. 3279 for (auto It = TidIter.first; It != TidIter.second; ++It) { 3280 Out << FS; 3281 auto Slot = Machine.getTypeIdSlot(It->second.first); 3282 assert(Slot != -1); 3283 Out << "^" << Slot; 3284 } 3285 } 3286 Out << ")"; 3287 } 3288 if (!TIDInfo.TypeTestAssumeVCalls.empty()) { 3289 Out << TIDFS; 3290 printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls"); 3291 } 3292 if (!TIDInfo.TypeCheckedLoadVCalls.empty()) { 3293 Out << TIDFS; 3294 printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls"); 3295 } 3296 if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) { 3297 Out << TIDFS; 3298 printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls, 3299 "typeTestAssumeConstVCalls"); 3300 } 3301 if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) { 3302 Out << TIDFS; 3303 printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls, 3304 "typeCheckedLoadConstVCalls"); 3305 } 3306 Out << ")"; 3307 } 3308 3309 void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) { 3310 auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID); 3311 if (TidIter.first == TidIter.second) { 3312 Out << "vFuncId: ("; 3313 Out << "guid: " << VFId.GUID; 3314 Out << ", offset: " << VFId.Offset; 3315 Out << ")"; 3316 return; 3317 } 3318 // Print all type id that correspond to this GUID. 3319 FieldSeparator FS; 3320 for (auto It = TidIter.first; It != TidIter.second; ++It) { 3321 Out << FS; 3322 Out << "vFuncId: ("; 3323 auto Slot = Machine.getTypeIdSlot(It->second.first); 3324 assert(Slot != -1); 3325 Out << "^" << Slot; 3326 Out << ", offset: " << VFId.Offset; 3327 Out << ")"; 3328 } 3329 } 3330 3331 void AssemblyWriter::printNonConstVCalls( 3332 const std::vector<FunctionSummary::VFuncId> &VCallList, const char *Tag) { 3333 Out << Tag << ": ("; 3334 FieldSeparator FS; 3335 for (auto &VFuncId : VCallList) { 3336 Out << FS; 3337 printVFuncId(VFuncId); 3338 } 3339 Out << ")"; 3340 } 3341 3342 void AssemblyWriter::printConstVCalls( 3343 const std::vector<FunctionSummary::ConstVCall> &VCallList, 3344 const char *Tag) { 3345 Out << Tag << ": ("; 3346 FieldSeparator FS; 3347 for (auto &ConstVCall : VCallList) { 3348 Out << FS; 3349 Out << "("; 3350 printVFuncId(ConstVCall.VFunc); 3351 if (!ConstVCall.Args.empty()) { 3352 Out << ", "; 3353 printArgs(ConstVCall.Args); 3354 } 3355 Out << ")"; 3356 } 3357 Out << ")"; 3358 } 3359 3360 void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) { 3361 GlobalValueSummary::GVFlags GVFlags = Summary.flags(); 3362 GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage; 3363 Out << getSummaryKindName(Summary.getSummaryKind()) << ": "; 3364 Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath()) 3365 << ", flags: ("; 3366 Out << "linkage: " << getLinkageName(LT); 3367 Out << ", visibility: " 3368 << getVisibilityName((GlobalValue::VisibilityTypes)GVFlags.Visibility); 3369 Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport; 3370 Out << ", live: " << GVFlags.Live; 3371 Out << ", dsoLocal: " << GVFlags.DSOLocal; 3372 Out << ", canAutoHide: " << GVFlags.CanAutoHide; 3373 Out << ")"; 3374 3375 if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind) 3376 printAliasSummary(cast<AliasSummary>(&Summary)); 3377 else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind) 3378 printFunctionSummary(cast<FunctionSummary>(&Summary)); 3379 else 3380 printGlobalVarSummary(cast<GlobalVarSummary>(&Summary)); 3381 3382 auto RefList = Summary.refs(); 3383 if (!RefList.empty()) { 3384 Out << ", refs: ("; 3385 FieldSeparator FS; 3386 for (auto &Ref : RefList) { 3387 Out << FS; 3388 if (Ref.isReadOnly()) 3389 Out << "readonly "; 3390 else if (Ref.isWriteOnly()) 3391 Out << "writeonly "; 3392 Out << "^" << Machine.getGUIDSlot(Ref.getGUID()); 3393 } 3394 Out << ")"; 3395 } 3396 3397 Out << ")"; 3398 } 3399 3400 void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) { 3401 Out << "^" << Slot << " = gv: ("; 3402 if (!VI.name().empty()) 3403 Out << "name: \"" << VI.name() << "\""; 3404 else 3405 Out << "guid: " << VI.getGUID(); 3406 if (!VI.getSummaryList().empty()) { 3407 Out << ", summaries: ("; 3408 FieldSeparator FS; 3409 for (auto &Summary : VI.getSummaryList()) { 3410 Out << FS; 3411 printSummary(*Summary); 3412 } 3413 Out << ")"; 3414 } 3415 Out << ")"; 3416 if (!VI.name().empty()) 3417 Out << " ; guid = " << VI.getGUID(); 3418 Out << "\n"; 3419 } 3420 3421 static void printMetadataIdentifier(StringRef Name, 3422 formatted_raw_ostream &Out) { 3423 if (Name.empty()) { 3424 Out << "<empty name> "; 3425 } else { 3426 if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' || 3427 Name[0] == '$' || Name[0] == '.' || Name[0] == '_') 3428 Out << Name[0]; 3429 else 3430 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F); 3431 for (unsigned i = 1, e = Name.size(); i != e; ++i) { 3432 unsigned char C = Name[i]; 3433 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' || 3434 C == '.' || C == '_') 3435 Out << C; 3436 else 3437 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F); 3438 } 3439 } 3440 } 3441 3442 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) { 3443 Out << '!'; 3444 printMetadataIdentifier(NMD->getName(), Out); 3445 Out << " = !{"; 3446 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 3447 if (i) 3448 Out << ", "; 3449 3450 // Write DIExpressions inline. 3451 // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose. 3452 MDNode *Op = NMD->getOperand(i); 3453 assert(!isa<DIArgList>(Op) && 3454 "DIArgLists should not appear in NamedMDNodes"); 3455 if (auto *Expr = dyn_cast<DIExpression>(Op)) { 3456 writeDIExpression(Out, Expr, nullptr, nullptr, nullptr); 3457 continue; 3458 } 3459 3460 int Slot = Machine.getMetadataSlot(Op); 3461 if (Slot == -1) 3462 Out << "<badref>"; 3463 else 3464 Out << '!' << Slot; 3465 } 3466 Out << "}\n"; 3467 } 3468 3469 static void PrintVisibility(GlobalValue::VisibilityTypes Vis, 3470 formatted_raw_ostream &Out) { 3471 switch (Vis) { 3472 case GlobalValue::DefaultVisibility: break; 3473 case GlobalValue::HiddenVisibility: Out << "hidden "; break; 3474 case GlobalValue::ProtectedVisibility: Out << "protected "; break; 3475 } 3476 } 3477 3478 static void PrintDSOLocation(const GlobalValue &GV, 3479 formatted_raw_ostream &Out) { 3480 if (GV.isDSOLocal() && !GV.isImplicitDSOLocal()) 3481 Out << "dso_local "; 3482 } 3483 3484 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT, 3485 formatted_raw_ostream &Out) { 3486 switch (SCT) { 3487 case GlobalValue::DefaultStorageClass: break; 3488 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break; 3489 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break; 3490 } 3491 } 3492 3493 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM, 3494 formatted_raw_ostream &Out) { 3495 switch (TLM) { 3496 case GlobalVariable::NotThreadLocal: 3497 break; 3498 case GlobalVariable::GeneralDynamicTLSModel: 3499 Out << "thread_local "; 3500 break; 3501 case GlobalVariable::LocalDynamicTLSModel: 3502 Out << "thread_local(localdynamic) "; 3503 break; 3504 case GlobalVariable::InitialExecTLSModel: 3505 Out << "thread_local(initialexec) "; 3506 break; 3507 case GlobalVariable::LocalExecTLSModel: 3508 Out << "thread_local(localexec) "; 3509 break; 3510 } 3511 } 3512 3513 static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) { 3514 switch (UA) { 3515 case GlobalVariable::UnnamedAddr::None: 3516 return ""; 3517 case GlobalVariable::UnnamedAddr::Local: 3518 return "local_unnamed_addr"; 3519 case GlobalVariable::UnnamedAddr::Global: 3520 return "unnamed_addr"; 3521 } 3522 llvm_unreachable("Unknown UnnamedAddr"); 3523 } 3524 3525 static void maybePrintComdat(formatted_raw_ostream &Out, 3526 const GlobalObject &GO) { 3527 const Comdat *C = GO.getComdat(); 3528 if (!C) 3529 return; 3530 3531 if (isa<GlobalVariable>(GO)) 3532 Out << ','; 3533 Out << " comdat"; 3534 3535 if (GO.getName() == C->getName()) 3536 return; 3537 3538 Out << '('; 3539 PrintLLVMName(Out, C->getName(), ComdatPrefix); 3540 Out << ')'; 3541 } 3542 3543 void AssemblyWriter::printGlobal(const GlobalVariable *GV) { 3544 if (GV->isMaterializable()) 3545 Out << "; Materializable\n"; 3546 3547 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent()); 3548 Out << " = "; 3549 3550 if (!GV->hasInitializer() && GV->hasExternalLinkage()) 3551 Out << "external "; 3552 3553 Out << getLinkageNameWithSpace(GV->getLinkage()); 3554 PrintDSOLocation(*GV, Out); 3555 PrintVisibility(GV->getVisibility(), Out); 3556 PrintDLLStorageClass(GV->getDLLStorageClass(), Out); 3557 PrintThreadLocalModel(GV->getThreadLocalMode(), Out); 3558 StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr()); 3559 if (!UA.empty()) 3560 Out << UA << ' '; 3561 3562 if (unsigned AddressSpace = GV->getType()->getAddressSpace()) 3563 Out << "addrspace(" << AddressSpace << ") "; 3564 if (GV->isExternallyInitialized()) Out << "externally_initialized "; 3565 Out << (GV->isConstant() ? "constant " : "global "); 3566 TypePrinter.print(GV->getValueType(), Out); 3567 3568 if (GV->hasInitializer()) { 3569 Out << ' '; 3570 writeOperand(GV->getInitializer(), false); 3571 } 3572 3573 if (GV->hasSection()) { 3574 Out << ", section \""; 3575 printEscapedString(GV->getSection(), Out); 3576 Out << '"'; 3577 } 3578 if (GV->hasPartition()) { 3579 Out << ", partition \""; 3580 printEscapedString(GV->getPartition(), Out); 3581 Out << '"'; 3582 } 3583 3584 maybePrintComdat(Out, *GV); 3585 if (GV->getAlignment()) 3586 Out << ", align " << GV->getAlignment(); 3587 3588 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 3589 GV->getAllMetadata(MDs); 3590 printMetadataAttachments(MDs, ", "); 3591 3592 auto Attrs = GV->getAttributes(); 3593 if (Attrs.hasAttributes()) 3594 Out << " #" << Machine.getAttributeGroupSlot(Attrs); 3595 3596 printInfoComment(*GV); 3597 } 3598 3599 void AssemblyWriter::printIndirectSymbol(const GlobalIndirectSymbol *GIS) { 3600 if (GIS->isMaterializable()) 3601 Out << "; Materializable\n"; 3602 3603 WriteAsOperandInternal(Out, GIS, &TypePrinter, &Machine, GIS->getParent()); 3604 Out << " = "; 3605 3606 Out << getLinkageNameWithSpace(GIS->getLinkage()); 3607 PrintDSOLocation(*GIS, Out); 3608 PrintVisibility(GIS->getVisibility(), Out); 3609 PrintDLLStorageClass(GIS->getDLLStorageClass(), Out); 3610 PrintThreadLocalModel(GIS->getThreadLocalMode(), Out); 3611 StringRef UA = getUnnamedAddrEncoding(GIS->getUnnamedAddr()); 3612 if (!UA.empty()) 3613 Out << UA << ' '; 3614 3615 if (isa<GlobalAlias>(GIS)) 3616 Out << "alias "; 3617 else if (isa<GlobalIFunc>(GIS)) 3618 Out << "ifunc "; 3619 else 3620 llvm_unreachable("Not an alias or ifunc!"); 3621 3622 TypePrinter.print(GIS->getValueType(), Out); 3623 3624 Out << ", "; 3625 3626 const Constant *IS = GIS->getIndirectSymbol(); 3627 3628 if (!IS) { 3629 TypePrinter.print(GIS->getType(), Out); 3630 Out << " <<NULL ALIASEE>>"; 3631 } else { 3632 writeOperand(IS, !isa<ConstantExpr>(IS)); 3633 } 3634 3635 if (GIS->hasPartition()) { 3636 Out << ", partition \""; 3637 printEscapedString(GIS->getPartition(), Out); 3638 Out << '"'; 3639 } 3640 3641 printInfoComment(*GIS); 3642 Out << '\n'; 3643 } 3644 3645 void AssemblyWriter::printComdat(const Comdat *C) { 3646 C->print(Out); 3647 } 3648 3649 void AssemblyWriter::printTypeIdentities() { 3650 if (TypePrinter.empty()) 3651 return; 3652 3653 Out << '\n'; 3654 3655 // Emit all numbered types. 3656 auto &NumberedTypes = TypePrinter.getNumberedTypes(); 3657 for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) { 3658 Out << '%' << I << " = type "; 3659 3660 // Make sure we print out at least one level of the type structure, so 3661 // that we do not get %2 = type %2 3662 TypePrinter.printStructBody(NumberedTypes[I], Out); 3663 Out << '\n'; 3664 } 3665 3666 auto &NamedTypes = TypePrinter.getNamedTypes(); 3667 for (unsigned I = 0, E = NamedTypes.size(); I != E; ++I) { 3668 PrintLLVMName(Out, NamedTypes[I]->getName(), LocalPrefix); 3669 Out << " = type "; 3670 3671 // Make sure we print out at least one level of the type structure, so 3672 // that we do not get %FILE = type %FILE 3673 TypePrinter.printStructBody(NamedTypes[I], Out); 3674 Out << '\n'; 3675 } 3676 } 3677 3678 /// printFunction - Print all aspects of a function. 3679 void AssemblyWriter::printFunction(const Function *F) { 3680 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out); 3681 3682 if (F->isMaterializable()) 3683 Out << "; Materializable\n"; 3684 3685 const AttributeList &Attrs = F->getAttributes(); 3686 if (Attrs.hasAttributes(AttributeList::FunctionIndex)) { 3687 AttributeSet AS = Attrs.getFnAttributes(); 3688 std::string AttrStr; 3689 3690 for (const Attribute &Attr : AS) { 3691 if (!Attr.isStringAttribute()) { 3692 if (!AttrStr.empty()) AttrStr += ' '; 3693 AttrStr += Attr.getAsString(); 3694 } 3695 } 3696 3697 if (!AttrStr.empty()) 3698 Out << "; Function Attrs: " << AttrStr << '\n'; 3699 } 3700 3701 Machine.incorporateFunction(F); 3702 3703 if (F->isDeclaration()) { 3704 Out << "declare"; 3705 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 3706 F->getAllMetadata(MDs); 3707 printMetadataAttachments(MDs, " "); 3708 Out << ' '; 3709 } else 3710 Out << "define "; 3711 3712 Out << getLinkageNameWithSpace(F->getLinkage()); 3713 PrintDSOLocation(*F, Out); 3714 PrintVisibility(F->getVisibility(), Out); 3715 PrintDLLStorageClass(F->getDLLStorageClass(), Out); 3716 3717 // Print the calling convention. 3718 if (F->getCallingConv() != CallingConv::C) { 3719 PrintCallingConv(F->getCallingConv(), Out); 3720 Out << " "; 3721 } 3722 3723 FunctionType *FT = F->getFunctionType(); 3724 if (Attrs.hasAttributes(AttributeList::ReturnIndex)) 3725 Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' '; 3726 TypePrinter.print(F->getReturnType(), Out); 3727 Out << ' '; 3728 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent()); 3729 Out << '('; 3730 3731 // Loop over the arguments, printing them... 3732 if (F->isDeclaration() && !IsForDebug) { 3733 // We're only interested in the type here - don't print argument names. 3734 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) { 3735 // Insert commas as we go... the first arg doesn't get a comma 3736 if (I) 3737 Out << ", "; 3738 // Output type... 3739 TypePrinter.print(FT->getParamType(I), Out); 3740 3741 AttributeSet ArgAttrs = Attrs.getParamAttributes(I); 3742 if (ArgAttrs.hasAttributes()) { 3743 Out << ' '; 3744 writeAttributeSet(ArgAttrs); 3745 } 3746 } 3747 } else { 3748 // The arguments are meaningful here, print them in detail. 3749 for (const Argument &Arg : F->args()) { 3750 // Insert commas as we go... the first arg doesn't get a comma 3751 if (Arg.getArgNo() != 0) 3752 Out << ", "; 3753 printArgument(&Arg, Attrs.getParamAttributes(Arg.getArgNo())); 3754 } 3755 } 3756 3757 // Finish printing arguments... 3758 if (FT->isVarArg()) { 3759 if (FT->getNumParams()) Out << ", "; 3760 Out << "..."; // Output varargs portion of signature! 3761 } 3762 Out << ')'; 3763 StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr()); 3764 if (!UA.empty()) 3765 Out << ' ' << UA; 3766 // We print the function address space if it is non-zero or if we are writing 3767 // a module with a non-zero program address space or if there is no valid 3768 // Module* so that the file can be parsed without the datalayout string. 3769 const Module *Mod = F->getParent(); 3770 if (F->getAddressSpace() != 0 || !Mod || 3771 Mod->getDataLayout().getProgramAddressSpace() != 0) 3772 Out << " addrspace(" << F->getAddressSpace() << ")"; 3773 if (Attrs.hasAttributes(AttributeList::FunctionIndex)) 3774 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes()); 3775 if (F->hasSection()) { 3776 Out << " section \""; 3777 printEscapedString(F->getSection(), Out); 3778 Out << '"'; 3779 } 3780 if (F->hasPartition()) { 3781 Out << " partition \""; 3782 printEscapedString(F->getPartition(), Out); 3783 Out << '"'; 3784 } 3785 maybePrintComdat(Out, *F); 3786 if (F->getAlignment()) 3787 Out << " align " << F->getAlignment(); 3788 if (F->hasGC()) 3789 Out << " gc \"" << F->getGC() << '"'; 3790 if (F->hasPrefixData()) { 3791 Out << " prefix "; 3792 writeOperand(F->getPrefixData(), true); 3793 } 3794 if (F->hasPrologueData()) { 3795 Out << " prologue "; 3796 writeOperand(F->getPrologueData(), true); 3797 } 3798 if (F->hasPersonalityFn()) { 3799 Out << " personality "; 3800 writeOperand(F->getPersonalityFn(), /*PrintType=*/true); 3801 } 3802 3803 if (F->isDeclaration()) { 3804 Out << '\n'; 3805 } else { 3806 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 3807 F->getAllMetadata(MDs); 3808 printMetadataAttachments(MDs, " "); 3809 3810 Out << " {"; 3811 // Output all of the function's basic blocks. 3812 for (const BasicBlock &BB : *F) 3813 printBasicBlock(&BB); 3814 3815 // Output the function's use-lists. 3816 printUseLists(F); 3817 3818 Out << "}\n"; 3819 } 3820 3821 Machine.purgeFunction(); 3822 } 3823 3824 /// printArgument - This member is called for every argument that is passed into 3825 /// the function. Simply print it out 3826 void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) { 3827 // Output type... 3828 TypePrinter.print(Arg->getType(), Out); 3829 3830 // Output parameter attributes list 3831 if (Attrs.hasAttributes()) { 3832 Out << ' '; 3833 writeAttributeSet(Attrs); 3834 } 3835 3836 // Output name, if available... 3837 if (Arg->hasName()) { 3838 Out << ' '; 3839 PrintLLVMName(Out, Arg); 3840 } else { 3841 int Slot = Machine.getLocalSlot(Arg); 3842 assert(Slot != -1 && "expect argument in function here"); 3843 Out << " %" << Slot; 3844 } 3845 } 3846 3847 /// printBasicBlock - This member is called for each basic block in a method. 3848 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) { 3849 bool IsEntryBlock = BB->getParent() && BB->isEntryBlock(); 3850 if (BB->hasName()) { // Print out the label if it exists... 3851 Out << "\n"; 3852 PrintLLVMName(Out, BB->getName(), LabelPrefix); 3853 Out << ':'; 3854 } else if (!IsEntryBlock) { 3855 Out << "\n"; 3856 int Slot = Machine.getLocalSlot(BB); 3857 if (Slot != -1) 3858 Out << Slot << ":"; 3859 else 3860 Out << "<badref>:"; 3861 } 3862 3863 if (!IsEntryBlock) { 3864 // Output predecessors for the block. 3865 Out.PadToColumn(50); 3866 Out << ";"; 3867 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB); 3868 3869 if (PI == PE) { 3870 Out << " No predecessors!"; 3871 } else { 3872 Out << " preds = "; 3873 writeOperand(*PI, false); 3874 for (++PI; PI != PE; ++PI) { 3875 Out << ", "; 3876 writeOperand(*PI, false); 3877 } 3878 } 3879 } 3880 3881 Out << "\n"; 3882 3883 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out); 3884 3885 // Output all of the instructions in the basic block... 3886 for (const Instruction &I : *BB) { 3887 printInstructionLine(I); 3888 } 3889 3890 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out); 3891 } 3892 3893 /// printInstructionLine - Print an instruction and a newline character. 3894 void AssemblyWriter::printInstructionLine(const Instruction &I) { 3895 printInstruction(I); 3896 Out << '\n'; 3897 } 3898 3899 /// printGCRelocateComment - print comment after call to the gc.relocate 3900 /// intrinsic indicating base and derived pointer names. 3901 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) { 3902 Out << " ; ("; 3903 writeOperand(Relocate.getBasePtr(), false); 3904 Out << ", "; 3905 writeOperand(Relocate.getDerivedPtr(), false); 3906 Out << ")"; 3907 } 3908 3909 /// printInfoComment - Print a little comment after the instruction indicating 3910 /// which slot it occupies. 3911 void AssemblyWriter::printInfoComment(const Value &V) { 3912 if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V)) 3913 printGCRelocateComment(*Relocate); 3914 3915 if (AnnotationWriter) 3916 AnnotationWriter->printInfoComment(V, Out); 3917 } 3918 3919 static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I, 3920 raw_ostream &Out) { 3921 // We print the address space of the call if it is non-zero. 3922 unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace(); 3923 bool PrintAddrSpace = CallAddrSpace != 0; 3924 if (!PrintAddrSpace) { 3925 const Module *Mod = getModuleFromVal(I); 3926 // We also print it if it is zero but not equal to the program address space 3927 // or if we can't find a valid Module* to make it possible to parse 3928 // the resulting file even without a datalayout string. 3929 if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0) 3930 PrintAddrSpace = true; 3931 } 3932 if (PrintAddrSpace) 3933 Out << " addrspace(" << CallAddrSpace << ")"; 3934 } 3935 3936 // This member is called for each Instruction in a function.. 3937 void AssemblyWriter::printInstruction(const Instruction &I) { 3938 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out); 3939 3940 // Print out indentation for an instruction. 3941 Out << " "; 3942 3943 // Print out name if it exists... 3944 if (I.hasName()) { 3945 PrintLLVMName(Out, &I); 3946 Out << " = "; 3947 } else if (!I.getType()->isVoidTy()) { 3948 // Print out the def slot taken. 3949 int SlotNum = Machine.getLocalSlot(&I); 3950 if (SlotNum == -1) 3951 Out << "<badref> = "; 3952 else 3953 Out << '%' << SlotNum << " = "; 3954 } 3955 3956 if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 3957 if (CI->isMustTailCall()) 3958 Out << "musttail "; 3959 else if (CI->isTailCall()) 3960 Out << "tail "; 3961 else if (CI->isNoTailCall()) 3962 Out << "notail "; 3963 } 3964 3965 // Print out the opcode... 3966 Out << I.getOpcodeName(); 3967 3968 // If this is an atomic load or store, print out the atomic marker. 3969 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) || 3970 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic())) 3971 Out << " atomic"; 3972 3973 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak()) 3974 Out << " weak"; 3975 3976 // If this is a volatile operation, print out the volatile marker. 3977 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) || 3978 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) || 3979 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) || 3980 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile())) 3981 Out << " volatile"; 3982 3983 // Print out optimization information. 3984 WriteOptimizationInfo(Out, &I); 3985 3986 // Print out the compare instruction predicates 3987 if (const CmpInst *CI = dyn_cast<CmpInst>(&I)) 3988 Out << ' ' << CmpInst::getPredicateName(CI->getPredicate()); 3989 3990 // Print out the atomicrmw operation 3991 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) 3992 Out << ' ' << AtomicRMWInst::getOperationName(RMWI->getOperation()); 3993 3994 // Print out the type of the operands... 3995 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr; 3996 3997 // Special case conditional branches to swizzle the condition out to the front 3998 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) { 3999 const BranchInst &BI(cast<BranchInst>(I)); 4000 Out << ' '; 4001 writeOperand(BI.getCondition(), true); 4002 Out << ", "; 4003 writeOperand(BI.getSuccessor(0), true); 4004 Out << ", "; 4005 writeOperand(BI.getSuccessor(1), true); 4006 4007 } else if (isa<SwitchInst>(I)) { 4008 const SwitchInst& SI(cast<SwitchInst>(I)); 4009 // Special case switch instruction to get formatting nice and correct. 4010 Out << ' '; 4011 writeOperand(SI.getCondition(), true); 4012 Out << ", "; 4013 writeOperand(SI.getDefaultDest(), true); 4014 Out << " ["; 4015 for (auto Case : SI.cases()) { 4016 Out << "\n "; 4017 writeOperand(Case.getCaseValue(), true); 4018 Out << ", "; 4019 writeOperand(Case.getCaseSuccessor(), true); 4020 } 4021 Out << "\n ]"; 4022 } else if (isa<IndirectBrInst>(I)) { 4023 // Special case indirectbr instruction to get formatting nice and correct. 4024 Out << ' '; 4025 writeOperand(Operand, true); 4026 Out << ", ["; 4027 4028 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) { 4029 if (i != 1) 4030 Out << ", "; 4031 writeOperand(I.getOperand(i), true); 4032 } 4033 Out << ']'; 4034 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) { 4035 Out << ' '; 4036 TypePrinter.print(I.getType(), Out); 4037 Out << ' '; 4038 4039 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) { 4040 if (op) Out << ", "; 4041 Out << "[ "; 4042 writeOperand(PN->getIncomingValue(op), false); Out << ", "; 4043 writeOperand(PN->getIncomingBlock(op), false); Out << " ]"; 4044 } 4045 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) { 4046 Out << ' '; 4047 writeOperand(I.getOperand(0), true); 4048 for (unsigned i : EVI->indices()) 4049 Out << ", " << i; 4050 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) { 4051 Out << ' '; 4052 writeOperand(I.getOperand(0), true); Out << ", "; 4053 writeOperand(I.getOperand(1), true); 4054 for (unsigned i : IVI->indices()) 4055 Out << ", " << i; 4056 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) { 4057 Out << ' '; 4058 TypePrinter.print(I.getType(), Out); 4059 if (LPI->isCleanup() || LPI->getNumClauses() != 0) 4060 Out << '\n'; 4061 4062 if (LPI->isCleanup()) 4063 Out << " cleanup"; 4064 4065 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) { 4066 if (i != 0 || LPI->isCleanup()) Out << "\n"; 4067 if (LPI->isCatch(i)) 4068 Out << " catch "; 4069 else 4070 Out << " filter "; 4071 4072 writeOperand(LPI->getClause(i), true); 4073 } 4074 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) { 4075 Out << " within "; 4076 writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false); 4077 Out << " ["; 4078 unsigned Op = 0; 4079 for (const BasicBlock *PadBB : CatchSwitch->handlers()) { 4080 if (Op > 0) 4081 Out << ", "; 4082 writeOperand(PadBB, /*PrintType=*/true); 4083 ++Op; 4084 } 4085 Out << "] unwind "; 4086 if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest()) 4087 writeOperand(UnwindDest, /*PrintType=*/true); 4088 else 4089 Out << "to caller"; 4090 } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) { 4091 Out << " within "; 4092 writeOperand(FPI->getParentPad(), /*PrintType=*/false); 4093 Out << " ["; 4094 for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps; 4095 ++Op) { 4096 if (Op > 0) 4097 Out << ", "; 4098 writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true); 4099 } 4100 Out << ']'; 4101 } else if (isa<ReturnInst>(I) && !Operand) { 4102 Out << " void"; 4103 } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) { 4104 Out << " from "; 4105 writeOperand(CRI->getOperand(0), /*PrintType=*/false); 4106 4107 Out << " to "; 4108 writeOperand(CRI->getOperand(1), /*PrintType=*/true); 4109 } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) { 4110 Out << " from "; 4111 writeOperand(CRI->getOperand(0), /*PrintType=*/false); 4112 4113 Out << " unwind "; 4114 if (CRI->hasUnwindDest()) 4115 writeOperand(CRI->getOperand(1), /*PrintType=*/true); 4116 else 4117 Out << "to caller"; 4118 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 4119 // Print the calling convention being used. 4120 if (CI->getCallingConv() != CallingConv::C) { 4121 Out << " "; 4122 PrintCallingConv(CI->getCallingConv(), Out); 4123 } 4124 4125 Operand = CI->getCalledOperand(); 4126 FunctionType *FTy = CI->getFunctionType(); 4127 Type *RetTy = FTy->getReturnType(); 4128 const AttributeList &PAL = CI->getAttributes(); 4129 4130 if (PAL.hasAttributes(AttributeList::ReturnIndex)) 4131 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex); 4132 4133 // Only print addrspace(N) if necessary: 4134 maybePrintCallAddrSpace(Operand, &I, Out); 4135 4136 // If possible, print out the short form of the call instruction. We can 4137 // only do this if the first argument is a pointer to a nonvararg function, 4138 // and if the return type is not a pointer to a function. 4139 // 4140 Out << ' '; 4141 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out); 4142 Out << ' '; 4143 writeOperand(Operand, false); 4144 Out << '('; 4145 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) { 4146 if (op > 0) 4147 Out << ", "; 4148 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op)); 4149 } 4150 4151 // Emit an ellipsis if this is a musttail call in a vararg function. This 4152 // is only to aid readability, musttail calls forward varargs by default. 4153 if (CI->isMustTailCall() && CI->getParent() && 4154 CI->getParent()->getParent() && 4155 CI->getParent()->getParent()->isVarArg()) 4156 Out << ", ..."; 4157 4158 Out << ')'; 4159 if (PAL.hasAttributes(AttributeList::FunctionIndex)) 4160 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes()); 4161 4162 writeOperandBundles(CI); 4163 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) { 4164 Operand = II->getCalledOperand(); 4165 FunctionType *FTy = II->getFunctionType(); 4166 Type *RetTy = FTy->getReturnType(); 4167 const AttributeList &PAL = II->getAttributes(); 4168 4169 // Print the calling convention being used. 4170 if (II->getCallingConv() != CallingConv::C) { 4171 Out << " "; 4172 PrintCallingConv(II->getCallingConv(), Out); 4173 } 4174 4175 if (PAL.hasAttributes(AttributeList::ReturnIndex)) 4176 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex); 4177 4178 // Only print addrspace(N) if necessary: 4179 maybePrintCallAddrSpace(Operand, &I, Out); 4180 4181 // If possible, print out the short form of the invoke instruction. We can 4182 // only do this if the first argument is a pointer to a nonvararg function, 4183 // and if the return type is not a pointer to a function. 4184 // 4185 Out << ' '; 4186 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out); 4187 Out << ' '; 4188 writeOperand(Operand, false); 4189 Out << '('; 4190 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) { 4191 if (op) 4192 Out << ", "; 4193 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op)); 4194 } 4195 4196 Out << ')'; 4197 if (PAL.hasAttributes(AttributeList::FunctionIndex)) 4198 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes()); 4199 4200 writeOperandBundles(II); 4201 4202 Out << "\n to "; 4203 writeOperand(II->getNormalDest(), true); 4204 Out << " unwind "; 4205 writeOperand(II->getUnwindDest(), true); 4206 } else if (const CallBrInst *CBI = dyn_cast<CallBrInst>(&I)) { 4207 Operand = CBI->getCalledOperand(); 4208 FunctionType *FTy = CBI->getFunctionType(); 4209 Type *RetTy = FTy->getReturnType(); 4210 const AttributeList &PAL = CBI->getAttributes(); 4211 4212 // Print the calling convention being used. 4213 if (CBI->getCallingConv() != CallingConv::C) { 4214 Out << " "; 4215 PrintCallingConv(CBI->getCallingConv(), Out); 4216 } 4217 4218 if (PAL.hasAttributes(AttributeList::ReturnIndex)) 4219 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex); 4220 4221 // If possible, print out the short form of the callbr instruction. We can 4222 // only do this if the first argument is a pointer to a nonvararg function, 4223 // and if the return type is not a pointer to a function. 4224 // 4225 Out << ' '; 4226 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out); 4227 Out << ' '; 4228 writeOperand(Operand, false); 4229 Out << '('; 4230 for (unsigned op = 0, Eop = CBI->getNumArgOperands(); op < Eop; ++op) { 4231 if (op) 4232 Out << ", "; 4233 writeParamOperand(CBI->getArgOperand(op), PAL.getParamAttributes(op)); 4234 } 4235 4236 Out << ')'; 4237 if (PAL.hasAttributes(AttributeList::FunctionIndex)) 4238 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes()); 4239 4240 writeOperandBundles(CBI); 4241 4242 Out << "\n to "; 4243 writeOperand(CBI->getDefaultDest(), true); 4244 Out << " ["; 4245 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) { 4246 if (i != 0) 4247 Out << ", "; 4248 writeOperand(CBI->getIndirectDest(i), true); 4249 } 4250 Out << ']'; 4251 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) { 4252 Out << ' '; 4253 if (AI->isUsedWithInAlloca()) 4254 Out << "inalloca "; 4255 if (AI->isSwiftError()) 4256 Out << "swifterror "; 4257 TypePrinter.print(AI->getAllocatedType(), Out); 4258 4259 // Explicitly write the array size if the code is broken, if it's an array 4260 // allocation, or if the type is not canonical for scalar allocations. The 4261 // latter case prevents the type from mutating when round-tripping through 4262 // assembly. 4263 if (!AI->getArraySize() || AI->isArrayAllocation() || 4264 !AI->getArraySize()->getType()->isIntegerTy(32)) { 4265 Out << ", "; 4266 writeOperand(AI->getArraySize(), true); 4267 } 4268 if (AI->getAlignment()) { 4269 Out << ", align " << AI->getAlignment(); 4270 } 4271 4272 unsigned AddrSpace = AI->getType()->getAddressSpace(); 4273 if (AddrSpace != 0) { 4274 Out << ", addrspace(" << AddrSpace << ')'; 4275 } 4276 } else if (isa<CastInst>(I)) { 4277 if (Operand) { 4278 Out << ' '; 4279 writeOperand(Operand, true); // Work with broken code 4280 } 4281 Out << " to "; 4282 TypePrinter.print(I.getType(), Out); 4283 } else if (isa<VAArgInst>(I)) { 4284 if (Operand) { 4285 Out << ' '; 4286 writeOperand(Operand, true); // Work with broken code 4287 } 4288 Out << ", "; 4289 TypePrinter.print(I.getType(), Out); 4290 } else if (Operand) { // Print the normal way. 4291 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 4292 Out << ' '; 4293 TypePrinter.print(GEP->getSourceElementType(), Out); 4294 Out << ','; 4295 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) { 4296 Out << ' '; 4297 TypePrinter.print(LI->getType(), Out); 4298 Out << ','; 4299 } 4300 4301 // PrintAllTypes - Instructions who have operands of all the same type 4302 // omit the type from all but the first operand. If the instruction has 4303 // different type operands (for example br), then they are all printed. 4304 bool PrintAllTypes = false; 4305 Type *TheType = Operand->getType(); 4306 4307 // Select, Store and ShuffleVector always print all types. 4308 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I) 4309 || isa<ReturnInst>(I)) { 4310 PrintAllTypes = true; 4311 } else { 4312 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) { 4313 Operand = I.getOperand(i); 4314 // note that Operand shouldn't be null, but the test helps make dump() 4315 // more tolerant of malformed IR 4316 if (Operand && Operand->getType() != TheType) { 4317 PrintAllTypes = true; // We have differing types! Print them all! 4318 break; 4319 } 4320 } 4321 } 4322 4323 if (!PrintAllTypes) { 4324 Out << ' '; 4325 TypePrinter.print(TheType, Out); 4326 } 4327 4328 Out << ' '; 4329 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) { 4330 if (i) Out << ", "; 4331 writeOperand(I.getOperand(i), PrintAllTypes); 4332 } 4333 } 4334 4335 // Print atomic ordering/alignment for memory operations 4336 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) { 4337 if (LI->isAtomic()) 4338 writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID()); 4339 if (LI->getAlignment()) 4340 Out << ", align " << LI->getAlignment(); 4341 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) { 4342 if (SI->isAtomic()) 4343 writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID()); 4344 if (SI->getAlignment()) 4345 Out << ", align " << SI->getAlignment(); 4346 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) { 4347 writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(), 4348 CXI->getFailureOrdering(), CXI->getSyncScopeID()); 4349 Out << ", align " << CXI->getAlign().value(); 4350 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) { 4351 writeAtomic(RMWI->getContext(), RMWI->getOrdering(), 4352 RMWI->getSyncScopeID()); 4353 Out << ", align " << RMWI->getAlign().value(); 4354 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) { 4355 writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID()); 4356 } else if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(&I)) { 4357 PrintShuffleMask(Out, SVI->getType(), SVI->getShuffleMask()); 4358 } 4359 4360 // Print Metadata info. 4361 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD; 4362 I.getAllMetadata(InstMD); 4363 printMetadataAttachments(InstMD, ", "); 4364 4365 // Print a nice comment. 4366 printInfoComment(I); 4367 } 4368 4369 void AssemblyWriter::printMetadataAttachments( 4370 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs, 4371 StringRef Separator) { 4372 if (MDs.empty()) 4373 return; 4374 4375 if (MDNames.empty()) 4376 MDs[0].second->getContext().getMDKindNames(MDNames); 4377 4378 for (const auto &I : MDs) { 4379 unsigned Kind = I.first; 4380 Out << Separator; 4381 if (Kind < MDNames.size()) { 4382 Out << "!"; 4383 printMetadataIdentifier(MDNames[Kind], Out); 4384 } else 4385 Out << "!<unknown kind #" << Kind << ">"; 4386 Out << ' '; 4387 WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule); 4388 } 4389 } 4390 4391 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) { 4392 Out << '!' << Slot << " = "; 4393 printMDNodeBody(Node); 4394 Out << "\n"; 4395 } 4396 4397 void AssemblyWriter::writeAllMDNodes() { 4398 SmallVector<const MDNode *, 16> Nodes; 4399 Nodes.resize(Machine.mdn_size()); 4400 for (auto &I : llvm::make_range(Machine.mdn_begin(), Machine.mdn_end())) 4401 Nodes[I.second] = cast<MDNode>(I.first); 4402 4403 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) { 4404 writeMDNode(i, Nodes[i]); 4405 } 4406 } 4407 4408 void AssemblyWriter::printMDNodeBody(const MDNode *Node) { 4409 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule); 4410 } 4411 4412 void AssemblyWriter::writeAttribute(const Attribute &Attr, bool InAttrGroup) { 4413 if (!Attr.isTypeAttribute()) { 4414 Out << Attr.getAsString(InAttrGroup); 4415 return; 4416 } 4417 4418 Out << Attribute::getNameFromAttrKind(Attr.getKindAsEnum()); 4419 if (Type *Ty = Attr.getValueAsType()) { 4420 Out << '('; 4421 TypePrinter.print(Ty, Out); 4422 Out << ')'; 4423 } 4424 } 4425 4426 void AssemblyWriter::writeAttributeSet(const AttributeSet &AttrSet, 4427 bool InAttrGroup) { 4428 bool FirstAttr = true; 4429 for (const auto &Attr : AttrSet) { 4430 if (!FirstAttr) 4431 Out << ' '; 4432 writeAttribute(Attr, InAttrGroup); 4433 FirstAttr = false; 4434 } 4435 } 4436 4437 void AssemblyWriter::writeAllAttributeGroups() { 4438 std::vector<std::pair<AttributeSet, unsigned>> asVec; 4439 asVec.resize(Machine.as_size()); 4440 4441 for (auto &I : llvm::make_range(Machine.as_begin(), Machine.as_end())) 4442 asVec[I.second] = I; 4443 4444 for (const auto &I : asVec) 4445 Out << "attributes #" << I.second << " = { " 4446 << I.first.getAsString(true) << " }\n"; 4447 } 4448 4449 void AssemblyWriter::printUseListOrder(const Value *V, 4450 const std::vector<unsigned> &Shuffle) { 4451 bool IsInFunction = Machine.getFunction(); 4452 if (IsInFunction) 4453 Out << " "; 4454 4455 Out << "uselistorder"; 4456 if (const BasicBlock *BB = IsInFunction ? nullptr : dyn_cast<BasicBlock>(V)) { 4457 Out << "_bb "; 4458 writeOperand(BB->getParent(), false); 4459 Out << ", "; 4460 writeOperand(BB, false); 4461 } else { 4462 Out << " "; 4463 writeOperand(V, true); 4464 } 4465 Out << ", { "; 4466 4467 assert(Shuffle.size() >= 2 && "Shuffle too small"); 4468 Out << Shuffle[0]; 4469 for (unsigned I = 1, E = Shuffle.size(); I != E; ++I) 4470 Out << ", " << Shuffle[I]; 4471 Out << " }\n"; 4472 } 4473 4474 void AssemblyWriter::printUseLists(const Function *F) { 4475 auto It = UseListOrders.find(F); 4476 if (It == UseListOrders.end()) 4477 return; 4478 4479 Out << "\n; uselistorder directives\n"; 4480 for (const auto &Pair : It->second) 4481 printUseListOrder(Pair.first, Pair.second); 4482 } 4483 4484 //===----------------------------------------------------------------------===// 4485 // External Interface declarations 4486 //===----------------------------------------------------------------------===// 4487 4488 void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW, 4489 bool ShouldPreserveUseListOrder, 4490 bool IsForDebug) const { 4491 SlotTracker SlotTable(this->getParent()); 4492 formatted_raw_ostream OS(ROS); 4493 AssemblyWriter W(OS, SlotTable, this->getParent(), AAW, 4494 IsForDebug, 4495 ShouldPreserveUseListOrder); 4496 W.printFunction(this); 4497 } 4498 4499 void BasicBlock::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW, 4500 bool ShouldPreserveUseListOrder, 4501 bool IsForDebug) const { 4502 SlotTracker SlotTable(this->getParent()); 4503 formatted_raw_ostream OS(ROS); 4504 AssemblyWriter W(OS, SlotTable, this->getModule(), AAW, 4505 IsForDebug, 4506 ShouldPreserveUseListOrder); 4507 W.printBasicBlock(this); 4508 } 4509 4510 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW, 4511 bool ShouldPreserveUseListOrder, bool IsForDebug) const { 4512 SlotTracker SlotTable(this); 4513 formatted_raw_ostream OS(ROS); 4514 AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug, 4515 ShouldPreserveUseListOrder); 4516 W.printModule(this); 4517 } 4518 4519 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const { 4520 SlotTracker SlotTable(getParent()); 4521 formatted_raw_ostream OS(ROS); 4522 AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug); 4523 W.printNamedMDNode(this); 4524 } 4525 4526 void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST, 4527 bool IsForDebug) const { 4528 Optional<SlotTracker> LocalST; 4529 SlotTracker *SlotTable; 4530 if (auto *ST = MST.getMachine()) 4531 SlotTable = ST; 4532 else { 4533 LocalST.emplace(getParent()); 4534 SlotTable = &*LocalST; 4535 } 4536 4537 formatted_raw_ostream OS(ROS); 4538 AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug); 4539 W.printNamedMDNode(this); 4540 } 4541 4542 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const { 4543 PrintLLVMName(ROS, getName(), ComdatPrefix); 4544 ROS << " = comdat "; 4545 4546 switch (getSelectionKind()) { 4547 case Comdat::Any: 4548 ROS << "any"; 4549 break; 4550 case Comdat::ExactMatch: 4551 ROS << "exactmatch"; 4552 break; 4553 case Comdat::Largest: 4554 ROS << "largest"; 4555 break; 4556 case Comdat::NoDeduplicate: 4557 ROS << "nodeduplicate"; 4558 break; 4559 case Comdat::SameSize: 4560 ROS << "samesize"; 4561 break; 4562 } 4563 4564 ROS << '\n'; 4565 } 4566 4567 void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const { 4568 TypePrinting TP; 4569 TP.print(const_cast<Type*>(this), OS); 4570 4571 if (NoDetails) 4572 return; 4573 4574 // If the type is a named struct type, print the body as well. 4575 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this))) 4576 if (!STy->isLiteral()) { 4577 OS << " = type "; 4578 TP.printStructBody(STy, OS); 4579 } 4580 } 4581 4582 static bool isReferencingMDNode(const Instruction &I) { 4583 if (const auto *CI = dyn_cast<CallInst>(&I)) 4584 if (Function *F = CI->getCalledFunction()) 4585 if (F->isIntrinsic()) 4586 for (auto &Op : I.operands()) 4587 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op)) 4588 if (isa<MDNode>(V->getMetadata())) 4589 return true; 4590 return false; 4591 } 4592 4593 void Value::print(raw_ostream &ROS, bool IsForDebug) const { 4594 bool ShouldInitializeAllMetadata = false; 4595 if (auto *I = dyn_cast<Instruction>(this)) 4596 ShouldInitializeAllMetadata = isReferencingMDNode(*I); 4597 else if (isa<Function>(this) || isa<MetadataAsValue>(this)) 4598 ShouldInitializeAllMetadata = true; 4599 4600 ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata); 4601 print(ROS, MST, IsForDebug); 4602 } 4603 4604 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST, 4605 bool IsForDebug) const { 4606 formatted_raw_ostream OS(ROS); 4607 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr)); 4608 SlotTracker &SlotTable = 4609 MST.getMachine() ? *MST.getMachine() : EmptySlotTable; 4610 auto incorporateFunction = [&](const Function *F) { 4611 if (F) 4612 MST.incorporateFunction(*F); 4613 }; 4614 4615 if (const Instruction *I = dyn_cast<Instruction>(this)) { 4616 incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr); 4617 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug); 4618 W.printInstruction(*I); 4619 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) { 4620 incorporateFunction(BB->getParent()); 4621 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug); 4622 W.printBasicBlock(BB); 4623 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) { 4624 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug); 4625 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV)) 4626 W.printGlobal(V); 4627 else if (const Function *F = dyn_cast<Function>(GV)) 4628 W.printFunction(F); 4629 else 4630 W.printIndirectSymbol(cast<GlobalIndirectSymbol>(GV)); 4631 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) { 4632 V->getMetadata()->print(ROS, MST, getModuleFromVal(V)); 4633 } else if (const Constant *C = dyn_cast<Constant>(this)) { 4634 TypePrinting TypePrinter; 4635 TypePrinter.print(C->getType(), OS); 4636 OS << ' '; 4637 WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr); 4638 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) { 4639 this->printAsOperand(OS, /* PrintType */ true, MST); 4640 } else { 4641 llvm_unreachable("Unknown value to print out!"); 4642 } 4643 } 4644 4645 /// Print without a type, skipping the TypePrinting object. 4646 /// 4647 /// \return \c true iff printing was successful. 4648 static bool printWithoutType(const Value &V, raw_ostream &O, 4649 SlotTracker *Machine, const Module *M) { 4650 if (V.hasName() || isa<GlobalValue>(V) || 4651 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) { 4652 WriteAsOperandInternal(O, &V, nullptr, Machine, M); 4653 return true; 4654 } 4655 return false; 4656 } 4657 4658 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType, 4659 ModuleSlotTracker &MST) { 4660 TypePrinting TypePrinter(MST.getModule()); 4661 if (PrintType) { 4662 TypePrinter.print(V.getType(), O); 4663 O << ' '; 4664 } 4665 4666 WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(), 4667 MST.getModule()); 4668 } 4669 4670 void Value::printAsOperand(raw_ostream &O, bool PrintType, 4671 const Module *M) const { 4672 if (!M) 4673 M = getModuleFromVal(this); 4674 4675 if (!PrintType) 4676 if (printWithoutType(*this, O, nullptr, M)) 4677 return; 4678 4679 SlotTracker Machine( 4680 M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this)); 4681 ModuleSlotTracker MST(Machine, M); 4682 printAsOperandImpl(*this, O, PrintType, MST); 4683 } 4684 4685 void Value::printAsOperand(raw_ostream &O, bool PrintType, 4686 ModuleSlotTracker &MST) const { 4687 if (!PrintType) 4688 if (printWithoutType(*this, O, MST.getMachine(), MST.getModule())) 4689 return; 4690 4691 printAsOperandImpl(*this, O, PrintType, MST); 4692 } 4693 4694 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD, 4695 ModuleSlotTracker &MST, const Module *M, 4696 bool OnlyAsOperand) { 4697 formatted_raw_ostream OS(ROS); 4698 4699 TypePrinting TypePrinter(M); 4700 4701 WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M, 4702 /* FromValue */ true); 4703 4704 auto *N = dyn_cast<MDNode>(&MD); 4705 if (OnlyAsOperand || !N || isa<DIExpression>(MD) || isa<DIArgList>(MD)) 4706 return; 4707 4708 OS << " = "; 4709 WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M); 4710 } 4711 4712 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const { 4713 ModuleSlotTracker MST(M, isa<MDNode>(this)); 4714 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true); 4715 } 4716 4717 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST, 4718 const Module *M) const { 4719 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true); 4720 } 4721 4722 void Metadata::print(raw_ostream &OS, const Module *M, 4723 bool /*IsForDebug*/) const { 4724 ModuleSlotTracker MST(M, isa<MDNode>(this)); 4725 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false); 4726 } 4727 4728 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST, 4729 const Module *M, bool /*IsForDebug*/) const { 4730 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false); 4731 } 4732 4733 void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const { 4734 SlotTracker SlotTable(this); 4735 formatted_raw_ostream OS(ROS); 4736 AssemblyWriter W(OS, SlotTable, this, IsForDebug); 4737 W.printModuleSummaryIndex(); 4738 } 4739 4740 void ModuleSlotTracker::collectMDNodes(MachineMDNodeListType &L, unsigned LB, 4741 unsigned UB) const { 4742 SlotTracker *ST = MachineStorage.get(); 4743 if (!ST) 4744 return; 4745 4746 for (auto &I : llvm::make_range(ST->mdn_begin(), ST->mdn_end())) 4747 if (I.second >= LB && I.second < UB) 4748 L.push_back(std::make_pair(I.second, I.first)); 4749 } 4750 4751 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 4752 // Value::dump - allow easy printing of Values from the debugger. 4753 LLVM_DUMP_METHOD 4754 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; } 4755 4756 // Type::dump - allow easy printing of Types from the debugger. 4757 LLVM_DUMP_METHOD 4758 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; } 4759 4760 // Module::dump() - Allow printing of Modules from the debugger. 4761 LLVM_DUMP_METHOD 4762 void Module::dump() const { 4763 print(dbgs(), nullptr, 4764 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true); 4765 } 4766 4767 // Allow printing of Comdats from the debugger. 4768 LLVM_DUMP_METHOD 4769 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); } 4770 4771 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger. 4772 LLVM_DUMP_METHOD 4773 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); } 4774 4775 LLVM_DUMP_METHOD 4776 void Metadata::dump() const { dump(nullptr); } 4777 4778 LLVM_DUMP_METHOD 4779 void Metadata::dump(const Module *M) const { 4780 print(dbgs(), M, /*IsForDebug=*/true); 4781 dbgs() << '\n'; 4782 } 4783 4784 // Allow printing of ModuleSummaryIndex from the debugger. 4785 LLVM_DUMP_METHOD 4786 void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); } 4787 #endif 4788