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