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