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