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