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