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