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