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