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