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