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