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->hasIndices()) 1594 for (unsigned I : CE->getIndices()) 1595 Out << ", " << I; 1596 1597 if (CE->isCast()) { 1598 Out << " to "; 1599 WriterCtx.TypePrinter->print(CE->getType(), Out); 1600 } 1601 1602 if (CE->getOpcode() == Instruction::ShuffleVector) 1603 PrintShuffleMask(Out, CE->getType(), CE->getShuffleMask()); 1604 1605 Out << ')'; 1606 return; 1607 } 1608 1609 Out << "<placeholder or erroneous Constant>"; 1610 } 1611 1612 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node, 1613 AsmWriterContext &WriterCtx) { 1614 Out << "!{"; 1615 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) { 1616 const Metadata *MD = Node->getOperand(mi); 1617 if (!MD) 1618 Out << "null"; 1619 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) { 1620 Value *V = MDV->getValue(); 1621 WriterCtx.TypePrinter->print(V->getType(), Out); 1622 Out << ' '; 1623 WriteAsOperandInternal(Out, V, WriterCtx); 1624 } else { 1625 WriteAsOperandInternal(Out, MD, WriterCtx); 1626 WriterCtx.onWriteMetadataAsOperand(MD); 1627 } 1628 if (mi + 1 != me) 1629 Out << ", "; 1630 } 1631 1632 Out << "}"; 1633 } 1634 1635 namespace { 1636 1637 struct FieldSeparator { 1638 bool Skip = true; 1639 const char *Sep; 1640 1641 FieldSeparator(const char *Sep = ", ") : Sep(Sep) {} 1642 }; 1643 1644 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) { 1645 if (FS.Skip) { 1646 FS.Skip = false; 1647 return OS; 1648 } 1649 return OS << FS.Sep; 1650 } 1651 1652 struct MDFieldPrinter { 1653 raw_ostream &Out; 1654 FieldSeparator FS; 1655 AsmWriterContext &WriterCtx; 1656 1657 explicit MDFieldPrinter(raw_ostream &Out) 1658 : Out(Out), WriterCtx(AsmWriterContext::getEmpty()) {} 1659 MDFieldPrinter(raw_ostream &Out, AsmWriterContext &Ctx) 1660 : Out(Out), WriterCtx(Ctx) {} 1661 1662 void printTag(const DINode *N); 1663 void printMacinfoType(const DIMacroNode *N); 1664 void printChecksum(const DIFile::ChecksumInfo<StringRef> &N); 1665 void printString(StringRef Name, StringRef Value, 1666 bool ShouldSkipEmpty = true); 1667 void printMetadata(StringRef Name, const Metadata *MD, 1668 bool ShouldSkipNull = true); 1669 template <class IntTy> 1670 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true); 1671 void printAPInt(StringRef Name, const APInt &Int, bool IsUnsigned, 1672 bool ShouldSkipZero); 1673 void printBool(StringRef Name, bool Value, Optional<bool> Default = None); 1674 void printDIFlags(StringRef Name, DINode::DIFlags Flags); 1675 void printDISPFlags(StringRef Name, DISubprogram::DISPFlags Flags); 1676 template <class IntTy, class Stringifier> 1677 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString, 1678 bool ShouldSkipZero = true); 1679 void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK); 1680 void printNameTableKind(StringRef Name, 1681 DICompileUnit::DebugNameTableKind NTK); 1682 }; 1683 1684 } // end anonymous namespace 1685 1686 void MDFieldPrinter::printTag(const DINode *N) { 1687 Out << FS << "tag: "; 1688 auto Tag = dwarf::TagString(N->getTag()); 1689 if (!Tag.empty()) 1690 Out << Tag; 1691 else 1692 Out << N->getTag(); 1693 } 1694 1695 void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) { 1696 Out << FS << "type: "; 1697 auto Type = dwarf::MacinfoString(N->getMacinfoType()); 1698 if (!Type.empty()) 1699 Out << Type; 1700 else 1701 Out << N->getMacinfoType(); 1702 } 1703 1704 void MDFieldPrinter::printChecksum( 1705 const DIFile::ChecksumInfo<StringRef> &Checksum) { 1706 Out << FS << "checksumkind: " << Checksum.getKindAsString(); 1707 printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false); 1708 } 1709 1710 void MDFieldPrinter::printString(StringRef Name, StringRef Value, 1711 bool ShouldSkipEmpty) { 1712 if (ShouldSkipEmpty && Value.empty()) 1713 return; 1714 1715 Out << FS << Name << ": \""; 1716 printEscapedString(Value, Out); 1717 Out << "\""; 1718 } 1719 1720 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD, 1721 AsmWriterContext &WriterCtx) { 1722 if (!MD) { 1723 Out << "null"; 1724 return; 1725 } 1726 WriteAsOperandInternal(Out, MD, WriterCtx); 1727 WriterCtx.onWriteMetadataAsOperand(MD); 1728 } 1729 1730 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD, 1731 bool ShouldSkipNull) { 1732 if (ShouldSkipNull && !MD) 1733 return; 1734 1735 Out << FS << Name << ": "; 1736 writeMetadataAsOperand(Out, MD, WriterCtx); 1737 } 1738 1739 template <class IntTy> 1740 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) { 1741 if (ShouldSkipZero && !Int) 1742 return; 1743 1744 Out << FS << Name << ": " << Int; 1745 } 1746 1747 void MDFieldPrinter::printAPInt(StringRef Name, const APInt &Int, 1748 bool IsUnsigned, bool ShouldSkipZero) { 1749 if (ShouldSkipZero && Int.isZero()) 1750 return; 1751 1752 Out << FS << Name << ": "; 1753 Int.print(Out, !IsUnsigned); 1754 } 1755 1756 void MDFieldPrinter::printBool(StringRef Name, bool Value, 1757 Optional<bool> Default) { 1758 if (Default && Value == *Default) 1759 return; 1760 Out << FS << Name << ": " << (Value ? "true" : "false"); 1761 } 1762 1763 void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) { 1764 if (!Flags) 1765 return; 1766 1767 Out << FS << Name << ": "; 1768 1769 SmallVector<DINode::DIFlags, 8> SplitFlags; 1770 auto Extra = DINode::splitFlags(Flags, SplitFlags); 1771 1772 FieldSeparator FlagsFS(" | "); 1773 for (auto F : SplitFlags) { 1774 auto StringF = DINode::getFlagString(F); 1775 assert(!StringF.empty() && "Expected valid flag"); 1776 Out << FlagsFS << StringF; 1777 } 1778 if (Extra || SplitFlags.empty()) 1779 Out << FlagsFS << Extra; 1780 } 1781 1782 void MDFieldPrinter::printDISPFlags(StringRef Name, 1783 DISubprogram::DISPFlags Flags) { 1784 // Always print this field, because no flags in the IR at all will be 1785 // interpreted as old-style isDefinition: true. 1786 Out << FS << Name << ": "; 1787 1788 if (!Flags) { 1789 Out << 0; 1790 return; 1791 } 1792 1793 SmallVector<DISubprogram::DISPFlags, 8> SplitFlags; 1794 auto Extra = DISubprogram::splitFlags(Flags, SplitFlags); 1795 1796 FieldSeparator FlagsFS(" | "); 1797 for (auto F : SplitFlags) { 1798 auto StringF = DISubprogram::getFlagString(F); 1799 assert(!StringF.empty() && "Expected valid flag"); 1800 Out << FlagsFS << StringF; 1801 } 1802 if (Extra || SplitFlags.empty()) 1803 Out << FlagsFS << Extra; 1804 } 1805 1806 void MDFieldPrinter::printEmissionKind(StringRef Name, 1807 DICompileUnit::DebugEmissionKind EK) { 1808 Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK); 1809 } 1810 1811 void MDFieldPrinter::printNameTableKind(StringRef Name, 1812 DICompileUnit::DebugNameTableKind NTK) { 1813 if (NTK == DICompileUnit::DebugNameTableKind::Default) 1814 return; 1815 Out << FS << Name << ": " << DICompileUnit::nameTableKindString(NTK); 1816 } 1817 1818 template <class IntTy, class Stringifier> 1819 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value, 1820 Stringifier toString, bool ShouldSkipZero) { 1821 if (!Value) 1822 return; 1823 1824 Out << FS << Name << ": "; 1825 auto S = toString(Value); 1826 if (!S.empty()) 1827 Out << S; 1828 else 1829 Out << Value; 1830 } 1831 1832 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N, 1833 AsmWriterContext &WriterCtx) { 1834 Out << "!GenericDINode("; 1835 MDFieldPrinter Printer(Out, WriterCtx); 1836 Printer.printTag(N); 1837 Printer.printString("header", N->getHeader()); 1838 if (N->getNumDwarfOperands()) { 1839 Out << Printer.FS << "operands: {"; 1840 FieldSeparator IFS; 1841 for (auto &I : N->dwarf_operands()) { 1842 Out << IFS; 1843 writeMetadataAsOperand(Out, I, WriterCtx); 1844 } 1845 Out << "}"; 1846 } 1847 Out << ")"; 1848 } 1849 1850 static void writeDILocation(raw_ostream &Out, const DILocation *DL, 1851 AsmWriterContext &WriterCtx) { 1852 Out << "!DILocation("; 1853 MDFieldPrinter Printer(Out, WriterCtx); 1854 // Always output the line, since 0 is a relevant and important value for it. 1855 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false); 1856 Printer.printInt("column", DL->getColumn()); 1857 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false); 1858 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt()); 1859 Printer.printBool("isImplicitCode", DL->isImplicitCode(), 1860 /* Default */ false); 1861 Out << ")"; 1862 } 1863 1864 static void writeDISubrange(raw_ostream &Out, const DISubrange *N, 1865 AsmWriterContext &WriterCtx) { 1866 Out << "!DISubrange("; 1867 MDFieldPrinter Printer(Out, WriterCtx); 1868 1869 auto *Count = N->getRawCountNode(); 1870 if (auto *CE = dyn_cast_or_null<ConstantAsMetadata>(Count)) { 1871 auto *CV = cast<ConstantInt>(CE->getValue()); 1872 Printer.printInt("count", CV->getSExtValue(), 1873 /* ShouldSkipZero */ false); 1874 } else 1875 Printer.printMetadata("count", Count, /*ShouldSkipNull */ true); 1876 1877 // A lowerBound of constant 0 should not be skipped, since it is different 1878 // from an unspecified lower bound (= nullptr). 1879 auto *LBound = N->getRawLowerBound(); 1880 if (auto *LE = dyn_cast_or_null<ConstantAsMetadata>(LBound)) { 1881 auto *LV = cast<ConstantInt>(LE->getValue()); 1882 Printer.printInt("lowerBound", LV->getSExtValue(), 1883 /* ShouldSkipZero */ false); 1884 } else 1885 Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true); 1886 1887 auto *UBound = N->getRawUpperBound(); 1888 if (auto *UE = dyn_cast_or_null<ConstantAsMetadata>(UBound)) { 1889 auto *UV = cast<ConstantInt>(UE->getValue()); 1890 Printer.printInt("upperBound", UV->getSExtValue(), 1891 /* ShouldSkipZero */ false); 1892 } else 1893 Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true); 1894 1895 auto *Stride = N->getRawStride(); 1896 if (auto *SE = dyn_cast_or_null<ConstantAsMetadata>(Stride)) { 1897 auto *SV = cast<ConstantInt>(SE->getValue()); 1898 Printer.printInt("stride", SV->getSExtValue(), /* ShouldSkipZero */ false); 1899 } else 1900 Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true); 1901 1902 Out << ")"; 1903 } 1904 1905 static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N, 1906 AsmWriterContext &WriterCtx) { 1907 Out << "!DIGenericSubrange("; 1908 MDFieldPrinter Printer(Out, WriterCtx); 1909 1910 auto IsConstant = [&](Metadata *Bound) -> bool { 1911 if (auto *BE = dyn_cast_or_null<DIExpression>(Bound)) { 1912 return BE->isConstant() && 1913 DIExpression::SignedOrUnsignedConstant::SignedConstant == 1914 *BE->isConstant(); 1915 } 1916 return false; 1917 }; 1918 1919 auto GetConstant = [&](Metadata *Bound) -> int64_t { 1920 assert(IsConstant(Bound) && "Expected constant"); 1921 auto *BE = dyn_cast_or_null<DIExpression>(Bound); 1922 return static_cast<int64_t>(BE->getElement(1)); 1923 }; 1924 1925 auto *Count = N->getRawCountNode(); 1926 if (IsConstant(Count)) 1927 Printer.printInt("count", GetConstant(Count), 1928 /* ShouldSkipZero */ false); 1929 else 1930 Printer.printMetadata("count", Count, /*ShouldSkipNull */ true); 1931 1932 auto *LBound = N->getRawLowerBound(); 1933 if (IsConstant(LBound)) 1934 Printer.printInt("lowerBound", GetConstant(LBound), 1935 /* ShouldSkipZero */ false); 1936 else 1937 Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true); 1938 1939 auto *UBound = N->getRawUpperBound(); 1940 if (IsConstant(UBound)) 1941 Printer.printInt("upperBound", GetConstant(UBound), 1942 /* ShouldSkipZero */ false); 1943 else 1944 Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true); 1945 1946 auto *Stride = N->getRawStride(); 1947 if (IsConstant(Stride)) 1948 Printer.printInt("stride", GetConstant(Stride), 1949 /* ShouldSkipZero */ false); 1950 else 1951 Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true); 1952 1953 Out << ")"; 1954 } 1955 1956 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N, 1957 AsmWriterContext &) { 1958 Out << "!DIEnumerator("; 1959 MDFieldPrinter Printer(Out); 1960 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false); 1961 Printer.printAPInt("value", N->getValue(), N->isUnsigned(), 1962 /*ShouldSkipZero=*/false); 1963 if (N->isUnsigned()) 1964 Printer.printBool("isUnsigned", true); 1965 Out << ")"; 1966 } 1967 1968 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N, 1969 AsmWriterContext &) { 1970 Out << "!DIBasicType("; 1971 MDFieldPrinter Printer(Out); 1972 if (N->getTag() != dwarf::DW_TAG_base_type) 1973 Printer.printTag(N); 1974 Printer.printString("name", N->getName()); 1975 Printer.printInt("size", N->getSizeInBits()); 1976 Printer.printInt("align", N->getAlignInBits()); 1977 Printer.printDwarfEnum("encoding", N->getEncoding(), 1978 dwarf::AttributeEncodingString); 1979 Printer.printDIFlags("flags", N->getFlags()); 1980 Out << ")"; 1981 } 1982 1983 static void writeDIStringType(raw_ostream &Out, const DIStringType *N, 1984 AsmWriterContext &WriterCtx) { 1985 Out << "!DIStringType("; 1986 MDFieldPrinter Printer(Out, WriterCtx); 1987 if (N->getTag() != dwarf::DW_TAG_string_type) 1988 Printer.printTag(N); 1989 Printer.printString("name", N->getName()); 1990 Printer.printMetadata("stringLength", N->getRawStringLength()); 1991 Printer.printMetadata("stringLengthExpression", N->getRawStringLengthExp()); 1992 Printer.printMetadata("stringLocationExpression", 1993 N->getRawStringLocationExp()); 1994 Printer.printInt("size", N->getSizeInBits()); 1995 Printer.printInt("align", N->getAlignInBits()); 1996 Printer.printDwarfEnum("encoding", N->getEncoding(), 1997 dwarf::AttributeEncodingString); 1998 Out << ")"; 1999 } 2000 2001 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N, 2002 AsmWriterContext &WriterCtx) { 2003 Out << "!DIDerivedType("; 2004 MDFieldPrinter Printer(Out, WriterCtx); 2005 Printer.printTag(N); 2006 Printer.printString("name", N->getName()); 2007 Printer.printMetadata("scope", N->getRawScope()); 2008 Printer.printMetadata("file", N->getRawFile()); 2009 Printer.printInt("line", N->getLine()); 2010 Printer.printMetadata("baseType", N->getRawBaseType(), 2011 /* ShouldSkipNull */ false); 2012 Printer.printInt("size", N->getSizeInBits()); 2013 Printer.printInt("align", N->getAlignInBits()); 2014 Printer.printInt("offset", N->getOffsetInBits()); 2015 Printer.printDIFlags("flags", N->getFlags()); 2016 Printer.printMetadata("extraData", N->getRawExtraData()); 2017 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace()) 2018 Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace, 2019 /* ShouldSkipZero */ false); 2020 Printer.printMetadata("annotations", N->getRawAnnotations()); 2021 Out << ")"; 2022 } 2023 2024 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N, 2025 AsmWriterContext &WriterCtx) { 2026 Out << "!DICompositeType("; 2027 MDFieldPrinter Printer(Out, WriterCtx); 2028 Printer.printTag(N); 2029 Printer.printString("name", N->getName()); 2030 Printer.printMetadata("scope", N->getRawScope()); 2031 Printer.printMetadata("file", N->getRawFile()); 2032 Printer.printInt("line", N->getLine()); 2033 Printer.printMetadata("baseType", N->getRawBaseType()); 2034 Printer.printInt("size", N->getSizeInBits()); 2035 Printer.printInt("align", N->getAlignInBits()); 2036 Printer.printInt("offset", N->getOffsetInBits()); 2037 Printer.printDIFlags("flags", N->getFlags()); 2038 Printer.printMetadata("elements", N->getRawElements()); 2039 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(), 2040 dwarf::LanguageString); 2041 Printer.printMetadata("vtableHolder", N->getRawVTableHolder()); 2042 Printer.printMetadata("templateParams", N->getRawTemplateParams()); 2043 Printer.printString("identifier", N->getIdentifier()); 2044 Printer.printMetadata("discriminator", N->getRawDiscriminator()); 2045 Printer.printMetadata("dataLocation", N->getRawDataLocation()); 2046 Printer.printMetadata("associated", N->getRawAssociated()); 2047 Printer.printMetadata("allocated", N->getRawAllocated()); 2048 if (auto *RankConst = N->getRankConst()) 2049 Printer.printInt("rank", RankConst->getSExtValue(), 2050 /* ShouldSkipZero */ false); 2051 else 2052 Printer.printMetadata("rank", N->getRawRank(), /*ShouldSkipNull */ true); 2053 Printer.printMetadata("annotations", N->getRawAnnotations()); 2054 Out << ")"; 2055 } 2056 2057 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N, 2058 AsmWriterContext &WriterCtx) { 2059 Out << "!DISubroutineType("; 2060 MDFieldPrinter Printer(Out, WriterCtx); 2061 Printer.printDIFlags("flags", N->getFlags()); 2062 Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString); 2063 Printer.printMetadata("types", N->getRawTypeArray(), 2064 /* ShouldSkipNull */ false); 2065 Out << ")"; 2066 } 2067 2068 static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &) { 2069 Out << "!DIFile("; 2070 MDFieldPrinter Printer(Out); 2071 Printer.printString("filename", N->getFilename(), 2072 /* ShouldSkipEmpty */ false); 2073 Printer.printString("directory", N->getDirectory(), 2074 /* ShouldSkipEmpty */ false); 2075 // Print all values for checksum together, or not at all. 2076 if (N->getChecksum()) 2077 Printer.printChecksum(*N->getChecksum()); 2078 Printer.printString("source", N->getSource().getValueOr(StringRef()), 2079 /* ShouldSkipEmpty */ true); 2080 Out << ")"; 2081 } 2082 2083 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N, 2084 AsmWriterContext &WriterCtx) { 2085 Out << "!DICompileUnit("; 2086 MDFieldPrinter Printer(Out, WriterCtx); 2087 Printer.printDwarfEnum("language", N->getSourceLanguage(), 2088 dwarf::LanguageString, /* ShouldSkipZero */ false); 2089 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false); 2090 Printer.printString("producer", N->getProducer()); 2091 Printer.printBool("isOptimized", N->isOptimized()); 2092 Printer.printString("flags", N->getFlags()); 2093 Printer.printInt("runtimeVersion", N->getRuntimeVersion(), 2094 /* ShouldSkipZero */ false); 2095 Printer.printString("splitDebugFilename", N->getSplitDebugFilename()); 2096 Printer.printEmissionKind("emissionKind", N->getEmissionKind()); 2097 Printer.printMetadata("enums", N->getRawEnumTypes()); 2098 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes()); 2099 Printer.printMetadata("globals", N->getRawGlobalVariables()); 2100 Printer.printMetadata("imports", N->getRawImportedEntities()); 2101 Printer.printMetadata("macros", N->getRawMacros()); 2102 Printer.printInt("dwoId", N->getDWOId()); 2103 Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true); 2104 Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(), 2105 false); 2106 Printer.printNameTableKind("nameTableKind", N->getNameTableKind()); 2107 Printer.printBool("rangesBaseAddress", N->getRangesBaseAddress(), false); 2108 Printer.printString("sysroot", N->getSysRoot()); 2109 Printer.printString("sdk", N->getSDK()); 2110 Out << ")"; 2111 } 2112 2113 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N, 2114 AsmWriterContext &WriterCtx) { 2115 Out << "!DISubprogram("; 2116 MDFieldPrinter Printer(Out, WriterCtx); 2117 Printer.printString("name", N->getName()); 2118 Printer.printString("linkageName", N->getLinkageName()); 2119 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2120 Printer.printMetadata("file", N->getRawFile()); 2121 Printer.printInt("line", N->getLine()); 2122 Printer.printMetadata("type", N->getRawType()); 2123 Printer.printInt("scopeLine", N->getScopeLine()); 2124 Printer.printMetadata("containingType", N->getRawContainingType()); 2125 if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none || 2126 N->getVirtualIndex() != 0) 2127 Printer.printInt("virtualIndex", N->getVirtualIndex(), false); 2128 Printer.printInt("thisAdjustment", N->getThisAdjustment()); 2129 Printer.printDIFlags("flags", N->getFlags()); 2130 Printer.printDISPFlags("spFlags", N->getSPFlags()); 2131 Printer.printMetadata("unit", N->getRawUnit()); 2132 Printer.printMetadata("templateParams", N->getRawTemplateParams()); 2133 Printer.printMetadata("declaration", N->getRawDeclaration()); 2134 Printer.printMetadata("retainedNodes", N->getRawRetainedNodes()); 2135 Printer.printMetadata("thrownTypes", N->getRawThrownTypes()); 2136 Printer.printMetadata("annotations", N->getRawAnnotations()); 2137 Printer.printString("targetFuncName", N->getTargetFuncName()); 2138 Out << ")"; 2139 } 2140 2141 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N, 2142 AsmWriterContext &WriterCtx) { 2143 Out << "!DILexicalBlock("; 2144 MDFieldPrinter Printer(Out, WriterCtx); 2145 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2146 Printer.printMetadata("file", N->getRawFile()); 2147 Printer.printInt("line", N->getLine()); 2148 Printer.printInt("column", N->getColumn()); 2149 Out << ")"; 2150 } 2151 2152 static void writeDILexicalBlockFile(raw_ostream &Out, 2153 const DILexicalBlockFile *N, 2154 AsmWriterContext &WriterCtx) { 2155 Out << "!DILexicalBlockFile("; 2156 MDFieldPrinter Printer(Out, WriterCtx); 2157 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2158 Printer.printMetadata("file", N->getRawFile()); 2159 Printer.printInt("discriminator", N->getDiscriminator(), 2160 /* ShouldSkipZero */ false); 2161 Out << ")"; 2162 } 2163 2164 static void writeDINamespace(raw_ostream &Out, const DINamespace *N, 2165 AsmWriterContext &WriterCtx) { 2166 Out << "!DINamespace("; 2167 MDFieldPrinter Printer(Out, WriterCtx); 2168 Printer.printString("name", N->getName()); 2169 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2170 Printer.printBool("exportSymbols", N->getExportSymbols(), false); 2171 Out << ")"; 2172 } 2173 2174 static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N, 2175 AsmWriterContext &WriterCtx) { 2176 Out << "!DICommonBlock("; 2177 MDFieldPrinter Printer(Out, WriterCtx); 2178 Printer.printMetadata("scope", N->getRawScope(), false); 2179 Printer.printMetadata("declaration", N->getRawDecl(), false); 2180 Printer.printString("name", N->getName()); 2181 Printer.printMetadata("file", N->getRawFile()); 2182 Printer.printInt("line", N->getLineNo()); 2183 Out << ")"; 2184 } 2185 2186 static void writeDIMacro(raw_ostream &Out, const DIMacro *N, 2187 AsmWriterContext &WriterCtx) { 2188 Out << "!DIMacro("; 2189 MDFieldPrinter Printer(Out, WriterCtx); 2190 Printer.printMacinfoType(N); 2191 Printer.printInt("line", N->getLine()); 2192 Printer.printString("name", N->getName()); 2193 Printer.printString("value", N->getValue()); 2194 Out << ")"; 2195 } 2196 2197 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N, 2198 AsmWriterContext &WriterCtx) { 2199 Out << "!DIMacroFile("; 2200 MDFieldPrinter Printer(Out, WriterCtx); 2201 Printer.printInt("line", N->getLine()); 2202 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false); 2203 Printer.printMetadata("nodes", N->getRawElements()); 2204 Out << ")"; 2205 } 2206 2207 static void writeDIModule(raw_ostream &Out, const DIModule *N, 2208 AsmWriterContext &WriterCtx) { 2209 Out << "!DIModule("; 2210 MDFieldPrinter Printer(Out, WriterCtx); 2211 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2212 Printer.printString("name", N->getName()); 2213 Printer.printString("configMacros", N->getConfigurationMacros()); 2214 Printer.printString("includePath", N->getIncludePath()); 2215 Printer.printString("apinotes", N->getAPINotesFile()); 2216 Printer.printMetadata("file", N->getRawFile()); 2217 Printer.printInt("line", N->getLineNo()); 2218 Printer.printBool("isDecl", N->getIsDecl(), /* Default */ false); 2219 Out << ")"; 2220 } 2221 2222 static void writeDITemplateTypeParameter(raw_ostream &Out, 2223 const DITemplateTypeParameter *N, 2224 AsmWriterContext &WriterCtx) { 2225 Out << "!DITemplateTypeParameter("; 2226 MDFieldPrinter Printer(Out, WriterCtx); 2227 Printer.printString("name", N->getName()); 2228 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false); 2229 Printer.printBool("defaulted", N->isDefault(), /* Default= */ false); 2230 Out << ")"; 2231 } 2232 2233 static void writeDITemplateValueParameter(raw_ostream &Out, 2234 const DITemplateValueParameter *N, 2235 AsmWriterContext &WriterCtx) { 2236 Out << "!DITemplateValueParameter("; 2237 MDFieldPrinter Printer(Out, WriterCtx); 2238 if (N->getTag() != dwarf::DW_TAG_template_value_parameter) 2239 Printer.printTag(N); 2240 Printer.printString("name", N->getName()); 2241 Printer.printMetadata("type", N->getRawType()); 2242 Printer.printBool("defaulted", N->isDefault(), /* Default= */ false); 2243 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false); 2244 Out << ")"; 2245 } 2246 2247 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N, 2248 AsmWriterContext &WriterCtx) { 2249 Out << "!DIGlobalVariable("; 2250 MDFieldPrinter Printer(Out, WriterCtx); 2251 Printer.printString("name", N->getName()); 2252 Printer.printString("linkageName", N->getLinkageName()); 2253 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2254 Printer.printMetadata("file", N->getRawFile()); 2255 Printer.printInt("line", N->getLine()); 2256 Printer.printMetadata("type", N->getRawType()); 2257 Printer.printBool("isLocal", N->isLocalToUnit()); 2258 Printer.printBool("isDefinition", N->isDefinition()); 2259 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration()); 2260 Printer.printMetadata("templateParams", N->getRawTemplateParams()); 2261 Printer.printInt("align", N->getAlignInBits()); 2262 Printer.printMetadata("annotations", N->getRawAnnotations()); 2263 Out << ")"; 2264 } 2265 2266 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N, 2267 AsmWriterContext &WriterCtx) { 2268 Out << "!DILocalVariable("; 2269 MDFieldPrinter Printer(Out, WriterCtx); 2270 Printer.printString("name", N->getName()); 2271 Printer.printInt("arg", N->getArg()); 2272 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2273 Printer.printMetadata("file", N->getRawFile()); 2274 Printer.printInt("line", N->getLine()); 2275 Printer.printMetadata("type", N->getRawType()); 2276 Printer.printDIFlags("flags", N->getFlags()); 2277 Printer.printInt("align", N->getAlignInBits()); 2278 Printer.printMetadata("annotations", N->getRawAnnotations()); 2279 Out << ")"; 2280 } 2281 2282 static void writeDILabel(raw_ostream &Out, const DILabel *N, 2283 AsmWriterContext &WriterCtx) { 2284 Out << "!DILabel("; 2285 MDFieldPrinter Printer(Out, WriterCtx); 2286 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2287 Printer.printString("name", N->getName()); 2288 Printer.printMetadata("file", N->getRawFile()); 2289 Printer.printInt("line", N->getLine()); 2290 Out << ")"; 2291 } 2292 2293 static void writeDIExpression(raw_ostream &Out, const DIExpression *N, 2294 AsmWriterContext &WriterCtx) { 2295 Out << "!DIExpression("; 2296 FieldSeparator FS; 2297 if (N->isValid()) { 2298 for (const DIExpression::ExprOperand &Op : N->expr_ops()) { 2299 auto OpStr = dwarf::OperationEncodingString(Op.getOp()); 2300 assert(!OpStr.empty() && "Expected valid opcode"); 2301 2302 Out << FS << OpStr; 2303 if (Op.getOp() == dwarf::DW_OP_LLVM_convert) { 2304 Out << FS << Op.getArg(0); 2305 Out << FS << dwarf::AttributeEncodingString(Op.getArg(1)); 2306 } else { 2307 for (unsigned A = 0, AE = Op.getNumArgs(); A != AE; ++A) 2308 Out << FS << Op.getArg(A); 2309 } 2310 } 2311 } else { 2312 for (const auto &I : N->getElements()) 2313 Out << FS << I; 2314 } 2315 Out << ")"; 2316 } 2317 2318 static void writeDIArgList(raw_ostream &Out, const DIArgList *N, 2319 AsmWriterContext &WriterCtx, 2320 bool FromValue = false) { 2321 assert(FromValue && 2322 "Unexpected DIArgList metadata outside of value argument"); 2323 Out << "!DIArgList("; 2324 FieldSeparator FS; 2325 MDFieldPrinter Printer(Out, WriterCtx); 2326 for (Metadata *Arg : N->getArgs()) { 2327 Out << FS; 2328 WriteAsOperandInternal(Out, Arg, WriterCtx, true); 2329 } 2330 Out << ")"; 2331 } 2332 2333 static void writeDIGlobalVariableExpression(raw_ostream &Out, 2334 const DIGlobalVariableExpression *N, 2335 AsmWriterContext &WriterCtx) { 2336 Out << "!DIGlobalVariableExpression("; 2337 MDFieldPrinter Printer(Out, WriterCtx); 2338 Printer.printMetadata("var", N->getVariable()); 2339 Printer.printMetadata("expr", N->getExpression()); 2340 Out << ")"; 2341 } 2342 2343 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N, 2344 AsmWriterContext &WriterCtx) { 2345 Out << "!DIObjCProperty("; 2346 MDFieldPrinter Printer(Out, WriterCtx); 2347 Printer.printString("name", N->getName()); 2348 Printer.printMetadata("file", N->getRawFile()); 2349 Printer.printInt("line", N->getLine()); 2350 Printer.printString("setter", N->getSetterName()); 2351 Printer.printString("getter", N->getGetterName()); 2352 Printer.printInt("attributes", N->getAttributes()); 2353 Printer.printMetadata("type", N->getRawType()); 2354 Out << ")"; 2355 } 2356 2357 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N, 2358 AsmWriterContext &WriterCtx) { 2359 Out << "!DIImportedEntity("; 2360 MDFieldPrinter Printer(Out, WriterCtx); 2361 Printer.printTag(N); 2362 Printer.printString("name", N->getName()); 2363 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2364 Printer.printMetadata("entity", N->getRawEntity()); 2365 Printer.printMetadata("file", N->getRawFile()); 2366 Printer.printInt("line", N->getLine()); 2367 Printer.printMetadata("elements", N->getRawElements()); 2368 Out << ")"; 2369 } 2370 2371 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node, 2372 AsmWriterContext &Ctx) { 2373 if (Node->isDistinct()) 2374 Out << "distinct "; 2375 else if (Node->isTemporary()) 2376 Out << "<temporary!> "; // Handle broken code. 2377 2378 switch (Node->getMetadataID()) { 2379 default: 2380 llvm_unreachable("Expected uniquable MDNode"); 2381 #define HANDLE_MDNODE_LEAF(CLASS) \ 2382 case Metadata::CLASS##Kind: \ 2383 write##CLASS(Out, cast<CLASS>(Node), Ctx); \ 2384 break; 2385 #include "llvm/IR/Metadata.def" 2386 } 2387 } 2388 2389 // Full implementation of printing a Value as an operand with support for 2390 // TypePrinting, etc. 2391 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, 2392 AsmWriterContext &WriterCtx) { 2393 if (V->hasName()) { 2394 PrintLLVMName(Out, V); 2395 return; 2396 } 2397 2398 const Constant *CV = dyn_cast<Constant>(V); 2399 if (CV && !isa<GlobalValue>(CV)) { 2400 assert(WriterCtx.TypePrinter && "Constants require TypePrinting!"); 2401 WriteConstantInternal(Out, CV, WriterCtx); 2402 return; 2403 } 2404 2405 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 2406 Out << "asm "; 2407 if (IA->hasSideEffects()) 2408 Out << "sideeffect "; 2409 if (IA->isAlignStack()) 2410 Out << "alignstack "; 2411 // We don't emit the AD_ATT dialect as it's the assumed default. 2412 if (IA->getDialect() == InlineAsm::AD_Intel) 2413 Out << "inteldialect "; 2414 if (IA->canThrow()) 2415 Out << "unwind "; 2416 Out << '"'; 2417 printEscapedString(IA->getAsmString(), Out); 2418 Out << "\", \""; 2419 printEscapedString(IA->getConstraintString(), Out); 2420 Out << '"'; 2421 return; 2422 } 2423 2424 if (auto *MD = dyn_cast<MetadataAsValue>(V)) { 2425 WriteAsOperandInternal(Out, MD->getMetadata(), WriterCtx, 2426 /* FromValue */ true); 2427 return; 2428 } 2429 2430 char Prefix = '%'; 2431 int Slot; 2432 auto *Machine = WriterCtx.Machine; 2433 // If we have a SlotTracker, use it. 2434 if (Machine) { 2435 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 2436 Slot = Machine->getGlobalSlot(GV); 2437 Prefix = '@'; 2438 } else { 2439 Slot = Machine->getLocalSlot(V); 2440 2441 // If the local value didn't succeed, then we may be referring to a value 2442 // from a different function. Translate it, as this can happen when using 2443 // address of blocks. 2444 if (Slot == -1) 2445 if ((Machine = createSlotTracker(V))) { 2446 Slot = Machine->getLocalSlot(V); 2447 delete Machine; 2448 } 2449 } 2450 } else if ((Machine = createSlotTracker(V))) { 2451 // Otherwise, create one to get the # and then destroy it. 2452 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 2453 Slot = Machine->getGlobalSlot(GV); 2454 Prefix = '@'; 2455 } else { 2456 Slot = Machine->getLocalSlot(V); 2457 } 2458 delete Machine; 2459 Machine = nullptr; 2460 } else { 2461 Slot = -1; 2462 } 2463 2464 if (Slot != -1) 2465 Out << Prefix << Slot; 2466 else 2467 Out << "<badref>"; 2468 } 2469 2470 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD, 2471 AsmWriterContext &WriterCtx, 2472 bool FromValue) { 2473 // Write DIExpressions and DIArgLists inline when used as a value. Improves 2474 // readability of debug info intrinsics. 2475 if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) { 2476 writeDIExpression(Out, Expr, WriterCtx); 2477 return; 2478 } 2479 if (const DIArgList *ArgList = dyn_cast<DIArgList>(MD)) { 2480 writeDIArgList(Out, ArgList, WriterCtx, FromValue); 2481 return; 2482 } 2483 2484 if (const MDNode *N = dyn_cast<MDNode>(MD)) { 2485 std::unique_ptr<SlotTracker> MachineStorage; 2486 SaveAndRestore<SlotTracker *> SARMachine(WriterCtx.Machine); 2487 if (!WriterCtx.Machine) { 2488 MachineStorage = std::make_unique<SlotTracker>(WriterCtx.Context); 2489 WriterCtx.Machine = MachineStorage.get(); 2490 } 2491 int Slot = WriterCtx.Machine->getMetadataSlot(N); 2492 if (Slot == -1) { 2493 if (const DILocation *Loc = dyn_cast<DILocation>(N)) { 2494 writeDILocation(Out, Loc, WriterCtx); 2495 return; 2496 } 2497 // Give the pointer value instead of "badref", since this comes up all 2498 // the time when debugging. 2499 Out << "<" << N << ">"; 2500 } else 2501 Out << '!' << Slot; 2502 return; 2503 } 2504 2505 if (const MDString *MDS = dyn_cast<MDString>(MD)) { 2506 Out << "!\""; 2507 printEscapedString(MDS->getString(), Out); 2508 Out << '"'; 2509 return; 2510 } 2511 2512 auto *V = cast<ValueAsMetadata>(MD); 2513 assert(WriterCtx.TypePrinter && "TypePrinter required for metadata values"); 2514 assert((FromValue || !isa<LocalAsMetadata>(V)) && 2515 "Unexpected function-local metadata outside of value argument"); 2516 2517 WriterCtx.TypePrinter->print(V->getValue()->getType(), Out); 2518 Out << ' '; 2519 WriteAsOperandInternal(Out, V->getValue(), WriterCtx); 2520 } 2521 2522 namespace { 2523 2524 class AssemblyWriter { 2525 formatted_raw_ostream &Out; 2526 const Module *TheModule = nullptr; 2527 const ModuleSummaryIndex *TheIndex = nullptr; 2528 std::unique_ptr<SlotTracker> SlotTrackerStorage; 2529 SlotTracker &Machine; 2530 TypePrinting TypePrinter; 2531 AssemblyAnnotationWriter *AnnotationWriter = nullptr; 2532 SetVector<const Comdat *> Comdats; 2533 bool IsForDebug; 2534 bool ShouldPreserveUseListOrder; 2535 UseListOrderMap UseListOrders; 2536 SmallVector<StringRef, 8> MDNames; 2537 /// Synchronization scope names registered with LLVMContext. 2538 SmallVector<StringRef, 8> SSNs; 2539 DenseMap<const GlobalValueSummary *, GlobalValue::GUID> SummaryToGUIDMap; 2540 2541 public: 2542 /// Construct an AssemblyWriter with an external SlotTracker 2543 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M, 2544 AssemblyAnnotationWriter *AAW, bool IsForDebug, 2545 bool ShouldPreserveUseListOrder = false); 2546 2547 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, 2548 const ModuleSummaryIndex *Index, bool IsForDebug); 2549 2550 AsmWriterContext getContext() { 2551 return AsmWriterContext(&TypePrinter, &Machine, TheModule); 2552 } 2553 2554 void printMDNodeBody(const MDNode *MD); 2555 void printNamedMDNode(const NamedMDNode *NMD); 2556 2557 void printModule(const Module *M); 2558 2559 void writeOperand(const Value *Op, bool PrintType); 2560 void writeParamOperand(const Value *Operand, AttributeSet Attrs); 2561 void writeOperandBundles(const CallBase *Call); 2562 void writeSyncScope(const LLVMContext &Context, 2563 SyncScope::ID SSID); 2564 void writeAtomic(const LLVMContext &Context, 2565 AtomicOrdering Ordering, 2566 SyncScope::ID SSID); 2567 void writeAtomicCmpXchg(const LLVMContext &Context, 2568 AtomicOrdering SuccessOrdering, 2569 AtomicOrdering FailureOrdering, 2570 SyncScope::ID SSID); 2571 2572 void writeAllMDNodes(); 2573 void writeMDNode(unsigned Slot, const MDNode *Node); 2574 void writeAttribute(const Attribute &Attr, bool InAttrGroup = false); 2575 void writeAttributeSet(const AttributeSet &AttrSet, bool InAttrGroup = false); 2576 void writeAllAttributeGroups(); 2577 2578 void printTypeIdentities(); 2579 void printGlobal(const GlobalVariable *GV); 2580 void printAlias(const GlobalAlias *GA); 2581 void printIFunc(const GlobalIFunc *GI); 2582 void printComdat(const Comdat *C); 2583 void printFunction(const Function *F); 2584 void printArgument(const Argument *FA, AttributeSet Attrs); 2585 void printBasicBlock(const BasicBlock *BB); 2586 void printInstructionLine(const Instruction &I); 2587 void printInstruction(const Instruction &I); 2588 2589 void printUseListOrder(const Value *V, const std::vector<unsigned> &Shuffle); 2590 void printUseLists(const Function *F); 2591 2592 void printModuleSummaryIndex(); 2593 void printSummaryInfo(unsigned Slot, const ValueInfo &VI); 2594 void printSummary(const GlobalValueSummary &Summary); 2595 void printAliasSummary(const AliasSummary *AS); 2596 void printGlobalVarSummary(const GlobalVarSummary *GS); 2597 void printFunctionSummary(const FunctionSummary *FS); 2598 void printTypeIdSummary(const TypeIdSummary &TIS); 2599 void printTypeIdCompatibleVtableSummary(const TypeIdCompatibleVtableInfo &TI); 2600 void printTypeTestResolution(const TypeTestResolution &TTRes); 2601 void printArgs(const std::vector<uint64_t> &Args); 2602 void printWPDRes(const WholeProgramDevirtResolution &WPDRes); 2603 void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo); 2604 void printVFuncId(const FunctionSummary::VFuncId VFId); 2605 void 2606 printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> &VCallList, 2607 const char *Tag); 2608 void 2609 printConstVCalls(const std::vector<FunctionSummary::ConstVCall> &VCallList, 2610 const char *Tag); 2611 2612 private: 2613 /// Print out metadata attachments. 2614 void printMetadataAttachments( 2615 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs, 2616 StringRef Separator); 2617 2618 // printInfoComment - Print a little comment after the instruction indicating 2619 // which slot it occupies. 2620 void printInfoComment(const Value &V); 2621 2622 // printGCRelocateComment - print comment after call to the gc.relocate 2623 // intrinsic indicating base and derived pointer names. 2624 void printGCRelocateComment(const GCRelocateInst &Relocate); 2625 }; 2626 2627 } // end anonymous namespace 2628 2629 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, 2630 const Module *M, AssemblyAnnotationWriter *AAW, 2631 bool IsForDebug, bool ShouldPreserveUseListOrder) 2632 : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW), 2633 IsForDebug(IsForDebug), 2634 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) { 2635 if (!TheModule) 2636 return; 2637 for (const GlobalObject &GO : TheModule->global_objects()) 2638 if (const Comdat *C = GO.getComdat()) 2639 Comdats.insert(C); 2640 } 2641 2642 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, 2643 const ModuleSummaryIndex *Index, bool IsForDebug) 2644 : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr), 2645 IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {} 2646 2647 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) { 2648 if (!Operand) { 2649 Out << "<null operand!>"; 2650 return; 2651 } 2652 if (PrintType) { 2653 TypePrinter.print(Operand->getType(), Out); 2654 Out << ' '; 2655 } 2656 auto WriterCtx = getContext(); 2657 WriteAsOperandInternal(Out, Operand, WriterCtx); 2658 } 2659 2660 void AssemblyWriter::writeSyncScope(const LLVMContext &Context, 2661 SyncScope::ID SSID) { 2662 switch (SSID) { 2663 case SyncScope::System: { 2664 break; 2665 } 2666 default: { 2667 if (SSNs.empty()) 2668 Context.getSyncScopeNames(SSNs); 2669 2670 Out << " syncscope(\""; 2671 printEscapedString(SSNs[SSID], Out); 2672 Out << "\")"; 2673 break; 2674 } 2675 } 2676 } 2677 2678 void AssemblyWriter::writeAtomic(const LLVMContext &Context, 2679 AtomicOrdering Ordering, 2680 SyncScope::ID SSID) { 2681 if (Ordering == AtomicOrdering::NotAtomic) 2682 return; 2683 2684 writeSyncScope(Context, SSID); 2685 Out << " " << toIRString(Ordering); 2686 } 2687 2688 void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context, 2689 AtomicOrdering SuccessOrdering, 2690 AtomicOrdering FailureOrdering, 2691 SyncScope::ID SSID) { 2692 assert(SuccessOrdering != AtomicOrdering::NotAtomic && 2693 FailureOrdering != AtomicOrdering::NotAtomic); 2694 2695 writeSyncScope(Context, SSID); 2696 Out << " " << toIRString(SuccessOrdering); 2697 Out << " " << toIRString(FailureOrdering); 2698 } 2699 2700 void AssemblyWriter::writeParamOperand(const Value *Operand, 2701 AttributeSet Attrs) { 2702 if (!Operand) { 2703 Out << "<null operand!>"; 2704 return; 2705 } 2706 2707 // Print the type 2708 TypePrinter.print(Operand->getType(), Out); 2709 // Print parameter attributes list 2710 if (Attrs.hasAttributes()) { 2711 Out << ' '; 2712 writeAttributeSet(Attrs); 2713 } 2714 Out << ' '; 2715 // Print the operand 2716 auto WriterCtx = getContext(); 2717 WriteAsOperandInternal(Out, Operand, WriterCtx); 2718 } 2719 2720 void AssemblyWriter::writeOperandBundles(const CallBase *Call) { 2721 if (!Call->hasOperandBundles()) 2722 return; 2723 2724 Out << " [ "; 2725 2726 bool FirstBundle = true; 2727 for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i) { 2728 OperandBundleUse BU = Call->getOperandBundleAt(i); 2729 2730 if (!FirstBundle) 2731 Out << ", "; 2732 FirstBundle = false; 2733 2734 Out << '"'; 2735 printEscapedString(BU.getTagName(), Out); 2736 Out << '"'; 2737 2738 Out << '('; 2739 2740 bool FirstInput = true; 2741 auto WriterCtx = getContext(); 2742 for (const auto &Input : BU.Inputs) { 2743 if (!FirstInput) 2744 Out << ", "; 2745 FirstInput = false; 2746 2747 TypePrinter.print(Input->getType(), Out); 2748 Out << " "; 2749 WriteAsOperandInternal(Out, Input, WriterCtx); 2750 } 2751 2752 Out << ')'; 2753 } 2754 2755 Out << " ]"; 2756 } 2757 2758 void AssemblyWriter::printModule(const Module *M) { 2759 Machine.initializeIfNeeded(); 2760 2761 if (ShouldPreserveUseListOrder) 2762 UseListOrders = predictUseListOrder(M); 2763 2764 if (!M->getModuleIdentifier().empty() && 2765 // Don't print the ID if it will start a new line (which would 2766 // require a comment char before it). 2767 M->getModuleIdentifier().find('\n') == std::string::npos) 2768 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n"; 2769 2770 if (!M->getSourceFileName().empty()) { 2771 Out << "source_filename = \""; 2772 printEscapedString(M->getSourceFileName(), Out); 2773 Out << "\"\n"; 2774 } 2775 2776 const std::string &DL = M->getDataLayoutStr(); 2777 if (!DL.empty()) 2778 Out << "target datalayout = \"" << DL << "\"\n"; 2779 if (!M->getTargetTriple().empty()) 2780 Out << "target triple = \"" << M->getTargetTriple() << "\"\n"; 2781 2782 if (!M->getModuleInlineAsm().empty()) { 2783 Out << '\n'; 2784 2785 // Split the string into lines, to make it easier to read the .ll file. 2786 StringRef Asm = M->getModuleInlineAsm(); 2787 do { 2788 StringRef Front; 2789 std::tie(Front, Asm) = Asm.split('\n'); 2790 2791 // We found a newline, print the portion of the asm string from the 2792 // last newline up to this newline. 2793 Out << "module asm \""; 2794 printEscapedString(Front, Out); 2795 Out << "\"\n"; 2796 } while (!Asm.empty()); 2797 } 2798 2799 printTypeIdentities(); 2800 2801 // Output all comdats. 2802 if (!Comdats.empty()) 2803 Out << '\n'; 2804 for (const Comdat *C : Comdats) { 2805 printComdat(C); 2806 if (C != Comdats.back()) 2807 Out << '\n'; 2808 } 2809 2810 // Output all globals. 2811 if (!M->global_empty()) Out << '\n'; 2812 for (const GlobalVariable &GV : M->globals()) { 2813 printGlobal(&GV); Out << '\n'; 2814 } 2815 2816 // Output all aliases. 2817 if (!M->alias_empty()) Out << "\n"; 2818 for (const GlobalAlias &GA : M->aliases()) 2819 printAlias(&GA); 2820 2821 // Output all ifuncs. 2822 if (!M->ifunc_empty()) Out << "\n"; 2823 for (const GlobalIFunc &GI : M->ifuncs()) 2824 printIFunc(&GI); 2825 2826 // Output all of the functions. 2827 for (const Function &F : *M) { 2828 Out << '\n'; 2829 printFunction(&F); 2830 } 2831 2832 // Output global use-lists. 2833 printUseLists(nullptr); 2834 2835 // Output all attribute groups. 2836 if (!Machine.as_empty()) { 2837 Out << '\n'; 2838 writeAllAttributeGroups(); 2839 } 2840 2841 // Output named metadata. 2842 if (!M->named_metadata_empty()) Out << '\n'; 2843 2844 for (const NamedMDNode &Node : M->named_metadata()) 2845 printNamedMDNode(&Node); 2846 2847 // Output metadata. 2848 if (!Machine.mdn_empty()) { 2849 Out << '\n'; 2850 writeAllMDNodes(); 2851 } 2852 } 2853 2854 void AssemblyWriter::printModuleSummaryIndex() { 2855 assert(TheIndex); 2856 int NumSlots = Machine.initializeIndexIfNeeded(); 2857 2858 Out << "\n"; 2859 2860 // Print module path entries. To print in order, add paths to a vector 2861 // indexed by module slot. 2862 std::vector<std::pair<std::string, ModuleHash>> moduleVec; 2863 std::string RegularLTOModuleName = 2864 ModuleSummaryIndex::getRegularLTOModuleName(); 2865 moduleVec.resize(TheIndex->modulePaths().size()); 2866 for (auto &ModPath : TheIndex->modulePaths()) 2867 moduleVec[Machine.getModulePathSlot(ModPath.first())] = std::make_pair( 2868 // A module id of -1 is a special entry for a regular LTO module created 2869 // during the thin link. 2870 ModPath.second.first == -1u ? RegularLTOModuleName 2871 : (std::string)std::string(ModPath.first()), 2872 ModPath.second.second); 2873 2874 unsigned i = 0; 2875 for (auto &ModPair : moduleVec) { 2876 Out << "^" << i++ << " = module: ("; 2877 Out << "path: \""; 2878 printEscapedString(ModPair.first, Out); 2879 Out << "\", hash: ("; 2880 FieldSeparator FS; 2881 for (auto Hash : ModPair.second) 2882 Out << FS << Hash; 2883 Out << "))\n"; 2884 } 2885 2886 // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer 2887 // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID). 2888 for (auto &GlobalList : *TheIndex) { 2889 auto GUID = GlobalList.first; 2890 for (auto &Summary : GlobalList.second.SummaryList) 2891 SummaryToGUIDMap[Summary.get()] = GUID; 2892 } 2893 2894 // Print the global value summary entries. 2895 for (auto &GlobalList : *TheIndex) { 2896 auto GUID = GlobalList.first; 2897 auto VI = TheIndex->getValueInfo(GlobalList); 2898 printSummaryInfo(Machine.getGUIDSlot(GUID), VI); 2899 } 2900 2901 // Print the TypeIdMap entries. 2902 for (const auto &TID : TheIndex->typeIds()) { 2903 Out << "^" << Machine.getTypeIdSlot(TID.second.first) 2904 << " = typeid: (name: \"" << TID.second.first << "\""; 2905 printTypeIdSummary(TID.second.second); 2906 Out << ") ; guid = " << TID.first << "\n"; 2907 } 2908 2909 // Print the TypeIdCompatibleVtableMap entries. 2910 for (auto &TId : TheIndex->typeIdCompatibleVtableMap()) { 2911 auto GUID = GlobalValue::getGUID(TId.first); 2912 Out << "^" << Machine.getGUIDSlot(GUID) 2913 << " = typeidCompatibleVTable: (name: \"" << TId.first << "\""; 2914 printTypeIdCompatibleVtableSummary(TId.second); 2915 Out << ") ; guid = " << GUID << "\n"; 2916 } 2917 2918 // Don't emit flags when it's not really needed (value is zero by default). 2919 if (TheIndex->getFlags()) { 2920 Out << "^" << NumSlots << " = flags: " << TheIndex->getFlags() << "\n"; 2921 ++NumSlots; 2922 } 2923 2924 Out << "^" << NumSlots << " = blockcount: " << TheIndex->getBlockCount() 2925 << "\n"; 2926 } 2927 2928 static const char * 2929 getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) { 2930 switch (K) { 2931 case WholeProgramDevirtResolution::Indir: 2932 return "indir"; 2933 case WholeProgramDevirtResolution::SingleImpl: 2934 return "singleImpl"; 2935 case WholeProgramDevirtResolution::BranchFunnel: 2936 return "branchFunnel"; 2937 } 2938 llvm_unreachable("invalid WholeProgramDevirtResolution kind"); 2939 } 2940 2941 static const char *getWholeProgDevirtResByArgKindName( 2942 WholeProgramDevirtResolution::ByArg::Kind K) { 2943 switch (K) { 2944 case WholeProgramDevirtResolution::ByArg::Indir: 2945 return "indir"; 2946 case WholeProgramDevirtResolution::ByArg::UniformRetVal: 2947 return "uniformRetVal"; 2948 case WholeProgramDevirtResolution::ByArg::UniqueRetVal: 2949 return "uniqueRetVal"; 2950 case WholeProgramDevirtResolution::ByArg::VirtualConstProp: 2951 return "virtualConstProp"; 2952 } 2953 llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind"); 2954 } 2955 2956 static const char *getTTResKindName(TypeTestResolution::Kind K) { 2957 switch (K) { 2958 case TypeTestResolution::Unknown: 2959 return "unknown"; 2960 case TypeTestResolution::Unsat: 2961 return "unsat"; 2962 case TypeTestResolution::ByteArray: 2963 return "byteArray"; 2964 case TypeTestResolution::Inline: 2965 return "inline"; 2966 case TypeTestResolution::Single: 2967 return "single"; 2968 case TypeTestResolution::AllOnes: 2969 return "allOnes"; 2970 } 2971 llvm_unreachable("invalid TypeTestResolution kind"); 2972 } 2973 2974 void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) { 2975 Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind) 2976 << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth; 2977 2978 // The following fields are only used if the target does not support the use 2979 // of absolute symbols to store constants. Print only if non-zero. 2980 if (TTRes.AlignLog2) 2981 Out << ", alignLog2: " << TTRes.AlignLog2; 2982 if (TTRes.SizeM1) 2983 Out << ", sizeM1: " << TTRes.SizeM1; 2984 if (TTRes.BitMask) 2985 // BitMask is uint8_t which causes it to print the corresponding char. 2986 Out << ", bitMask: " << (unsigned)TTRes.BitMask; 2987 if (TTRes.InlineBits) 2988 Out << ", inlineBits: " << TTRes.InlineBits; 2989 2990 Out << ")"; 2991 } 2992 2993 void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) { 2994 Out << ", summary: ("; 2995 printTypeTestResolution(TIS.TTRes); 2996 if (!TIS.WPDRes.empty()) { 2997 Out << ", wpdResolutions: ("; 2998 FieldSeparator FS; 2999 for (auto &WPDRes : TIS.WPDRes) { 3000 Out << FS; 3001 Out << "(offset: " << WPDRes.first << ", "; 3002 printWPDRes(WPDRes.second); 3003 Out << ")"; 3004 } 3005 Out << ")"; 3006 } 3007 Out << ")"; 3008 } 3009 3010 void AssemblyWriter::printTypeIdCompatibleVtableSummary( 3011 const TypeIdCompatibleVtableInfo &TI) { 3012 Out << ", summary: ("; 3013 FieldSeparator FS; 3014 for (auto &P : TI) { 3015 Out << FS; 3016 Out << "(offset: " << P.AddressPointOffset << ", "; 3017 Out << "^" << Machine.getGUIDSlot(P.VTableVI.getGUID()); 3018 Out << ")"; 3019 } 3020 Out << ")"; 3021 } 3022 3023 void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) { 3024 Out << "args: ("; 3025 FieldSeparator FS; 3026 for (auto arg : Args) { 3027 Out << FS; 3028 Out << arg; 3029 } 3030 Out << ")"; 3031 } 3032 3033 void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) { 3034 Out << "wpdRes: (kind: "; 3035 Out << getWholeProgDevirtResKindName(WPDRes.TheKind); 3036 3037 if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl) 3038 Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\""; 3039 3040 if (!WPDRes.ResByArg.empty()) { 3041 Out << ", resByArg: ("; 3042 FieldSeparator FS; 3043 for (auto &ResByArg : WPDRes.ResByArg) { 3044 Out << FS; 3045 printArgs(ResByArg.first); 3046 Out << ", byArg: (kind: "; 3047 Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind); 3048 if (ResByArg.second.TheKind == 3049 WholeProgramDevirtResolution::ByArg::UniformRetVal || 3050 ResByArg.second.TheKind == 3051 WholeProgramDevirtResolution::ByArg::UniqueRetVal) 3052 Out << ", info: " << ResByArg.second.Info; 3053 3054 // The following fields are only used if the target does not support the 3055 // use of absolute symbols to store constants. Print only if non-zero. 3056 if (ResByArg.second.Byte || ResByArg.second.Bit) 3057 Out << ", byte: " << ResByArg.second.Byte 3058 << ", bit: " << ResByArg.second.Bit; 3059 3060 Out << ")"; 3061 } 3062 Out << ")"; 3063 } 3064 Out << ")"; 3065 } 3066 3067 static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) { 3068 switch (SK) { 3069 case GlobalValueSummary::AliasKind: 3070 return "alias"; 3071 case GlobalValueSummary::FunctionKind: 3072 return "function"; 3073 case GlobalValueSummary::GlobalVarKind: 3074 return "variable"; 3075 } 3076 llvm_unreachable("invalid summary kind"); 3077 } 3078 3079 void AssemblyWriter::printAliasSummary(const AliasSummary *AS) { 3080 Out << ", aliasee: "; 3081 // The indexes emitted for distributed backends may not include the 3082 // aliasee summary (only if it is being imported directly). Handle 3083 // that case by just emitting "null" as the aliasee. 3084 if (AS->hasAliasee()) 3085 Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]); 3086 else 3087 Out << "null"; 3088 } 3089 3090 void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) { 3091 auto VTableFuncs = GS->vTableFuncs(); 3092 Out << ", varFlags: (readonly: " << GS->VarFlags.MaybeReadOnly << ", " 3093 << "writeonly: " << GS->VarFlags.MaybeWriteOnly << ", " 3094 << "constant: " << GS->VarFlags.Constant; 3095 if (!VTableFuncs.empty()) 3096 Out << ", " 3097 << "vcall_visibility: " << GS->VarFlags.VCallVisibility; 3098 Out << ")"; 3099 3100 if (!VTableFuncs.empty()) { 3101 Out << ", vTableFuncs: ("; 3102 FieldSeparator FS; 3103 for (auto &P : VTableFuncs) { 3104 Out << FS; 3105 Out << "(virtFunc: ^" << Machine.getGUIDSlot(P.FuncVI.getGUID()) 3106 << ", offset: " << P.VTableOffset; 3107 Out << ")"; 3108 } 3109 Out << ")"; 3110 } 3111 } 3112 3113 static std::string getLinkageName(GlobalValue::LinkageTypes LT) { 3114 switch (LT) { 3115 case GlobalValue::ExternalLinkage: 3116 return "external"; 3117 case GlobalValue::PrivateLinkage: 3118 return "private"; 3119 case GlobalValue::InternalLinkage: 3120 return "internal"; 3121 case GlobalValue::LinkOnceAnyLinkage: 3122 return "linkonce"; 3123 case GlobalValue::LinkOnceODRLinkage: 3124 return "linkonce_odr"; 3125 case GlobalValue::WeakAnyLinkage: 3126 return "weak"; 3127 case GlobalValue::WeakODRLinkage: 3128 return "weak_odr"; 3129 case GlobalValue::CommonLinkage: 3130 return "common"; 3131 case GlobalValue::AppendingLinkage: 3132 return "appending"; 3133 case GlobalValue::ExternalWeakLinkage: 3134 return "extern_weak"; 3135 case GlobalValue::AvailableExternallyLinkage: 3136 return "available_externally"; 3137 } 3138 llvm_unreachable("invalid linkage"); 3139 } 3140 3141 // When printing the linkage types in IR where the ExternalLinkage is 3142 // not printed, and other linkage types are expected to be printed with 3143 // a space after the name. 3144 static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) { 3145 if (LT == GlobalValue::ExternalLinkage) 3146 return ""; 3147 return getLinkageName(LT) + " "; 3148 } 3149 3150 static const char *getVisibilityName(GlobalValue::VisibilityTypes Vis) { 3151 switch (Vis) { 3152 case GlobalValue::DefaultVisibility: 3153 return "default"; 3154 case GlobalValue::HiddenVisibility: 3155 return "hidden"; 3156 case GlobalValue::ProtectedVisibility: 3157 return "protected"; 3158 } 3159 llvm_unreachable("invalid visibility"); 3160 } 3161 3162 void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) { 3163 Out << ", insts: " << FS->instCount(); 3164 if (FS->fflags().anyFlagSet()) 3165 Out << ", " << FS->fflags(); 3166 3167 if (!FS->calls().empty()) { 3168 Out << ", calls: ("; 3169 FieldSeparator IFS; 3170 for (auto &Call : FS->calls()) { 3171 Out << IFS; 3172 Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID()); 3173 if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown) 3174 Out << ", hotness: " << getHotnessName(Call.second.getHotness()); 3175 else if (Call.second.RelBlockFreq) 3176 Out << ", relbf: " << Call.second.RelBlockFreq; 3177 Out << ")"; 3178 } 3179 Out << ")"; 3180 } 3181 3182 if (const auto *TIdInfo = FS->getTypeIdInfo()) 3183 printTypeIdInfo(*TIdInfo); 3184 3185 auto PrintRange = [&](const ConstantRange &Range) { 3186 Out << "[" << Range.getSignedMin() << ", " << Range.getSignedMax() << "]"; 3187 }; 3188 3189 if (!FS->paramAccesses().empty()) { 3190 Out << ", params: ("; 3191 FieldSeparator IFS; 3192 for (auto &PS : FS->paramAccesses()) { 3193 Out << IFS; 3194 Out << "(param: " << PS.ParamNo; 3195 Out << ", offset: "; 3196 PrintRange(PS.Use); 3197 if (!PS.Calls.empty()) { 3198 Out << ", calls: ("; 3199 FieldSeparator IFS; 3200 for (auto &Call : PS.Calls) { 3201 Out << IFS; 3202 Out << "(callee: ^" << Machine.getGUIDSlot(Call.Callee.getGUID()); 3203 Out << ", param: " << Call.ParamNo; 3204 Out << ", offset: "; 3205 PrintRange(Call.Offsets); 3206 Out << ")"; 3207 } 3208 Out << ")"; 3209 } 3210 Out << ")"; 3211 } 3212 Out << ")"; 3213 } 3214 } 3215 3216 void AssemblyWriter::printTypeIdInfo( 3217 const FunctionSummary::TypeIdInfo &TIDInfo) { 3218 Out << ", typeIdInfo: ("; 3219 FieldSeparator TIDFS; 3220 if (!TIDInfo.TypeTests.empty()) { 3221 Out << TIDFS; 3222 Out << "typeTests: ("; 3223 FieldSeparator FS; 3224 for (auto &GUID : TIDInfo.TypeTests) { 3225 auto TidIter = TheIndex->typeIds().equal_range(GUID); 3226 if (TidIter.first == TidIter.second) { 3227 Out << FS; 3228 Out << GUID; 3229 continue; 3230 } 3231 // Print all type id that correspond to this GUID. 3232 for (auto It = TidIter.first; It != TidIter.second; ++It) { 3233 Out << FS; 3234 auto Slot = Machine.getTypeIdSlot(It->second.first); 3235 assert(Slot != -1); 3236 Out << "^" << Slot; 3237 } 3238 } 3239 Out << ")"; 3240 } 3241 if (!TIDInfo.TypeTestAssumeVCalls.empty()) { 3242 Out << TIDFS; 3243 printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls"); 3244 } 3245 if (!TIDInfo.TypeCheckedLoadVCalls.empty()) { 3246 Out << TIDFS; 3247 printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls"); 3248 } 3249 if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) { 3250 Out << TIDFS; 3251 printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls, 3252 "typeTestAssumeConstVCalls"); 3253 } 3254 if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) { 3255 Out << TIDFS; 3256 printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls, 3257 "typeCheckedLoadConstVCalls"); 3258 } 3259 Out << ")"; 3260 } 3261 3262 void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) { 3263 auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID); 3264 if (TidIter.first == TidIter.second) { 3265 Out << "vFuncId: ("; 3266 Out << "guid: " << VFId.GUID; 3267 Out << ", offset: " << VFId.Offset; 3268 Out << ")"; 3269 return; 3270 } 3271 // Print all type id that correspond to this GUID. 3272 FieldSeparator FS; 3273 for (auto It = TidIter.first; It != TidIter.second; ++It) { 3274 Out << FS; 3275 Out << "vFuncId: ("; 3276 auto Slot = Machine.getTypeIdSlot(It->second.first); 3277 assert(Slot != -1); 3278 Out << "^" << Slot; 3279 Out << ", offset: " << VFId.Offset; 3280 Out << ")"; 3281 } 3282 } 3283 3284 void AssemblyWriter::printNonConstVCalls( 3285 const std::vector<FunctionSummary::VFuncId> &VCallList, const char *Tag) { 3286 Out << Tag << ": ("; 3287 FieldSeparator FS; 3288 for (auto &VFuncId : VCallList) { 3289 Out << FS; 3290 printVFuncId(VFuncId); 3291 } 3292 Out << ")"; 3293 } 3294 3295 void AssemblyWriter::printConstVCalls( 3296 const std::vector<FunctionSummary::ConstVCall> &VCallList, 3297 const char *Tag) { 3298 Out << Tag << ": ("; 3299 FieldSeparator FS; 3300 for (auto &ConstVCall : VCallList) { 3301 Out << FS; 3302 Out << "("; 3303 printVFuncId(ConstVCall.VFunc); 3304 if (!ConstVCall.Args.empty()) { 3305 Out << ", "; 3306 printArgs(ConstVCall.Args); 3307 } 3308 Out << ")"; 3309 } 3310 Out << ")"; 3311 } 3312 3313 void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) { 3314 GlobalValueSummary::GVFlags GVFlags = Summary.flags(); 3315 GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage; 3316 Out << getSummaryKindName(Summary.getSummaryKind()) << ": "; 3317 Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath()) 3318 << ", flags: ("; 3319 Out << "linkage: " << getLinkageName(LT); 3320 Out << ", visibility: " 3321 << getVisibilityName((GlobalValue::VisibilityTypes)GVFlags.Visibility); 3322 Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport; 3323 Out << ", live: " << GVFlags.Live; 3324 Out << ", dsoLocal: " << GVFlags.DSOLocal; 3325 Out << ", canAutoHide: " << GVFlags.CanAutoHide; 3326 Out << ")"; 3327 3328 if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind) 3329 printAliasSummary(cast<AliasSummary>(&Summary)); 3330 else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind) 3331 printFunctionSummary(cast<FunctionSummary>(&Summary)); 3332 else 3333 printGlobalVarSummary(cast<GlobalVarSummary>(&Summary)); 3334 3335 auto RefList = Summary.refs(); 3336 if (!RefList.empty()) { 3337 Out << ", refs: ("; 3338 FieldSeparator FS; 3339 for (auto &Ref : RefList) { 3340 Out << FS; 3341 if (Ref.isReadOnly()) 3342 Out << "readonly "; 3343 else if (Ref.isWriteOnly()) 3344 Out << "writeonly "; 3345 Out << "^" << Machine.getGUIDSlot(Ref.getGUID()); 3346 } 3347 Out << ")"; 3348 } 3349 3350 Out << ")"; 3351 } 3352 3353 void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) { 3354 Out << "^" << Slot << " = gv: ("; 3355 if (!VI.name().empty()) 3356 Out << "name: \"" << VI.name() << "\""; 3357 else 3358 Out << "guid: " << VI.getGUID(); 3359 if (!VI.getSummaryList().empty()) { 3360 Out << ", summaries: ("; 3361 FieldSeparator FS; 3362 for (auto &Summary : VI.getSummaryList()) { 3363 Out << FS; 3364 printSummary(*Summary); 3365 } 3366 Out << ")"; 3367 } 3368 Out << ")"; 3369 if (!VI.name().empty()) 3370 Out << " ; guid = " << VI.getGUID(); 3371 Out << "\n"; 3372 } 3373 3374 static void printMetadataIdentifier(StringRef Name, 3375 formatted_raw_ostream &Out) { 3376 if (Name.empty()) { 3377 Out << "<empty name> "; 3378 } else { 3379 if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' || 3380 Name[0] == '$' || Name[0] == '.' || Name[0] == '_') 3381 Out << Name[0]; 3382 else 3383 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F); 3384 for (unsigned i = 1, e = Name.size(); i != e; ++i) { 3385 unsigned char C = Name[i]; 3386 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' || 3387 C == '.' || C == '_') 3388 Out << C; 3389 else 3390 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F); 3391 } 3392 } 3393 } 3394 3395 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) { 3396 Out << '!'; 3397 printMetadataIdentifier(NMD->getName(), Out); 3398 Out << " = !{"; 3399 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 3400 if (i) 3401 Out << ", "; 3402 3403 // Write DIExpressions inline. 3404 // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose. 3405 MDNode *Op = NMD->getOperand(i); 3406 assert(!isa<DIArgList>(Op) && 3407 "DIArgLists should not appear in NamedMDNodes"); 3408 if (auto *Expr = dyn_cast<DIExpression>(Op)) { 3409 writeDIExpression(Out, Expr, AsmWriterContext::getEmpty()); 3410 continue; 3411 } 3412 3413 int Slot = Machine.getMetadataSlot(Op); 3414 if (Slot == -1) 3415 Out << "<badref>"; 3416 else 3417 Out << '!' << Slot; 3418 } 3419 Out << "}\n"; 3420 } 3421 3422 static void PrintVisibility(GlobalValue::VisibilityTypes Vis, 3423 formatted_raw_ostream &Out) { 3424 switch (Vis) { 3425 case GlobalValue::DefaultVisibility: break; 3426 case GlobalValue::HiddenVisibility: Out << "hidden "; break; 3427 case GlobalValue::ProtectedVisibility: Out << "protected "; break; 3428 } 3429 } 3430 3431 static void PrintDSOLocation(const GlobalValue &GV, 3432 formatted_raw_ostream &Out) { 3433 if (GV.isDSOLocal() && !GV.isImplicitDSOLocal()) 3434 Out << "dso_local "; 3435 } 3436 3437 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT, 3438 formatted_raw_ostream &Out) { 3439 switch (SCT) { 3440 case GlobalValue::DefaultStorageClass: break; 3441 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break; 3442 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break; 3443 } 3444 } 3445 3446 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM, 3447 formatted_raw_ostream &Out) { 3448 switch (TLM) { 3449 case GlobalVariable::NotThreadLocal: 3450 break; 3451 case GlobalVariable::GeneralDynamicTLSModel: 3452 Out << "thread_local "; 3453 break; 3454 case GlobalVariable::LocalDynamicTLSModel: 3455 Out << "thread_local(localdynamic) "; 3456 break; 3457 case GlobalVariable::InitialExecTLSModel: 3458 Out << "thread_local(initialexec) "; 3459 break; 3460 case GlobalVariable::LocalExecTLSModel: 3461 Out << "thread_local(localexec) "; 3462 break; 3463 } 3464 } 3465 3466 static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) { 3467 switch (UA) { 3468 case GlobalVariable::UnnamedAddr::None: 3469 return ""; 3470 case GlobalVariable::UnnamedAddr::Local: 3471 return "local_unnamed_addr"; 3472 case GlobalVariable::UnnamedAddr::Global: 3473 return "unnamed_addr"; 3474 } 3475 llvm_unreachable("Unknown UnnamedAddr"); 3476 } 3477 3478 static void maybePrintComdat(formatted_raw_ostream &Out, 3479 const GlobalObject &GO) { 3480 const Comdat *C = GO.getComdat(); 3481 if (!C) 3482 return; 3483 3484 if (isa<GlobalVariable>(GO)) 3485 Out << ','; 3486 Out << " comdat"; 3487 3488 if (GO.getName() == C->getName()) 3489 return; 3490 3491 Out << '('; 3492 PrintLLVMName(Out, C->getName(), ComdatPrefix); 3493 Out << ')'; 3494 } 3495 3496 void AssemblyWriter::printGlobal(const GlobalVariable *GV) { 3497 if (GV->isMaterializable()) 3498 Out << "; Materializable\n"; 3499 3500 AsmWriterContext WriterCtx(&TypePrinter, &Machine, GV->getParent()); 3501 WriteAsOperandInternal(Out, GV, WriterCtx); 3502 Out << " = "; 3503 3504 if (!GV->hasInitializer() && GV->hasExternalLinkage()) 3505 Out << "external "; 3506 3507 Out << getLinkageNameWithSpace(GV->getLinkage()); 3508 PrintDSOLocation(*GV, Out); 3509 PrintVisibility(GV->getVisibility(), Out); 3510 PrintDLLStorageClass(GV->getDLLStorageClass(), Out); 3511 PrintThreadLocalModel(GV->getThreadLocalMode(), Out); 3512 StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr()); 3513 if (!UA.empty()) 3514 Out << UA << ' '; 3515 3516 if (unsigned AddressSpace = GV->getType()->getAddressSpace()) 3517 Out << "addrspace(" << AddressSpace << ") "; 3518 if (GV->isExternallyInitialized()) Out << "externally_initialized "; 3519 Out << (GV->isConstant() ? "constant " : "global "); 3520 TypePrinter.print(GV->getValueType(), Out); 3521 3522 if (GV->hasInitializer()) { 3523 Out << ' '; 3524 writeOperand(GV->getInitializer(), false); 3525 } 3526 3527 if (GV->hasSection()) { 3528 Out << ", section \""; 3529 printEscapedString(GV->getSection(), Out); 3530 Out << '"'; 3531 } 3532 if (GV->hasPartition()) { 3533 Out << ", partition \""; 3534 printEscapedString(GV->getPartition(), Out); 3535 Out << '"'; 3536 } 3537 3538 using SanitizerMetadata = llvm::GlobalValue::SanitizerMetadata; 3539 if (GV->hasSanitizerMetadata()) { 3540 SanitizerMetadata MD = GV->getSanitizerMetadata(); 3541 if (MD.NoAddress) 3542 Out << ", no_sanitize_address"; 3543 if (MD.NoHWAddress) 3544 Out << ", no_sanitize_hwaddress"; 3545 if (MD.NoMemtag) 3546 Out << ", no_sanitize_memtag"; 3547 if (MD.IsDynInit) 3548 Out << ", sanitize_address_dyninit"; 3549 } 3550 3551 maybePrintComdat(Out, *GV); 3552 if (MaybeAlign A = GV->getAlign()) 3553 Out << ", align " << A->value(); 3554 3555 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 3556 GV->getAllMetadata(MDs); 3557 printMetadataAttachments(MDs, ", "); 3558 3559 auto Attrs = GV->getAttributes(); 3560 if (Attrs.hasAttributes()) 3561 Out << " #" << Machine.getAttributeGroupSlot(Attrs); 3562 3563 printInfoComment(*GV); 3564 } 3565 3566 void AssemblyWriter::printAlias(const GlobalAlias *GA) { 3567 if (GA->isMaterializable()) 3568 Out << "; Materializable\n"; 3569 3570 AsmWriterContext WriterCtx(&TypePrinter, &Machine, GA->getParent()); 3571 WriteAsOperandInternal(Out, GA, WriterCtx); 3572 Out << " = "; 3573 3574 Out << getLinkageNameWithSpace(GA->getLinkage()); 3575 PrintDSOLocation(*GA, Out); 3576 PrintVisibility(GA->getVisibility(), Out); 3577 PrintDLLStorageClass(GA->getDLLStorageClass(), Out); 3578 PrintThreadLocalModel(GA->getThreadLocalMode(), Out); 3579 StringRef UA = getUnnamedAddrEncoding(GA->getUnnamedAddr()); 3580 if (!UA.empty()) 3581 Out << UA << ' '; 3582 3583 Out << "alias "; 3584 3585 TypePrinter.print(GA->getValueType(), Out); 3586 Out << ", "; 3587 3588 if (const Constant *Aliasee = GA->getAliasee()) { 3589 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee)); 3590 } else { 3591 TypePrinter.print(GA->getType(), Out); 3592 Out << " <<NULL ALIASEE>>"; 3593 } 3594 3595 if (GA->hasPartition()) { 3596 Out << ", partition \""; 3597 printEscapedString(GA->getPartition(), Out); 3598 Out << '"'; 3599 } 3600 3601 printInfoComment(*GA); 3602 Out << '\n'; 3603 } 3604 3605 void AssemblyWriter::printIFunc(const GlobalIFunc *GI) { 3606 if (GI->isMaterializable()) 3607 Out << "; Materializable\n"; 3608 3609 AsmWriterContext WriterCtx(&TypePrinter, &Machine, GI->getParent()); 3610 WriteAsOperandInternal(Out, GI, WriterCtx); 3611 Out << " = "; 3612 3613 Out << getLinkageNameWithSpace(GI->getLinkage()); 3614 PrintDSOLocation(*GI, Out); 3615 PrintVisibility(GI->getVisibility(), Out); 3616 3617 Out << "ifunc "; 3618 3619 TypePrinter.print(GI->getValueType(), Out); 3620 Out << ", "; 3621 3622 if (const Constant *Resolver = GI->getResolver()) { 3623 writeOperand(Resolver, !isa<ConstantExpr>(Resolver)); 3624 } else { 3625 TypePrinter.print(GI->getType(), Out); 3626 Out << " <<NULL RESOLVER>>"; 3627 } 3628 3629 if (GI->hasPartition()) { 3630 Out << ", partition \""; 3631 printEscapedString(GI->getPartition(), Out); 3632 Out << '"'; 3633 } 3634 3635 printInfoComment(*GI); 3636 Out << '\n'; 3637 } 3638 3639 void AssemblyWriter::printComdat(const Comdat *C) { 3640 C->print(Out); 3641 } 3642 3643 void AssemblyWriter::printTypeIdentities() { 3644 if (TypePrinter.empty()) 3645 return; 3646 3647 Out << '\n'; 3648 3649 // Emit all numbered types. 3650 auto &NumberedTypes = TypePrinter.getNumberedTypes(); 3651 for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) { 3652 Out << '%' << I << " = type "; 3653 3654 // Make sure we print out at least one level of the type structure, so 3655 // that we do not get %2 = type %2 3656 TypePrinter.printStructBody(NumberedTypes[I], Out); 3657 Out << '\n'; 3658 } 3659 3660 auto &NamedTypes = TypePrinter.getNamedTypes(); 3661 for (StructType *NamedType : NamedTypes) { 3662 PrintLLVMName(Out, NamedType->getName(), LocalPrefix); 3663 Out << " = type "; 3664 3665 // Make sure we print out at least one level of the type structure, so 3666 // that we do not get %FILE = type %FILE 3667 TypePrinter.printStructBody(NamedType, Out); 3668 Out << '\n'; 3669 } 3670 } 3671 3672 /// printFunction - Print all aspects of a function. 3673 void AssemblyWriter::printFunction(const Function *F) { 3674 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out); 3675 3676 if (F->isMaterializable()) 3677 Out << "; Materializable\n"; 3678 3679 const AttributeList &Attrs = F->getAttributes(); 3680 if (Attrs.hasFnAttrs()) { 3681 AttributeSet AS = Attrs.getFnAttrs(); 3682 std::string AttrStr; 3683 3684 for (const Attribute &Attr : AS) { 3685 if (!Attr.isStringAttribute()) { 3686 if (!AttrStr.empty()) AttrStr += ' '; 3687 AttrStr += Attr.getAsString(); 3688 } 3689 } 3690 3691 if (!AttrStr.empty()) 3692 Out << "; Function Attrs: " << AttrStr << '\n'; 3693 } 3694 3695 Machine.incorporateFunction(F); 3696 3697 if (F->isDeclaration()) { 3698 Out << "declare"; 3699 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 3700 F->getAllMetadata(MDs); 3701 printMetadataAttachments(MDs, " "); 3702 Out << ' '; 3703 } else 3704 Out << "define "; 3705 3706 Out << getLinkageNameWithSpace(F->getLinkage()); 3707 PrintDSOLocation(*F, Out); 3708 PrintVisibility(F->getVisibility(), Out); 3709 PrintDLLStorageClass(F->getDLLStorageClass(), Out); 3710 3711 // Print the calling convention. 3712 if (F->getCallingConv() != CallingConv::C) { 3713 PrintCallingConv(F->getCallingConv(), Out); 3714 Out << " "; 3715 } 3716 3717 FunctionType *FT = F->getFunctionType(); 3718 if (Attrs.hasRetAttrs()) 3719 Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' '; 3720 TypePrinter.print(F->getReturnType(), Out); 3721 AsmWriterContext WriterCtx(&TypePrinter, &Machine, F->getParent()); 3722 Out << ' '; 3723 WriteAsOperandInternal(Out, F, WriterCtx); 3724 Out << '('; 3725 3726 // Loop over the arguments, printing them... 3727 if (F->isDeclaration() && !IsForDebug) { 3728 // We're only interested in the type here - don't print argument names. 3729 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) { 3730 // Insert commas as we go... the first arg doesn't get a comma 3731 if (I) 3732 Out << ", "; 3733 // Output type... 3734 TypePrinter.print(FT->getParamType(I), Out); 3735 3736 AttributeSet ArgAttrs = Attrs.getParamAttrs(I); 3737 if (ArgAttrs.hasAttributes()) { 3738 Out << ' '; 3739 writeAttributeSet(ArgAttrs); 3740 } 3741 } 3742 } else { 3743 // The arguments are meaningful here, print them in detail. 3744 for (const Argument &Arg : F->args()) { 3745 // Insert commas as we go... the first arg doesn't get a comma 3746 if (Arg.getArgNo() != 0) 3747 Out << ", "; 3748 printArgument(&Arg, Attrs.getParamAttrs(Arg.getArgNo())); 3749 } 3750 } 3751 3752 // Finish printing arguments... 3753 if (FT->isVarArg()) { 3754 if (FT->getNumParams()) Out << ", "; 3755 Out << "..."; // Output varargs portion of signature! 3756 } 3757 Out << ')'; 3758 StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr()); 3759 if (!UA.empty()) 3760 Out << ' ' << UA; 3761 // We print the function address space if it is non-zero or if we are writing 3762 // a module with a non-zero program address space or if there is no valid 3763 // Module* so that the file can be parsed without the datalayout string. 3764 const Module *Mod = F->getParent(); 3765 if (F->getAddressSpace() != 0 || !Mod || 3766 Mod->getDataLayout().getProgramAddressSpace() != 0) 3767 Out << " addrspace(" << F->getAddressSpace() << ")"; 3768 if (Attrs.hasFnAttrs()) 3769 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttrs()); 3770 if (F->hasSection()) { 3771 Out << " section \""; 3772 printEscapedString(F->getSection(), Out); 3773 Out << '"'; 3774 } 3775 if (F->hasPartition()) { 3776 Out << " partition \""; 3777 printEscapedString(F->getPartition(), Out); 3778 Out << '"'; 3779 } 3780 maybePrintComdat(Out, *F); 3781 if (MaybeAlign A = F->getAlign()) 3782 Out << " align " << A->value(); 3783 if (F->hasGC()) 3784 Out << " gc \"" << F->getGC() << '"'; 3785 if (F->hasPrefixData()) { 3786 Out << " prefix "; 3787 writeOperand(F->getPrefixData(), true); 3788 } 3789 if (F->hasPrologueData()) { 3790 Out << " prologue "; 3791 writeOperand(F->getPrologueData(), true); 3792 } 3793 if (F->hasPersonalityFn()) { 3794 Out << " personality "; 3795 writeOperand(F->getPersonalityFn(), /*PrintType=*/true); 3796 } 3797 3798 if (F->isDeclaration()) { 3799 Out << '\n'; 3800 } else { 3801 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 3802 F->getAllMetadata(MDs); 3803 printMetadataAttachments(MDs, " "); 3804 3805 Out << " {"; 3806 // Output all of the function's basic blocks. 3807 for (const BasicBlock &BB : *F) 3808 printBasicBlock(&BB); 3809 3810 // Output the function's use-lists. 3811 printUseLists(F); 3812 3813 Out << "}\n"; 3814 } 3815 3816 Machine.purgeFunction(); 3817 } 3818 3819 /// printArgument - This member is called for every argument that is passed into 3820 /// the function. Simply print it out 3821 void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) { 3822 // Output type... 3823 TypePrinter.print(Arg->getType(), Out); 3824 3825 // Output parameter attributes list 3826 if (Attrs.hasAttributes()) { 3827 Out << ' '; 3828 writeAttributeSet(Attrs); 3829 } 3830 3831 // Output name, if available... 3832 if (Arg->hasName()) { 3833 Out << ' '; 3834 PrintLLVMName(Out, Arg); 3835 } else { 3836 int Slot = Machine.getLocalSlot(Arg); 3837 assert(Slot != -1 && "expect argument in function here"); 3838 Out << " %" << Slot; 3839 } 3840 } 3841 3842 /// printBasicBlock - This member is called for each basic block in a method. 3843 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) { 3844 bool IsEntryBlock = BB->getParent() && BB->isEntryBlock(); 3845 if (BB->hasName()) { // Print out the label if it exists... 3846 Out << "\n"; 3847 PrintLLVMName(Out, BB->getName(), LabelPrefix); 3848 Out << ':'; 3849 } else if (!IsEntryBlock) { 3850 Out << "\n"; 3851 int Slot = Machine.getLocalSlot(BB); 3852 if (Slot != -1) 3853 Out << Slot << ":"; 3854 else 3855 Out << "<badref>:"; 3856 } 3857 3858 if (!IsEntryBlock) { 3859 // Output predecessors for the block. 3860 Out.PadToColumn(50); 3861 Out << ";"; 3862 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB); 3863 3864 if (PI == PE) { 3865 Out << " No predecessors!"; 3866 } else { 3867 Out << " preds = "; 3868 writeOperand(*PI, false); 3869 for (++PI; PI != PE; ++PI) { 3870 Out << ", "; 3871 writeOperand(*PI, false); 3872 } 3873 } 3874 } 3875 3876 Out << "\n"; 3877 3878 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out); 3879 3880 // Output all of the instructions in the basic block... 3881 for (const Instruction &I : *BB) { 3882 printInstructionLine(I); 3883 } 3884 3885 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out); 3886 } 3887 3888 /// printInstructionLine - Print an instruction and a newline character. 3889 void AssemblyWriter::printInstructionLine(const Instruction &I) { 3890 printInstruction(I); 3891 Out << '\n'; 3892 } 3893 3894 /// printGCRelocateComment - print comment after call to the gc.relocate 3895 /// intrinsic indicating base and derived pointer names. 3896 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) { 3897 Out << " ; ("; 3898 writeOperand(Relocate.getBasePtr(), false); 3899 Out << ", "; 3900 writeOperand(Relocate.getDerivedPtr(), false); 3901 Out << ")"; 3902 } 3903 3904 /// printInfoComment - Print a little comment after the instruction indicating 3905 /// which slot it occupies. 3906 void AssemblyWriter::printInfoComment(const Value &V) { 3907 if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V)) 3908 printGCRelocateComment(*Relocate); 3909 3910 if (AnnotationWriter) 3911 AnnotationWriter->printInfoComment(V, Out); 3912 } 3913 3914 static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I, 3915 raw_ostream &Out) { 3916 // We print the address space of the call if it is non-zero. 3917 unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace(); 3918 bool PrintAddrSpace = CallAddrSpace != 0; 3919 if (!PrintAddrSpace) { 3920 const Module *Mod = getModuleFromVal(I); 3921 // We also print it if it is zero but not equal to the program address space 3922 // or if we can't find a valid Module* to make it possible to parse 3923 // the resulting file even without a datalayout string. 3924 if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0) 3925 PrintAddrSpace = true; 3926 } 3927 if (PrintAddrSpace) 3928 Out << " addrspace(" << CallAddrSpace << ")"; 3929 } 3930 3931 // This member is called for each Instruction in a function.. 3932 void AssemblyWriter::printInstruction(const Instruction &I) { 3933 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out); 3934 3935 // Print out indentation for an instruction. 3936 Out << " "; 3937 3938 // Print out name if it exists... 3939 if (I.hasName()) { 3940 PrintLLVMName(Out, &I); 3941 Out << " = "; 3942 } else if (!I.getType()->isVoidTy()) { 3943 // Print out the def slot taken. 3944 int SlotNum = Machine.getLocalSlot(&I); 3945 if (SlotNum == -1) 3946 Out << "<badref> = "; 3947 else 3948 Out << '%' << SlotNum << " = "; 3949 } 3950 3951 if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 3952 if (CI->isMustTailCall()) 3953 Out << "musttail "; 3954 else if (CI->isTailCall()) 3955 Out << "tail "; 3956 else if (CI->isNoTailCall()) 3957 Out << "notail "; 3958 } 3959 3960 // Print out the opcode... 3961 Out << I.getOpcodeName(); 3962 3963 // If this is an atomic load or store, print out the atomic marker. 3964 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) || 3965 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic())) 3966 Out << " atomic"; 3967 3968 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak()) 3969 Out << " weak"; 3970 3971 // If this is a volatile operation, print out the volatile marker. 3972 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) || 3973 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) || 3974 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) || 3975 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile())) 3976 Out << " volatile"; 3977 3978 // Print out optimization information. 3979 WriteOptimizationInfo(Out, &I); 3980 3981 // Print out the compare instruction predicates 3982 if (const CmpInst *CI = dyn_cast<CmpInst>(&I)) 3983 Out << ' ' << CmpInst::getPredicateName(CI->getPredicate()); 3984 3985 // Print out the atomicrmw operation 3986 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) 3987 Out << ' ' << AtomicRMWInst::getOperationName(RMWI->getOperation()); 3988 3989 // Print out the type of the operands... 3990 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr; 3991 3992 // Special case conditional branches to swizzle the condition out to the front 3993 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) { 3994 const BranchInst &BI(cast<BranchInst>(I)); 3995 Out << ' '; 3996 writeOperand(BI.getCondition(), true); 3997 Out << ", "; 3998 writeOperand(BI.getSuccessor(0), true); 3999 Out << ", "; 4000 writeOperand(BI.getSuccessor(1), true); 4001 4002 } else if (isa<SwitchInst>(I)) { 4003 const SwitchInst& SI(cast<SwitchInst>(I)); 4004 // Special case switch instruction to get formatting nice and correct. 4005 Out << ' '; 4006 writeOperand(SI.getCondition(), true); 4007 Out << ", "; 4008 writeOperand(SI.getDefaultDest(), true); 4009 Out << " ["; 4010 for (auto Case : SI.cases()) { 4011 Out << "\n "; 4012 writeOperand(Case.getCaseValue(), true); 4013 Out << ", "; 4014 writeOperand(Case.getCaseSuccessor(), true); 4015 } 4016 Out << "\n ]"; 4017 } else if (isa<IndirectBrInst>(I)) { 4018 // Special case indirectbr instruction to get formatting nice and correct. 4019 Out << ' '; 4020 writeOperand(Operand, true); 4021 Out << ", ["; 4022 4023 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) { 4024 if (i != 1) 4025 Out << ", "; 4026 writeOperand(I.getOperand(i), true); 4027 } 4028 Out << ']'; 4029 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) { 4030 Out << ' '; 4031 TypePrinter.print(I.getType(), Out); 4032 Out << ' '; 4033 4034 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) { 4035 if (op) Out << ", "; 4036 Out << "[ "; 4037 writeOperand(PN->getIncomingValue(op), false); Out << ", "; 4038 writeOperand(PN->getIncomingBlock(op), false); Out << " ]"; 4039 } 4040 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) { 4041 Out << ' '; 4042 writeOperand(I.getOperand(0), true); 4043 for (unsigned i : EVI->indices()) 4044 Out << ", " << i; 4045 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) { 4046 Out << ' '; 4047 writeOperand(I.getOperand(0), true); Out << ", "; 4048 writeOperand(I.getOperand(1), true); 4049 for (unsigned i : IVI->indices()) 4050 Out << ", " << i; 4051 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) { 4052 Out << ' '; 4053 TypePrinter.print(I.getType(), Out); 4054 if (LPI->isCleanup() || LPI->getNumClauses() != 0) 4055 Out << '\n'; 4056 4057 if (LPI->isCleanup()) 4058 Out << " cleanup"; 4059 4060 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) { 4061 if (i != 0 || LPI->isCleanup()) Out << "\n"; 4062 if (LPI->isCatch(i)) 4063 Out << " catch "; 4064 else 4065 Out << " filter "; 4066 4067 writeOperand(LPI->getClause(i), true); 4068 } 4069 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) { 4070 Out << " within "; 4071 writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false); 4072 Out << " ["; 4073 unsigned Op = 0; 4074 for (const BasicBlock *PadBB : CatchSwitch->handlers()) { 4075 if (Op > 0) 4076 Out << ", "; 4077 writeOperand(PadBB, /*PrintType=*/true); 4078 ++Op; 4079 } 4080 Out << "] unwind "; 4081 if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest()) 4082 writeOperand(UnwindDest, /*PrintType=*/true); 4083 else 4084 Out << "to caller"; 4085 } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) { 4086 Out << " within "; 4087 writeOperand(FPI->getParentPad(), /*PrintType=*/false); 4088 Out << " ["; 4089 for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps; 4090 ++Op) { 4091 if (Op > 0) 4092 Out << ", "; 4093 writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true); 4094 } 4095 Out << ']'; 4096 } else if (isa<ReturnInst>(I) && !Operand) { 4097 Out << " void"; 4098 } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) { 4099 Out << " from "; 4100 writeOperand(CRI->getOperand(0), /*PrintType=*/false); 4101 4102 Out << " to "; 4103 writeOperand(CRI->getOperand(1), /*PrintType=*/true); 4104 } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) { 4105 Out << " from "; 4106 writeOperand(CRI->getOperand(0), /*PrintType=*/false); 4107 4108 Out << " unwind "; 4109 if (CRI->hasUnwindDest()) 4110 writeOperand(CRI->getOperand(1), /*PrintType=*/true); 4111 else 4112 Out << "to caller"; 4113 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 4114 // Print the calling convention being used. 4115 if (CI->getCallingConv() != CallingConv::C) { 4116 Out << " "; 4117 PrintCallingConv(CI->getCallingConv(), Out); 4118 } 4119 4120 Operand = CI->getCalledOperand(); 4121 FunctionType *FTy = CI->getFunctionType(); 4122 Type *RetTy = FTy->getReturnType(); 4123 const AttributeList &PAL = CI->getAttributes(); 4124 4125 if (PAL.hasRetAttrs()) 4126 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex); 4127 4128 // Only print addrspace(N) if necessary: 4129 maybePrintCallAddrSpace(Operand, &I, Out); 4130 4131 // If possible, print out the short form of the call instruction. We can 4132 // only do this if the first argument is a pointer to a nonvararg function, 4133 // and if the return type is not a pointer to a function. 4134 // 4135 Out << ' '; 4136 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out); 4137 Out << ' '; 4138 writeOperand(Operand, false); 4139 Out << '('; 4140 for (unsigned op = 0, Eop = CI->arg_size(); op < Eop; ++op) { 4141 if (op > 0) 4142 Out << ", "; 4143 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttrs(op)); 4144 } 4145 4146 // Emit an ellipsis if this is a musttail call in a vararg function. This 4147 // is only to aid readability, musttail calls forward varargs by default. 4148 if (CI->isMustTailCall() && CI->getParent() && 4149 CI->getParent()->getParent() && 4150 CI->getParent()->getParent()->isVarArg()) 4151 Out << ", ..."; 4152 4153 Out << ')'; 4154 if (PAL.hasFnAttrs()) 4155 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs()); 4156 4157 writeOperandBundles(CI); 4158 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) { 4159 Operand = II->getCalledOperand(); 4160 FunctionType *FTy = II->getFunctionType(); 4161 Type *RetTy = FTy->getReturnType(); 4162 const AttributeList &PAL = II->getAttributes(); 4163 4164 // Print the calling convention being used. 4165 if (II->getCallingConv() != CallingConv::C) { 4166 Out << " "; 4167 PrintCallingConv(II->getCallingConv(), Out); 4168 } 4169 4170 if (PAL.hasRetAttrs()) 4171 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex); 4172 4173 // Only print addrspace(N) if necessary: 4174 maybePrintCallAddrSpace(Operand, &I, Out); 4175 4176 // If possible, print out the short form of the invoke instruction. We can 4177 // only do this if the first argument is a pointer to a nonvararg function, 4178 // and if the return type is not a pointer to a function. 4179 // 4180 Out << ' '; 4181 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out); 4182 Out << ' '; 4183 writeOperand(Operand, false); 4184 Out << '('; 4185 for (unsigned op = 0, Eop = II->arg_size(); op < Eop; ++op) { 4186 if (op) 4187 Out << ", "; 4188 writeParamOperand(II->getArgOperand(op), PAL.getParamAttrs(op)); 4189 } 4190 4191 Out << ')'; 4192 if (PAL.hasFnAttrs()) 4193 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs()); 4194 4195 writeOperandBundles(II); 4196 4197 Out << "\n to "; 4198 writeOperand(II->getNormalDest(), true); 4199 Out << " unwind "; 4200 writeOperand(II->getUnwindDest(), true); 4201 } else if (const CallBrInst *CBI = dyn_cast<CallBrInst>(&I)) { 4202 Operand = CBI->getCalledOperand(); 4203 FunctionType *FTy = CBI->getFunctionType(); 4204 Type *RetTy = FTy->getReturnType(); 4205 const AttributeList &PAL = CBI->getAttributes(); 4206 4207 // Print the calling convention being used. 4208 if (CBI->getCallingConv() != CallingConv::C) { 4209 Out << " "; 4210 PrintCallingConv(CBI->getCallingConv(), Out); 4211 } 4212 4213 if (PAL.hasRetAttrs()) 4214 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex); 4215 4216 // If possible, print out the short form of the callbr instruction. We can 4217 // only do this if the first argument is a pointer to a nonvararg function, 4218 // and if the return type is not a pointer to a function. 4219 // 4220 Out << ' '; 4221 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out); 4222 Out << ' '; 4223 writeOperand(Operand, false); 4224 Out << '('; 4225 for (unsigned op = 0, Eop = CBI->arg_size(); op < Eop; ++op) { 4226 if (op) 4227 Out << ", "; 4228 writeParamOperand(CBI->getArgOperand(op), PAL.getParamAttrs(op)); 4229 } 4230 4231 Out << ')'; 4232 if (PAL.hasFnAttrs()) 4233 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs()); 4234 4235 writeOperandBundles(CBI); 4236 4237 Out << "\n to "; 4238 writeOperand(CBI->getDefaultDest(), true); 4239 Out << " ["; 4240 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) { 4241 if (i != 0) 4242 Out << ", "; 4243 writeOperand(CBI->getIndirectDest(i), true); 4244 } 4245 Out << ']'; 4246 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) { 4247 Out << ' '; 4248 if (AI->isUsedWithInAlloca()) 4249 Out << "inalloca "; 4250 if (AI->isSwiftError()) 4251 Out << "swifterror "; 4252 TypePrinter.print(AI->getAllocatedType(), Out); 4253 4254 // Explicitly write the array size if the code is broken, if it's an array 4255 // allocation, or if the type is not canonical for scalar allocations. The 4256 // latter case prevents the type from mutating when round-tripping through 4257 // assembly. 4258 if (!AI->getArraySize() || AI->isArrayAllocation() || 4259 !AI->getArraySize()->getType()->isIntegerTy(32)) { 4260 Out << ", "; 4261 writeOperand(AI->getArraySize(), true); 4262 } 4263 if (MaybeAlign A = AI->getAlign()) { 4264 Out << ", align " << A->value(); 4265 } 4266 4267 unsigned AddrSpace = AI->getType()->getAddressSpace(); 4268 if (AddrSpace != 0) { 4269 Out << ", addrspace(" << AddrSpace << ')'; 4270 } 4271 } else if (isa<CastInst>(I)) { 4272 if (Operand) { 4273 Out << ' '; 4274 writeOperand(Operand, true); // Work with broken code 4275 } 4276 Out << " to "; 4277 TypePrinter.print(I.getType(), Out); 4278 } else if (isa<VAArgInst>(I)) { 4279 if (Operand) { 4280 Out << ' '; 4281 writeOperand(Operand, true); // Work with broken code 4282 } 4283 Out << ", "; 4284 TypePrinter.print(I.getType(), Out); 4285 } else if (Operand) { // Print the normal way. 4286 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 4287 Out << ' '; 4288 TypePrinter.print(GEP->getSourceElementType(), Out); 4289 Out << ','; 4290 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) { 4291 Out << ' '; 4292 TypePrinter.print(LI->getType(), Out); 4293 Out << ','; 4294 } 4295 4296 // PrintAllTypes - Instructions who have operands of all the same type 4297 // omit the type from all but the first operand. If the instruction has 4298 // different type operands (for example br), then they are all printed. 4299 bool PrintAllTypes = false; 4300 Type *TheType = Operand->getType(); 4301 4302 // Select, Store and ShuffleVector always print all types. 4303 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I) 4304 || isa<ReturnInst>(I)) { 4305 PrintAllTypes = true; 4306 } else { 4307 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) { 4308 Operand = I.getOperand(i); 4309 // note that Operand shouldn't be null, but the test helps make dump() 4310 // more tolerant of malformed IR 4311 if (Operand && Operand->getType() != TheType) { 4312 PrintAllTypes = true; // We have differing types! Print them all! 4313 break; 4314 } 4315 } 4316 } 4317 4318 if (!PrintAllTypes) { 4319 Out << ' '; 4320 TypePrinter.print(TheType, Out); 4321 } 4322 4323 Out << ' '; 4324 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) { 4325 if (i) Out << ", "; 4326 writeOperand(I.getOperand(i), PrintAllTypes); 4327 } 4328 } 4329 4330 // Print atomic ordering/alignment for memory operations 4331 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) { 4332 if (LI->isAtomic()) 4333 writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID()); 4334 if (MaybeAlign A = LI->getAlign()) 4335 Out << ", align " << A->value(); 4336 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) { 4337 if (SI->isAtomic()) 4338 writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID()); 4339 if (MaybeAlign A = SI->getAlign()) 4340 Out << ", align " << A->value(); 4341 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) { 4342 writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(), 4343 CXI->getFailureOrdering(), CXI->getSyncScopeID()); 4344 Out << ", align " << CXI->getAlign().value(); 4345 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) { 4346 writeAtomic(RMWI->getContext(), RMWI->getOrdering(), 4347 RMWI->getSyncScopeID()); 4348 Out << ", align " << RMWI->getAlign().value(); 4349 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) { 4350 writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID()); 4351 } else if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(&I)) { 4352 PrintShuffleMask(Out, SVI->getType(), SVI->getShuffleMask()); 4353 } 4354 4355 // Print Metadata info. 4356 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD; 4357 I.getAllMetadata(InstMD); 4358 printMetadataAttachments(InstMD, ", "); 4359 4360 // Print a nice comment. 4361 printInfoComment(I); 4362 } 4363 4364 void AssemblyWriter::printMetadataAttachments( 4365 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs, 4366 StringRef Separator) { 4367 if (MDs.empty()) 4368 return; 4369 4370 if (MDNames.empty()) 4371 MDs[0].second->getContext().getMDKindNames(MDNames); 4372 4373 auto WriterCtx = getContext(); 4374 for (const auto &I : MDs) { 4375 unsigned Kind = I.first; 4376 Out << Separator; 4377 if (Kind < MDNames.size()) { 4378 Out << "!"; 4379 printMetadataIdentifier(MDNames[Kind], Out); 4380 } else 4381 Out << "!<unknown kind #" << Kind << ">"; 4382 Out << ' '; 4383 WriteAsOperandInternal(Out, I.second, WriterCtx); 4384 } 4385 } 4386 4387 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) { 4388 Out << '!' << Slot << " = "; 4389 printMDNodeBody(Node); 4390 Out << "\n"; 4391 } 4392 4393 void AssemblyWriter::writeAllMDNodes() { 4394 SmallVector<const MDNode *, 16> Nodes; 4395 Nodes.resize(Machine.mdn_size()); 4396 for (auto &I : llvm::make_range(Machine.mdn_begin(), Machine.mdn_end())) 4397 Nodes[I.second] = cast<MDNode>(I.first); 4398 4399 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) { 4400 writeMDNode(i, Nodes[i]); 4401 } 4402 } 4403 4404 void AssemblyWriter::printMDNodeBody(const MDNode *Node) { 4405 auto WriterCtx = getContext(); 4406 WriteMDNodeBodyInternal(Out, Node, WriterCtx); 4407 } 4408 4409 void AssemblyWriter::writeAttribute(const Attribute &Attr, bool InAttrGroup) { 4410 if (!Attr.isTypeAttribute()) { 4411 Out << Attr.getAsString(InAttrGroup); 4412 return; 4413 } 4414 4415 Out << Attribute::getNameFromAttrKind(Attr.getKindAsEnum()); 4416 if (Type *Ty = Attr.getValueAsType()) { 4417 Out << '('; 4418 TypePrinter.print(Ty, Out); 4419 Out << ')'; 4420 } 4421 } 4422 4423 void AssemblyWriter::writeAttributeSet(const AttributeSet &AttrSet, 4424 bool InAttrGroup) { 4425 bool FirstAttr = true; 4426 for (const auto &Attr : AttrSet) { 4427 if (!FirstAttr) 4428 Out << ' '; 4429 writeAttribute(Attr, InAttrGroup); 4430 FirstAttr = false; 4431 } 4432 } 4433 4434 void AssemblyWriter::writeAllAttributeGroups() { 4435 std::vector<std::pair<AttributeSet, unsigned>> asVec; 4436 asVec.resize(Machine.as_size()); 4437 4438 for (auto &I : llvm::make_range(Machine.as_begin(), Machine.as_end())) 4439 asVec[I.second] = I; 4440 4441 for (const auto &I : asVec) 4442 Out << "attributes #" << I.second << " = { " 4443 << I.first.getAsString(true) << " }\n"; 4444 } 4445 4446 void AssemblyWriter::printUseListOrder(const Value *V, 4447 const std::vector<unsigned> &Shuffle) { 4448 bool IsInFunction = Machine.getFunction(); 4449 if (IsInFunction) 4450 Out << " "; 4451 4452 Out << "uselistorder"; 4453 if (const BasicBlock *BB = IsInFunction ? nullptr : dyn_cast<BasicBlock>(V)) { 4454 Out << "_bb "; 4455 writeOperand(BB->getParent(), false); 4456 Out << ", "; 4457 writeOperand(BB, false); 4458 } else { 4459 Out << " "; 4460 writeOperand(V, true); 4461 } 4462 Out << ", { "; 4463 4464 assert(Shuffle.size() >= 2 && "Shuffle too small"); 4465 Out << Shuffle[0]; 4466 for (unsigned I = 1, E = Shuffle.size(); I != E; ++I) 4467 Out << ", " << Shuffle[I]; 4468 Out << " }\n"; 4469 } 4470 4471 void AssemblyWriter::printUseLists(const Function *F) { 4472 auto It = UseListOrders.find(F); 4473 if (It == UseListOrders.end()) 4474 return; 4475 4476 Out << "\n; uselistorder directives\n"; 4477 for (const auto &Pair : It->second) 4478 printUseListOrder(Pair.first, Pair.second); 4479 } 4480 4481 //===----------------------------------------------------------------------===// 4482 // External Interface declarations 4483 //===----------------------------------------------------------------------===// 4484 4485 void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW, 4486 bool ShouldPreserveUseListOrder, 4487 bool IsForDebug) const { 4488 SlotTracker SlotTable(this->getParent()); 4489 formatted_raw_ostream OS(ROS); 4490 AssemblyWriter W(OS, SlotTable, this->getParent(), AAW, 4491 IsForDebug, 4492 ShouldPreserveUseListOrder); 4493 W.printFunction(this); 4494 } 4495 4496 void BasicBlock::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW, 4497 bool ShouldPreserveUseListOrder, 4498 bool IsForDebug) const { 4499 SlotTracker SlotTable(this->getParent()); 4500 formatted_raw_ostream OS(ROS); 4501 AssemblyWriter W(OS, SlotTable, this->getModule(), AAW, 4502 IsForDebug, 4503 ShouldPreserveUseListOrder); 4504 W.printBasicBlock(this); 4505 } 4506 4507 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW, 4508 bool ShouldPreserveUseListOrder, bool IsForDebug) const { 4509 SlotTracker SlotTable(this); 4510 formatted_raw_ostream OS(ROS); 4511 AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug, 4512 ShouldPreserveUseListOrder); 4513 W.printModule(this); 4514 } 4515 4516 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const { 4517 SlotTracker SlotTable(getParent()); 4518 formatted_raw_ostream OS(ROS); 4519 AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug); 4520 W.printNamedMDNode(this); 4521 } 4522 4523 void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST, 4524 bool IsForDebug) const { 4525 Optional<SlotTracker> LocalST; 4526 SlotTracker *SlotTable; 4527 if (auto *ST = MST.getMachine()) 4528 SlotTable = ST; 4529 else { 4530 LocalST.emplace(getParent()); 4531 SlotTable = &*LocalST; 4532 } 4533 4534 formatted_raw_ostream OS(ROS); 4535 AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug); 4536 W.printNamedMDNode(this); 4537 } 4538 4539 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const { 4540 PrintLLVMName(ROS, getName(), ComdatPrefix); 4541 ROS << " = comdat "; 4542 4543 switch (getSelectionKind()) { 4544 case Comdat::Any: 4545 ROS << "any"; 4546 break; 4547 case Comdat::ExactMatch: 4548 ROS << "exactmatch"; 4549 break; 4550 case Comdat::Largest: 4551 ROS << "largest"; 4552 break; 4553 case Comdat::NoDeduplicate: 4554 ROS << "nodeduplicate"; 4555 break; 4556 case Comdat::SameSize: 4557 ROS << "samesize"; 4558 break; 4559 } 4560 4561 ROS << '\n'; 4562 } 4563 4564 void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const { 4565 TypePrinting TP; 4566 TP.print(const_cast<Type*>(this), OS); 4567 4568 if (NoDetails) 4569 return; 4570 4571 // If the type is a named struct type, print the body as well. 4572 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this))) 4573 if (!STy->isLiteral()) { 4574 OS << " = type "; 4575 TP.printStructBody(STy, OS); 4576 } 4577 } 4578 4579 static bool isReferencingMDNode(const Instruction &I) { 4580 if (const auto *CI = dyn_cast<CallInst>(&I)) 4581 if (Function *F = CI->getCalledFunction()) 4582 if (F->isIntrinsic()) 4583 for (auto &Op : I.operands()) 4584 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op)) 4585 if (isa<MDNode>(V->getMetadata())) 4586 return true; 4587 return false; 4588 } 4589 4590 void Value::print(raw_ostream &ROS, bool IsForDebug) const { 4591 bool ShouldInitializeAllMetadata = false; 4592 if (auto *I = dyn_cast<Instruction>(this)) 4593 ShouldInitializeAllMetadata = isReferencingMDNode(*I); 4594 else if (isa<Function>(this) || isa<MetadataAsValue>(this)) 4595 ShouldInitializeAllMetadata = true; 4596 4597 ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata); 4598 print(ROS, MST, IsForDebug); 4599 } 4600 4601 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST, 4602 bool IsForDebug) const { 4603 formatted_raw_ostream OS(ROS); 4604 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr)); 4605 SlotTracker &SlotTable = 4606 MST.getMachine() ? *MST.getMachine() : EmptySlotTable; 4607 auto incorporateFunction = [&](const Function *F) { 4608 if (F) 4609 MST.incorporateFunction(*F); 4610 }; 4611 4612 if (const Instruction *I = dyn_cast<Instruction>(this)) { 4613 incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr); 4614 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug); 4615 W.printInstruction(*I); 4616 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) { 4617 incorporateFunction(BB->getParent()); 4618 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug); 4619 W.printBasicBlock(BB); 4620 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) { 4621 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug); 4622 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV)) 4623 W.printGlobal(V); 4624 else if (const Function *F = dyn_cast<Function>(GV)) 4625 W.printFunction(F); 4626 else if (const GlobalAlias *A = dyn_cast<GlobalAlias>(GV)) 4627 W.printAlias(A); 4628 else if (const GlobalIFunc *I = dyn_cast<GlobalIFunc>(GV)) 4629 W.printIFunc(I); 4630 else 4631 llvm_unreachable("Unknown GlobalValue to print out!"); 4632 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) { 4633 V->getMetadata()->print(ROS, MST, getModuleFromVal(V)); 4634 } else if (const Constant *C = dyn_cast<Constant>(this)) { 4635 TypePrinting TypePrinter; 4636 TypePrinter.print(C->getType(), OS); 4637 OS << ' '; 4638 AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine()); 4639 WriteConstantInternal(OS, C, WriterCtx); 4640 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) { 4641 this->printAsOperand(OS, /* PrintType */ true, MST); 4642 } else { 4643 llvm_unreachable("Unknown value to print out!"); 4644 } 4645 } 4646 4647 /// Print without a type, skipping the TypePrinting object. 4648 /// 4649 /// \return \c true iff printing was successful. 4650 static bool printWithoutType(const Value &V, raw_ostream &O, 4651 SlotTracker *Machine, const Module *M) { 4652 if (V.hasName() || isa<GlobalValue>(V) || 4653 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) { 4654 AsmWriterContext WriterCtx(nullptr, Machine, M); 4655 WriteAsOperandInternal(O, &V, WriterCtx); 4656 return true; 4657 } 4658 return false; 4659 } 4660 4661 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType, 4662 ModuleSlotTracker &MST) { 4663 TypePrinting TypePrinter(MST.getModule()); 4664 if (PrintType) { 4665 TypePrinter.print(V.getType(), O); 4666 O << ' '; 4667 } 4668 4669 AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine(), MST.getModule()); 4670 WriteAsOperandInternal(O, &V, WriterCtx); 4671 } 4672 4673 void Value::printAsOperand(raw_ostream &O, bool PrintType, 4674 const Module *M) const { 4675 if (!M) 4676 M = getModuleFromVal(this); 4677 4678 if (!PrintType) 4679 if (printWithoutType(*this, O, nullptr, M)) 4680 return; 4681 4682 SlotTracker Machine( 4683 M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this)); 4684 ModuleSlotTracker MST(Machine, M); 4685 printAsOperandImpl(*this, O, PrintType, MST); 4686 } 4687 4688 void Value::printAsOperand(raw_ostream &O, bool PrintType, 4689 ModuleSlotTracker &MST) const { 4690 if (!PrintType) 4691 if (printWithoutType(*this, O, MST.getMachine(), MST.getModule())) 4692 return; 4693 4694 printAsOperandImpl(*this, O, PrintType, MST); 4695 } 4696 4697 /// Recursive version of printMetadataImpl. 4698 static void printMetadataImplRec(raw_ostream &ROS, const Metadata &MD, 4699 AsmWriterContext &WriterCtx) { 4700 formatted_raw_ostream OS(ROS); 4701 WriteAsOperandInternal(OS, &MD, WriterCtx, /* FromValue */ true); 4702 4703 auto *N = dyn_cast<MDNode>(&MD); 4704 if (!N || isa<DIExpression>(MD) || isa<DIArgList>(MD)) 4705 return; 4706 4707 OS << " = "; 4708 WriteMDNodeBodyInternal(OS, N, WriterCtx); 4709 } 4710 4711 namespace { 4712 struct MDTreeAsmWriterContext : public AsmWriterContext { 4713 unsigned Level; 4714 // {Level, Printed string} 4715 using EntryTy = std::pair<unsigned, std::string>; 4716 SmallVector<EntryTy, 4> Buffer; 4717 4718 // Used to break the cycle in case there is any. 4719 SmallPtrSet<const Metadata *, 4> Visited; 4720 4721 raw_ostream &MainOS; 4722 4723 MDTreeAsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M, 4724 raw_ostream &OS, const Metadata *InitMD) 4725 : AsmWriterContext(TP, ST, M), Level(0U), Visited({InitMD}), MainOS(OS) {} 4726 4727 void onWriteMetadataAsOperand(const Metadata *MD) override { 4728 if (Visited.count(MD)) 4729 return; 4730 Visited.insert(MD); 4731 4732 std::string Str; 4733 raw_string_ostream SS(Str); 4734 ++Level; 4735 // A placeholder entry to memorize the correct 4736 // position in buffer. 4737 Buffer.emplace_back(std::make_pair(Level, "")); 4738 unsigned InsertIdx = Buffer.size() - 1; 4739 4740 printMetadataImplRec(SS, *MD, *this); 4741 Buffer[InsertIdx].second = std::move(SS.str()); 4742 --Level; 4743 } 4744 4745 ~MDTreeAsmWriterContext() { 4746 for (const auto &Entry : Buffer) { 4747 MainOS << "\n"; 4748 unsigned NumIndent = Entry.first * 2U; 4749 MainOS.indent(NumIndent) << Entry.second; 4750 } 4751 } 4752 }; 4753 } // end anonymous namespace 4754 4755 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD, 4756 ModuleSlotTracker &MST, const Module *M, 4757 bool OnlyAsOperand, bool PrintAsTree = false) { 4758 formatted_raw_ostream OS(ROS); 4759 4760 TypePrinting TypePrinter(M); 4761 4762 std::unique_ptr<AsmWriterContext> WriterCtx; 4763 if (PrintAsTree && !OnlyAsOperand) 4764 WriterCtx = std::make_unique<MDTreeAsmWriterContext>( 4765 &TypePrinter, MST.getMachine(), M, OS, &MD); 4766 else 4767 WriterCtx = 4768 std::make_unique<AsmWriterContext>(&TypePrinter, MST.getMachine(), M); 4769 4770 WriteAsOperandInternal(OS, &MD, *WriterCtx, /* FromValue */ true); 4771 4772 auto *N = dyn_cast<MDNode>(&MD); 4773 if (OnlyAsOperand || !N || isa<DIExpression>(MD) || isa<DIArgList>(MD)) 4774 return; 4775 4776 OS << " = "; 4777 WriteMDNodeBodyInternal(OS, N, *WriterCtx); 4778 } 4779 4780 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const { 4781 ModuleSlotTracker MST(M, isa<MDNode>(this)); 4782 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true); 4783 } 4784 4785 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST, 4786 const Module *M) const { 4787 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true); 4788 } 4789 4790 void Metadata::print(raw_ostream &OS, const Module *M, 4791 bool /*IsForDebug*/) const { 4792 ModuleSlotTracker MST(M, isa<MDNode>(this)); 4793 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false); 4794 } 4795 4796 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST, 4797 const Module *M, bool /*IsForDebug*/) const { 4798 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false); 4799 } 4800 4801 void MDNode::printTree(raw_ostream &OS, const Module *M) const { 4802 ModuleSlotTracker MST(M, true); 4803 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false, 4804 /*PrintAsTree=*/true); 4805 } 4806 4807 void MDNode::printTree(raw_ostream &OS, ModuleSlotTracker &MST, 4808 const Module *M) const { 4809 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false, 4810 /*PrintAsTree=*/true); 4811 } 4812 4813 void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const { 4814 SlotTracker SlotTable(this); 4815 formatted_raw_ostream OS(ROS); 4816 AssemblyWriter W(OS, SlotTable, this, IsForDebug); 4817 W.printModuleSummaryIndex(); 4818 } 4819 4820 void ModuleSlotTracker::collectMDNodes(MachineMDNodeListType &L, unsigned LB, 4821 unsigned UB) const { 4822 SlotTracker *ST = MachineStorage.get(); 4823 if (!ST) 4824 return; 4825 4826 for (auto &I : llvm::make_range(ST->mdn_begin(), ST->mdn_end())) 4827 if (I.second >= LB && I.second < UB) 4828 L.push_back(std::make_pair(I.second, I.first)); 4829 } 4830 4831 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 4832 // Value::dump - allow easy printing of Values from the debugger. 4833 LLVM_DUMP_METHOD 4834 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; } 4835 4836 // Type::dump - allow easy printing of Types from the debugger. 4837 LLVM_DUMP_METHOD 4838 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; } 4839 4840 // Module::dump() - Allow printing of Modules from the debugger. 4841 LLVM_DUMP_METHOD 4842 void Module::dump() const { 4843 print(dbgs(), nullptr, 4844 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true); 4845 } 4846 4847 // Allow printing of Comdats from the debugger. 4848 LLVM_DUMP_METHOD 4849 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); } 4850 4851 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger. 4852 LLVM_DUMP_METHOD 4853 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); } 4854 4855 LLVM_DUMP_METHOD 4856 void Metadata::dump() const { dump(nullptr); } 4857 4858 LLVM_DUMP_METHOD 4859 void Metadata::dump(const Module *M) const { 4860 print(dbgs(), M, /*IsForDebug=*/true); 4861 dbgs() << '\n'; 4862 } 4863 4864 LLVM_DUMP_METHOD 4865 void MDNode::dumpTree() const { dumpTree(nullptr); } 4866 4867 LLVM_DUMP_METHOD 4868 void MDNode::dumpTree(const Module *M) const { 4869 printTree(dbgs(), M); 4870 dbgs() << '\n'; 4871 } 4872 4873 // Allow printing of ModuleSummaryIndex from the debugger. 4874 LLVM_DUMP_METHOD 4875 void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); } 4876 #endif 4877