2 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
4 // The LLVM Compiler Infrastructure
6 // This file is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
9 //===----------------------------------------------------------------------===//
11 // This library implements the functionality defined in llvm/IR/Writer.h
13 // Note that these routines must be extremely tolerant of various errors in the
14 // LLVM code, because it can be used for debugging transformations.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/IR/AssemblyAnnotationWriter.h"
24 #include "llvm/IR/Attributes.h"
25 #include "llvm/IR/CFG.h"
26 #include "llvm/IR/CallingConv.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/IRPrintingPasses.h"
31 #include "llvm/IR/InlineAsm.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/ModuleSlotTracker.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/IR/Statepoint.h"
38 #include "llvm/IR/TypeFinder.h"
39 #include "llvm/IR/UseListOrder.h"
40 #include "llvm/IR/ValueSymbolTable.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/Dwarf.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/Format.h"
45 #include "llvm/Support/FormattedStream.h"
46 #include "llvm/Support/MathExtras.h"
47 #include "llvm/Support/raw_ostream.h"
52 // Make virtual table appear in this compilation unit.
53 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
55 //===----------------------------------------------------------------------===//
57 //===----------------------------------------------------------------------===//
61 DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
63 unsigned size() const { return IDs.size(); }
64 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
65 std::pair<unsigned, bool> lookup(const Value *V) const {
68 void index(const Value *V) {
69 // Explicitly sequence get-size and insert-value operations to avoid UB.
70 unsigned ID = IDs.size() + 1;
76 static void orderValue(const Value *V, OrderMap &OM) {
77 if (OM.lookup(V).first)
80 if (const Constant *C = dyn_cast<Constant>(V))
81 if (C->getNumOperands() && !isa<GlobalValue>(C))
82 for (const Value *Op : C->operands())
83 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
86 // Note: we cannot cache this lookup above, since inserting into the map
87 // changes the map's size, and thus affects the other IDs.
91 static OrderMap orderModule(const Module *M) {
92 // This needs to match the order used by ValueEnumerator::ValueEnumerator()
93 // and ValueEnumerator::incorporateFunction().
96 for (const GlobalVariable &G : M->globals()) {
97 if (G.hasInitializer())
98 if (!isa<GlobalValue>(G.getInitializer()))
99 orderValue(G.getInitializer(), OM);
102 for (const GlobalAlias &A : M->aliases()) {
103 if (!isa<GlobalValue>(A.getAliasee()))
104 orderValue(A.getAliasee(), OM);
107 for (const GlobalIFunc &I : M->ifuncs()) {
108 if (!isa<GlobalValue>(I.getResolver()))
109 orderValue(I.getResolver(), OM);
112 for (const Function &F : *M) {
113 for (const Use &U : F.operands())
114 if (!isa<GlobalValue>(U.get()))
115 orderValue(U.get(), OM);
119 if (F.isDeclaration())
122 for (const Argument &A : F.args())
124 for (const BasicBlock &BB : F) {
126 for (const Instruction &I : BB) {
127 for (const Value *Op : I.operands())
128 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
138 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
139 unsigned ID, const OrderMap &OM,
140 UseListOrderStack &Stack) {
141 // Predict use-list order for this one.
142 typedef std::pair<const Use *, unsigned> Entry;
143 SmallVector<Entry, 64> List;
144 for (const Use &U : V->uses())
145 // Check if this user will be serialized.
146 if (OM.lookup(U.getUser()).first)
147 List.push_back(std::make_pair(&U, List.size()));
150 // We may have lost some users.
154 !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
155 if (auto *BA = dyn_cast<BlockAddress>(V))
156 ID = OM.lookup(BA->getBasicBlock()).first;
157 std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
158 const Use *LU = L.first;
159 const Use *RU = R.first;
163 auto LID = OM.lookup(LU->getUser()).first;
164 auto RID = OM.lookup(RU->getUser()).first;
166 // If ID is 4, then expect: 7 6 5 1 2 3.
180 // LID and RID are equal, so we have different operands of the same user.
181 // Assume operands are added in order for all instructions.
184 return LU->getOperandNo() < RU->getOperandNo();
185 return LU->getOperandNo() > RU->getOperandNo();
189 List.begin(), List.end(),
190 [](const Entry &L, const Entry &R) { return L.second < R.second; }))
191 // Order is already correct.
194 // Store the shuffle.
195 Stack.emplace_back(V, F, List.size());
196 assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
197 for (size_t I = 0, E = List.size(); I != E; ++I)
198 Stack.back().Shuffle[I] = List[I].second;
201 static void predictValueUseListOrder(const Value *V, const Function *F,
202 OrderMap &OM, UseListOrderStack &Stack) {
203 auto &IDPair = OM[V];
204 assert(IDPair.first && "Unmapped value");
206 // Already predicted.
209 // Do the actual prediction.
210 IDPair.second = true;
211 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
212 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
214 // Recursive descent into constants.
215 if (const Constant *C = dyn_cast<Constant>(V))
216 if (C->getNumOperands()) // Visit GlobalValues.
217 for (const Value *Op : C->operands())
218 if (isa<Constant>(Op)) // Visit GlobalValues.
219 predictValueUseListOrder(Op, F, OM, Stack);
222 static UseListOrderStack predictUseListOrder(const Module *M) {
223 OrderMap OM = orderModule(M);
225 // Use-list orders need to be serialized after all the users have been added
226 // to a value, or else the shuffles will be incomplete. Store them per
227 // function in a stack.
229 // Aside from function order, the order of values doesn't matter much here.
230 UseListOrderStack Stack;
232 // We want to visit the functions backward now so we can list function-local
233 // constants in the last Function they're used in. Module-level constants
234 // have already been visited above.
235 for (const Function &F : make_range(M->rbegin(), M->rend())) {
236 if (F.isDeclaration())
238 for (const BasicBlock &BB : F)
239 predictValueUseListOrder(&BB, &F, OM, Stack);
240 for (const Argument &A : F.args())
241 predictValueUseListOrder(&A, &F, OM, Stack);
242 for (const BasicBlock &BB : F)
243 for (const Instruction &I : BB)
244 for (const Value *Op : I.operands())
245 if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
246 predictValueUseListOrder(Op, &F, OM, Stack);
247 for (const BasicBlock &BB : F)
248 for (const Instruction &I : BB)
249 predictValueUseListOrder(&I, &F, OM, Stack);
252 // Visit globals last.
253 for (const GlobalVariable &G : M->globals())
254 predictValueUseListOrder(&G, nullptr, OM, Stack);
255 for (const Function &F : *M)
256 predictValueUseListOrder(&F, nullptr, OM, Stack);
257 for (const GlobalAlias &A : M->aliases())
258 predictValueUseListOrder(&A, nullptr, OM, Stack);
259 for (const GlobalIFunc &I : M->ifuncs())
260 predictValueUseListOrder(&I, nullptr, OM, Stack);
261 for (const GlobalVariable &G : M->globals())
262 if (G.hasInitializer())
263 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
264 for (const GlobalAlias &A : M->aliases())
265 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
266 for (const GlobalIFunc &I : M->ifuncs())
267 predictValueUseListOrder(I.getResolver(), nullptr, OM, Stack);
268 for (const Function &F : *M)
269 for (const Use &U : F.operands())
270 predictValueUseListOrder(U.get(), nullptr, OM, Stack);
275 static const Module *getModuleFromVal(const Value *V) {
276 if (const Argument *MA = dyn_cast<Argument>(V))
277 return MA->getParent() ? MA->getParent()->getParent() : nullptr;
279 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
280 return BB->getParent() ? BB->getParent()->getParent() : nullptr;
282 if (const Instruction *I = dyn_cast<Instruction>(V)) {
283 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
284 return M ? M->getParent() : nullptr;
287 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
288 return GV->getParent();
290 if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
291 for (const User *U : MAV->users())
292 if (isa<Instruction>(U))
293 if (const Module *M = getModuleFromVal(U))
301 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
303 default: Out << "cc" << cc; break;
304 case CallingConv::Fast: Out << "fastcc"; break;
305 case CallingConv::Cold: Out << "coldcc"; break;
306 case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
307 case CallingConv::AnyReg: Out << "anyregcc"; break;
308 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
309 case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
310 case CallingConv::CXX_FAST_TLS: Out << "cxx_fast_tlscc"; break;
311 case CallingConv::GHC: Out << "ghccc"; break;
312 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
313 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
314 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
315 case CallingConv::X86_RegCall: Out << "x86_regcallcc"; break;
316 case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
317 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
318 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
319 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
320 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
321 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
322 case CallingConv::AVR_INTR: Out << "avr_intrcc "; break;
323 case CallingConv::AVR_SIGNAL: Out << "avr_signalcc "; break;
324 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
325 case CallingConv::PTX_Device: Out << "ptx_device"; break;
326 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
327 case CallingConv::X86_64_Win64: Out << "x86_64_win64cc"; break;
328 case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
329 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
330 case CallingConv::Swift: Out << "swiftcc"; break;
331 case CallingConv::X86_INTR: Out << "x86_intrcc"; break;
332 case CallingConv::HHVM: Out << "hhvmcc"; break;
333 case CallingConv::HHVM_C: Out << "hhvm_ccc"; break;
334 case CallingConv::AMDGPU_VS: Out << "amdgpu_vs"; break;
335 case CallingConv::AMDGPU_HS: Out << "amdgpu_hs"; break;
336 case CallingConv::AMDGPU_GS: Out << "amdgpu_gs"; break;
337 case CallingConv::AMDGPU_PS: Out << "amdgpu_ps"; break;
338 case CallingConv::AMDGPU_CS: Out << "amdgpu_cs"; break;
339 case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;
343 void llvm::PrintEscapedString(StringRef Name, raw_ostream &Out) {
344 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
345 unsigned char C = Name[i];
346 if (isprint(C) && C != '\\' && C != '"')
349 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
361 void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
362 assert(!Name.empty() && "Cannot get empty name!");
364 // Scan the name to see if it needs quotes first.
365 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
367 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
368 // By making this unsigned, the value passed in to isalnum will always be
369 // in the range 0-255. This is important when building with MSVC because
370 // its implementation will assert. This situation can arise when dealing
371 // with UTF-8 multibyte characters.
372 unsigned char C = Name[i];
373 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
381 // If we didn't need any quotes, just write out the name in one blast.
387 // Okay, we need quotes. Output the quotes and escape any scary characters as
390 PrintEscapedString(Name, OS);
394 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
395 /// (if the string only contains simple characters) or is surrounded with ""'s
396 /// (if it has special chars in it). Print it out.
397 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
413 printLLVMNameWithoutPrefix(OS, Name);
416 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
417 /// (if the string only contains simple characters) or is surrounded with ""'s
418 /// (if it has special chars in it). Print it out.
419 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
420 PrintLLVMName(OS, V->getName(),
421 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
427 TypePrinting(const TypePrinting &) = delete;
428 void operator=(const TypePrinting&) = delete;
431 /// NamedTypes - The named types that are used by the current module.
432 TypeFinder NamedTypes;
434 /// NumberedTypes - The numbered types, along with their value.
435 DenseMap<StructType*, unsigned> NumberedTypes;
437 TypePrinting() = default;
439 void incorporateTypes(const Module &M);
441 void print(Type *Ty, raw_ostream &OS);
443 void printStructBody(StructType *Ty, raw_ostream &OS);
447 void TypePrinting::incorporateTypes(const Module &M) {
448 NamedTypes.run(M, false);
450 // The list of struct types we got back includes all the struct types, split
451 // the unnamed ones out to a numbering and remove the anonymous structs.
452 unsigned NextNumber = 0;
454 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
455 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
456 StructType *STy = *I;
458 // Ignore anonymous types.
459 if (STy->isLiteral())
462 if (STy->getName().empty())
463 NumberedTypes[STy] = NextNumber++;
468 NamedTypes.erase(NextToUse, NamedTypes.end());
472 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
473 /// use of type names or up references to shorten the type name where possible.
474 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
475 switch (Ty->getTypeID()) {
476 case Type::VoidTyID: OS << "void"; return;
477 case Type::HalfTyID: OS << "half"; return;
478 case Type::FloatTyID: OS << "float"; return;
479 case Type::DoubleTyID: OS << "double"; return;
480 case Type::X86_FP80TyID: OS << "x86_fp80"; return;
481 case Type::FP128TyID: OS << "fp128"; return;
482 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
483 case Type::LabelTyID: OS << "label"; return;
484 case Type::MetadataTyID: OS << "metadata"; return;
485 case Type::X86_MMXTyID: OS << "x86_mmx"; return;
486 case Type::TokenTyID: OS << "token"; return;
487 case Type::IntegerTyID:
488 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
491 case Type::FunctionTyID: {
492 FunctionType *FTy = cast<FunctionType>(Ty);
493 print(FTy->getReturnType(), OS);
495 for (FunctionType::param_iterator I = FTy->param_begin(),
496 E = FTy->param_end(); I != E; ++I) {
497 if (I != FTy->param_begin())
501 if (FTy->isVarArg()) {
502 if (FTy->getNumParams()) OS << ", ";
508 case Type::StructTyID: {
509 StructType *STy = cast<StructType>(Ty);
511 if (STy->isLiteral())
512 return printStructBody(STy, OS);
514 if (!STy->getName().empty())
515 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
517 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
518 if (I != NumberedTypes.end())
519 OS << '%' << I->second;
520 else // Not enumerated, print the hex address.
521 OS << "%\"type " << STy << '\"';
524 case Type::PointerTyID: {
525 PointerType *PTy = cast<PointerType>(Ty);
526 print(PTy->getElementType(), OS);
527 if (unsigned AddressSpace = PTy->getAddressSpace())
528 OS << " addrspace(" << AddressSpace << ')';
532 case Type::ArrayTyID: {
533 ArrayType *ATy = cast<ArrayType>(Ty);
534 OS << '[' << ATy->getNumElements() << " x ";
535 print(ATy->getElementType(), OS);
539 case Type::VectorTyID: {
540 VectorType *PTy = cast<VectorType>(Ty);
541 OS << "<" << PTy->getNumElements() << " x ";
542 print(PTy->getElementType(), OS);
547 llvm_unreachable("Invalid TypeID");
550 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
551 if (STy->isOpaque()) {
559 if (STy->getNumElements() == 0) {
562 StructType::element_iterator I = STy->element_begin();
565 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
577 //===----------------------------------------------------------------------===//
578 // SlotTracker Class: Enumerate slot numbers for unnamed values
579 //===----------------------------------------------------------------------===//
580 /// This class provides computation of slot numbers for LLVM Assembly writing.
584 /// ValueMap - A mapping of Values to slot numbers.
585 typedef DenseMap<const Value*, unsigned> ValueMap;
588 /// TheModule - The module for which we are holding slot numbers.
589 const Module* TheModule;
591 /// TheFunction - The function for which we are holding slot numbers.
592 const Function* TheFunction;
593 bool FunctionProcessed;
594 bool ShouldInitializeAllMetadata;
596 /// mMap - The slot map for the module level data.
600 /// fMap - The slot map for the function level data.
604 /// mdnMap - Map for MDNodes.
605 DenseMap<const MDNode*, unsigned> mdnMap;
608 /// asMap - The slot map for attribute sets.
609 DenseMap<AttributeSet, unsigned> asMap;
612 /// Construct from a module.
614 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
615 /// functions, giving correct numbering for metadata referenced only from
616 /// within a function (even if no functions have been initialized).
617 explicit SlotTracker(const Module *M,
618 bool ShouldInitializeAllMetadata = false);
619 /// Construct from a function, starting out in incorp state.
621 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
622 /// functions, giving correct numbering for metadata referenced only from
623 /// within a function (even if no functions have been initialized).
624 explicit SlotTracker(const Function *F,
625 bool ShouldInitializeAllMetadata = false);
627 /// Return the slot number of the specified value in it's type
628 /// plane. If something is not in the SlotTracker, return -1.
629 int getLocalSlot(const Value *V);
630 int getGlobalSlot(const GlobalValue *V);
631 int getMetadataSlot(const MDNode *N);
632 int getAttributeGroupSlot(AttributeSet AS);
634 /// If you'd like to deal with a function instead of just a module, use
635 /// this method to get its data into the SlotTracker.
636 void incorporateFunction(const Function *F) {
638 FunctionProcessed = false;
641 const Function *getFunction() const { return TheFunction; }
643 /// After calling incorporateFunction, use this method to remove the
644 /// most recently incorporated function from the SlotTracker. This
645 /// will reset the state of the machine back to just the module contents.
646 void purgeFunction();
648 /// MDNode map iterators.
649 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
650 mdn_iterator mdn_begin() { return mdnMap.begin(); }
651 mdn_iterator mdn_end() { return mdnMap.end(); }
652 unsigned mdn_size() const { return mdnMap.size(); }
653 bool mdn_empty() const { return mdnMap.empty(); }
655 /// AttributeSet map iterators.
656 typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
657 as_iterator as_begin() { return asMap.begin(); }
658 as_iterator as_end() { return asMap.end(); }
659 unsigned as_size() const { return asMap.size(); }
660 bool as_empty() const { return asMap.empty(); }
662 /// This function does the actual initialization.
663 inline void initialize();
665 // Implementation Details
667 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
668 void CreateModuleSlot(const GlobalValue *V);
670 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
671 void CreateMetadataSlot(const MDNode *N);
673 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
674 void CreateFunctionSlot(const Value *V);
676 /// \brief Insert the specified AttributeSet into the slot table.
677 void CreateAttributeSetSlot(AttributeSet AS);
679 /// Add all of the module level global variables (and their initializers)
680 /// and function declarations, but not the contents of those functions.
681 void processModule();
683 /// Add all of the functions arguments, basic blocks, and instructions.
684 void processFunction();
686 /// Add the metadata directly attached to a GlobalObject.
687 void processGlobalObjectMetadata(const GlobalObject &GO);
689 /// Add all of the metadata from a function.
690 void processFunctionMetadata(const Function &F);
692 /// Add all of the metadata from an instruction.
693 void processInstructionMetadata(const Instruction &I);
695 SlotTracker(const SlotTracker &) = delete;
696 void operator=(const SlotTracker &) = delete;
700 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
702 : M(M), F(F), Machine(&Machine) {}
704 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
705 bool ShouldInitializeAllMetadata)
706 : ShouldCreateStorage(M),
707 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
709 ModuleSlotTracker::~ModuleSlotTracker() {}
711 SlotTracker *ModuleSlotTracker::getMachine() {
712 if (!ShouldCreateStorage)
715 ShouldCreateStorage = false;
717 llvm::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
718 Machine = MachineStorage.get();
722 void ModuleSlotTracker::incorporateFunction(const Function &F) {
723 // Using getMachine() may lazily create the slot tracker.
727 // Nothing to do if this is the right function already.
731 Machine->purgeFunction();
732 Machine->incorporateFunction(&F);
736 int ModuleSlotTracker::getLocalSlot(const Value *V) {
737 assert(F && "No function incorporated");
738 return Machine->getLocalSlot(V);
741 static SlotTracker *createSlotTracker(const Value *V) {
742 if (const Argument *FA = dyn_cast<Argument>(V))
743 return new SlotTracker(FA->getParent());
745 if (const Instruction *I = dyn_cast<Instruction>(V))
747 return new SlotTracker(I->getParent()->getParent());
749 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
750 return new SlotTracker(BB->getParent());
752 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
753 return new SlotTracker(GV->getParent());
755 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
756 return new SlotTracker(GA->getParent());
758 if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
759 return new SlotTracker(GIF->getParent());
761 if (const Function *Func = dyn_cast<Function>(V))
762 return new SlotTracker(Func);
768 #define ST_DEBUG(X) dbgs() << X
773 // Module level constructor. Causes the contents of the Module (sans functions)
774 // to be added to the slot table.
775 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
776 : TheModule(M), TheFunction(nullptr), FunctionProcessed(false),
777 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
778 fNext(0), mdnNext(0), asNext(0) {}
780 // Function level constructor. Causes the contents of the Module and the one
781 // function provided to be added to the slot table.
782 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
783 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
784 FunctionProcessed(false),
785 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
786 fNext(0), mdnNext(0), asNext(0) {}
788 inline void SlotTracker::initialize() {
791 TheModule = nullptr; ///< Prevent re-processing next time we're called.
794 if (TheFunction && !FunctionProcessed)
798 // Iterate through all the global variables, functions, and global
799 // variable initializers and create slots for them.
800 void SlotTracker::processModule() {
801 ST_DEBUG("begin processModule!\n");
803 // Add all of the unnamed global variables to the value table.
804 for (const GlobalVariable &Var : TheModule->globals()) {
806 CreateModuleSlot(&Var);
807 processGlobalObjectMetadata(Var);
810 for (const GlobalAlias &A : TheModule->aliases()) {
812 CreateModuleSlot(&A);
815 for (const GlobalIFunc &I : TheModule->ifuncs()) {
817 CreateModuleSlot(&I);
820 // Add metadata used by named metadata.
821 for (const NamedMDNode &NMD : TheModule->named_metadata()) {
822 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
823 CreateMetadataSlot(NMD.getOperand(i));
826 for (const Function &F : *TheModule) {
828 // Add all the unnamed functions to the table.
829 CreateModuleSlot(&F);
831 if (ShouldInitializeAllMetadata)
832 processFunctionMetadata(F);
834 // Add all the function attributes to the table.
835 // FIXME: Add attributes of other objects?
836 AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
837 if (FnAttrs.hasAttributes())
838 CreateAttributeSetSlot(FnAttrs);
841 ST_DEBUG("end processModule!\n");
844 // Process the arguments, basic blocks, and instructions of a function.
845 void SlotTracker::processFunction() {
846 ST_DEBUG("begin processFunction!\n");
849 // Process function metadata if it wasn't hit at the module-level.
850 if (!ShouldInitializeAllMetadata)
851 processFunctionMetadata(*TheFunction);
853 // Add all the function arguments with no names.
854 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
855 AE = TheFunction->arg_end(); AI != AE; ++AI)
857 CreateFunctionSlot(&*AI);
859 ST_DEBUG("Inserting Instructions:\n");
861 // Add all of the basic blocks and instructions with no names.
862 for (auto &BB : *TheFunction) {
864 CreateFunctionSlot(&BB);
867 if (!I.getType()->isVoidTy() && !I.hasName())
868 CreateFunctionSlot(&I);
870 // We allow direct calls to any llvm.foo function here, because the
871 // target may not be linked into the optimizer.
872 if (auto CS = ImmutableCallSite(&I)) {
873 // Add all the call attributes to the table.
874 AttributeSet Attrs = CS.getAttributes().getFnAttributes();
875 if (Attrs.hasAttributes())
876 CreateAttributeSetSlot(Attrs);
881 FunctionProcessed = true;
883 ST_DEBUG("end processFunction!\n");
886 void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) {
887 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
888 GO.getAllMetadata(MDs);
890 CreateMetadataSlot(MD.second);
893 void SlotTracker::processFunctionMetadata(const Function &F) {
894 processGlobalObjectMetadata(F);
897 processInstructionMetadata(I);
901 void SlotTracker::processInstructionMetadata(const Instruction &I) {
902 // Process metadata used directly by intrinsics.
903 if (const CallInst *CI = dyn_cast<CallInst>(&I))
904 if (Function *F = CI->getCalledFunction())
905 if (F->isIntrinsic())
906 for (auto &Op : I.operands())
907 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
908 if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
909 CreateMetadataSlot(N);
911 // Process metadata attached to this instruction.
912 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
913 I.getAllMetadata(MDs);
915 CreateMetadataSlot(MD.second);
918 /// Clean up after incorporating a function. This is the only way to get out of
919 /// the function incorporation state that affects get*Slot/Create*Slot. Function
920 /// incorporation state is indicated by TheFunction != 0.
921 void SlotTracker::purgeFunction() {
922 ST_DEBUG("begin purgeFunction!\n");
923 fMap.clear(); // Simply discard the function level map
924 TheFunction = nullptr;
925 FunctionProcessed = false;
926 ST_DEBUG("end purgeFunction!\n");
929 /// getGlobalSlot - Get the slot number of a global value.
930 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
931 // Check for uninitialized state and do lazy initialization.
934 // Find the value in the module map
935 ValueMap::iterator MI = mMap.find(V);
936 return MI == mMap.end() ? -1 : (int)MI->second;
939 /// getMetadataSlot - Get the slot number of a MDNode.
940 int SlotTracker::getMetadataSlot(const MDNode *N) {
941 // Check for uninitialized state and do lazy initialization.
944 // Find the MDNode in the module map
945 mdn_iterator MI = mdnMap.find(N);
946 return MI == mdnMap.end() ? -1 : (int)MI->second;
950 /// getLocalSlot - Get the slot number for a value that is local to a function.
951 int SlotTracker::getLocalSlot(const Value *V) {
952 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
954 // Check for uninitialized state and do lazy initialization.
957 ValueMap::iterator FI = fMap.find(V);
958 return FI == fMap.end() ? -1 : (int)FI->second;
961 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
962 // Check for uninitialized state and do lazy initialization.
965 // Find the AttributeSet in the module map.
966 as_iterator AI = asMap.find(AS);
967 return AI == asMap.end() ? -1 : (int)AI->second;
970 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
971 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
972 assert(V && "Can't insert a null Value into SlotTracker!");
973 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
974 assert(!V->hasName() && "Doesn't need a slot!");
976 unsigned DestSlot = mNext++;
979 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
981 // G = Global, F = Function, A = Alias, I = IFunc, o = other
982 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
983 (isa<Function>(V) ? 'F' :
984 (isa<GlobalAlias>(V) ? 'A' :
985 (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");
988 /// CreateSlot - Create a new slot for the specified value if it has no name.
989 void SlotTracker::CreateFunctionSlot(const Value *V) {
990 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
992 unsigned DestSlot = fNext++;
995 // G = Global, F = Function, o = other
996 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
997 DestSlot << " [o]\n");
1000 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
1001 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
1002 assert(N && "Can't insert a null Value into SlotTracker!");
1004 unsigned DestSlot = mdnNext;
1005 if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
1009 // Recursively add any MDNodes referenced by operands.
1010 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1011 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
1012 CreateMetadataSlot(Op);
1015 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
1016 assert(AS.hasAttributes() && "Doesn't need a slot!");
1018 as_iterator I = asMap.find(AS);
1019 if (I != asMap.end())
1022 unsigned DestSlot = asNext++;
1023 asMap[AS] = DestSlot;
1026 //===----------------------------------------------------------------------===//
1027 // AsmWriter Implementation
1028 //===----------------------------------------------------------------------===//
1030 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1031 TypePrinting *TypePrinter,
1032 SlotTracker *Machine,
1033 const Module *Context);
1035 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1036 TypePrinting *TypePrinter,
1037 SlotTracker *Machine, const Module *Context,
1038 bool FromValue = false);
1040 static void writeAtomicRMWOperation(raw_ostream &Out,
1041 AtomicRMWInst::BinOp Op) {
1043 default: Out << " <unknown operation " << Op << ">"; break;
1044 case AtomicRMWInst::Xchg: Out << " xchg"; break;
1045 case AtomicRMWInst::Add: Out << " add"; break;
1046 case AtomicRMWInst::Sub: Out << " sub"; break;
1047 case AtomicRMWInst::And: Out << " and"; break;
1048 case AtomicRMWInst::Nand: Out << " nand"; break;
1049 case AtomicRMWInst::Or: Out << " or"; break;
1050 case AtomicRMWInst::Xor: Out << " xor"; break;
1051 case AtomicRMWInst::Max: Out << " max"; break;
1052 case AtomicRMWInst::Min: Out << " min"; break;
1053 case AtomicRMWInst::UMax: Out << " umax"; break;
1054 case AtomicRMWInst::UMin: Out << " umin"; break;
1058 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1059 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
1060 // Unsafe algebra implies all the others, no need to write them all out
1061 if (FPO->hasUnsafeAlgebra())
1064 if (FPO->hasNoNaNs())
1066 if (FPO->hasNoInfs())
1068 if (FPO->hasNoSignedZeros())
1070 if (FPO->hasAllowReciprocal())
1072 if (FPO->hasAllowContract())
1077 if (const OverflowingBinaryOperator *OBO =
1078 dyn_cast<OverflowingBinaryOperator>(U)) {
1079 if (OBO->hasNoUnsignedWrap())
1081 if (OBO->hasNoSignedWrap())
1083 } else if (const PossiblyExactOperator *Div =
1084 dyn_cast<PossiblyExactOperator>(U)) {
1087 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1088 if (GEP->isInBounds())
1093 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1094 TypePrinting &TypePrinter,
1095 SlotTracker *Machine,
1096 const Module *Context) {
1097 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1098 if (CI->getType()->isIntegerTy(1)) {
1099 Out << (CI->getZExtValue() ? "true" : "false");
1102 Out << CI->getValue();
1106 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1107 const APFloat &APF = CFP->getValueAPF();
1108 if (&APF.getSemantics() == &APFloat::IEEEsingle() ||
1109 &APF.getSemantics() == &APFloat::IEEEdouble()) {
1110 // We would like to output the FP constant value in exponential notation,
1111 // but we cannot do this if doing so will lose precision. Check here to
1112 // make sure that we only output it in exponential format if we can parse
1113 // the value back and get the same value.
1116 bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble();
1117 bool isInf = APF.isInfinity();
1118 bool isNaN = APF.isNaN();
1119 if (!isInf && !isNaN) {
1120 double Val = isDouble ? APF.convertToDouble() : APF.convertToFloat();
1121 SmallString<128> StrVal;
1122 APF.toString(StrVal, 6, 0, false);
1123 // Check to make sure that the stringized number is not some string like
1124 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
1125 // that the string matches the "[-+]?[0-9]" regex.
1127 assert(((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1128 ((StrVal[0] == '-' || StrVal[0] == '+') &&
1129 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
1130 "[-+]?[0-9] regex does not match!");
1131 // Reparse stringized version!
1132 if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {
1137 // Otherwise we could not reparse it to exactly the same value, so we must
1138 // output the string in hexadecimal format! Note that loading and storing
1139 // floating point types changes the bits of NaNs on some hosts, notably
1140 // x86, so we must not use these types.
1141 static_assert(sizeof(double) == sizeof(uint64_t),
1142 "assuming that double is 64 bits!");
1144 // Floats are represented in ASCII IR as double, convert.
1146 apf.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
1148 Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
1152 // Either half, or some form of long double.
1153 // These appear as a magic letter identifying the type, then a
1154 // fixed number of hex digits.
1156 APInt API = APF.bitcastToAPInt();
1157 if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) {
1159 Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
1161 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1164 } else if (&APF.getSemantics() == &APFloat::IEEEquad()) {
1166 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1168 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1170 } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {
1172 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1174 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1176 } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) {
1178 Out << format_hex_no_prefix(API.getZExtValue(), 4,
1181 llvm_unreachable("Unsupported floating point type");
1185 if (isa<ConstantAggregateZero>(CV)) {
1186 Out << "zeroinitializer";
1190 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1191 Out << "blockaddress(";
1192 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
1195 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
1201 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1202 Type *ETy = CA->getType()->getElementType();
1204 TypePrinter.print(ETy, Out);
1206 WriteAsOperandInternal(Out, CA->getOperand(0),
1207 &TypePrinter, Machine,
1209 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1211 TypePrinter.print(ETy, Out);
1213 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
1220 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1221 // As a special case, print the array as a string if it is an array of
1222 // i8 with ConstantInt values.
1223 if (CA->isString()) {
1225 PrintEscapedString(CA->getAsString(), Out);
1230 Type *ETy = CA->getType()->getElementType();
1232 TypePrinter.print(ETy, Out);
1234 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
1235 &TypePrinter, Machine,
1237 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1239 TypePrinter.print(ETy, Out);
1241 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
1249 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1250 if (CS->getType()->isPacked())
1253 unsigned N = CS->getNumOperands();
1256 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1259 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1262 for (unsigned i = 1; i < N; i++) {
1264 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1267 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1274 if (CS->getType()->isPacked())
1279 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1280 Type *ETy = CV->getType()->getVectorElementType();
1282 TypePrinter.print(ETy, Out);
1284 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
1286 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
1288 TypePrinter.print(ETy, Out);
1290 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1297 if (isa<ConstantPointerNull>(CV)) {
1302 if (isa<ConstantTokenNone>(CV)) {
1307 if (isa<UndefValue>(CV)) {
1312 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1313 Out << CE->getOpcodeName();
1314 WriteOptimizationInfo(Out, CE);
1315 if (CE->isCompare())
1316 Out << ' ' << CmpInst::getPredicateName(
1317 static_cast<CmpInst::Predicate>(CE->getPredicate()));
1320 Optional<unsigned> InRangeOp;
1321 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1322 TypePrinter.print(GEP->getSourceElementType(), Out);
1324 InRangeOp = GEP->getInRangeIndex();
1329 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1330 if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp)
1332 TypePrinter.print((*OI)->getType(), Out);
1334 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1335 if (OI+1 != CE->op_end())
1339 if (CE->hasIndices()) {
1340 ArrayRef<unsigned> Indices = CE->getIndices();
1341 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1342 Out << ", " << Indices[i];
1347 TypePrinter.print(CE->getType(), Out);
1354 Out << "<placeholder or erroneous Constant>";
1357 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1358 TypePrinting *TypePrinter, SlotTracker *Machine,
1359 const Module *Context) {
1361 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1362 const Metadata *MD = Node->getOperand(mi);
1365 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1366 Value *V = MDV->getValue();
1367 TypePrinter->print(V->getType(), Out);
1369 WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
1371 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1381 struct FieldSeparator {
1384 FieldSeparator(const char *Sep = ", ") : Skip(true), Sep(Sep) {}
1386 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1391 return OS << FS.Sep;
1393 struct MDFieldPrinter {
1396 TypePrinting *TypePrinter;
1397 SlotTracker *Machine;
1398 const Module *Context;
1400 explicit MDFieldPrinter(raw_ostream &Out)
1401 : Out(Out), TypePrinter(nullptr), Machine(nullptr), Context(nullptr) {}
1402 MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
1403 SlotTracker *Machine, const Module *Context)
1404 : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
1406 void printTag(const DINode *N);
1407 void printMacinfoType(const DIMacroNode *N);
1408 void printChecksumKind(const DIFile *N);
1409 void printString(StringRef Name, StringRef Value,
1410 bool ShouldSkipEmpty = true);
1411 void printMetadata(StringRef Name, const Metadata *MD,
1412 bool ShouldSkipNull = true);
1413 template <class IntTy>
1414 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1415 void printBool(StringRef Name, bool Value, Optional<bool> Default = None);
1416 void printDIFlags(StringRef Name, DINode::DIFlags Flags);
1417 template <class IntTy, class Stringifier>
1418 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1419 bool ShouldSkipZero = true);
1420 void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
1424 void MDFieldPrinter::printTag(const DINode *N) {
1425 Out << FS << "tag: ";
1426 auto Tag = dwarf::TagString(N->getTag());
1433 void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
1434 Out << FS << "type: ";
1435 auto Type = dwarf::MacinfoString(N->getMacinfoType());
1439 Out << N->getMacinfoType();
1442 void MDFieldPrinter::printChecksumKind(const DIFile *N) {
1443 if (N->getChecksumKind() == DIFile::CSK_None)
1444 // Skip CSK_None checksum kind.
1446 Out << FS << "checksumkind: " << N->getChecksumKindAsString();
1449 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1450 bool ShouldSkipEmpty) {
1451 if (ShouldSkipEmpty && Value.empty())
1454 Out << FS << Name << ": \"";
1455 PrintEscapedString(Value, Out);
1459 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1460 TypePrinting *TypePrinter,
1461 SlotTracker *Machine,
1462 const Module *Context) {
1467 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1470 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1471 bool ShouldSkipNull) {
1472 if (ShouldSkipNull && !MD)
1475 Out << FS << Name << ": ";
1476 writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
1479 template <class IntTy>
1480 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1481 if (ShouldSkipZero && !Int)
1484 Out << FS << Name << ": " << Int;
1487 void MDFieldPrinter::printBool(StringRef Name, bool Value,
1488 Optional<bool> Default) {
1489 if (Default && Value == *Default)
1491 Out << FS << Name << ": " << (Value ? "true" : "false");
1494 void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
1498 Out << FS << Name << ": ";
1500 SmallVector<DINode::DIFlags, 8> SplitFlags;
1501 auto Extra = DINode::splitFlags(Flags, SplitFlags);
1503 FieldSeparator FlagsFS(" | ");
1504 for (auto F : SplitFlags) {
1505 auto StringF = DINode::getFlagString(F);
1506 assert(!StringF.empty() && "Expected valid flag");
1507 Out << FlagsFS << StringF;
1509 if (Extra || SplitFlags.empty())
1510 Out << FlagsFS << Extra;
1513 void MDFieldPrinter::printEmissionKind(StringRef Name,
1514 DICompileUnit::DebugEmissionKind EK) {
1515 Out << FS << Name << ": " << DICompileUnit::EmissionKindString(EK);
1519 template <class IntTy, class Stringifier>
1520 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1521 Stringifier toString, bool ShouldSkipZero) {
1525 Out << FS << Name << ": ";
1526 auto S = toString(Value);
1533 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1534 TypePrinting *TypePrinter, SlotTracker *Machine,
1535 const Module *Context) {
1536 Out << "!GenericDINode(";
1537 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1538 Printer.printTag(N);
1539 Printer.printString("header", N->getHeader());
1540 if (N->getNumDwarfOperands()) {
1541 Out << Printer.FS << "operands: {";
1543 for (auto &I : N->dwarf_operands()) {
1545 writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
1552 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1553 TypePrinting *TypePrinter, SlotTracker *Machine,
1554 const Module *Context) {
1555 Out << "!DILocation(";
1556 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1557 // Always output the line, since 0 is a relevant and important value for it.
1558 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1559 Printer.printInt("column", DL->getColumn());
1560 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1561 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
1565 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1566 TypePrinting *, SlotTracker *, const Module *) {
1567 Out << "!DISubrange(";
1568 MDFieldPrinter Printer(Out);
1569 Printer.printInt("count", N->getCount(), /* ShouldSkipZero */ false);
1570 Printer.printInt("lowerBound", N->getLowerBound());
1574 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1575 TypePrinting *, SlotTracker *, const Module *) {
1576 Out << "!DIEnumerator(";
1577 MDFieldPrinter Printer(Out);
1578 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1579 Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
1583 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1584 TypePrinting *, SlotTracker *, const Module *) {
1585 Out << "!DIBasicType(";
1586 MDFieldPrinter Printer(Out);
1587 if (N->getTag() != dwarf::DW_TAG_base_type)
1588 Printer.printTag(N);
1589 Printer.printString("name", N->getName());
1590 Printer.printInt("size", N->getSizeInBits());
1591 Printer.printInt("align", N->getAlignInBits());
1592 Printer.printDwarfEnum("encoding", N->getEncoding(),
1593 dwarf::AttributeEncodingString);
1597 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
1598 TypePrinting *TypePrinter, SlotTracker *Machine,
1599 const Module *Context) {
1600 Out << "!DIDerivedType(";
1601 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1602 Printer.printTag(N);
1603 Printer.printString("name", N->getName());
1604 Printer.printMetadata("scope", N->getRawScope());
1605 Printer.printMetadata("file", N->getRawFile());
1606 Printer.printInt("line", N->getLine());
1607 Printer.printMetadata("baseType", N->getRawBaseType(),
1608 /* ShouldSkipNull */ false);
1609 Printer.printInt("size", N->getSizeInBits());
1610 Printer.printInt("align", N->getAlignInBits());
1611 Printer.printInt("offset", N->getOffsetInBits());
1612 Printer.printDIFlags("flags", N->getFlags());
1613 Printer.printMetadata("extraData", N->getRawExtraData());
1614 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1615 Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
1616 /* ShouldSkipZero */ false);
1620 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
1621 TypePrinting *TypePrinter,
1622 SlotTracker *Machine, const Module *Context) {
1623 Out << "!DICompositeType(";
1624 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1625 Printer.printTag(N);
1626 Printer.printString("name", N->getName());
1627 Printer.printMetadata("scope", N->getRawScope());
1628 Printer.printMetadata("file", N->getRawFile());
1629 Printer.printInt("line", N->getLine());
1630 Printer.printMetadata("baseType", N->getRawBaseType());
1631 Printer.printInt("size", N->getSizeInBits());
1632 Printer.printInt("align", N->getAlignInBits());
1633 Printer.printInt("offset", N->getOffsetInBits());
1634 Printer.printDIFlags("flags", N->getFlags());
1635 Printer.printMetadata("elements", N->getRawElements());
1636 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
1637 dwarf::LanguageString);
1638 Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
1639 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1640 Printer.printString("identifier", N->getIdentifier());
1644 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
1645 TypePrinting *TypePrinter,
1646 SlotTracker *Machine, const Module *Context) {
1647 Out << "!DISubroutineType(";
1648 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1649 Printer.printDIFlags("flags", N->getFlags());
1650 Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
1651 Printer.printMetadata("types", N->getRawTypeArray(),
1652 /* ShouldSkipNull */ false);
1656 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
1657 SlotTracker *, const Module *) {
1659 MDFieldPrinter Printer(Out);
1660 Printer.printString("filename", N->getFilename(),
1661 /* ShouldSkipEmpty */ false);
1662 Printer.printString("directory", N->getDirectory(),
1663 /* ShouldSkipEmpty */ false);
1664 Printer.printChecksumKind(N);
1665 Printer.printString("checksum", N->getChecksum(), /* ShouldSkipEmpty */ true);
1669 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
1670 TypePrinting *TypePrinter, SlotTracker *Machine,
1671 const Module *Context) {
1672 Out << "!DICompileUnit(";
1673 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1674 Printer.printDwarfEnum("language", N->getSourceLanguage(),
1675 dwarf::LanguageString, /* ShouldSkipZero */ false);
1676 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1677 Printer.printString("producer", N->getProducer());
1678 Printer.printBool("isOptimized", N->isOptimized());
1679 Printer.printString("flags", N->getFlags());
1680 Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
1681 /* ShouldSkipZero */ false);
1682 Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
1683 Printer.printEmissionKind("emissionKind", N->getEmissionKind());
1684 Printer.printMetadata("enums", N->getRawEnumTypes());
1685 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
1686 Printer.printMetadata("globals", N->getRawGlobalVariables());
1687 Printer.printMetadata("imports", N->getRawImportedEntities());
1688 Printer.printMetadata("macros", N->getRawMacros());
1689 Printer.printInt("dwoId", N->getDWOId());
1690 Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
1691 Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
1696 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
1697 TypePrinting *TypePrinter, SlotTracker *Machine,
1698 const Module *Context) {
1699 Out << "!DISubprogram(";
1700 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1701 Printer.printString("name", N->getName());
1702 Printer.printString("linkageName", N->getLinkageName());
1703 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1704 Printer.printMetadata("file", N->getRawFile());
1705 Printer.printInt("line", N->getLine());
1706 Printer.printMetadata("type", N->getRawType());
1707 Printer.printBool("isLocal", N->isLocalToUnit());
1708 Printer.printBool("isDefinition", N->isDefinition());
1709 Printer.printInt("scopeLine", N->getScopeLine());
1710 Printer.printMetadata("containingType", N->getRawContainingType());
1711 Printer.printDwarfEnum("virtuality", N->getVirtuality(),
1712 dwarf::VirtualityString);
1713 if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
1714 N->getVirtualIndex() != 0)
1715 Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
1716 Printer.printInt("thisAdjustment", N->getThisAdjustment());
1717 Printer.printDIFlags("flags", N->getFlags());
1718 Printer.printBool("isOptimized", N->isOptimized());
1719 Printer.printMetadata("unit", N->getRawUnit());
1720 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1721 Printer.printMetadata("declaration", N->getRawDeclaration());
1722 Printer.printMetadata("variables", N->getRawVariables());
1723 Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
1727 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
1728 TypePrinting *TypePrinter, SlotTracker *Machine,
1729 const Module *Context) {
1730 Out << "!DILexicalBlock(";
1731 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1732 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1733 Printer.printMetadata("file", N->getRawFile());
1734 Printer.printInt("line", N->getLine());
1735 Printer.printInt("column", N->getColumn());
1739 static void writeDILexicalBlockFile(raw_ostream &Out,
1740 const DILexicalBlockFile *N,
1741 TypePrinting *TypePrinter,
1742 SlotTracker *Machine,
1743 const Module *Context) {
1744 Out << "!DILexicalBlockFile(";
1745 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1746 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1747 Printer.printMetadata("file", N->getRawFile());
1748 Printer.printInt("discriminator", N->getDiscriminator(),
1749 /* ShouldSkipZero */ false);
1753 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
1754 TypePrinting *TypePrinter, SlotTracker *Machine,
1755 const Module *Context) {
1756 Out << "!DINamespace(";
1757 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1758 Printer.printString("name", N->getName());
1759 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1760 Printer.printBool("exportSymbols", N->getExportSymbols(), false);
1764 static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
1765 TypePrinting *TypePrinter, SlotTracker *Machine,
1766 const Module *Context) {
1768 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1769 Printer.printMacinfoType(N);
1770 Printer.printInt("line", N->getLine());
1771 Printer.printString("name", N->getName());
1772 Printer.printString("value", N->getValue());
1776 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
1777 TypePrinting *TypePrinter, SlotTracker *Machine,
1778 const Module *Context) {
1779 Out << "!DIMacroFile(";
1780 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1781 Printer.printInt("line", N->getLine());
1782 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1783 Printer.printMetadata("nodes", N->getRawElements());
1787 static void writeDIModule(raw_ostream &Out, const DIModule *N,
1788 TypePrinting *TypePrinter, SlotTracker *Machine,
1789 const Module *Context) {
1790 Out << "!DIModule(";
1791 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1792 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1793 Printer.printString("name", N->getName());
1794 Printer.printString("configMacros", N->getConfigurationMacros());
1795 Printer.printString("includePath", N->getIncludePath());
1796 Printer.printString("isysroot", N->getISysRoot());
1801 static void writeDITemplateTypeParameter(raw_ostream &Out,
1802 const DITemplateTypeParameter *N,
1803 TypePrinting *TypePrinter,
1804 SlotTracker *Machine,
1805 const Module *Context) {
1806 Out << "!DITemplateTypeParameter(";
1807 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1808 Printer.printString("name", N->getName());
1809 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
1813 static void writeDITemplateValueParameter(raw_ostream &Out,
1814 const DITemplateValueParameter *N,
1815 TypePrinting *TypePrinter,
1816 SlotTracker *Machine,
1817 const Module *Context) {
1818 Out << "!DITemplateValueParameter(";
1819 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1820 if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
1821 Printer.printTag(N);
1822 Printer.printString("name", N->getName());
1823 Printer.printMetadata("type", N->getRawType());
1824 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
1828 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
1829 TypePrinting *TypePrinter,
1830 SlotTracker *Machine, const Module *Context) {
1831 Out << "!DIGlobalVariable(";
1832 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1833 Printer.printString("name", N->getName());
1834 Printer.printString("linkageName", N->getLinkageName());
1835 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1836 Printer.printMetadata("file", N->getRawFile());
1837 Printer.printInt("line", N->getLine());
1838 Printer.printMetadata("type", N->getRawType());
1839 Printer.printBool("isLocal", N->isLocalToUnit());
1840 Printer.printBool("isDefinition", N->isDefinition());
1841 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
1842 Printer.printInt("align", N->getAlignInBits());
1846 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
1847 TypePrinting *TypePrinter,
1848 SlotTracker *Machine, const Module *Context) {
1849 Out << "!DILocalVariable(";
1850 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1851 Printer.printString("name", N->getName());
1852 Printer.printInt("arg", N->getArg());
1853 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1854 Printer.printMetadata("file", N->getRawFile());
1855 Printer.printInt("line", N->getLine());
1856 Printer.printMetadata("type", N->getRawType());
1857 Printer.printDIFlags("flags", N->getFlags());
1858 Printer.printInt("align", N->getAlignInBits());
1862 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
1863 TypePrinting *TypePrinter, SlotTracker *Machine,
1864 const Module *Context) {
1865 Out << "!DIExpression(";
1868 for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
1869 auto OpStr = dwarf::OperationEncodingString(I->getOp());
1870 assert(!OpStr.empty() && "Expected valid opcode");
1873 for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
1874 Out << FS << I->getArg(A);
1877 for (const auto &I : N->getElements())
1883 static void writeDIGlobalVariableExpression(raw_ostream &Out,
1884 const DIGlobalVariableExpression *N,
1885 TypePrinting *TypePrinter,
1886 SlotTracker *Machine,
1887 const Module *Context) {
1888 Out << "!DIGlobalVariableExpression(";
1889 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1890 Printer.printMetadata("var", N->getVariable());
1891 Printer.printMetadata("expr", N->getExpression());
1895 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
1896 TypePrinting *TypePrinter, SlotTracker *Machine,
1897 const Module *Context) {
1898 Out << "!DIObjCProperty(";
1899 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1900 Printer.printString("name", N->getName());
1901 Printer.printMetadata("file", N->getRawFile());
1902 Printer.printInt("line", N->getLine());
1903 Printer.printString("setter", N->getSetterName());
1904 Printer.printString("getter", N->getGetterName());
1905 Printer.printInt("attributes", N->getAttributes());
1906 Printer.printMetadata("type", N->getRawType());
1910 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
1911 TypePrinting *TypePrinter,
1912 SlotTracker *Machine, const Module *Context) {
1913 Out << "!DIImportedEntity(";
1914 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1915 Printer.printTag(N);
1916 Printer.printString("name", N->getName());
1917 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1918 Printer.printMetadata("entity", N->getRawEntity());
1919 Printer.printInt("line", N->getLine());
1924 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1925 TypePrinting *TypePrinter,
1926 SlotTracker *Machine,
1927 const Module *Context) {
1928 if (Node->isDistinct())
1930 else if (Node->isTemporary())
1931 Out << "<temporary!> "; // Handle broken code.
1933 switch (Node->getMetadataID()) {
1935 llvm_unreachable("Expected uniquable MDNode");
1936 #define HANDLE_MDNODE_LEAF(CLASS) \
1937 case Metadata::CLASS##Kind: \
1938 write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \
1940 #include "llvm/IR/Metadata.def"
1944 // Full implementation of printing a Value as an operand with support for
1945 // TypePrinting, etc.
1946 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1947 TypePrinting *TypePrinter,
1948 SlotTracker *Machine,
1949 const Module *Context) {
1951 PrintLLVMName(Out, V);
1955 const Constant *CV = dyn_cast<Constant>(V);
1956 if (CV && !isa<GlobalValue>(CV)) {
1957 assert(TypePrinter && "Constants require TypePrinting!");
1958 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1962 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1964 if (IA->hasSideEffects())
1965 Out << "sideeffect ";
1966 if (IA->isAlignStack())
1967 Out << "alignstack ";
1968 // We don't emit the AD_ATT dialect as it's the assumed default.
1969 if (IA->getDialect() == InlineAsm::AD_Intel)
1970 Out << "inteldialect ";
1972 PrintEscapedString(IA->getAsmString(), Out);
1974 PrintEscapedString(IA->getConstraintString(), Out);
1979 if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
1980 WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
1981 Context, /* FromValue */ true);
1987 // If we have a SlotTracker, use it.
1989 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1990 Slot = Machine->getGlobalSlot(GV);
1993 Slot = Machine->getLocalSlot(V);
1995 // If the local value didn't succeed, then we may be referring to a value
1996 // from a different function. Translate it, as this can happen when using
1997 // address of blocks.
1999 if ((Machine = createSlotTracker(V))) {
2000 Slot = Machine->getLocalSlot(V);
2004 } else if ((Machine = createSlotTracker(V))) {
2005 // Otherwise, create one to get the # and then destroy it.
2006 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2007 Slot = Machine->getGlobalSlot(GV);
2010 Slot = Machine->getLocalSlot(V);
2019 Out << Prefix << Slot;
2024 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
2025 TypePrinting *TypePrinter,
2026 SlotTracker *Machine, const Module *Context,
2028 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2029 std::unique_ptr<SlotTracker> MachineStorage;
2031 MachineStorage = make_unique<SlotTracker>(Context);
2032 Machine = MachineStorage.get();
2034 int Slot = Machine->getMetadataSlot(N);
2036 // Give the pointer value instead of "badref", since this comes up all
2037 // the time when debugging.
2038 Out << "<" << N << ">";
2044 if (const MDString *MDS = dyn_cast<MDString>(MD)) {
2046 PrintEscapedString(MDS->getString(), Out);
2051 auto *V = cast<ValueAsMetadata>(MD);
2052 assert(TypePrinter && "TypePrinter required for metadata values");
2053 assert((FromValue || !isa<LocalAsMetadata>(V)) &&
2054 "Unexpected function-local metadata outside of value argument");
2056 TypePrinter->print(V->getValue()->getType(), Out);
2058 WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
2062 class AssemblyWriter {
2063 formatted_raw_ostream &Out;
2064 const Module *TheModule;
2065 std::unique_ptr<SlotTracker> SlotTrackerStorage;
2066 SlotTracker &Machine;
2067 TypePrinting TypePrinter;
2068 AssemblyAnnotationWriter *AnnotationWriter;
2069 SetVector<const Comdat *> Comdats;
2071 bool ShouldPreserveUseListOrder;
2072 UseListOrderStack UseListOrders;
2073 SmallVector<StringRef, 8> MDNames;
2076 /// Construct an AssemblyWriter with an external SlotTracker
2077 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
2078 AssemblyAnnotationWriter *AAW, bool IsForDebug,
2079 bool ShouldPreserveUseListOrder = false);
2081 void printMDNodeBody(const MDNode *MD);
2082 void printNamedMDNode(const NamedMDNode *NMD);
2084 void printModule(const Module *M);
2086 void writeOperand(const Value *Op, bool PrintType);
2087 void writeParamOperand(const Value *Operand, AttributeSet Attrs);
2088 void writeOperandBundles(ImmutableCallSite CS);
2089 void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
2090 void writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2091 AtomicOrdering FailureOrdering,
2092 SynchronizationScope SynchScope);
2094 void writeAllMDNodes();
2095 void writeMDNode(unsigned Slot, const MDNode *Node);
2096 void writeAllAttributeGroups();
2098 void printTypeIdentities();
2099 void printGlobal(const GlobalVariable *GV);
2100 void printIndirectSymbol(const GlobalIndirectSymbol *GIS);
2101 void printComdat(const Comdat *C);
2102 void printFunction(const Function *F);
2103 void printArgument(const Argument *FA, AttributeSet Attrs);
2104 void printBasicBlock(const BasicBlock *BB);
2105 void printInstructionLine(const Instruction &I);
2106 void printInstruction(const Instruction &I);
2108 void printUseListOrder(const UseListOrder &Order);
2109 void printUseLists(const Function *F);
2112 /// \brief Print out metadata attachments.
2113 void printMetadataAttachments(
2114 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2115 StringRef Separator);
2117 // printInfoComment - Print a little comment after the instruction indicating
2118 // which slot it occupies.
2119 void printInfoComment(const Value &V);
2121 // printGCRelocateComment - print comment after call to the gc.relocate
2122 // intrinsic indicating base and derived pointer names.
2123 void printGCRelocateComment(const GCRelocateInst &Relocate);
2127 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2128 const Module *M, AssemblyAnnotationWriter *AAW,
2129 bool IsForDebug, bool ShouldPreserveUseListOrder)
2130 : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW),
2131 IsForDebug(IsForDebug),
2132 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2135 TypePrinter.incorporateTypes(*TheModule);
2136 for (const GlobalObject &GO : TheModule->global_objects())
2137 if (const Comdat *C = GO.getComdat())
2141 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2143 Out << "<null operand!>";
2147 TypePrinter.print(Operand->getType(), Out);
2150 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2153 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
2154 SynchronizationScope SynchScope) {
2155 if (Ordering == AtomicOrdering::NotAtomic)
2158 switch (SynchScope) {
2159 case SingleThread: Out << " singlethread"; break;
2160 case CrossThread: break;
2163 Out << " " << toIRString(Ordering);
2166 void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2167 AtomicOrdering FailureOrdering,
2168 SynchronizationScope SynchScope) {
2169 assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
2170 FailureOrdering != AtomicOrdering::NotAtomic);
2172 switch (SynchScope) {
2173 case SingleThread: Out << " singlethread"; break;
2174 case CrossThread: break;
2177 Out << " " << toIRString(SuccessOrdering);
2178 Out << " " << toIRString(FailureOrdering);
2181 void AssemblyWriter::writeParamOperand(const Value *Operand,
2182 AttributeSet Attrs) {
2184 Out << "<null operand!>";
2189 TypePrinter.print(Operand->getType(), Out);
2190 // Print parameter attributes list
2191 if (Attrs.hasAttributes())
2192 Out << ' ' << Attrs.getAsString();
2194 // Print the operand
2195 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2198 void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS) {
2199 if (!CS.hasOperandBundles())
2204 bool FirstBundle = true;
2205 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2206 OperandBundleUse BU = CS.getOperandBundleAt(i);
2210 FirstBundle = false;
2213 PrintEscapedString(BU.getTagName(), Out);
2218 bool FirstInput = true;
2219 for (const auto &Input : BU.Inputs) {
2224 TypePrinter.print(Input->getType(), Out);
2226 WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
2235 void AssemblyWriter::printModule(const Module *M) {
2236 Machine.initialize();
2238 if (ShouldPreserveUseListOrder)
2239 UseListOrders = predictUseListOrder(M);
2241 if (!M->getModuleIdentifier().empty() &&
2242 // Don't print the ID if it will start a new line (which would
2243 // require a comment char before it).
2244 M->getModuleIdentifier().find('\n') == std::string::npos)
2245 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2247 if (!M->getSourceFileName().empty()) {
2248 Out << "source_filename = \"";
2249 PrintEscapedString(M->getSourceFileName(), Out);
2253 const std::string &DL = M->getDataLayoutStr();
2255 Out << "target datalayout = \"" << DL << "\"\n";
2256 if (!M->getTargetTriple().empty())
2257 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2259 if (!M->getModuleInlineAsm().empty()) {
2262 // Split the string into lines, to make it easier to read the .ll file.
2263 StringRef Asm = M->getModuleInlineAsm();
2266 std::tie(Front, Asm) = Asm.split('\n');
2268 // We found a newline, print the portion of the asm string from the
2269 // last newline up to this newline.
2270 Out << "module asm \"";
2271 PrintEscapedString(Front, Out);
2273 } while (!Asm.empty());
2276 printTypeIdentities();
2278 // Output all comdats.
2279 if (!Comdats.empty())
2281 for (const Comdat *C : Comdats) {
2283 if (C != Comdats.back())
2287 // Output all globals.
2288 if (!M->global_empty()) Out << '\n';
2289 for (const GlobalVariable &GV : M->globals()) {
2290 printGlobal(&GV); Out << '\n';
2293 // Output all aliases.
2294 if (!M->alias_empty()) Out << "\n";
2295 for (const GlobalAlias &GA : M->aliases())
2296 printIndirectSymbol(&GA);
2298 // Output all ifuncs.
2299 if (!M->ifunc_empty()) Out << "\n";
2300 for (const GlobalIFunc &GI : M->ifuncs())
2301 printIndirectSymbol(&GI);
2303 // Output global use-lists.
2304 printUseLists(nullptr);
2306 // Output all of the functions.
2307 for (const Function &F : *M)
2309 assert(UseListOrders.empty() && "All use-lists should have been consumed");
2311 // Output all attribute groups.
2312 if (!Machine.as_empty()) {
2314 writeAllAttributeGroups();
2317 // Output named metadata.
2318 if (!M->named_metadata_empty()) Out << '\n';
2320 for (const NamedMDNode &Node : M->named_metadata())
2321 printNamedMDNode(&Node);
2324 if (!Machine.mdn_empty()) {
2330 static void printMetadataIdentifier(StringRef Name,
2331 formatted_raw_ostream &Out) {
2333 Out << "<empty name> ";
2335 if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
2336 Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
2339 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
2340 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
2341 unsigned char C = Name[i];
2342 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
2343 C == '.' || C == '_')
2346 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
2351 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
2353 printMetadataIdentifier(NMD->getName(), Out);
2355 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2358 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
2367 static const char *getLinkagePrintName(GlobalValue::LinkageTypes LT) {
2369 case GlobalValue::ExternalLinkage:
2371 case GlobalValue::PrivateLinkage:
2373 case GlobalValue::InternalLinkage:
2375 case GlobalValue::LinkOnceAnyLinkage:
2377 case GlobalValue::LinkOnceODRLinkage:
2378 return "linkonce_odr ";
2379 case GlobalValue::WeakAnyLinkage:
2381 case GlobalValue::WeakODRLinkage:
2383 case GlobalValue::CommonLinkage:
2385 case GlobalValue::AppendingLinkage:
2386 return "appending ";
2387 case GlobalValue::ExternalWeakLinkage:
2388 return "extern_weak ";
2389 case GlobalValue::AvailableExternallyLinkage:
2390 return "available_externally ";
2392 llvm_unreachable("invalid linkage");
2395 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
2396 formatted_raw_ostream &Out) {
2398 case GlobalValue::DefaultVisibility: break;
2399 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
2400 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
2404 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
2405 formatted_raw_ostream &Out) {
2407 case GlobalValue::DefaultStorageClass: break;
2408 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
2409 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
2413 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
2414 formatted_raw_ostream &Out) {
2416 case GlobalVariable::NotThreadLocal:
2418 case GlobalVariable::GeneralDynamicTLSModel:
2419 Out << "thread_local ";
2421 case GlobalVariable::LocalDynamicTLSModel:
2422 Out << "thread_local(localdynamic) ";
2424 case GlobalVariable::InitialExecTLSModel:
2425 Out << "thread_local(initialexec) ";
2427 case GlobalVariable::LocalExecTLSModel:
2428 Out << "thread_local(localexec) ";
2433 static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
2435 case GlobalVariable::UnnamedAddr::None:
2437 case GlobalVariable::UnnamedAddr::Local:
2438 return "local_unnamed_addr";
2439 case GlobalVariable::UnnamedAddr::Global:
2440 return "unnamed_addr";
2442 llvm_unreachable("Unknown UnnamedAddr");
2445 static void maybePrintComdat(formatted_raw_ostream &Out,
2446 const GlobalObject &GO) {
2447 const Comdat *C = GO.getComdat();
2451 if (isa<GlobalVariable>(GO))
2455 if (GO.getName() == C->getName())
2459 PrintLLVMName(Out, C->getName(), ComdatPrefix);
2463 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
2464 if (GV->isMaterializable())
2465 Out << "; Materializable\n";
2467 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
2470 if (!GV->hasInitializer() && GV->hasExternalLinkage())
2473 Out << getLinkagePrintName(GV->getLinkage());
2474 PrintVisibility(GV->getVisibility(), Out);
2475 PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
2476 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
2477 StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());
2481 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
2482 Out << "addrspace(" << AddressSpace << ") ";
2483 if (GV->isExternallyInitialized()) Out << "externally_initialized ";
2484 Out << (GV->isConstant() ? "constant " : "global ");
2485 TypePrinter.print(GV->getValueType(), Out);
2487 if (GV->hasInitializer()) {
2489 writeOperand(GV->getInitializer(), false);
2492 if (GV->hasSection()) {
2493 Out << ", section \"";
2494 PrintEscapedString(GV->getSection(), Out);
2497 maybePrintComdat(Out, *GV);
2498 if (GV->getAlignment())
2499 Out << ", align " << GV->getAlignment();
2501 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2502 GV->getAllMetadata(MDs);
2503 printMetadataAttachments(MDs, ", ");
2505 printInfoComment(*GV);
2508 void AssemblyWriter::printIndirectSymbol(const GlobalIndirectSymbol *GIS) {
2509 if (GIS->isMaterializable())
2510 Out << "; Materializable\n";
2512 WriteAsOperandInternal(Out, GIS, &TypePrinter, &Machine, GIS->getParent());
2515 Out << getLinkagePrintName(GIS->getLinkage());
2516 PrintVisibility(GIS->getVisibility(), Out);
2517 PrintDLLStorageClass(GIS->getDLLStorageClass(), Out);
2518 PrintThreadLocalModel(GIS->getThreadLocalMode(), Out);
2519 StringRef UA = getUnnamedAddrEncoding(GIS->getUnnamedAddr());
2523 if (isa<GlobalAlias>(GIS))
2525 else if (isa<GlobalIFunc>(GIS))
2528 llvm_unreachable("Not an alias or ifunc!");
2530 TypePrinter.print(GIS->getValueType(), Out);
2534 const Constant *IS = GIS->getIndirectSymbol();
2537 TypePrinter.print(GIS->getType(), Out);
2538 Out << " <<NULL ALIASEE>>";
2540 writeOperand(IS, !isa<ConstantExpr>(IS));
2543 printInfoComment(*GIS);
2547 void AssemblyWriter::printComdat(const Comdat *C) {
2551 void AssemblyWriter::printTypeIdentities() {
2552 if (TypePrinter.NumberedTypes.empty() &&
2553 TypePrinter.NamedTypes.empty())
2558 // We know all the numbers that each type is used and we know that it is a
2559 // dense assignment. Convert the map to an index table.
2560 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
2561 for (DenseMap<StructType*, unsigned>::iterator I =
2562 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
2564 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
2565 NumberedTypes[I->second] = I->first;
2568 // Emit all numbered types.
2569 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
2570 Out << '%' << i << " = type ";
2572 // Make sure we print out at least one level of the type structure, so
2573 // that we do not get %2 = type %2
2574 TypePrinter.printStructBody(NumberedTypes[i], Out);
2578 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
2579 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
2582 // Make sure we print out at least one level of the type structure, so
2583 // that we do not get %FILE = type %FILE
2584 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
2589 /// printFunction - Print all aspects of a function.
2591 void AssemblyWriter::printFunction(const Function *F) {
2592 // Print out the return type and name.
2595 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
2597 if (F->isMaterializable())
2598 Out << "; Materializable\n";
2600 const AttributeList &Attrs = F->getAttributes();
2601 if (Attrs.hasAttributes(AttributeList::FunctionIndex)) {
2602 AttributeSet AS = Attrs.getFnAttributes();
2603 std::string AttrStr;
2605 for (const Attribute &Attr : AS) {
2606 if (!Attr.isStringAttribute()) {
2607 if (!AttrStr.empty()) AttrStr += ' ';
2608 AttrStr += Attr.getAsString();
2612 if (!AttrStr.empty())
2613 Out << "; Function Attrs: " << AttrStr << '\n';
2616 Machine.incorporateFunction(F);
2618 if (F->isDeclaration()) {
2620 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2621 F->getAllMetadata(MDs);
2622 printMetadataAttachments(MDs, " ");
2627 Out << getLinkagePrintName(F->getLinkage());
2628 PrintVisibility(F->getVisibility(), Out);
2629 PrintDLLStorageClass(F->getDLLStorageClass(), Out);
2631 // Print the calling convention.
2632 if (F->getCallingConv() != CallingConv::C) {
2633 PrintCallingConv(F->getCallingConv(), Out);
2637 FunctionType *FT = F->getFunctionType();
2638 if (Attrs.hasAttributes(AttributeList::ReturnIndex))
2639 Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
2640 TypePrinter.print(F->getReturnType(), Out);
2642 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
2645 // Loop over the arguments, printing them...
2646 if (F->isDeclaration() && !IsForDebug) {
2647 // We're only interested in the type here - don't print argument names.
2648 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
2649 // Insert commas as we go... the first arg doesn't get a comma
2653 TypePrinter.print(FT->getParamType(I), Out);
2655 AttributeSet ArgAttrs = Attrs.getParamAttributes(I);
2656 if (ArgAttrs.hasAttributes())
2657 Out << ' ' << ArgAttrs.getAsString();
2660 // The arguments are meaningful here, print them in detail.
2661 for (const Argument &Arg : F->args()) {
2662 // Insert commas as we go... the first arg doesn't get a comma
2663 if (Arg.getArgNo() != 0)
2665 printArgument(&Arg, Attrs.getParamAttributes(Arg.getArgNo()));
2669 // Finish printing arguments...
2670 if (FT->isVarArg()) {
2671 if (FT->getNumParams()) Out << ", ";
2672 Out << "..."; // Output varargs portion of signature!
2675 StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
2678 if (Attrs.hasAttributes(AttributeList::FunctionIndex))
2679 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
2680 if (F->hasSection()) {
2681 Out << " section \"";
2682 PrintEscapedString(F->getSection(), Out);
2685 maybePrintComdat(Out, *F);
2686 if (F->getAlignment())
2687 Out << " align " << F->getAlignment();
2689 Out << " gc \"" << F->getGC() << '"';
2690 if (F->hasPrefixData()) {
2692 writeOperand(F->getPrefixData(), true);
2694 if (F->hasPrologueData()) {
2695 Out << " prologue ";
2696 writeOperand(F->getPrologueData(), true);
2698 if (F->hasPersonalityFn()) {
2699 Out << " personality ";
2700 writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
2703 if (F->isDeclaration()) {
2706 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2707 F->getAllMetadata(MDs);
2708 printMetadataAttachments(MDs, " ");
2711 // Output all of the function's basic blocks.
2712 for (const BasicBlock &BB : *F)
2713 printBasicBlock(&BB);
2715 // Output the function's use-lists.
2721 Machine.purgeFunction();
2724 /// printArgument - This member is called for every argument that is passed into
2725 /// the function. Simply print it out
2727 void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
2729 TypePrinter.print(Arg->getType(), Out);
2731 // Output parameter attributes list
2732 if (Attrs.hasAttributes())
2733 Out << ' ' << Attrs.getAsString();
2735 // Output name, if available...
2736 if (Arg->hasName()) {
2738 PrintLLVMName(Out, Arg);
2742 /// printBasicBlock - This member is called for each basic block in a method.
2744 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
2745 if (BB->hasName()) { // Print out the label if it exists...
2747 PrintLLVMName(Out, BB->getName(), LabelPrefix);
2749 } else if (!BB->use_empty()) { // Don't print block # of no uses...
2750 Out << "\n; <label>:";
2751 int Slot = Machine.getLocalSlot(BB);
2758 if (!BB->getParent()) {
2759 Out.PadToColumn(50);
2760 Out << "; Error: Block without parent!";
2761 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
2762 // Output predecessors for the block.
2763 Out.PadToColumn(50);
2765 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
2768 Out << " No predecessors!";
2771 writeOperand(*PI, false);
2772 for (++PI; PI != PE; ++PI) {
2774 writeOperand(*PI, false);
2781 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
2783 // Output all of the instructions in the basic block...
2784 for (const Instruction &I : *BB) {
2785 printInstructionLine(I);
2788 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
2791 /// printInstructionLine - Print an instruction and a newline character.
2792 void AssemblyWriter::printInstructionLine(const Instruction &I) {
2793 printInstruction(I);
2797 /// printGCRelocateComment - print comment after call to the gc.relocate
2798 /// intrinsic indicating base and derived pointer names.
2799 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
2801 writeOperand(Relocate.getBasePtr(), false);
2803 writeOperand(Relocate.getDerivedPtr(), false);
2807 /// printInfoComment - Print a little comment after the instruction indicating
2808 /// which slot it occupies.
2810 void AssemblyWriter::printInfoComment(const Value &V) {
2811 if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
2812 printGCRelocateComment(*Relocate);
2814 if (AnnotationWriter)
2815 AnnotationWriter->printInfoComment(V, Out);
2818 // This member is called for each Instruction in a function..
2819 void AssemblyWriter::printInstruction(const Instruction &I) {
2820 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
2822 // Print out indentation for an instruction.
2825 // Print out name if it exists...
2827 PrintLLVMName(Out, &I);
2829 } else if (!I.getType()->isVoidTy()) {
2830 // Print out the def slot taken.
2831 int SlotNum = Machine.getLocalSlot(&I);
2833 Out << "<badref> = ";
2835 Out << '%' << SlotNum << " = ";
2838 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2839 if (CI->isMustTailCall())
2841 else if (CI->isTailCall())
2843 else if (CI->isNoTailCall())
2847 // Print out the opcode...
2848 Out << I.getOpcodeName();
2850 // If this is an atomic load or store, print out the atomic marker.
2851 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
2852 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
2855 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
2858 // If this is a volatile operation, print out the volatile marker.
2859 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
2860 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
2861 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
2862 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
2865 // Print out optimization information.
2866 WriteOptimizationInfo(Out, &I);
2868 // Print out the compare instruction predicates
2869 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
2870 Out << ' ' << CmpInst::getPredicateName(CI->getPredicate());
2872 // Print out the atomicrmw operation
2873 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
2874 writeAtomicRMWOperation(Out, RMWI->getOperation());
2876 // Print out the type of the operands...
2877 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
2879 // Special case conditional branches to swizzle the condition out to the front
2880 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
2881 const BranchInst &BI(cast<BranchInst>(I));
2883 writeOperand(BI.getCondition(), true);
2885 writeOperand(BI.getSuccessor(0), true);
2887 writeOperand(BI.getSuccessor(1), true);
2889 } else if (isa<SwitchInst>(I)) {
2890 const SwitchInst& SI(cast<SwitchInst>(I));
2891 // Special case switch instruction to get formatting nice and correct.
2893 writeOperand(SI.getCondition(), true);
2895 writeOperand(SI.getDefaultDest(), true);
2897 for (auto Case : SI.cases()) {
2899 writeOperand(Case.getCaseValue(), true);
2901 writeOperand(Case.getCaseSuccessor(), true);
2904 } else if (isa<IndirectBrInst>(I)) {
2905 // Special case indirectbr instruction to get formatting nice and correct.
2907 writeOperand(Operand, true);
2910 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2913 writeOperand(I.getOperand(i), true);
2916 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
2918 TypePrinter.print(I.getType(), Out);
2921 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
2922 if (op) Out << ", ";
2924 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
2925 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
2927 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
2929 writeOperand(I.getOperand(0), true);
2930 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
2932 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
2934 writeOperand(I.getOperand(0), true); Out << ", ";
2935 writeOperand(I.getOperand(1), true);
2936 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
2938 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
2940 TypePrinter.print(I.getType(), Out);
2941 if (LPI->isCleanup() || LPI->getNumClauses() != 0)
2944 if (LPI->isCleanup())
2947 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
2948 if (i != 0 || LPI->isCleanup()) Out << "\n";
2949 if (LPI->isCatch(i))
2954 writeOperand(LPI->getClause(i), true);
2956 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
2958 writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
2961 for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
2964 writeOperand(PadBB, /*PrintType=*/true);
2968 if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
2969 writeOperand(UnwindDest, /*PrintType=*/true);
2972 } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
2974 writeOperand(FPI->getParentPad(), /*PrintType=*/false);
2976 for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps;
2980 writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
2983 } else if (isa<ReturnInst>(I) && !Operand) {
2985 } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
2987 writeOperand(CRI->getOperand(0), /*PrintType=*/false);
2990 writeOperand(CRI->getOperand(1), /*PrintType=*/true);
2991 } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
2993 writeOperand(CRI->getOperand(0), /*PrintType=*/false);
2996 if (CRI->hasUnwindDest())
2997 writeOperand(CRI->getOperand(1), /*PrintType=*/true);
3000 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3001 // Print the calling convention being used.
3002 if (CI->getCallingConv() != CallingConv::C) {
3004 PrintCallingConv(CI->getCallingConv(), Out);
3007 Operand = CI->getCalledValue();
3008 FunctionType *FTy = CI->getFunctionType();
3009 Type *RetTy = FTy->getReturnType();
3010 const AttributeList &PAL = CI->getAttributes();
3012 if (PAL.hasAttributes(AttributeList::ReturnIndex))
3013 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3015 // If possible, print out the short form of the call instruction. We can
3016 // only do this if the first argument is a pointer to a nonvararg function,
3017 // and if the return type is not a pointer to a function.
3020 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3022 writeOperand(Operand, false);
3024 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
3027 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op));
3030 // Emit an ellipsis if this is a musttail call in a vararg function. This
3031 // is only to aid readability, musttail calls forward varargs by default.
3032 if (CI->isMustTailCall() && CI->getParent() &&
3033 CI->getParent()->getParent() &&
3034 CI->getParent()->getParent()->isVarArg())
3038 if (PAL.hasAttributes(AttributeList::FunctionIndex))
3039 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3041 writeOperandBundles(CI);
3043 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
3044 Operand = II->getCalledValue();
3045 FunctionType *FTy = II->getFunctionType();
3046 Type *RetTy = FTy->getReturnType();
3047 const AttributeList &PAL = II->getAttributes();
3049 // Print the calling convention being used.
3050 if (II->getCallingConv() != CallingConv::C) {
3052 PrintCallingConv(II->getCallingConv(), Out);
3055 if (PAL.hasAttributes(AttributeList::ReturnIndex))
3056 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3058 // If possible, print out the short form of the invoke instruction. We can
3059 // only do this if the first argument is a pointer to a nonvararg function,
3060 // and if the return type is not a pointer to a function.
3063 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3065 writeOperand(Operand, false);
3067 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
3070 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op));
3074 if (PAL.hasAttributes(AttributeList::FunctionIndex))
3075 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3077 writeOperandBundles(II);
3080 writeOperand(II->getNormalDest(), true);
3082 writeOperand(II->getUnwindDest(), true);
3084 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
3086 if (AI->isUsedWithInAlloca())
3088 if (AI->isSwiftError())
3089 Out << "swifterror ";
3090 TypePrinter.print(AI->getAllocatedType(), Out);
3092 // Explicitly write the array size if the code is broken, if it's an array
3093 // allocation, or if the type is not canonical for scalar allocations. The
3094 // latter case prevents the type from mutating when round-tripping through
3096 if (!AI->getArraySize() || AI->isArrayAllocation() ||
3097 !AI->getArraySize()->getType()->isIntegerTy(32)) {
3099 writeOperand(AI->getArraySize(), true);
3101 if (AI->getAlignment()) {
3102 Out << ", align " << AI->getAlignment();
3105 unsigned AddrSpace = AI->getType()->getAddressSpace();
3106 if (AddrSpace != 0) {
3107 Out << ", addrspace(" << AddrSpace << ')';
3110 } else if (isa<CastInst>(I)) {
3113 writeOperand(Operand, true); // Work with broken code
3116 TypePrinter.print(I.getType(), Out);
3117 } else if (isa<VAArgInst>(I)) {
3120 writeOperand(Operand, true); // Work with broken code
3123 TypePrinter.print(I.getType(), Out);
3124 } else if (Operand) { // Print the normal way.
3125 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
3127 TypePrinter.print(GEP->getSourceElementType(), Out);
3129 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
3131 TypePrinter.print(LI->getType(), Out);
3135 // PrintAllTypes - Instructions who have operands of all the same type
3136 // omit the type from all but the first operand. If the instruction has
3137 // different type operands (for example br), then they are all printed.
3138 bool PrintAllTypes = false;
3139 Type *TheType = Operand->getType();
3141 // Select, Store and ShuffleVector always print all types.
3142 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
3143 || isa<ReturnInst>(I)) {
3144 PrintAllTypes = true;
3146 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
3147 Operand = I.getOperand(i);
3148 // note that Operand shouldn't be null, but the test helps make dump()
3149 // more tolerant of malformed IR
3150 if (Operand && Operand->getType() != TheType) {
3151 PrintAllTypes = true; // We have differing types! Print them all!
3157 if (!PrintAllTypes) {
3159 TypePrinter.print(TheType, Out);
3163 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
3165 writeOperand(I.getOperand(i), PrintAllTypes);
3169 // Print atomic ordering/alignment for memory operations
3170 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
3172 writeAtomic(LI->getOrdering(), LI->getSynchScope());
3173 if (LI->getAlignment())
3174 Out << ", align " << LI->getAlignment();
3175 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
3177 writeAtomic(SI->getOrdering(), SI->getSynchScope());
3178 if (SI->getAlignment())
3179 Out << ", align " << SI->getAlignment();
3180 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
3181 writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
3182 CXI->getSynchScope());
3183 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
3184 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
3185 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
3186 writeAtomic(FI->getOrdering(), FI->getSynchScope());
3189 // Print Metadata info.
3190 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
3191 I.getAllMetadata(InstMD);
3192 printMetadataAttachments(InstMD, ", ");
3194 // Print a nice comment.
3195 printInfoComment(I);
3198 void AssemblyWriter::printMetadataAttachments(
3199 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
3200 StringRef Separator) {
3204 if (MDNames.empty())
3205 MDs[0].second->getContext().getMDKindNames(MDNames);
3207 for (const auto &I : MDs) {
3208 unsigned Kind = I.first;
3210 if (Kind < MDNames.size()) {
3212 printMetadataIdentifier(MDNames[Kind], Out);
3214 Out << "!<unknown kind #" << Kind << ">";
3216 WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
3220 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
3221 Out << '!' << Slot << " = ";
3222 printMDNodeBody(Node);
3226 void AssemblyWriter::writeAllMDNodes() {
3227 SmallVector<const MDNode *, 16> Nodes;
3228 Nodes.resize(Machine.mdn_size());
3229 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
3231 Nodes[I->second] = cast<MDNode>(I->first);
3233 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
3234 writeMDNode(i, Nodes[i]);
3238 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
3239 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
3242 void AssemblyWriter::writeAllAttributeGroups() {
3243 std::vector<std::pair<AttributeSet, unsigned>> asVec;
3244 asVec.resize(Machine.as_size());
3246 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
3248 asVec[I->second] = *I;
3250 for (const auto &I : asVec)
3251 Out << "attributes #" << I.second << " = { "
3252 << I.first.getAsString(true) << " }\n";
3255 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
3256 bool IsInFunction = Machine.getFunction();
3260 Out << "uselistorder";
3261 if (const BasicBlock *BB =
3262 IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
3264 writeOperand(BB->getParent(), false);
3266 writeOperand(BB, false);
3269 writeOperand(Order.V, true);
3273 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3274 Out << Order.Shuffle[0];
3275 for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
3276 Out << ", " << Order.Shuffle[I];
3280 void AssemblyWriter::printUseLists(const Function *F) {
3282 [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
3287 Out << "\n; uselistorder directives\n";
3289 printUseListOrder(UseListOrders.back());
3290 UseListOrders.pop_back();
3294 //===----------------------------------------------------------------------===//
3295 // External Interface declarations
3296 //===----------------------------------------------------------------------===//
3298 void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
3299 bool ShouldPreserveUseListOrder,
3300 bool IsForDebug) const {
3301 SlotTracker SlotTable(this->getParent());
3302 formatted_raw_ostream OS(ROS);
3303 AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
3305 ShouldPreserveUseListOrder);
3306 W.printFunction(this);
3309 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
3310 bool ShouldPreserveUseListOrder, bool IsForDebug) const {
3311 SlotTracker SlotTable(this);
3312 formatted_raw_ostream OS(ROS);
3313 AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
3314 ShouldPreserveUseListOrder);
3315 W.printModule(this);
3318 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
3319 SlotTracker SlotTable(getParent());
3320 formatted_raw_ostream OS(ROS);
3321 AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
3322 W.printNamedMDNode(this);
3325 void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
3326 bool IsForDebug) const {
3327 Optional<SlotTracker> LocalST;
3328 SlotTracker *SlotTable;
3329 if (auto *ST = MST.getMachine())
3332 LocalST.emplace(getParent());
3333 SlotTable = &*LocalST;
3336 formatted_raw_ostream OS(ROS);
3337 AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
3338 W.printNamedMDNode(this);
3341 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
3342 PrintLLVMName(ROS, getName(), ComdatPrefix);
3343 ROS << " = comdat ";
3345 switch (getSelectionKind()) {
3349 case Comdat::ExactMatch:
3350 ROS << "exactmatch";
3352 case Comdat::Largest:
3355 case Comdat::NoDuplicates:
3356 ROS << "noduplicates";
3358 case Comdat::SameSize:
3366 void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
3368 TP.print(const_cast<Type*>(this), OS);
3373 // If the type is a named struct type, print the body as well.
3374 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
3375 if (!STy->isLiteral()) {
3377 TP.printStructBody(STy, OS);
3381 static bool isReferencingMDNode(const Instruction &I) {
3382 if (const auto *CI = dyn_cast<CallInst>(&I))
3383 if (Function *F = CI->getCalledFunction())
3384 if (F->isIntrinsic())
3385 for (auto &Op : I.operands())
3386 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
3387 if (isa<MDNode>(V->getMetadata()))
3392 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
3393 bool ShouldInitializeAllMetadata = false;
3394 if (auto *I = dyn_cast<Instruction>(this))
3395 ShouldInitializeAllMetadata = isReferencingMDNode(*I);
3396 else if (isa<Function>(this) || isa<MetadataAsValue>(this))
3397 ShouldInitializeAllMetadata = true;
3399 ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
3400 print(ROS, MST, IsForDebug);
3403 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
3404 bool IsForDebug) const {
3405 formatted_raw_ostream OS(ROS);
3406 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
3407 SlotTracker &SlotTable =
3408 MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
3409 auto incorporateFunction = [&](const Function *F) {
3411 MST.incorporateFunction(*F);
3414 if (const Instruction *I = dyn_cast<Instruction>(this)) {
3415 incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
3416 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
3417 W.printInstruction(*I);
3418 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
3419 incorporateFunction(BB->getParent());
3420 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
3421 W.printBasicBlock(BB);
3422 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
3423 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
3424 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
3426 else if (const Function *F = dyn_cast<Function>(GV))
3429 W.printIndirectSymbol(cast<GlobalIndirectSymbol>(GV));
3430 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
3431 V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
3432 } else if (const Constant *C = dyn_cast<Constant>(this)) {
3433 TypePrinting TypePrinter;
3434 TypePrinter.print(C->getType(), OS);
3436 WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
3437 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
3438 this->printAsOperand(OS, /* PrintType */ true, MST);
3440 llvm_unreachable("Unknown value to print out!");
3444 /// Print without a type, skipping the TypePrinting object.
3446 /// \return \c true iff printing was successful.
3447 static bool printWithoutType(const Value &V, raw_ostream &O,
3448 SlotTracker *Machine, const Module *M) {
3449 if (V.hasName() || isa<GlobalValue>(V) ||
3450 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
3451 WriteAsOperandInternal(O, &V, nullptr, Machine, M);
3457 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
3458 ModuleSlotTracker &MST) {
3459 TypePrinting TypePrinter;
3460 if (const Module *M = MST.getModule())
3461 TypePrinter.incorporateTypes(*M);
3463 TypePrinter.print(V.getType(), O);
3467 WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
3471 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3472 const Module *M) const {
3474 M = getModuleFromVal(this);
3477 if (printWithoutType(*this, O, nullptr, M))
3480 SlotTracker Machine(
3481 M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
3482 ModuleSlotTracker MST(Machine, M);
3483 printAsOperandImpl(*this, O, PrintType, MST);
3486 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3487 ModuleSlotTracker &MST) const {
3489 if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
3492 printAsOperandImpl(*this, O, PrintType, MST);
3495 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
3496 ModuleSlotTracker &MST, const Module *M,
3497 bool OnlyAsOperand) {
3498 formatted_raw_ostream OS(ROS);
3500 TypePrinting TypePrinter;
3502 TypePrinter.incorporateTypes(*M);
3504 WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
3505 /* FromValue */ true);
3507 auto *N = dyn_cast<MDNode>(&MD);
3508 if (OnlyAsOperand || !N)
3512 WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
3515 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
3516 ModuleSlotTracker MST(M, isa<MDNode>(this));
3517 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3520 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
3521 const Module *M) const {
3522 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3525 void Metadata::print(raw_ostream &OS, const Module *M,
3526 bool /*IsForDebug*/) const {
3527 ModuleSlotTracker MST(M, isa<MDNode>(this));
3528 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3531 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
3532 const Module *M, bool /*IsForDebug*/) const {
3533 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3536 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3537 // Value::dump - allow easy printing of Values from the debugger.
3539 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3541 // Type::dump - allow easy printing of Types from the debugger.
3543 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3545 // Module::dump() - Allow printing of Modules from the debugger.
3547 void Module::dump() const {
3548 print(dbgs(), nullptr,
3549 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
3552 // \brief Allow printing of Comdats from the debugger.
3554 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3556 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
3558 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3561 void Metadata::dump() const { dump(nullptr); }
3564 void Metadata::dump(const Module *M) const {
3565 print(dbgs(), M, /*IsForDebug=*/true);