1 //===- AsmWriter.cpp - Printing LLVM as an assembly file ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/IR/Writer.h
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.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/ADT/APFloat.h"
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/iterator_range.h"
30 #include "llvm/BinaryFormat/Dwarf.h"
31 #include "llvm/IR/Argument.h"
32 #include "llvm/IR/AssemblyAnnotationWriter.h"
33 #include "llvm/IR/Attributes.h"
34 #include "llvm/IR/BasicBlock.h"
35 #include "llvm/IR/CFG.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Comdat.h"
39 #include "llvm/IR/Constant.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DebugInfoMetadata.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/GlobalAlias.h"
45 #include "llvm/IR/GlobalIFunc.h"
46 #include "llvm/IR/GlobalIndirectSymbol.h"
47 #include "llvm/IR/GlobalObject.h"
48 #include "llvm/IR/GlobalValue.h"
49 #include "llvm/IR/GlobalVariable.h"
50 #include "llvm/IR/IRPrintingPasses.h"
51 #include "llvm/IR/InlineAsm.h"
52 #include "llvm/IR/InstrTypes.h"
53 #include "llvm/IR/Instruction.h"
54 #include "llvm/IR/Instructions.h"
55 #include "llvm/IR/LLVMContext.h"
56 #include "llvm/IR/Metadata.h"
57 #include "llvm/IR/Module.h"
58 #include "llvm/IR/ModuleSlotTracker.h"
59 #include "llvm/IR/Operator.h"
60 #include "llvm/IR/Statepoint.h"
61 #include "llvm/IR/Type.h"
62 #include "llvm/IR/TypeFinder.h"
63 #include "llvm/IR/Use.h"
64 #include "llvm/IR/UseListOrder.h"
65 #include "llvm/IR/User.h"
66 #include "llvm/IR/Value.h"
67 #include "llvm/Support/AtomicOrdering.h"
68 #include "llvm/Support/Casting.h"
69 #include "llvm/Support/Compiler.h"
70 #include "llvm/Support/Debug.h"
71 #include "llvm/Support/ErrorHandling.h"
72 #include "llvm/Support/Format.h"
73 #include "llvm/Support/FormattedStream.h"
74 #include "llvm/Support/raw_ostream.h"
89 // Make virtual table appear in this compilation unit.
90 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() = default;
92 //===----------------------------------------------------------------------===//
94 //===----------------------------------------------------------------------===//
99 DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
101 unsigned size() const { return IDs.size(); }
102 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
104 std::pair<unsigned, bool> lookup(const Value *V) const {
105 return IDs.lookup(V);
108 void index(const Value *V) {
109 // Explicitly sequence get-size and insert-value operations to avoid UB.
110 unsigned ID = IDs.size() + 1;
115 } // end anonymous namespace
117 static void orderValue(const Value *V, OrderMap &OM) {
118 if (OM.lookup(V).first)
121 if (const Constant *C = dyn_cast<Constant>(V))
122 if (C->getNumOperands() && !isa<GlobalValue>(C))
123 for (const Value *Op : C->operands())
124 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
127 // Note: we cannot cache this lookup above, since inserting into the map
128 // changes the map's size, and thus affects the other IDs.
132 static OrderMap orderModule(const Module *M) {
133 // This needs to match the order used by ValueEnumerator::ValueEnumerator()
134 // and ValueEnumerator::incorporateFunction().
137 for (const GlobalVariable &G : M->globals()) {
138 if (G.hasInitializer())
139 if (!isa<GlobalValue>(G.getInitializer()))
140 orderValue(G.getInitializer(), OM);
143 for (const GlobalAlias &A : M->aliases()) {
144 if (!isa<GlobalValue>(A.getAliasee()))
145 orderValue(A.getAliasee(), OM);
148 for (const GlobalIFunc &I : M->ifuncs()) {
149 if (!isa<GlobalValue>(I.getResolver()))
150 orderValue(I.getResolver(), OM);
153 for (const Function &F : *M) {
154 for (const Use &U : F.operands())
155 if (!isa<GlobalValue>(U.get()))
156 orderValue(U.get(), OM);
160 if (F.isDeclaration())
163 for (const Argument &A : F.args())
165 for (const BasicBlock &BB : F) {
167 for (const Instruction &I : BB) {
168 for (const Value *Op : I.operands())
169 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
179 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
180 unsigned ID, const OrderMap &OM,
181 UseListOrderStack &Stack) {
182 // Predict use-list order for this one.
183 using Entry = std::pair<const Use *, unsigned>;
184 SmallVector<Entry, 64> List;
185 for (const Use &U : V->uses())
186 // Check if this user will be serialized.
187 if (OM.lookup(U.getUser()).first)
188 List.push_back(std::make_pair(&U, List.size()));
191 // We may have lost some users.
195 !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
196 if (auto *BA = dyn_cast<BlockAddress>(V))
197 ID = OM.lookup(BA->getBasicBlock()).first;
198 std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
199 const Use *LU = L.first;
200 const Use *RU = R.first;
204 auto LID = OM.lookup(LU->getUser()).first;
205 auto RID = OM.lookup(RU->getUser()).first;
207 // If ID is 4, then expect: 7 6 5 1 2 3.
221 // LID and RID are equal, so we have different operands of the same user.
222 // Assume operands are added in order for all instructions.
225 return LU->getOperandNo() < RU->getOperandNo();
226 return LU->getOperandNo() > RU->getOperandNo();
230 List.begin(), List.end(),
231 [](const Entry &L, const Entry &R) { return L.second < R.second; }))
232 // Order is already correct.
235 // Store the shuffle.
236 Stack.emplace_back(V, F, List.size());
237 assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
238 for (size_t I = 0, E = List.size(); I != E; ++I)
239 Stack.back().Shuffle[I] = List[I].second;
242 static void predictValueUseListOrder(const Value *V, const Function *F,
243 OrderMap &OM, UseListOrderStack &Stack) {
244 auto &IDPair = OM[V];
245 assert(IDPair.first && "Unmapped value");
247 // Already predicted.
250 // Do the actual prediction.
251 IDPair.second = true;
252 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
253 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
255 // Recursive descent into constants.
256 if (const Constant *C = dyn_cast<Constant>(V))
257 if (C->getNumOperands()) // Visit GlobalValues.
258 for (const Value *Op : C->operands())
259 if (isa<Constant>(Op)) // Visit GlobalValues.
260 predictValueUseListOrder(Op, F, OM, Stack);
263 static UseListOrderStack predictUseListOrder(const Module *M) {
264 OrderMap OM = orderModule(M);
266 // Use-list orders need to be serialized after all the users have been added
267 // to a value, or else the shuffles will be incomplete. Store them per
268 // function in a stack.
270 // Aside from function order, the order of values doesn't matter much here.
271 UseListOrderStack Stack;
273 // We want to visit the functions backward now so we can list function-local
274 // constants in the last Function they're used in. Module-level constants
275 // have already been visited above.
276 for (const Function &F : make_range(M->rbegin(), M->rend())) {
277 if (F.isDeclaration())
279 for (const BasicBlock &BB : F)
280 predictValueUseListOrder(&BB, &F, OM, Stack);
281 for (const Argument &A : F.args())
282 predictValueUseListOrder(&A, &F, OM, Stack);
283 for (const BasicBlock &BB : F)
284 for (const Instruction &I : BB)
285 for (const Value *Op : I.operands())
286 if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
287 predictValueUseListOrder(Op, &F, OM, Stack);
288 for (const BasicBlock &BB : F)
289 for (const Instruction &I : BB)
290 predictValueUseListOrder(&I, &F, OM, Stack);
293 // Visit globals last.
294 for (const GlobalVariable &G : M->globals())
295 predictValueUseListOrder(&G, nullptr, OM, Stack);
296 for (const Function &F : *M)
297 predictValueUseListOrder(&F, nullptr, OM, Stack);
298 for (const GlobalAlias &A : M->aliases())
299 predictValueUseListOrder(&A, nullptr, OM, Stack);
300 for (const GlobalIFunc &I : M->ifuncs())
301 predictValueUseListOrder(&I, nullptr, OM, Stack);
302 for (const GlobalVariable &G : M->globals())
303 if (G.hasInitializer())
304 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
305 for (const GlobalAlias &A : M->aliases())
306 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
307 for (const GlobalIFunc &I : M->ifuncs())
308 predictValueUseListOrder(I.getResolver(), nullptr, OM, Stack);
309 for (const Function &F : *M)
310 for (const Use &U : F.operands())
311 predictValueUseListOrder(U.get(), nullptr, OM, Stack);
316 static const Module *getModuleFromVal(const Value *V) {
317 if (const Argument *MA = dyn_cast<Argument>(V))
318 return MA->getParent() ? MA->getParent()->getParent() : nullptr;
320 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
321 return BB->getParent() ? BB->getParent()->getParent() : nullptr;
323 if (const Instruction *I = dyn_cast<Instruction>(V)) {
324 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
325 return M ? M->getParent() : nullptr;
328 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
329 return GV->getParent();
331 if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
332 for (const User *U : MAV->users())
333 if (isa<Instruction>(U))
334 if (const Module *M = getModuleFromVal(U))
342 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
344 default: Out << "cc" << cc; break;
345 case CallingConv::Fast: Out << "fastcc"; break;
346 case CallingConv::Cold: Out << "coldcc"; break;
347 case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
348 case CallingConv::AnyReg: Out << "anyregcc"; break;
349 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
350 case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
351 case CallingConv::CXX_FAST_TLS: Out << "cxx_fast_tlscc"; break;
352 case CallingConv::GHC: Out << "ghccc"; break;
353 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
354 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
355 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
356 case CallingConv::X86_RegCall: Out << "x86_regcallcc"; break;
357 case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
358 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
359 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
360 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
361 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
362 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
363 case CallingConv::AVR_INTR: Out << "avr_intrcc "; break;
364 case CallingConv::AVR_SIGNAL: Out << "avr_signalcc "; break;
365 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
366 case CallingConv::PTX_Device: Out << "ptx_device"; break;
367 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
368 case CallingConv::Win64: Out << "win64cc"; break;
369 case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
370 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
371 case CallingConv::Swift: Out << "swiftcc"; break;
372 case CallingConv::X86_INTR: Out << "x86_intrcc"; break;
373 case CallingConv::HHVM: Out << "hhvmcc"; break;
374 case CallingConv::HHVM_C: Out << "hhvm_ccc"; break;
375 case CallingConv::AMDGPU_VS: Out << "amdgpu_vs"; break;
376 case CallingConv::AMDGPU_LS: Out << "amdgpu_ls"; break;
377 case CallingConv::AMDGPU_HS: Out << "amdgpu_hs"; break;
378 case CallingConv::AMDGPU_ES: Out << "amdgpu_es"; break;
379 case CallingConv::AMDGPU_GS: Out << "amdgpu_gs"; break;
380 case CallingConv::AMDGPU_PS: Out << "amdgpu_ps"; break;
381 case CallingConv::AMDGPU_CS: Out << "amdgpu_cs"; break;
382 case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;
386 void llvm::PrintEscapedString(StringRef Name, raw_ostream &Out) {
387 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
388 unsigned char C = Name[i];
389 if (isprint(C) && C != '\\' && C != '"')
392 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
404 void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
405 assert(!Name.empty() && "Cannot get empty name!");
407 // Scan the name to see if it needs quotes first.
408 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
410 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
411 // By making this unsigned, the value passed in to isalnum will always be
412 // in the range 0-255. This is important when building with MSVC because
413 // its implementation will assert. This situation can arise when dealing
414 // with UTF-8 multibyte characters.
415 unsigned char C = Name[i];
416 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
424 // If we didn't need any quotes, just write out the name in one blast.
430 // Okay, we need quotes. Output the quotes and escape any scary characters as
433 PrintEscapedString(Name, OS);
437 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
438 /// (if the string only contains simple characters) or is surrounded with ""'s
439 /// (if it has special chars in it). Print it out.
440 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
456 printLLVMNameWithoutPrefix(OS, Name);
459 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
460 /// (if the string only contains simple characters) or is surrounded with ""'s
461 /// (if it has special chars in it). Print it out.
462 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
463 PrintLLVMName(OS, V->getName(),
464 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
471 /// NamedTypes - The named types that are used by the current module.
472 TypeFinder NamedTypes;
474 /// NumberedTypes - The numbered types, along with their value.
475 DenseMap<StructType*, unsigned> NumberedTypes;
477 TypePrinting() = default;
478 TypePrinting(const TypePrinting &) = delete;
479 TypePrinting &operator=(const TypePrinting &) = delete;
481 void incorporateTypes(const Module &M);
483 void print(Type *Ty, raw_ostream &OS);
485 void printStructBody(StructType *Ty, raw_ostream &OS);
488 } // end anonymous namespace
490 void TypePrinting::incorporateTypes(const Module &M) {
491 NamedTypes.run(M, false);
493 // The list of struct types we got back includes all the struct types, split
494 // the unnamed ones out to a numbering and remove the anonymous structs.
495 unsigned NextNumber = 0;
497 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
498 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
499 StructType *STy = *I;
501 // Ignore anonymous types.
502 if (STy->isLiteral())
505 if (STy->getName().empty())
506 NumberedTypes[STy] = NextNumber++;
511 NamedTypes.erase(NextToUse, NamedTypes.end());
515 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
516 /// use of type names or up references to shorten the type name where possible.
517 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
518 switch (Ty->getTypeID()) {
519 case Type::VoidTyID: OS << "void"; return;
520 case Type::HalfTyID: OS << "half"; return;
521 case Type::FloatTyID: OS << "float"; return;
522 case Type::DoubleTyID: OS << "double"; return;
523 case Type::X86_FP80TyID: OS << "x86_fp80"; return;
524 case Type::FP128TyID: OS << "fp128"; return;
525 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
526 case Type::LabelTyID: OS << "label"; return;
527 case Type::MetadataTyID: OS << "metadata"; return;
528 case Type::X86_MMXTyID: OS << "x86_mmx"; return;
529 case Type::TokenTyID: OS << "token"; return;
530 case Type::IntegerTyID:
531 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
534 case Type::FunctionTyID: {
535 FunctionType *FTy = cast<FunctionType>(Ty);
536 print(FTy->getReturnType(), OS);
538 for (FunctionType::param_iterator I = FTy->param_begin(),
539 E = FTy->param_end(); I != E; ++I) {
540 if (I != FTy->param_begin())
544 if (FTy->isVarArg()) {
545 if (FTy->getNumParams()) OS << ", ";
551 case Type::StructTyID: {
552 StructType *STy = cast<StructType>(Ty);
554 if (STy->isLiteral())
555 return printStructBody(STy, OS);
557 if (!STy->getName().empty())
558 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
560 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
561 if (I != NumberedTypes.end())
562 OS << '%' << I->second;
563 else // Not enumerated, print the hex address.
564 OS << "%\"type " << STy << '\"';
567 case Type::PointerTyID: {
568 PointerType *PTy = cast<PointerType>(Ty);
569 print(PTy->getElementType(), OS);
570 if (unsigned AddressSpace = PTy->getAddressSpace())
571 OS << " addrspace(" << AddressSpace << ')';
575 case Type::ArrayTyID: {
576 ArrayType *ATy = cast<ArrayType>(Ty);
577 OS << '[' << ATy->getNumElements() << " x ";
578 print(ATy->getElementType(), OS);
582 case Type::VectorTyID: {
583 VectorType *PTy = cast<VectorType>(Ty);
584 OS << "<" << PTy->getNumElements() << " x ";
585 print(PTy->getElementType(), OS);
590 llvm_unreachable("Invalid TypeID");
593 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
594 if (STy->isOpaque()) {
602 if (STy->getNumElements() == 0) {
605 StructType::element_iterator I = STy->element_begin();
608 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
621 //===----------------------------------------------------------------------===//
622 // SlotTracker Class: Enumerate slot numbers for unnamed values
623 //===----------------------------------------------------------------------===//
624 /// This class provides computation of slot numbers for LLVM Assembly writing.
628 /// ValueMap - A mapping of Values to slot numbers.
629 using ValueMap = DenseMap<const Value *, unsigned>;
632 /// TheModule - The module for which we are holding slot numbers.
633 const Module* TheModule;
635 /// TheFunction - The function for which we are holding slot numbers.
636 const Function* TheFunction = nullptr;
637 bool FunctionProcessed = false;
638 bool ShouldInitializeAllMetadata;
640 /// mMap - The slot map for the module level data.
644 /// fMap - The slot map for the function level data.
648 /// mdnMap - Map for MDNodes.
649 DenseMap<const MDNode*, unsigned> mdnMap;
650 unsigned mdnNext = 0;
652 /// asMap - The slot map for attribute sets.
653 DenseMap<AttributeSet, unsigned> asMap;
657 /// Construct from a module.
659 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
660 /// functions, giving correct numbering for metadata referenced only from
661 /// within a function (even if no functions have been initialized).
662 explicit SlotTracker(const Module *M,
663 bool ShouldInitializeAllMetadata = false);
665 /// Construct from a function, starting out in incorp state.
667 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
668 /// functions, giving correct numbering for metadata referenced only from
669 /// within a function (even if no functions have been initialized).
670 explicit SlotTracker(const Function *F,
671 bool ShouldInitializeAllMetadata = false);
673 SlotTracker(const SlotTracker &) = delete;
674 SlotTracker &operator=(const SlotTracker &) = delete;
676 /// Return the slot number of the specified value in it's type
677 /// plane. If something is not in the SlotTracker, return -1.
678 int getLocalSlot(const Value *V);
679 int getGlobalSlot(const GlobalValue *V);
680 int getMetadataSlot(const MDNode *N);
681 int getAttributeGroupSlot(AttributeSet AS);
683 /// If you'd like to deal with a function instead of just a module, use
684 /// this method to get its data into the SlotTracker.
685 void incorporateFunction(const Function *F) {
687 FunctionProcessed = false;
690 const Function *getFunction() const { return TheFunction; }
692 /// After calling incorporateFunction, use this method to remove the
693 /// most recently incorporated function from the SlotTracker. This
694 /// will reset the state of the machine back to just the module contents.
695 void purgeFunction();
697 /// MDNode map iterators.
698 using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;
700 mdn_iterator mdn_begin() { return mdnMap.begin(); }
701 mdn_iterator mdn_end() { return mdnMap.end(); }
702 unsigned mdn_size() const { return mdnMap.size(); }
703 bool mdn_empty() const { return mdnMap.empty(); }
705 /// AttributeSet map iterators.
706 using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;
708 as_iterator as_begin() { return asMap.begin(); }
709 as_iterator as_end() { return asMap.end(); }
710 unsigned as_size() const { return asMap.size(); }
711 bool as_empty() const { return asMap.empty(); }
713 /// This function does the actual initialization.
714 inline void initialize();
716 // Implementation Details
718 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
719 void CreateModuleSlot(const GlobalValue *V);
721 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
722 void CreateMetadataSlot(const MDNode *N);
724 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
725 void CreateFunctionSlot(const Value *V);
727 /// \brief Insert the specified AttributeSet into the slot table.
728 void CreateAttributeSetSlot(AttributeSet AS);
730 /// Add all of the module level global variables (and their initializers)
731 /// and function declarations, but not the contents of those functions.
732 void processModule();
734 /// Add all of the functions arguments, basic blocks, and instructions.
735 void processFunction();
737 /// Add the metadata directly attached to a GlobalObject.
738 void processGlobalObjectMetadata(const GlobalObject &GO);
740 /// Add all of the metadata from a function.
741 void processFunctionMetadata(const Function &F);
743 /// Add all of the metadata from an instruction.
744 void processInstructionMetadata(const Instruction &I);
747 } // end namespace llvm
749 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
751 : M(M), F(F), Machine(&Machine) {}
753 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
754 bool ShouldInitializeAllMetadata)
755 : ShouldCreateStorage(M),
756 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
758 ModuleSlotTracker::~ModuleSlotTracker() = default;
760 SlotTracker *ModuleSlotTracker::getMachine() {
761 if (!ShouldCreateStorage)
764 ShouldCreateStorage = false;
766 llvm::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
767 Machine = MachineStorage.get();
771 void ModuleSlotTracker::incorporateFunction(const Function &F) {
772 // Using getMachine() may lazily create the slot tracker.
776 // Nothing to do if this is the right function already.
780 Machine->purgeFunction();
781 Machine->incorporateFunction(&F);
785 int ModuleSlotTracker::getLocalSlot(const Value *V) {
786 assert(F && "No function incorporated");
787 return Machine->getLocalSlot(V);
790 static SlotTracker *createSlotTracker(const Value *V) {
791 if (const Argument *FA = dyn_cast<Argument>(V))
792 return new SlotTracker(FA->getParent());
794 if (const Instruction *I = dyn_cast<Instruction>(V))
796 return new SlotTracker(I->getParent()->getParent());
798 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
799 return new SlotTracker(BB->getParent());
801 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
802 return new SlotTracker(GV->getParent());
804 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
805 return new SlotTracker(GA->getParent());
807 if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
808 return new SlotTracker(GIF->getParent());
810 if (const Function *Func = dyn_cast<Function>(V))
811 return new SlotTracker(Func);
817 #define ST_DEBUG(X) dbgs() << X
822 // Module level constructor. Causes the contents of the Module (sans functions)
823 // to be added to the slot table.
824 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
825 : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
827 // Function level constructor. Causes the contents of the Module and the one
828 // function provided to be added to the slot table.
829 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
830 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
831 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
833 inline void SlotTracker::initialize() {
836 TheModule = nullptr; ///< Prevent re-processing next time we're called.
839 if (TheFunction && !FunctionProcessed)
843 // Iterate through all the global variables, functions, and global
844 // variable initializers and create slots for them.
845 void SlotTracker::processModule() {
846 ST_DEBUG("begin processModule!\n");
848 // Add all of the unnamed global variables to the value table.
849 for (const GlobalVariable &Var : TheModule->globals()) {
851 CreateModuleSlot(&Var);
852 processGlobalObjectMetadata(Var);
853 auto Attrs = Var.getAttributes();
854 if (Attrs.hasAttributes())
855 CreateAttributeSetSlot(Attrs);
858 for (const GlobalAlias &A : TheModule->aliases()) {
860 CreateModuleSlot(&A);
863 for (const GlobalIFunc &I : TheModule->ifuncs()) {
865 CreateModuleSlot(&I);
868 // Add metadata used by named metadata.
869 for (const NamedMDNode &NMD : TheModule->named_metadata()) {
870 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
871 CreateMetadataSlot(NMD.getOperand(i));
874 for (const Function &F : *TheModule) {
876 // Add all the unnamed functions to the table.
877 CreateModuleSlot(&F);
879 if (ShouldInitializeAllMetadata)
880 processFunctionMetadata(F);
882 // Add all the function attributes to the table.
883 // FIXME: Add attributes of other objects?
884 AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
885 if (FnAttrs.hasAttributes())
886 CreateAttributeSetSlot(FnAttrs);
889 ST_DEBUG("end processModule!\n");
892 // Process the arguments, basic blocks, and instructions of a function.
893 void SlotTracker::processFunction() {
894 ST_DEBUG("begin processFunction!\n");
897 // Process function metadata if it wasn't hit at the module-level.
898 if (!ShouldInitializeAllMetadata)
899 processFunctionMetadata(*TheFunction);
901 // Add all the function arguments with no names.
902 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
903 AE = TheFunction->arg_end(); AI != AE; ++AI)
905 CreateFunctionSlot(&*AI);
907 ST_DEBUG("Inserting Instructions:\n");
909 // Add all of the basic blocks and instructions with no names.
910 for (auto &BB : *TheFunction) {
912 CreateFunctionSlot(&BB);
915 if (!I.getType()->isVoidTy() && !I.hasName())
916 CreateFunctionSlot(&I);
918 // We allow direct calls to any llvm.foo function here, because the
919 // target may not be linked into the optimizer.
920 if (auto CS = ImmutableCallSite(&I)) {
921 // Add all the call attributes to the table.
922 AttributeSet Attrs = CS.getAttributes().getFnAttributes();
923 if (Attrs.hasAttributes())
924 CreateAttributeSetSlot(Attrs);
929 FunctionProcessed = true;
931 ST_DEBUG("end processFunction!\n");
934 void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) {
935 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
936 GO.getAllMetadata(MDs);
938 CreateMetadataSlot(MD.second);
941 void SlotTracker::processFunctionMetadata(const Function &F) {
942 processGlobalObjectMetadata(F);
945 processInstructionMetadata(I);
949 void SlotTracker::processInstructionMetadata(const Instruction &I) {
950 // Process metadata used directly by intrinsics.
951 if (const CallInst *CI = dyn_cast<CallInst>(&I))
952 if (Function *F = CI->getCalledFunction())
953 if (F->isIntrinsic())
954 for (auto &Op : I.operands())
955 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
956 if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
957 CreateMetadataSlot(N);
959 // Process metadata attached to this instruction.
960 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
961 I.getAllMetadata(MDs);
963 CreateMetadataSlot(MD.second);
966 /// Clean up after incorporating a function. This is the only way to get out of
967 /// the function incorporation state that affects get*Slot/Create*Slot. Function
968 /// incorporation state is indicated by TheFunction != 0.
969 void SlotTracker::purgeFunction() {
970 ST_DEBUG("begin purgeFunction!\n");
971 fMap.clear(); // Simply discard the function level map
972 TheFunction = nullptr;
973 FunctionProcessed = false;
974 ST_DEBUG("end purgeFunction!\n");
977 /// getGlobalSlot - Get the slot number of a global value.
978 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
979 // Check for uninitialized state and do lazy initialization.
982 // Find the value in the module map
983 ValueMap::iterator MI = mMap.find(V);
984 return MI == mMap.end() ? -1 : (int)MI->second;
987 /// getMetadataSlot - Get the slot number of a MDNode.
988 int SlotTracker::getMetadataSlot(const MDNode *N) {
989 // Check for uninitialized state and do lazy initialization.
992 // Find the MDNode in the module map
993 mdn_iterator MI = mdnMap.find(N);
994 return MI == mdnMap.end() ? -1 : (int)MI->second;
997 /// getLocalSlot - Get the slot number for a value that is local to a function.
998 int SlotTracker::getLocalSlot(const Value *V) {
999 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1001 // Check for uninitialized state and do lazy initialization.
1004 ValueMap::iterator FI = fMap.find(V);
1005 return FI == fMap.end() ? -1 : (int)FI->second;
1008 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
1009 // Check for uninitialized state and do lazy initialization.
1012 // Find the AttributeSet in the module map.
1013 as_iterator AI = asMap.find(AS);
1014 return AI == asMap.end() ? -1 : (int)AI->second;
1017 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1018 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
1019 assert(V && "Can't insert a null Value into SlotTracker!");
1020 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
1021 assert(!V->hasName() && "Doesn't need a slot!");
1023 unsigned DestSlot = mNext++;
1026 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1028 // G = Global, F = Function, A = Alias, I = IFunc, o = other
1029 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
1030 (isa<Function>(V) ? 'F' :
1031 (isa<GlobalAlias>(V) ? 'A' :
1032 (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");
1035 /// CreateSlot - Create a new slot for the specified value if it has no name.
1036 void SlotTracker::CreateFunctionSlot(const Value *V) {
1037 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
1039 unsigned DestSlot = fNext++;
1042 // G = Global, F = Function, o = other
1043 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1044 DestSlot << " [o]\n");
1047 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
1048 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
1049 assert(N && "Can't insert a null Value into SlotTracker!");
1051 // Don't make slots for DIExpressions. We just print them inline everywhere.
1052 if (isa<DIExpression>(N))
1055 unsigned DestSlot = mdnNext;
1056 if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
1060 // Recursively add any MDNodes referenced by operands.
1061 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1062 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
1063 CreateMetadataSlot(Op);
1066 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
1067 assert(AS.hasAttributes() && "Doesn't need a slot!");
1069 as_iterator I = asMap.find(AS);
1070 if (I != asMap.end())
1073 unsigned DestSlot = asNext++;
1074 asMap[AS] = DestSlot;
1077 //===----------------------------------------------------------------------===//
1078 // AsmWriter Implementation
1079 //===----------------------------------------------------------------------===//
1081 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1082 TypePrinting *TypePrinter,
1083 SlotTracker *Machine,
1084 const Module *Context);
1086 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1087 TypePrinting *TypePrinter,
1088 SlotTracker *Machine, const Module *Context,
1089 bool FromValue = false);
1091 static void writeAtomicRMWOperation(raw_ostream &Out,
1092 AtomicRMWInst::BinOp Op) {
1094 default: Out << " <unknown operation " << Op << ">"; break;
1095 case AtomicRMWInst::Xchg: Out << " xchg"; break;
1096 case AtomicRMWInst::Add: Out << " add"; break;
1097 case AtomicRMWInst::Sub: Out << " sub"; break;
1098 case AtomicRMWInst::And: Out << " and"; break;
1099 case AtomicRMWInst::Nand: Out << " nand"; break;
1100 case AtomicRMWInst::Or: Out << " or"; break;
1101 case AtomicRMWInst::Xor: Out << " xor"; break;
1102 case AtomicRMWInst::Max: Out << " max"; break;
1103 case AtomicRMWInst::Min: Out << " min"; break;
1104 case AtomicRMWInst::UMax: Out << " umax"; break;
1105 case AtomicRMWInst::UMin: Out << " umin"; break;
1109 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1110 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
1111 // 'Fast' is an abbreviation for all fast-math-flags.
1115 if (FPO->hasAllowReassoc())
1117 if (FPO->hasNoNaNs())
1119 if (FPO->hasNoInfs())
1121 if (FPO->hasNoSignedZeros())
1123 if (FPO->hasAllowReciprocal())
1125 if (FPO->hasAllowContract())
1127 if (FPO->hasApproxFunc())
1132 if (const OverflowingBinaryOperator *OBO =
1133 dyn_cast<OverflowingBinaryOperator>(U)) {
1134 if (OBO->hasNoUnsignedWrap())
1136 if (OBO->hasNoSignedWrap())
1138 } else if (const PossiblyExactOperator *Div =
1139 dyn_cast<PossiblyExactOperator>(U)) {
1142 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1143 if (GEP->isInBounds())
1148 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1149 TypePrinting &TypePrinter,
1150 SlotTracker *Machine,
1151 const Module *Context) {
1152 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1153 if (CI->getType()->isIntegerTy(1)) {
1154 Out << (CI->getZExtValue() ? "true" : "false");
1157 Out << CI->getValue();
1161 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1162 const APFloat &APF = CFP->getValueAPF();
1163 if (&APF.getSemantics() == &APFloat::IEEEsingle() ||
1164 &APF.getSemantics() == &APFloat::IEEEdouble()) {
1165 // We would like to output the FP constant value in exponential notation,
1166 // but we cannot do this if doing so will lose precision. Check here to
1167 // make sure that we only output it in exponential format if we can parse
1168 // the value back and get the same value.
1171 bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble();
1172 bool isInf = APF.isInfinity();
1173 bool isNaN = APF.isNaN();
1174 if (!isInf && !isNaN) {
1175 double Val = isDouble ? APF.convertToDouble() : APF.convertToFloat();
1176 SmallString<128> StrVal;
1177 APF.toString(StrVal, 6, 0, false);
1178 // Check to make sure that the stringized number is not some string like
1179 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
1180 // that the string matches the "[-+]?[0-9]" regex.
1182 assert(((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1183 ((StrVal[0] == '-' || StrVal[0] == '+') &&
1184 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
1185 "[-+]?[0-9] regex does not match!");
1186 // Reparse stringized version!
1187 if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {
1192 // Otherwise we could not reparse it to exactly the same value, so we must
1193 // output the string in hexadecimal format! Note that loading and storing
1194 // floating point types changes the bits of NaNs on some hosts, notably
1195 // x86, so we must not use these types.
1196 static_assert(sizeof(double) == sizeof(uint64_t),
1197 "assuming that double is 64 bits!");
1199 // Floats are represented in ASCII IR as double, convert.
1201 apf.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
1203 Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
1207 // Either half, or some form of long double.
1208 // These appear as a magic letter identifying the type, then a
1209 // fixed number of hex digits.
1211 APInt API = APF.bitcastToAPInt();
1212 if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) {
1214 Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
1216 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1219 } else if (&APF.getSemantics() == &APFloat::IEEEquad()) {
1221 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1223 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1225 } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {
1227 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1229 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1231 } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) {
1233 Out << format_hex_no_prefix(API.getZExtValue(), 4,
1236 llvm_unreachable("Unsupported floating point type");
1240 if (isa<ConstantAggregateZero>(CV)) {
1241 Out << "zeroinitializer";
1245 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1246 Out << "blockaddress(";
1247 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
1250 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
1256 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1257 Type *ETy = CA->getType()->getElementType();
1259 TypePrinter.print(ETy, Out);
1261 WriteAsOperandInternal(Out, CA->getOperand(0),
1262 &TypePrinter, Machine,
1264 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1266 TypePrinter.print(ETy, Out);
1268 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
1275 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1276 // As a special case, print the array as a string if it is an array of
1277 // i8 with ConstantInt values.
1278 if (CA->isString()) {
1280 PrintEscapedString(CA->getAsString(), Out);
1285 Type *ETy = CA->getType()->getElementType();
1287 TypePrinter.print(ETy, Out);
1289 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
1290 &TypePrinter, Machine,
1292 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1294 TypePrinter.print(ETy, Out);
1296 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
1303 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1304 if (CS->getType()->isPacked())
1307 unsigned N = CS->getNumOperands();
1310 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1313 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1316 for (unsigned i = 1; i < N; i++) {
1318 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1321 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1328 if (CS->getType()->isPacked())
1333 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1334 Type *ETy = CV->getType()->getVectorElementType();
1336 TypePrinter.print(ETy, Out);
1338 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
1340 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
1342 TypePrinter.print(ETy, Out);
1344 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1351 if (isa<ConstantPointerNull>(CV)) {
1356 if (isa<ConstantTokenNone>(CV)) {
1361 if (isa<UndefValue>(CV)) {
1366 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1367 Out << CE->getOpcodeName();
1368 WriteOptimizationInfo(Out, CE);
1369 if (CE->isCompare())
1370 Out << ' ' << CmpInst::getPredicateName(
1371 static_cast<CmpInst::Predicate>(CE->getPredicate()));
1374 Optional<unsigned> InRangeOp;
1375 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1376 TypePrinter.print(GEP->getSourceElementType(), Out);
1378 InRangeOp = GEP->getInRangeIndex();
1383 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1384 if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp)
1386 TypePrinter.print((*OI)->getType(), Out);
1388 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1389 if (OI+1 != CE->op_end())
1393 if (CE->hasIndices()) {
1394 ArrayRef<unsigned> Indices = CE->getIndices();
1395 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1396 Out << ", " << Indices[i];
1401 TypePrinter.print(CE->getType(), Out);
1408 Out << "<placeholder or erroneous Constant>";
1411 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1412 TypePrinting *TypePrinter, SlotTracker *Machine,
1413 const Module *Context) {
1415 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1416 const Metadata *MD = Node->getOperand(mi);
1419 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1420 Value *V = MDV->getValue();
1421 TypePrinter->print(V->getType(), Out);
1423 WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
1425 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1436 struct FieldSeparator {
1440 FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}
1443 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1448 return OS << FS.Sep;
1451 struct MDFieldPrinter {
1454 TypePrinting *TypePrinter = nullptr;
1455 SlotTracker *Machine = nullptr;
1456 const Module *Context = nullptr;
1458 explicit MDFieldPrinter(raw_ostream &Out) : Out(Out) {}
1459 MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
1460 SlotTracker *Machine, const Module *Context)
1461 : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
1464 void printTag(const DINode *N);
1465 void printMacinfoType(const DIMacroNode *N);
1466 void printChecksumKind(const DIFile *N);
1467 void printString(StringRef Name, StringRef Value,
1468 bool ShouldSkipEmpty = true);
1469 void printMetadata(StringRef Name, const Metadata *MD,
1470 bool ShouldSkipNull = true);
1471 template <class IntTy>
1472 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1473 void printBool(StringRef Name, bool Value, Optional<bool> Default = None);
1474 void printDIFlags(StringRef Name, DINode::DIFlags Flags);
1475 template <class IntTy, class Stringifier>
1476 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1477 bool ShouldSkipZero = true);
1478 void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
1481 } // end anonymous namespace
1483 void MDFieldPrinter::printTag(const DINode *N) {
1484 Out << FS << "tag: ";
1485 auto Tag = dwarf::TagString(N->getTag());
1492 void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
1493 Out << FS << "type: ";
1494 auto Type = dwarf::MacinfoString(N->getMacinfoType());
1498 Out << N->getMacinfoType();
1501 void MDFieldPrinter::printChecksumKind(const DIFile *N) {
1502 if (N->getChecksumKind() == DIFile::CSK_None)
1503 // Skip CSK_None checksum kind.
1505 Out << FS << "checksumkind: " << N->getChecksumKindAsString();
1508 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1509 bool ShouldSkipEmpty) {
1510 if (ShouldSkipEmpty && Value.empty())
1513 Out << FS << Name << ": \"";
1514 PrintEscapedString(Value, Out);
1518 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1519 TypePrinting *TypePrinter,
1520 SlotTracker *Machine,
1521 const Module *Context) {
1526 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1529 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1530 bool ShouldSkipNull) {
1531 if (ShouldSkipNull && !MD)
1534 Out << FS << Name << ": ";
1535 writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
1538 template <class IntTy>
1539 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1540 if (ShouldSkipZero && !Int)
1543 Out << FS << Name << ": " << Int;
1546 void MDFieldPrinter::printBool(StringRef Name, bool Value,
1547 Optional<bool> Default) {
1548 if (Default && Value == *Default)
1550 Out << FS << Name << ": " << (Value ? "true" : "false");
1553 void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
1557 Out << FS << Name << ": ";
1559 SmallVector<DINode::DIFlags, 8> SplitFlags;
1560 auto Extra = DINode::splitFlags(Flags, SplitFlags);
1562 FieldSeparator FlagsFS(" | ");
1563 for (auto F : SplitFlags) {
1564 auto StringF = DINode::getFlagString(F);
1565 assert(!StringF.empty() && "Expected valid flag");
1566 Out << FlagsFS << StringF;
1568 if (Extra || SplitFlags.empty())
1569 Out << FlagsFS << Extra;
1572 void MDFieldPrinter::printEmissionKind(StringRef Name,
1573 DICompileUnit::DebugEmissionKind EK) {
1574 Out << FS << Name << ": " << DICompileUnit::EmissionKindString(EK);
1577 template <class IntTy, class Stringifier>
1578 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1579 Stringifier toString, bool ShouldSkipZero) {
1583 Out << FS << Name << ": ";
1584 auto S = toString(Value);
1591 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1592 TypePrinting *TypePrinter, SlotTracker *Machine,
1593 const Module *Context) {
1594 Out << "!GenericDINode(";
1595 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1596 Printer.printTag(N);
1597 Printer.printString("header", N->getHeader());
1598 if (N->getNumDwarfOperands()) {
1599 Out << Printer.FS << "operands: {";
1601 for (auto &I : N->dwarf_operands()) {
1603 writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
1610 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1611 TypePrinting *TypePrinter, SlotTracker *Machine,
1612 const Module *Context) {
1613 Out << "!DILocation(";
1614 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1615 // Always output the line, since 0 is a relevant and important value for it.
1616 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1617 Printer.printInt("column", DL->getColumn());
1618 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1619 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
1623 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1624 TypePrinting *, SlotTracker *, const Module *) {
1625 Out << "!DISubrange(";
1626 MDFieldPrinter Printer(Out);
1627 Printer.printInt("count", N->getCount(), /* ShouldSkipZero */ false);
1628 Printer.printInt("lowerBound", N->getLowerBound());
1632 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1633 TypePrinting *, SlotTracker *, const Module *) {
1634 Out << "!DIEnumerator(";
1635 MDFieldPrinter Printer(Out);
1636 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1637 Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
1641 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1642 TypePrinting *, SlotTracker *, const Module *) {
1643 Out << "!DIBasicType(";
1644 MDFieldPrinter Printer(Out);
1645 if (N->getTag() != dwarf::DW_TAG_base_type)
1646 Printer.printTag(N);
1647 Printer.printString("name", N->getName());
1648 Printer.printInt("size", N->getSizeInBits());
1649 Printer.printInt("align", N->getAlignInBits());
1650 Printer.printDwarfEnum("encoding", N->getEncoding(),
1651 dwarf::AttributeEncodingString);
1655 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
1656 TypePrinting *TypePrinter, SlotTracker *Machine,
1657 const Module *Context) {
1658 Out << "!DIDerivedType(";
1659 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1660 Printer.printTag(N);
1661 Printer.printString("name", N->getName());
1662 Printer.printMetadata("scope", N->getRawScope());
1663 Printer.printMetadata("file", N->getRawFile());
1664 Printer.printInt("line", N->getLine());
1665 Printer.printMetadata("baseType", N->getRawBaseType(),
1666 /* ShouldSkipNull */ false);
1667 Printer.printInt("size", N->getSizeInBits());
1668 Printer.printInt("align", N->getAlignInBits());
1669 Printer.printInt("offset", N->getOffsetInBits());
1670 Printer.printDIFlags("flags", N->getFlags());
1671 Printer.printMetadata("extraData", N->getRawExtraData());
1672 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1673 Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
1674 /* ShouldSkipZero */ false);
1678 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
1679 TypePrinting *TypePrinter,
1680 SlotTracker *Machine, const Module *Context) {
1681 Out << "!DICompositeType(";
1682 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1683 Printer.printTag(N);
1684 Printer.printString("name", N->getName());
1685 Printer.printMetadata("scope", N->getRawScope());
1686 Printer.printMetadata("file", N->getRawFile());
1687 Printer.printInt("line", N->getLine());
1688 Printer.printMetadata("baseType", N->getRawBaseType());
1689 Printer.printInt("size", N->getSizeInBits());
1690 Printer.printInt("align", N->getAlignInBits());
1691 Printer.printInt("offset", N->getOffsetInBits());
1692 Printer.printDIFlags("flags", N->getFlags());
1693 Printer.printMetadata("elements", N->getRawElements());
1694 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
1695 dwarf::LanguageString);
1696 Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
1697 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1698 Printer.printString("identifier", N->getIdentifier());
1702 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
1703 TypePrinting *TypePrinter,
1704 SlotTracker *Machine, const Module *Context) {
1705 Out << "!DISubroutineType(";
1706 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1707 Printer.printDIFlags("flags", N->getFlags());
1708 Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
1709 Printer.printMetadata("types", N->getRawTypeArray(),
1710 /* ShouldSkipNull */ false);
1714 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
1715 SlotTracker *, const Module *) {
1717 MDFieldPrinter Printer(Out);
1718 Printer.printString("filename", N->getFilename(),
1719 /* ShouldSkipEmpty */ false);
1720 Printer.printString("directory", N->getDirectory(),
1721 /* ShouldSkipEmpty */ false);
1722 Printer.printChecksumKind(N);
1723 Printer.printString("checksum", N->getChecksum(), /* ShouldSkipEmpty */ true);
1727 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
1728 TypePrinting *TypePrinter, SlotTracker *Machine,
1729 const Module *Context) {
1730 Out << "!DICompileUnit(";
1731 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1732 Printer.printDwarfEnum("language", N->getSourceLanguage(),
1733 dwarf::LanguageString, /* ShouldSkipZero */ false);
1734 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1735 Printer.printString("producer", N->getProducer());
1736 Printer.printBool("isOptimized", N->isOptimized());
1737 Printer.printString("flags", N->getFlags());
1738 Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
1739 /* ShouldSkipZero */ false);
1740 Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
1741 Printer.printEmissionKind("emissionKind", N->getEmissionKind());
1742 Printer.printMetadata("enums", N->getRawEnumTypes());
1743 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
1744 Printer.printMetadata("globals", N->getRawGlobalVariables());
1745 Printer.printMetadata("imports", N->getRawImportedEntities());
1746 Printer.printMetadata("macros", N->getRawMacros());
1747 Printer.printInt("dwoId", N->getDWOId());
1748 Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
1749 Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
1751 Printer.printBool("gnuPubnames", N->getGnuPubnames(), false);
1755 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
1756 TypePrinting *TypePrinter, SlotTracker *Machine,
1757 const Module *Context) {
1758 Out << "!DISubprogram(";
1759 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1760 Printer.printString("name", N->getName());
1761 Printer.printString("linkageName", N->getLinkageName());
1762 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1763 Printer.printMetadata("file", N->getRawFile());
1764 Printer.printInt("line", N->getLine());
1765 Printer.printMetadata("type", N->getRawType());
1766 Printer.printBool("isLocal", N->isLocalToUnit());
1767 Printer.printBool("isDefinition", N->isDefinition());
1768 Printer.printInt("scopeLine", N->getScopeLine());
1769 Printer.printMetadata("containingType", N->getRawContainingType());
1770 Printer.printDwarfEnum("virtuality", N->getVirtuality(),
1771 dwarf::VirtualityString);
1772 if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
1773 N->getVirtualIndex() != 0)
1774 Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
1775 Printer.printInt("thisAdjustment", N->getThisAdjustment());
1776 Printer.printDIFlags("flags", N->getFlags());
1777 Printer.printBool("isOptimized", N->isOptimized());
1778 Printer.printMetadata("unit", N->getRawUnit());
1779 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1780 Printer.printMetadata("declaration", N->getRawDeclaration());
1781 Printer.printMetadata("variables", N->getRawVariables());
1782 Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
1786 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
1787 TypePrinting *TypePrinter, SlotTracker *Machine,
1788 const Module *Context) {
1789 Out << "!DILexicalBlock(";
1790 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1791 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1792 Printer.printMetadata("file", N->getRawFile());
1793 Printer.printInt("line", N->getLine());
1794 Printer.printInt("column", N->getColumn());
1798 static void writeDILexicalBlockFile(raw_ostream &Out,
1799 const DILexicalBlockFile *N,
1800 TypePrinting *TypePrinter,
1801 SlotTracker *Machine,
1802 const Module *Context) {
1803 Out << "!DILexicalBlockFile(";
1804 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1805 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1806 Printer.printMetadata("file", N->getRawFile());
1807 Printer.printInt("discriminator", N->getDiscriminator(),
1808 /* ShouldSkipZero */ false);
1812 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
1813 TypePrinting *TypePrinter, SlotTracker *Machine,
1814 const Module *Context) {
1815 Out << "!DINamespace(";
1816 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1817 Printer.printString("name", N->getName());
1818 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1819 Printer.printBool("exportSymbols", N->getExportSymbols(), false);
1823 static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
1824 TypePrinting *TypePrinter, SlotTracker *Machine,
1825 const Module *Context) {
1827 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1828 Printer.printMacinfoType(N);
1829 Printer.printInt("line", N->getLine());
1830 Printer.printString("name", N->getName());
1831 Printer.printString("value", N->getValue());
1835 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
1836 TypePrinting *TypePrinter, SlotTracker *Machine,
1837 const Module *Context) {
1838 Out << "!DIMacroFile(";
1839 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1840 Printer.printInt("line", N->getLine());
1841 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1842 Printer.printMetadata("nodes", N->getRawElements());
1846 static void writeDIModule(raw_ostream &Out, const DIModule *N,
1847 TypePrinting *TypePrinter, SlotTracker *Machine,
1848 const Module *Context) {
1849 Out << "!DIModule(";
1850 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1851 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1852 Printer.printString("name", N->getName());
1853 Printer.printString("configMacros", N->getConfigurationMacros());
1854 Printer.printString("includePath", N->getIncludePath());
1855 Printer.printString("isysroot", N->getISysRoot());
1860 static void writeDITemplateTypeParameter(raw_ostream &Out,
1861 const DITemplateTypeParameter *N,
1862 TypePrinting *TypePrinter,
1863 SlotTracker *Machine,
1864 const Module *Context) {
1865 Out << "!DITemplateTypeParameter(";
1866 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1867 Printer.printString("name", N->getName());
1868 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
1872 static void writeDITemplateValueParameter(raw_ostream &Out,
1873 const DITemplateValueParameter *N,
1874 TypePrinting *TypePrinter,
1875 SlotTracker *Machine,
1876 const Module *Context) {
1877 Out << "!DITemplateValueParameter(";
1878 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1879 if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
1880 Printer.printTag(N);
1881 Printer.printString("name", N->getName());
1882 Printer.printMetadata("type", N->getRawType());
1883 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
1887 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
1888 TypePrinting *TypePrinter,
1889 SlotTracker *Machine, const Module *Context) {
1890 Out << "!DIGlobalVariable(";
1891 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1892 Printer.printString("name", N->getName());
1893 Printer.printString("linkageName", N->getLinkageName());
1894 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1895 Printer.printMetadata("file", N->getRawFile());
1896 Printer.printInt("line", N->getLine());
1897 Printer.printMetadata("type", N->getRawType());
1898 Printer.printBool("isLocal", N->isLocalToUnit());
1899 Printer.printBool("isDefinition", N->isDefinition());
1900 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
1901 Printer.printInt("align", N->getAlignInBits());
1905 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
1906 TypePrinting *TypePrinter,
1907 SlotTracker *Machine, const Module *Context) {
1908 Out << "!DILocalVariable(";
1909 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1910 Printer.printString("name", N->getName());
1911 Printer.printInt("arg", N->getArg());
1912 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1913 Printer.printMetadata("file", N->getRawFile());
1914 Printer.printInt("line", N->getLine());
1915 Printer.printMetadata("type", N->getRawType());
1916 Printer.printDIFlags("flags", N->getFlags());
1917 Printer.printInt("align", N->getAlignInBits());
1921 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
1922 TypePrinting *TypePrinter, SlotTracker *Machine,
1923 const Module *Context) {
1924 Out << "!DIExpression(";
1927 for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
1928 auto OpStr = dwarf::OperationEncodingString(I->getOp());
1929 assert(!OpStr.empty() && "Expected valid opcode");
1932 for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
1933 Out << FS << I->getArg(A);
1936 for (const auto &I : N->getElements())
1942 static void writeDIGlobalVariableExpression(raw_ostream &Out,
1943 const DIGlobalVariableExpression *N,
1944 TypePrinting *TypePrinter,
1945 SlotTracker *Machine,
1946 const Module *Context) {
1947 Out << "!DIGlobalVariableExpression(";
1948 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1949 Printer.printMetadata("var", N->getVariable());
1950 Printer.printMetadata("expr", N->getExpression());
1954 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
1955 TypePrinting *TypePrinter, SlotTracker *Machine,
1956 const Module *Context) {
1957 Out << "!DIObjCProperty(";
1958 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1959 Printer.printString("name", N->getName());
1960 Printer.printMetadata("file", N->getRawFile());
1961 Printer.printInt("line", N->getLine());
1962 Printer.printString("setter", N->getSetterName());
1963 Printer.printString("getter", N->getGetterName());
1964 Printer.printInt("attributes", N->getAttributes());
1965 Printer.printMetadata("type", N->getRawType());
1969 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
1970 TypePrinting *TypePrinter,
1971 SlotTracker *Machine, const Module *Context) {
1972 Out << "!DIImportedEntity(";
1973 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1974 Printer.printTag(N);
1975 Printer.printString("name", N->getName());
1976 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1977 Printer.printMetadata("entity", N->getRawEntity());
1978 Printer.printMetadata("file", N->getRawFile());
1979 Printer.printInt("line", N->getLine());
1983 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1984 TypePrinting *TypePrinter,
1985 SlotTracker *Machine,
1986 const Module *Context) {
1987 if (Node->isDistinct())
1989 else if (Node->isTemporary())
1990 Out << "<temporary!> "; // Handle broken code.
1992 switch (Node->getMetadataID()) {
1994 llvm_unreachable("Expected uniquable MDNode");
1995 #define HANDLE_MDNODE_LEAF(CLASS) \
1996 case Metadata::CLASS##Kind: \
1997 write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \
1999 #include "llvm/IR/Metadata.def"
2003 // Full implementation of printing a Value as an operand with support for
2004 // TypePrinting, etc.
2005 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
2006 TypePrinting *TypePrinter,
2007 SlotTracker *Machine,
2008 const Module *Context) {
2010 PrintLLVMName(Out, V);
2014 const Constant *CV = dyn_cast<Constant>(V);
2015 if (CV && !isa<GlobalValue>(CV)) {
2016 assert(TypePrinter && "Constants require TypePrinting!");
2017 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
2021 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2023 if (IA->hasSideEffects())
2024 Out << "sideeffect ";
2025 if (IA->isAlignStack())
2026 Out << "alignstack ";
2027 // We don't emit the AD_ATT dialect as it's the assumed default.
2028 if (IA->getDialect() == InlineAsm::AD_Intel)
2029 Out << "inteldialect ";
2031 PrintEscapedString(IA->getAsmString(), Out);
2033 PrintEscapedString(IA->getConstraintString(), Out);
2038 if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
2039 WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
2040 Context, /* FromValue */ true);
2046 // If we have a SlotTracker, use it.
2048 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2049 Slot = Machine->getGlobalSlot(GV);
2052 Slot = Machine->getLocalSlot(V);
2054 // If the local value didn't succeed, then we may be referring to a value
2055 // from a different function. Translate it, as this can happen when using
2056 // address of blocks.
2058 if ((Machine = createSlotTracker(V))) {
2059 Slot = Machine->getLocalSlot(V);
2063 } else if ((Machine = createSlotTracker(V))) {
2064 // Otherwise, create one to get the # and then destroy it.
2065 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2066 Slot = Machine->getGlobalSlot(GV);
2069 Slot = Machine->getLocalSlot(V);
2078 Out << Prefix << Slot;
2083 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
2084 TypePrinting *TypePrinter,
2085 SlotTracker *Machine, const Module *Context,
2087 // Write DIExpressions inline when used as a value. Improves readability of
2088 // debug info intrinsics.
2089 if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {
2090 writeDIExpression(Out, Expr, TypePrinter, Machine, Context);
2094 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2095 std::unique_ptr<SlotTracker> MachineStorage;
2097 MachineStorage = make_unique<SlotTracker>(Context);
2098 Machine = MachineStorage.get();
2100 int Slot = Machine->getMetadataSlot(N);
2102 // Give the pointer value instead of "badref", since this comes up all
2103 // the time when debugging.
2104 Out << "<" << N << ">";
2110 if (const MDString *MDS = dyn_cast<MDString>(MD)) {
2112 PrintEscapedString(MDS->getString(), Out);
2117 auto *V = cast<ValueAsMetadata>(MD);
2118 assert(TypePrinter && "TypePrinter required for metadata values");
2119 assert((FromValue || !isa<LocalAsMetadata>(V)) &&
2120 "Unexpected function-local metadata outside of value argument");
2122 TypePrinter->print(V->getValue()->getType(), Out);
2124 WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
2129 class AssemblyWriter {
2130 formatted_raw_ostream &Out;
2131 const Module *TheModule;
2132 std::unique_ptr<SlotTracker> SlotTrackerStorage;
2133 SlotTracker &Machine;
2134 TypePrinting TypePrinter;
2135 AssemblyAnnotationWriter *AnnotationWriter;
2136 SetVector<const Comdat *> Comdats;
2138 bool ShouldPreserveUseListOrder;
2139 UseListOrderStack UseListOrders;
2140 SmallVector<StringRef, 8> MDNames;
2141 /// Synchronization scope names registered with LLVMContext.
2142 SmallVector<StringRef, 8> SSNs;
2145 /// Construct an AssemblyWriter with an external SlotTracker
2146 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
2147 AssemblyAnnotationWriter *AAW, bool IsForDebug,
2148 bool ShouldPreserveUseListOrder = false);
2150 void printMDNodeBody(const MDNode *MD);
2151 void printNamedMDNode(const NamedMDNode *NMD);
2153 void printModule(const Module *M);
2155 void writeOperand(const Value *Op, bool PrintType);
2156 void writeParamOperand(const Value *Operand, AttributeSet Attrs);
2157 void writeOperandBundles(ImmutableCallSite CS);
2158 void writeSyncScope(const LLVMContext &Context,
2159 SyncScope::ID SSID);
2160 void writeAtomic(const LLVMContext &Context,
2161 AtomicOrdering Ordering,
2162 SyncScope::ID SSID);
2163 void writeAtomicCmpXchg(const LLVMContext &Context,
2164 AtomicOrdering SuccessOrdering,
2165 AtomicOrdering FailureOrdering,
2166 SyncScope::ID SSID);
2168 void writeAllMDNodes();
2169 void writeMDNode(unsigned Slot, const MDNode *Node);
2170 void writeAllAttributeGroups();
2172 void printTypeIdentities();
2173 void printGlobal(const GlobalVariable *GV);
2174 void printIndirectSymbol(const GlobalIndirectSymbol *GIS);
2175 void printComdat(const Comdat *C);
2176 void printFunction(const Function *F);
2177 void printArgument(const Argument *FA, AttributeSet Attrs);
2178 void printBasicBlock(const BasicBlock *BB);
2179 void printInstructionLine(const Instruction &I);
2180 void printInstruction(const Instruction &I);
2182 void printUseListOrder(const UseListOrder &Order);
2183 void printUseLists(const Function *F);
2186 /// \brief Print out metadata attachments.
2187 void printMetadataAttachments(
2188 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2189 StringRef Separator);
2191 // printInfoComment - Print a little comment after the instruction indicating
2192 // which slot it occupies.
2193 void printInfoComment(const Value &V);
2195 // printGCRelocateComment - print comment after call to the gc.relocate
2196 // intrinsic indicating base and derived pointer names.
2197 void printGCRelocateComment(const GCRelocateInst &Relocate);
2200 } // end anonymous namespace
2202 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2203 const Module *M, AssemblyAnnotationWriter *AAW,
2204 bool IsForDebug, bool ShouldPreserveUseListOrder)
2205 : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW),
2206 IsForDebug(IsForDebug),
2207 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2210 TypePrinter.incorporateTypes(*TheModule);
2211 for (const GlobalObject &GO : TheModule->global_objects())
2212 if (const Comdat *C = GO.getComdat())
2216 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2218 Out << "<null operand!>";
2222 TypePrinter.print(Operand->getType(), Out);
2225 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2228 void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
2229 SyncScope::ID SSID) {
2231 case SyncScope::System: {
2236 Context.getSyncScopeNames(SSNs);
2238 Out << " syncscope(\"";
2239 PrintEscapedString(SSNs[SSID], Out);
2246 void AssemblyWriter::writeAtomic(const LLVMContext &Context,
2247 AtomicOrdering Ordering,
2248 SyncScope::ID SSID) {
2249 if (Ordering == AtomicOrdering::NotAtomic)
2252 writeSyncScope(Context, SSID);
2253 Out << " " << toIRString(Ordering);
2256 void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
2257 AtomicOrdering SuccessOrdering,
2258 AtomicOrdering FailureOrdering,
2259 SyncScope::ID SSID) {
2260 assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
2261 FailureOrdering != AtomicOrdering::NotAtomic);
2263 writeSyncScope(Context, SSID);
2264 Out << " " << toIRString(SuccessOrdering);
2265 Out << " " << toIRString(FailureOrdering);
2268 void AssemblyWriter::writeParamOperand(const Value *Operand,
2269 AttributeSet Attrs) {
2271 Out << "<null operand!>";
2276 TypePrinter.print(Operand->getType(), Out);
2277 // Print parameter attributes list
2278 if (Attrs.hasAttributes())
2279 Out << ' ' << Attrs.getAsString();
2281 // Print the operand
2282 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2285 void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS) {
2286 if (!CS.hasOperandBundles())
2291 bool FirstBundle = true;
2292 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2293 OperandBundleUse BU = CS.getOperandBundleAt(i);
2297 FirstBundle = false;
2300 PrintEscapedString(BU.getTagName(), Out);
2305 bool FirstInput = true;
2306 for (const auto &Input : BU.Inputs) {
2311 TypePrinter.print(Input->getType(), Out);
2313 WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
2322 void AssemblyWriter::printModule(const Module *M) {
2323 Machine.initialize();
2325 if (ShouldPreserveUseListOrder)
2326 UseListOrders = predictUseListOrder(M);
2328 if (!M->getModuleIdentifier().empty() &&
2329 // Don't print the ID if it will start a new line (which would
2330 // require a comment char before it).
2331 M->getModuleIdentifier().find('\n') == std::string::npos)
2332 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2334 if (!M->getSourceFileName().empty()) {
2335 Out << "source_filename = \"";
2336 PrintEscapedString(M->getSourceFileName(), Out);
2340 const std::string &DL = M->getDataLayoutStr();
2342 Out << "target datalayout = \"" << DL << "\"\n";
2343 if (!M->getTargetTriple().empty())
2344 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2346 if (!M->getModuleInlineAsm().empty()) {
2349 // Split the string into lines, to make it easier to read the .ll file.
2350 StringRef Asm = M->getModuleInlineAsm();
2353 std::tie(Front, Asm) = Asm.split('\n');
2355 // We found a newline, print the portion of the asm string from the
2356 // last newline up to this newline.
2357 Out << "module asm \"";
2358 PrintEscapedString(Front, Out);
2360 } while (!Asm.empty());
2363 printTypeIdentities();
2365 // Output all comdats.
2366 if (!Comdats.empty())
2368 for (const Comdat *C : Comdats) {
2370 if (C != Comdats.back())
2374 // Output all globals.
2375 if (!M->global_empty()) Out << '\n';
2376 for (const GlobalVariable &GV : M->globals()) {
2377 printGlobal(&GV); Out << '\n';
2380 // Output all aliases.
2381 if (!M->alias_empty()) Out << "\n";
2382 for (const GlobalAlias &GA : M->aliases())
2383 printIndirectSymbol(&GA);
2385 // Output all ifuncs.
2386 if (!M->ifunc_empty()) Out << "\n";
2387 for (const GlobalIFunc &GI : M->ifuncs())
2388 printIndirectSymbol(&GI);
2390 // Output global use-lists.
2391 printUseLists(nullptr);
2393 // Output all of the functions.
2394 for (const Function &F : *M)
2396 assert(UseListOrders.empty() && "All use-lists should have been consumed");
2398 // Output all attribute groups.
2399 if (!Machine.as_empty()) {
2401 writeAllAttributeGroups();
2404 // Output named metadata.
2405 if (!M->named_metadata_empty()) Out << '\n';
2407 for (const NamedMDNode &Node : M->named_metadata())
2408 printNamedMDNode(&Node);
2411 if (!Machine.mdn_empty()) {
2417 static void printMetadataIdentifier(StringRef Name,
2418 formatted_raw_ostream &Out) {
2420 Out << "<empty name> ";
2422 if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
2423 Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
2426 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
2427 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
2428 unsigned char C = Name[i];
2429 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
2430 C == '.' || C == '_')
2433 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
2438 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
2440 printMetadataIdentifier(NMD->getName(), Out);
2442 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2446 // Write DIExpressions inline.
2447 // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
2448 MDNode *Op = NMD->getOperand(i);
2449 if (auto *Expr = dyn_cast<DIExpression>(Op)) {
2450 writeDIExpression(Out, Expr, nullptr, nullptr, nullptr);
2454 int Slot = Machine.getMetadataSlot(Op);
2463 static const char *getLinkagePrintName(GlobalValue::LinkageTypes LT) {
2465 case GlobalValue::ExternalLinkage:
2467 case GlobalValue::PrivateLinkage:
2469 case GlobalValue::InternalLinkage:
2471 case GlobalValue::LinkOnceAnyLinkage:
2473 case GlobalValue::LinkOnceODRLinkage:
2474 return "linkonce_odr ";
2475 case GlobalValue::WeakAnyLinkage:
2477 case GlobalValue::WeakODRLinkage:
2479 case GlobalValue::CommonLinkage:
2481 case GlobalValue::AppendingLinkage:
2482 return "appending ";
2483 case GlobalValue::ExternalWeakLinkage:
2484 return "extern_weak ";
2485 case GlobalValue::AvailableExternallyLinkage:
2486 return "available_externally ";
2488 llvm_unreachable("invalid linkage");
2491 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
2492 formatted_raw_ostream &Out) {
2494 case GlobalValue::DefaultVisibility: break;
2495 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
2496 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
2500 static void PrintDSOLocation(bool IsDSOLocal, formatted_raw_ostream &Out){
2502 Out << "dso_local ";
2505 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
2506 formatted_raw_ostream &Out) {
2508 case GlobalValue::DefaultStorageClass: break;
2509 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
2510 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
2514 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
2515 formatted_raw_ostream &Out) {
2517 case GlobalVariable::NotThreadLocal:
2519 case GlobalVariable::GeneralDynamicTLSModel:
2520 Out << "thread_local ";
2522 case GlobalVariable::LocalDynamicTLSModel:
2523 Out << "thread_local(localdynamic) ";
2525 case GlobalVariable::InitialExecTLSModel:
2526 Out << "thread_local(initialexec) ";
2528 case GlobalVariable::LocalExecTLSModel:
2529 Out << "thread_local(localexec) ";
2534 static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
2536 case GlobalVariable::UnnamedAddr::None:
2538 case GlobalVariable::UnnamedAddr::Local:
2539 return "local_unnamed_addr";
2540 case GlobalVariable::UnnamedAddr::Global:
2541 return "unnamed_addr";
2543 llvm_unreachable("Unknown UnnamedAddr");
2546 static void maybePrintComdat(formatted_raw_ostream &Out,
2547 const GlobalObject &GO) {
2548 const Comdat *C = GO.getComdat();
2552 if (isa<GlobalVariable>(GO))
2556 if (GO.getName() == C->getName())
2560 PrintLLVMName(Out, C->getName(), ComdatPrefix);
2564 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
2565 if (GV->isMaterializable())
2566 Out << "; Materializable\n";
2568 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
2571 if (!GV->hasInitializer() && GV->hasExternalLinkage())
2574 Out << getLinkagePrintName(GV->getLinkage());
2575 PrintDSOLocation(GV->isDSOLocal(), Out);
2576 PrintVisibility(GV->getVisibility(), Out);
2577 PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
2578 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
2579 StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());
2583 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
2584 Out << "addrspace(" << AddressSpace << ") ";
2585 if (GV->isExternallyInitialized()) Out << "externally_initialized ";
2586 Out << (GV->isConstant() ? "constant " : "global ");
2587 TypePrinter.print(GV->getValueType(), Out);
2589 if (GV->hasInitializer()) {
2591 writeOperand(GV->getInitializer(), false);
2594 if (GV->hasSection()) {
2595 Out << ", section \"";
2596 PrintEscapedString(GV->getSection(), Out);
2599 maybePrintComdat(Out, *GV);
2600 if (GV->getAlignment())
2601 Out << ", align " << GV->getAlignment();
2603 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2604 GV->getAllMetadata(MDs);
2605 printMetadataAttachments(MDs, ", ");
2607 auto Attrs = GV->getAttributes();
2608 if (Attrs.hasAttributes())
2609 Out << " #" << Machine.getAttributeGroupSlot(Attrs);
2611 printInfoComment(*GV);
2614 void AssemblyWriter::printIndirectSymbol(const GlobalIndirectSymbol *GIS) {
2615 if (GIS->isMaterializable())
2616 Out << "; Materializable\n";
2618 WriteAsOperandInternal(Out, GIS, &TypePrinter, &Machine, GIS->getParent());
2621 Out << getLinkagePrintName(GIS->getLinkage());
2622 PrintDSOLocation(GIS->isDSOLocal(), Out);
2623 PrintVisibility(GIS->getVisibility(), Out);
2624 PrintDLLStorageClass(GIS->getDLLStorageClass(), Out);
2625 PrintThreadLocalModel(GIS->getThreadLocalMode(), Out);
2626 StringRef UA = getUnnamedAddrEncoding(GIS->getUnnamedAddr());
2630 if (isa<GlobalAlias>(GIS))
2632 else if (isa<GlobalIFunc>(GIS))
2635 llvm_unreachable("Not an alias or ifunc!");
2637 TypePrinter.print(GIS->getValueType(), Out);
2641 const Constant *IS = GIS->getIndirectSymbol();
2644 TypePrinter.print(GIS->getType(), Out);
2645 Out << " <<NULL ALIASEE>>";
2647 writeOperand(IS, !isa<ConstantExpr>(IS));
2650 printInfoComment(*GIS);
2654 void AssemblyWriter::printComdat(const Comdat *C) {
2658 void AssemblyWriter::printTypeIdentities() {
2659 if (TypePrinter.NumberedTypes.empty() &&
2660 TypePrinter.NamedTypes.empty())
2665 // We know all the numbers that each type is used and we know that it is a
2666 // dense assignment. Convert the map to an index table.
2667 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
2668 for (DenseMap<StructType*, unsigned>::iterator I =
2669 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
2671 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
2672 NumberedTypes[I->second] = I->first;
2675 // Emit all numbered types.
2676 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
2677 Out << '%' << i << " = type ";
2679 // Make sure we print out at least one level of the type structure, so
2680 // that we do not get %2 = type %2
2681 TypePrinter.printStructBody(NumberedTypes[i], Out);
2685 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
2686 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
2689 // Make sure we print out at least one level of the type structure, so
2690 // that we do not get %FILE = type %FILE
2691 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
2696 /// printFunction - Print all aspects of a function.
2697 void AssemblyWriter::printFunction(const Function *F) {
2698 // Print out the return type and name.
2701 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
2703 if (F->isMaterializable())
2704 Out << "; Materializable\n";
2706 const AttributeList &Attrs = F->getAttributes();
2707 if (Attrs.hasAttributes(AttributeList::FunctionIndex)) {
2708 AttributeSet AS = Attrs.getFnAttributes();
2709 std::string AttrStr;
2711 for (const Attribute &Attr : AS) {
2712 if (!Attr.isStringAttribute()) {
2713 if (!AttrStr.empty()) AttrStr += ' ';
2714 AttrStr += Attr.getAsString();
2718 if (!AttrStr.empty())
2719 Out << "; Function Attrs: " << AttrStr << '\n';
2722 Machine.incorporateFunction(F);
2724 if (F->isDeclaration()) {
2726 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2727 F->getAllMetadata(MDs);
2728 printMetadataAttachments(MDs, " ");
2733 Out << getLinkagePrintName(F->getLinkage());
2734 PrintDSOLocation(F->isDSOLocal(), Out);
2735 PrintVisibility(F->getVisibility(), Out);
2736 PrintDLLStorageClass(F->getDLLStorageClass(), Out);
2738 // Print the calling convention.
2739 if (F->getCallingConv() != CallingConv::C) {
2740 PrintCallingConv(F->getCallingConv(), Out);
2744 FunctionType *FT = F->getFunctionType();
2745 if (Attrs.hasAttributes(AttributeList::ReturnIndex))
2746 Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
2747 TypePrinter.print(F->getReturnType(), Out);
2749 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
2752 // Loop over the arguments, printing them...
2753 if (F->isDeclaration() && !IsForDebug) {
2754 // We're only interested in the type here - don't print argument names.
2755 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
2756 // Insert commas as we go... the first arg doesn't get a comma
2760 TypePrinter.print(FT->getParamType(I), Out);
2762 AttributeSet ArgAttrs = Attrs.getParamAttributes(I);
2763 if (ArgAttrs.hasAttributes())
2764 Out << ' ' << ArgAttrs.getAsString();
2767 // The arguments are meaningful here, print them in detail.
2768 for (const Argument &Arg : F->args()) {
2769 // Insert commas as we go... the first arg doesn't get a comma
2770 if (Arg.getArgNo() != 0)
2772 printArgument(&Arg, Attrs.getParamAttributes(Arg.getArgNo()));
2776 // Finish printing arguments...
2777 if (FT->isVarArg()) {
2778 if (FT->getNumParams()) Out << ", ";
2779 Out << "..."; // Output varargs portion of signature!
2782 StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
2785 if (Attrs.hasAttributes(AttributeList::FunctionIndex))
2786 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
2787 if (F->hasSection()) {
2788 Out << " section \"";
2789 PrintEscapedString(F->getSection(), Out);
2792 maybePrintComdat(Out, *F);
2793 if (F->getAlignment())
2794 Out << " align " << F->getAlignment();
2796 Out << " gc \"" << F->getGC() << '"';
2797 if (F->hasPrefixData()) {
2799 writeOperand(F->getPrefixData(), true);
2801 if (F->hasPrologueData()) {
2802 Out << " prologue ";
2803 writeOperand(F->getPrologueData(), true);
2805 if (F->hasPersonalityFn()) {
2806 Out << " personality ";
2807 writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
2810 if (F->isDeclaration()) {
2813 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2814 F->getAllMetadata(MDs);
2815 printMetadataAttachments(MDs, " ");
2818 // Output all of the function's basic blocks.
2819 for (const BasicBlock &BB : *F)
2820 printBasicBlock(&BB);
2822 // Output the function's use-lists.
2828 Machine.purgeFunction();
2831 /// printArgument - This member is called for every argument that is passed into
2832 /// the function. Simply print it out
2833 void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
2835 TypePrinter.print(Arg->getType(), Out);
2837 // Output parameter attributes list
2838 if (Attrs.hasAttributes())
2839 Out << ' ' << Attrs.getAsString();
2841 // Output name, if available...
2842 if (Arg->hasName()) {
2844 PrintLLVMName(Out, Arg);
2848 /// printBasicBlock - This member is called for each basic block in a method.
2849 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
2850 if (BB->hasName()) { // Print out the label if it exists...
2852 PrintLLVMName(Out, BB->getName(), LabelPrefix);
2854 } else if (!BB->use_empty()) { // Don't print block # of no uses...
2855 Out << "\n; <label>:";
2856 int Slot = Machine.getLocalSlot(BB);
2863 if (!BB->getParent()) {
2864 Out.PadToColumn(50);
2865 Out << "; Error: Block without parent!";
2866 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
2867 // Output predecessors for the block.
2868 Out.PadToColumn(50);
2870 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
2873 Out << " No predecessors!";
2876 writeOperand(*PI, false);
2877 for (++PI; PI != PE; ++PI) {
2879 writeOperand(*PI, false);
2886 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
2888 // Output all of the instructions in the basic block...
2889 for (const Instruction &I : *BB) {
2890 printInstructionLine(I);
2893 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
2896 /// printInstructionLine - Print an instruction and a newline character.
2897 void AssemblyWriter::printInstructionLine(const Instruction &I) {
2898 printInstruction(I);
2902 /// printGCRelocateComment - print comment after call to the gc.relocate
2903 /// intrinsic indicating base and derived pointer names.
2904 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
2906 writeOperand(Relocate.getBasePtr(), false);
2908 writeOperand(Relocate.getDerivedPtr(), false);
2912 /// printInfoComment - Print a little comment after the instruction indicating
2913 /// which slot it occupies.
2914 void AssemblyWriter::printInfoComment(const Value &V) {
2915 if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
2916 printGCRelocateComment(*Relocate);
2918 if (AnnotationWriter)
2919 AnnotationWriter->printInfoComment(V, Out);
2922 // This member is called for each Instruction in a function..
2923 void AssemblyWriter::printInstruction(const Instruction &I) {
2924 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
2926 // Print out indentation for an instruction.
2929 // Print out name if it exists...
2931 PrintLLVMName(Out, &I);
2933 } else if (!I.getType()->isVoidTy()) {
2934 // Print out the def slot taken.
2935 int SlotNum = Machine.getLocalSlot(&I);
2937 Out << "<badref> = ";
2939 Out << '%' << SlotNum << " = ";
2942 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2943 if (CI->isMustTailCall())
2945 else if (CI->isTailCall())
2947 else if (CI->isNoTailCall())
2951 // Print out the opcode...
2952 Out << I.getOpcodeName();
2954 // If this is an atomic load or store, print out the atomic marker.
2955 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
2956 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
2959 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
2962 // If this is a volatile operation, print out the volatile marker.
2963 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
2964 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
2965 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
2966 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
2969 // Print out optimization information.
2970 WriteOptimizationInfo(Out, &I);
2972 // Print out the compare instruction predicates
2973 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
2974 Out << ' ' << CmpInst::getPredicateName(CI->getPredicate());
2976 // Print out the atomicrmw operation
2977 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
2978 writeAtomicRMWOperation(Out, RMWI->getOperation());
2980 // Print out the type of the operands...
2981 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
2983 // Special case conditional branches to swizzle the condition out to the front
2984 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
2985 const BranchInst &BI(cast<BranchInst>(I));
2987 writeOperand(BI.getCondition(), true);
2989 writeOperand(BI.getSuccessor(0), true);
2991 writeOperand(BI.getSuccessor(1), true);
2993 } else if (isa<SwitchInst>(I)) {
2994 const SwitchInst& SI(cast<SwitchInst>(I));
2995 // Special case switch instruction to get formatting nice and correct.
2997 writeOperand(SI.getCondition(), true);
2999 writeOperand(SI.getDefaultDest(), true);
3001 for (auto Case : SI.cases()) {
3003 writeOperand(Case.getCaseValue(), true);
3005 writeOperand(Case.getCaseSuccessor(), true);
3008 } else if (isa<IndirectBrInst>(I)) {
3009 // Special case indirectbr instruction to get formatting nice and correct.
3011 writeOperand(Operand, true);
3014 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
3017 writeOperand(I.getOperand(i), true);
3020 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
3022 TypePrinter.print(I.getType(), Out);
3025 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
3026 if (op) Out << ", ";
3028 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
3029 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
3031 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
3033 writeOperand(I.getOperand(0), true);
3034 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
3036 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
3038 writeOperand(I.getOperand(0), true); Out << ", ";
3039 writeOperand(I.getOperand(1), true);
3040 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
3042 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
3044 TypePrinter.print(I.getType(), Out);
3045 if (LPI->isCleanup() || LPI->getNumClauses() != 0)
3048 if (LPI->isCleanup())
3051 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
3052 if (i != 0 || LPI->isCleanup()) Out << "\n";
3053 if (LPI->isCatch(i))
3058 writeOperand(LPI->getClause(i), true);
3060 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
3062 writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
3065 for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
3068 writeOperand(PadBB, /*PrintType=*/true);
3072 if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
3073 writeOperand(UnwindDest, /*PrintType=*/true);
3076 } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
3078 writeOperand(FPI->getParentPad(), /*PrintType=*/false);
3080 for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps;
3084 writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
3087 } else if (isa<ReturnInst>(I) && !Operand) {
3089 } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
3091 writeOperand(CRI->getOperand(0), /*PrintType=*/false);
3094 writeOperand(CRI->getOperand(1), /*PrintType=*/true);
3095 } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
3097 writeOperand(CRI->getOperand(0), /*PrintType=*/false);
3100 if (CRI->hasUnwindDest())
3101 writeOperand(CRI->getOperand(1), /*PrintType=*/true);
3104 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3105 // Print the calling convention being used.
3106 if (CI->getCallingConv() != CallingConv::C) {
3108 PrintCallingConv(CI->getCallingConv(), Out);
3111 Operand = CI->getCalledValue();
3112 FunctionType *FTy = CI->getFunctionType();
3113 Type *RetTy = FTy->getReturnType();
3114 const AttributeList &PAL = CI->getAttributes();
3116 if (PAL.hasAttributes(AttributeList::ReturnIndex))
3117 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3119 // If possible, print out the short form of the call instruction. We can
3120 // only do this if the first argument is a pointer to a nonvararg function,
3121 // and if the return type is not a pointer to a function.
3124 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3126 writeOperand(Operand, false);
3128 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
3131 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op));
3134 // Emit an ellipsis if this is a musttail call in a vararg function. This
3135 // is only to aid readability, musttail calls forward varargs by default.
3136 if (CI->isMustTailCall() && CI->getParent() &&
3137 CI->getParent()->getParent() &&
3138 CI->getParent()->getParent()->isVarArg())
3142 if (PAL.hasAttributes(AttributeList::FunctionIndex))
3143 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3145 writeOperandBundles(CI);
3146 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
3147 Operand = II->getCalledValue();
3148 FunctionType *FTy = II->getFunctionType();
3149 Type *RetTy = FTy->getReturnType();
3150 const AttributeList &PAL = II->getAttributes();
3152 // Print the calling convention being used.
3153 if (II->getCallingConv() != CallingConv::C) {
3155 PrintCallingConv(II->getCallingConv(), Out);
3158 if (PAL.hasAttributes(AttributeList::ReturnIndex))
3159 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3161 // If possible, print out the short form of the invoke instruction. We can
3162 // only do this if the first argument is a pointer to a nonvararg function,
3163 // and if the return type is not a pointer to a function.
3166 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3168 writeOperand(Operand, false);
3170 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
3173 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op));
3177 if (PAL.hasAttributes(AttributeList::FunctionIndex))
3178 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3180 writeOperandBundles(II);
3183 writeOperand(II->getNormalDest(), true);
3185 writeOperand(II->getUnwindDest(), true);
3186 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
3188 if (AI->isUsedWithInAlloca())
3190 if (AI->isSwiftError())
3191 Out << "swifterror ";
3192 TypePrinter.print(AI->getAllocatedType(), Out);
3194 // Explicitly write the array size if the code is broken, if it's an array
3195 // allocation, or if the type is not canonical for scalar allocations. The
3196 // latter case prevents the type from mutating when round-tripping through
3198 if (!AI->getArraySize() || AI->isArrayAllocation() ||
3199 !AI->getArraySize()->getType()->isIntegerTy(32)) {
3201 writeOperand(AI->getArraySize(), true);
3203 if (AI->getAlignment()) {
3204 Out << ", align " << AI->getAlignment();
3207 unsigned AddrSpace = AI->getType()->getAddressSpace();
3208 if (AddrSpace != 0) {
3209 Out << ", addrspace(" << AddrSpace << ')';
3211 } else if (isa<CastInst>(I)) {
3214 writeOperand(Operand, true); // Work with broken code
3217 TypePrinter.print(I.getType(), Out);
3218 } else if (isa<VAArgInst>(I)) {
3221 writeOperand(Operand, true); // Work with broken code
3224 TypePrinter.print(I.getType(), Out);
3225 } else if (Operand) { // Print the normal way.
3226 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
3228 TypePrinter.print(GEP->getSourceElementType(), Out);
3230 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
3232 TypePrinter.print(LI->getType(), Out);
3236 // PrintAllTypes - Instructions who have operands of all the same type
3237 // omit the type from all but the first operand. If the instruction has
3238 // different type operands (for example br), then they are all printed.
3239 bool PrintAllTypes = false;
3240 Type *TheType = Operand->getType();
3242 // Select, Store and ShuffleVector always print all types.
3243 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
3244 || isa<ReturnInst>(I)) {
3245 PrintAllTypes = true;
3247 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
3248 Operand = I.getOperand(i);
3249 // note that Operand shouldn't be null, but the test helps make dump()
3250 // more tolerant of malformed IR
3251 if (Operand && Operand->getType() != TheType) {
3252 PrintAllTypes = true; // We have differing types! Print them all!
3258 if (!PrintAllTypes) {
3260 TypePrinter.print(TheType, Out);
3264 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
3266 writeOperand(I.getOperand(i), PrintAllTypes);
3270 // Print atomic ordering/alignment for memory operations
3271 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
3273 writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
3274 if (LI->getAlignment())
3275 Out << ", align " << LI->getAlignment();
3276 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
3278 writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
3279 if (SI->getAlignment())
3280 Out << ", align " << SI->getAlignment();
3281 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
3282 writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
3283 CXI->getFailureOrdering(), CXI->getSyncScopeID());
3284 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
3285 writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
3286 RMWI->getSyncScopeID());
3287 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
3288 writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
3291 // Print Metadata info.
3292 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
3293 I.getAllMetadata(InstMD);
3294 printMetadataAttachments(InstMD, ", ");
3296 // Print a nice comment.
3297 printInfoComment(I);
3300 void AssemblyWriter::printMetadataAttachments(
3301 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
3302 StringRef Separator) {
3306 if (MDNames.empty())
3307 MDs[0].second->getContext().getMDKindNames(MDNames);
3309 for (const auto &I : MDs) {
3310 unsigned Kind = I.first;
3312 if (Kind < MDNames.size()) {
3314 printMetadataIdentifier(MDNames[Kind], Out);
3316 Out << "!<unknown kind #" << Kind << ">";
3318 WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
3322 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
3323 Out << '!' << Slot << " = ";
3324 printMDNodeBody(Node);
3328 void AssemblyWriter::writeAllMDNodes() {
3329 SmallVector<const MDNode *, 16> Nodes;
3330 Nodes.resize(Machine.mdn_size());
3331 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
3333 Nodes[I->second] = cast<MDNode>(I->first);
3335 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
3336 writeMDNode(i, Nodes[i]);
3340 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
3341 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
3344 void AssemblyWriter::writeAllAttributeGroups() {
3345 std::vector<std::pair<AttributeSet, unsigned>> asVec;
3346 asVec.resize(Machine.as_size());
3348 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
3350 asVec[I->second] = *I;
3352 for (const auto &I : asVec)
3353 Out << "attributes #" << I.second << " = { "
3354 << I.first.getAsString(true) << " }\n";
3357 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
3358 bool IsInFunction = Machine.getFunction();
3362 Out << "uselistorder";
3363 if (const BasicBlock *BB =
3364 IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
3366 writeOperand(BB->getParent(), false);
3368 writeOperand(BB, false);
3371 writeOperand(Order.V, true);
3375 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3376 Out << Order.Shuffle[0];
3377 for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
3378 Out << ", " << Order.Shuffle[I];
3382 void AssemblyWriter::printUseLists(const Function *F) {
3384 [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
3389 Out << "\n; uselistorder directives\n";
3391 printUseListOrder(UseListOrders.back());
3392 UseListOrders.pop_back();
3396 //===----------------------------------------------------------------------===//
3397 // External Interface declarations
3398 //===----------------------------------------------------------------------===//
3400 void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
3401 bool ShouldPreserveUseListOrder,
3402 bool IsForDebug) const {
3403 SlotTracker SlotTable(this->getParent());
3404 formatted_raw_ostream OS(ROS);
3405 AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
3407 ShouldPreserveUseListOrder);
3408 W.printFunction(this);
3411 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
3412 bool ShouldPreserveUseListOrder, bool IsForDebug) const {
3413 SlotTracker SlotTable(this);
3414 formatted_raw_ostream OS(ROS);
3415 AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
3416 ShouldPreserveUseListOrder);
3417 W.printModule(this);
3420 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
3421 SlotTracker SlotTable(getParent());
3422 formatted_raw_ostream OS(ROS);
3423 AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
3424 W.printNamedMDNode(this);
3427 void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
3428 bool IsForDebug) const {
3429 Optional<SlotTracker> LocalST;
3430 SlotTracker *SlotTable;
3431 if (auto *ST = MST.getMachine())
3434 LocalST.emplace(getParent());
3435 SlotTable = &*LocalST;
3438 formatted_raw_ostream OS(ROS);
3439 AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
3440 W.printNamedMDNode(this);
3443 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
3444 PrintLLVMName(ROS, getName(), ComdatPrefix);
3445 ROS << " = comdat ";
3447 switch (getSelectionKind()) {
3451 case Comdat::ExactMatch:
3452 ROS << "exactmatch";
3454 case Comdat::Largest:
3457 case Comdat::NoDuplicates:
3458 ROS << "noduplicates";
3460 case Comdat::SameSize:
3468 void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
3470 TP.print(const_cast<Type*>(this), OS);
3475 // If the type is a named struct type, print the body as well.
3476 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
3477 if (!STy->isLiteral()) {
3479 TP.printStructBody(STy, OS);
3483 static bool isReferencingMDNode(const Instruction &I) {
3484 if (const auto *CI = dyn_cast<CallInst>(&I))
3485 if (Function *F = CI->getCalledFunction())
3486 if (F->isIntrinsic())
3487 for (auto &Op : I.operands())
3488 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
3489 if (isa<MDNode>(V->getMetadata()))
3494 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
3495 bool ShouldInitializeAllMetadata = false;
3496 if (auto *I = dyn_cast<Instruction>(this))
3497 ShouldInitializeAllMetadata = isReferencingMDNode(*I);
3498 else if (isa<Function>(this) || isa<MetadataAsValue>(this))
3499 ShouldInitializeAllMetadata = true;
3501 ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
3502 print(ROS, MST, IsForDebug);
3505 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
3506 bool IsForDebug) const {
3507 formatted_raw_ostream OS(ROS);
3508 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
3509 SlotTracker &SlotTable =
3510 MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
3511 auto incorporateFunction = [&](const Function *F) {
3513 MST.incorporateFunction(*F);
3516 if (const Instruction *I = dyn_cast<Instruction>(this)) {
3517 incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
3518 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
3519 W.printInstruction(*I);
3520 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
3521 incorporateFunction(BB->getParent());
3522 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
3523 W.printBasicBlock(BB);
3524 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
3525 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
3526 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
3528 else if (const Function *F = dyn_cast<Function>(GV))
3531 W.printIndirectSymbol(cast<GlobalIndirectSymbol>(GV));
3532 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
3533 V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
3534 } else if (const Constant *C = dyn_cast<Constant>(this)) {
3535 TypePrinting TypePrinter;
3536 TypePrinter.print(C->getType(), OS);
3538 WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
3539 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
3540 this->printAsOperand(OS, /* PrintType */ true, MST);
3542 llvm_unreachable("Unknown value to print out!");
3546 /// Print without a type, skipping the TypePrinting object.
3548 /// \return \c true iff printing was successful.
3549 static bool printWithoutType(const Value &V, raw_ostream &O,
3550 SlotTracker *Machine, const Module *M) {
3551 if (V.hasName() || isa<GlobalValue>(V) ||
3552 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
3553 WriteAsOperandInternal(O, &V, nullptr, Machine, M);
3559 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
3560 ModuleSlotTracker &MST) {
3561 TypePrinting TypePrinter;
3562 if (const Module *M = MST.getModule())
3563 TypePrinter.incorporateTypes(*M);
3565 TypePrinter.print(V.getType(), O);
3569 WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
3573 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3574 const Module *M) const {
3576 M = getModuleFromVal(this);
3579 if (printWithoutType(*this, O, nullptr, M))
3582 SlotTracker Machine(
3583 M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
3584 ModuleSlotTracker MST(Machine, M);
3585 printAsOperandImpl(*this, O, PrintType, MST);
3588 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3589 ModuleSlotTracker &MST) const {
3591 if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
3594 printAsOperandImpl(*this, O, PrintType, MST);
3597 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
3598 ModuleSlotTracker &MST, const Module *M,
3599 bool OnlyAsOperand) {
3600 formatted_raw_ostream OS(ROS);
3602 TypePrinting TypePrinter;
3604 TypePrinter.incorporateTypes(*M);
3606 WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
3607 /* FromValue */ true);
3609 auto *N = dyn_cast<MDNode>(&MD);
3610 if (OnlyAsOperand || !N || isa<DIExpression>(MD))
3614 WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
3617 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
3618 ModuleSlotTracker MST(M, isa<MDNode>(this));
3619 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3622 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
3623 const Module *M) const {
3624 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3627 void Metadata::print(raw_ostream &OS, const Module *M,
3628 bool /*IsForDebug*/) const {
3629 ModuleSlotTracker MST(M, isa<MDNode>(this));
3630 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3633 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
3634 const Module *M, bool /*IsForDebug*/) const {
3635 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3638 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3639 // Value::dump - allow easy printing of Values from the debugger.
3641 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3643 // Type::dump - allow easy printing of Types from the debugger.
3645 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3647 // Module::dump() - Allow printing of Modules from the debugger.
3649 void Module::dump() const {
3650 print(dbgs(), nullptr,
3651 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
3654 // \brief Allow printing of Comdats from the debugger.
3656 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3658 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
3660 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3663 void Metadata::dump() const { dump(nullptr); }
3666 void Metadata::dump(const Module *M) const {
3667 print(dbgs(), M, /*IsForDebug=*/true);