1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/IR/Writer.h
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/IR/AssemblyAnnotationWriter.h"
23 #include "llvm/IR/CFG.h"
24 #include "llvm/IR/CallingConv.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DebugInfo.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/IRPrintingPasses.h"
29 #include "llvm/IR/InlineAsm.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ModuleSlotTracker.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/IR/Statepoint.h"
36 #include "llvm/IR/TypeFinder.h"
37 #include "llvm/IR/UseListOrder.h"
38 #include "llvm/IR/ValueSymbolTable.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Dwarf.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/raw_ostream.h"
49 // Make virtual table appear in this compilation unit.
50 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
52 //===----------------------------------------------------------------------===//
54 //===----------------------------------------------------------------------===//
58 DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
60 unsigned size() const { return IDs.size(); }
61 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
62 std::pair<unsigned, bool> lookup(const Value *V) const {
65 void index(const Value *V) {
66 // Explicitly sequence get-size and insert-value operations to avoid UB.
67 unsigned ID = IDs.size() + 1;
73 static void orderValue(const Value *V, OrderMap &OM) {
74 if (OM.lookup(V).first)
77 if (const Constant *C = dyn_cast<Constant>(V))
78 if (C->getNumOperands() && !isa<GlobalValue>(C))
79 for (const Value *Op : C->operands())
80 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
83 // Note: we cannot cache this lookup above, since inserting into the map
84 // changes the map's size, and thus affects the other IDs.
88 static OrderMap orderModule(const Module *M) {
89 // This needs to match the order used by ValueEnumerator::ValueEnumerator()
90 // and ValueEnumerator::incorporateFunction().
93 for (const GlobalVariable &G : M->globals()) {
94 if (G.hasInitializer())
95 if (!isa<GlobalValue>(G.getInitializer()))
96 orderValue(G.getInitializer(), OM);
99 for (const GlobalAlias &A : M->aliases()) {
100 if (!isa<GlobalValue>(A.getAliasee()))
101 orderValue(A.getAliasee(), OM);
104 for (const Function &F : *M) {
105 if (F.hasPrefixData())
106 if (!isa<GlobalValue>(F.getPrefixData()))
107 orderValue(F.getPrefixData(), OM);
109 if (F.hasPrologueData())
110 if (!isa<GlobalValue>(F.getPrologueData()))
111 orderValue(F.getPrologueData(), OM);
113 if (F.hasPersonalityFn())
114 if (!isa<GlobalValue>(F.getPersonalityFn()))
115 orderValue(F.getPersonalityFn(), 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 GlobalVariable &G : M->globals())
260 if (G.hasInitializer())
261 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
262 for (const GlobalAlias &A : M->aliases())
263 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
264 for (const Function &F : *M)
265 if (F.hasPrefixData())
266 predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
271 static const Module *getModuleFromVal(const Value *V) {
272 if (const Argument *MA = dyn_cast<Argument>(V))
273 return MA->getParent() ? MA->getParent()->getParent() : nullptr;
275 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
276 return BB->getParent() ? BB->getParent()->getParent() : nullptr;
278 if (const Instruction *I = dyn_cast<Instruction>(V)) {
279 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
280 return M ? M->getParent() : nullptr;
283 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
284 return GV->getParent();
286 if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
287 for (const User *U : MAV->users())
288 if (isa<Instruction>(U))
289 if (const Module *M = getModuleFromVal(U))
297 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
299 default: Out << "cc" << cc; break;
300 case CallingConv::Fast: Out << "fastcc"; break;
301 case CallingConv::Cold: Out << "coldcc"; break;
302 case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
303 case CallingConv::AnyReg: Out << "anyregcc"; break;
304 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
305 case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
306 case CallingConv::GHC: Out << "ghccc"; break;
307 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
308 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
309 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
310 case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
311 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
312 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
313 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
314 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
315 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
316 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
317 case CallingConv::PTX_Device: Out << "ptx_device"; break;
318 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
319 case CallingConv::X86_64_Win64: Out << "x86_64_win64cc"; break;
320 case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
321 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
322 case CallingConv::HHVM: Out << "hhvmcc"; break;
323 case CallingConv::HHVM_C: Out << "hhvm_ccc"; break;
327 // PrintEscapedString - Print each character of the specified string, escaping
328 // it if it is not printable or if it is an escape char.
329 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
330 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
331 unsigned char C = Name[i];
332 if (isprint(C) && C != '\\' && C != '"')
335 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
347 void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
348 assert(!Name.empty() && "Cannot get empty name!");
350 // Scan the name to see if it needs quotes first.
351 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
353 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
354 // By making this unsigned, the value passed in to isalnum will always be
355 // in the range 0-255. This is important when building with MSVC because
356 // its implementation will assert. This situation can arise when dealing
357 // with UTF-8 multibyte characters.
358 unsigned char C = Name[i];
359 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
367 // If we didn't need any quotes, just write out the name in one blast.
373 // Okay, we need quotes. Output the quotes and escape any scary characters as
376 PrintEscapedString(Name, OS);
380 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
381 /// (if the string only contains simple characters) or is surrounded with ""'s
382 /// (if it has special chars in it). Print it out.
383 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
399 printLLVMNameWithoutPrefix(OS, Name);
402 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
403 /// (if the string only contains simple characters) or is surrounded with ""'s
404 /// (if it has special chars in it). Print it out.
405 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
406 PrintLLVMName(OS, V->getName(),
407 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
413 TypePrinting(const TypePrinting &) = delete;
414 void operator=(const TypePrinting&) = delete;
417 /// NamedTypes - The named types that are used by the current module.
418 TypeFinder NamedTypes;
420 /// NumberedTypes - The numbered types, along with their value.
421 DenseMap<StructType*, unsigned> NumberedTypes;
423 TypePrinting() = default;
425 void incorporateTypes(const Module &M);
427 void print(Type *Ty, raw_ostream &OS);
429 void printStructBody(StructType *Ty, raw_ostream &OS);
433 void TypePrinting::incorporateTypes(const Module &M) {
434 NamedTypes.run(M, false);
436 // The list of struct types we got back includes all the struct types, split
437 // the unnamed ones out to a numbering and remove the anonymous structs.
438 unsigned NextNumber = 0;
440 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
441 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
442 StructType *STy = *I;
444 // Ignore anonymous types.
445 if (STy->isLiteral())
448 if (STy->getName().empty())
449 NumberedTypes[STy] = NextNumber++;
454 NamedTypes.erase(NextToUse, NamedTypes.end());
458 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
459 /// use of type names or up references to shorten the type name where possible.
460 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
461 switch (Ty->getTypeID()) {
462 case Type::VoidTyID: OS << "void"; return;
463 case Type::HalfTyID: OS << "half"; return;
464 case Type::FloatTyID: OS << "float"; return;
465 case Type::DoubleTyID: OS << "double"; return;
466 case Type::X86_FP80TyID: OS << "x86_fp80"; return;
467 case Type::FP128TyID: OS << "fp128"; return;
468 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
469 case Type::LabelTyID: OS << "label"; return;
470 case Type::MetadataTyID: OS << "metadata"; return;
471 case Type::X86_MMXTyID: OS << "x86_mmx"; return;
472 case Type::TokenTyID: OS << "token"; return;
473 case Type::IntegerTyID:
474 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
477 case Type::FunctionTyID: {
478 FunctionType *FTy = cast<FunctionType>(Ty);
479 print(FTy->getReturnType(), OS);
481 for (FunctionType::param_iterator I = FTy->param_begin(),
482 E = FTy->param_end(); I != E; ++I) {
483 if (I != FTy->param_begin())
487 if (FTy->isVarArg()) {
488 if (FTy->getNumParams()) OS << ", ";
494 case Type::StructTyID: {
495 StructType *STy = cast<StructType>(Ty);
497 if (STy->isLiteral())
498 return printStructBody(STy, OS);
500 if (!STy->getName().empty())
501 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
503 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
504 if (I != NumberedTypes.end())
505 OS << '%' << I->second;
506 else // Not enumerated, print the hex address.
507 OS << "%\"type " << STy << '\"';
510 case Type::PointerTyID: {
511 PointerType *PTy = cast<PointerType>(Ty);
512 print(PTy->getElementType(), OS);
513 if (unsigned AddressSpace = PTy->getAddressSpace())
514 OS << " addrspace(" << AddressSpace << ')';
518 case Type::ArrayTyID: {
519 ArrayType *ATy = cast<ArrayType>(Ty);
520 OS << '[' << ATy->getNumElements() << " x ";
521 print(ATy->getElementType(), OS);
525 case Type::VectorTyID: {
526 VectorType *PTy = cast<VectorType>(Ty);
527 OS << "<" << PTy->getNumElements() << " x ";
528 print(PTy->getElementType(), OS);
533 llvm_unreachable("Invalid TypeID");
536 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
537 if (STy->isOpaque()) {
545 if (STy->getNumElements() == 0) {
548 StructType::element_iterator I = STy->element_begin();
551 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
563 //===----------------------------------------------------------------------===//
564 // SlotTracker Class: Enumerate slot numbers for unnamed values
565 //===----------------------------------------------------------------------===//
566 /// This class provides computation of slot numbers for LLVM Assembly writing.
570 /// ValueMap - A mapping of Values to slot numbers.
571 typedef DenseMap<const Value*, unsigned> ValueMap;
574 /// TheModule - The module for which we are holding slot numbers.
575 const Module* TheModule;
577 /// TheFunction - The function for which we are holding slot numbers.
578 const Function* TheFunction;
579 bool FunctionProcessed;
580 bool ShouldInitializeAllMetadata;
582 /// mMap - The slot map for the module level data.
586 /// fMap - The slot map for the function level data.
590 /// mdnMap - Map for MDNodes.
591 DenseMap<const MDNode*, unsigned> mdnMap;
594 /// asMap - The slot map for attribute sets.
595 DenseMap<AttributeSet, unsigned> asMap;
598 /// Construct from a module.
600 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
601 /// functions, giving correct numbering for metadata referenced only from
602 /// within a function (even if no functions have been initialized).
603 explicit SlotTracker(const Module *M,
604 bool ShouldInitializeAllMetadata = false);
605 /// Construct from a function, starting out in incorp state.
607 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
608 /// functions, giving correct numbering for metadata referenced only from
609 /// within a function (even if no functions have been initialized).
610 explicit SlotTracker(const Function *F,
611 bool ShouldInitializeAllMetadata = false);
613 /// Return the slot number of the specified value in it's type
614 /// plane. If something is not in the SlotTracker, return -1.
615 int getLocalSlot(const Value *V);
616 int getGlobalSlot(const GlobalValue *V);
617 int getMetadataSlot(const MDNode *N);
618 int getAttributeGroupSlot(AttributeSet AS);
620 /// If you'd like to deal with a function instead of just a module, use
621 /// this method to get its data into the SlotTracker.
622 void incorporateFunction(const Function *F) {
624 FunctionProcessed = false;
627 const Function *getFunction() const { return TheFunction; }
629 /// After calling incorporateFunction, use this method to remove the
630 /// most recently incorporated function from the SlotTracker. This
631 /// will reset the state of the machine back to just the module contents.
632 void purgeFunction();
634 /// MDNode map iterators.
635 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
636 mdn_iterator mdn_begin() { return mdnMap.begin(); }
637 mdn_iterator mdn_end() { return mdnMap.end(); }
638 unsigned mdn_size() const { return mdnMap.size(); }
639 bool mdn_empty() const { return mdnMap.empty(); }
641 /// AttributeSet map iterators.
642 typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
643 as_iterator as_begin() { return asMap.begin(); }
644 as_iterator as_end() { return asMap.end(); }
645 unsigned as_size() const { return asMap.size(); }
646 bool as_empty() const { return asMap.empty(); }
648 /// This function does the actual initialization.
649 inline void initialize();
651 // Implementation Details
653 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
654 void CreateModuleSlot(const GlobalValue *V);
656 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
657 void CreateMetadataSlot(const MDNode *N);
659 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
660 void CreateFunctionSlot(const Value *V);
662 /// \brief Insert the specified AttributeSet into the slot table.
663 void CreateAttributeSetSlot(AttributeSet AS);
665 /// Add all of the module level global variables (and their initializers)
666 /// and function declarations, but not the contents of those functions.
667 void processModule();
669 /// Add all of the functions arguments, basic blocks, and instructions.
670 void processFunction();
672 /// Add all of the metadata from a function.
673 void processFunctionMetadata(const Function &F);
675 /// Add all of the metadata from an instruction.
676 void processInstructionMetadata(const Instruction &I);
678 SlotTracker(const SlotTracker &) = delete;
679 void operator=(const SlotTracker &) = delete;
683 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
685 : M(M), F(F), Machine(&Machine) {}
687 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
688 bool ShouldInitializeAllMetadata)
689 : MachineStorage(M ? new SlotTracker(M, ShouldInitializeAllMetadata)
691 M(M), Machine(MachineStorage.get()) {}
693 ModuleSlotTracker::~ModuleSlotTracker() {}
695 void ModuleSlotTracker::incorporateFunction(const Function &F) {
699 // Nothing to do if this is the right function already.
703 Machine->purgeFunction();
704 Machine->incorporateFunction(&F);
708 int ModuleSlotTracker::getLocalSlot(const Value *V) {
709 assert(F && "No function incorporated");
710 return Machine->getLocalSlot(V);
713 static SlotTracker *createSlotTracker(const Value *V) {
714 if (const Argument *FA = dyn_cast<Argument>(V))
715 return new SlotTracker(FA->getParent());
717 if (const Instruction *I = dyn_cast<Instruction>(V))
719 return new SlotTracker(I->getParent()->getParent());
721 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
722 return new SlotTracker(BB->getParent());
724 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
725 return new SlotTracker(GV->getParent());
727 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
728 return new SlotTracker(GA->getParent());
730 if (const Function *Func = dyn_cast<Function>(V))
731 return new SlotTracker(Func);
737 #define ST_DEBUG(X) dbgs() << X
742 // Module level constructor. Causes the contents of the Module (sans functions)
743 // to be added to the slot table.
744 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
745 : TheModule(M), TheFunction(nullptr), FunctionProcessed(false),
746 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
747 fNext(0), mdnNext(0), asNext(0) {}
749 // Function level constructor. Causes the contents of the Module and the one
750 // function provided to be added to the slot table.
751 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
752 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
753 FunctionProcessed(false),
754 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
755 fNext(0), mdnNext(0), asNext(0) {}
757 inline void SlotTracker::initialize() {
760 TheModule = nullptr; ///< Prevent re-processing next time we're called.
763 if (TheFunction && !FunctionProcessed)
767 // Iterate through all the global variables, functions, and global
768 // variable initializers and create slots for them.
769 void SlotTracker::processModule() {
770 ST_DEBUG("begin processModule!\n");
772 // Add all of the unnamed global variables to the value table.
773 for (const GlobalVariable &Var : TheModule->globals()) {
775 CreateModuleSlot(&Var);
778 for (const GlobalAlias &A : TheModule->aliases()) {
780 CreateModuleSlot(&A);
783 // Add metadata used by named metadata.
784 for (const NamedMDNode &NMD : TheModule->named_metadata()) {
785 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
786 CreateMetadataSlot(NMD.getOperand(i));
789 for (const Function &F : *TheModule) {
791 // Add all the unnamed functions to the table.
792 CreateModuleSlot(&F);
794 if (ShouldInitializeAllMetadata)
795 processFunctionMetadata(F);
797 // Add all the function attributes to the table.
798 // FIXME: Add attributes of other objects?
799 AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
800 if (FnAttrs.hasAttributes(AttributeSet::FunctionIndex))
801 CreateAttributeSetSlot(FnAttrs);
804 ST_DEBUG("end processModule!\n");
807 // Process the arguments, basic blocks, and instructions of a function.
808 void SlotTracker::processFunction() {
809 ST_DEBUG("begin processFunction!\n");
812 // Process function metadata if it wasn't hit at the module-level.
813 if (!ShouldInitializeAllMetadata)
814 processFunctionMetadata(*TheFunction);
816 // Add all the function arguments with no names.
817 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
818 AE = TheFunction->arg_end(); AI != AE; ++AI)
820 CreateFunctionSlot(&*AI);
822 ST_DEBUG("Inserting Instructions:\n");
824 // Add all of the basic blocks and instructions with no names.
825 for (auto &BB : *TheFunction) {
827 CreateFunctionSlot(&BB);
830 if (!I.getType()->isVoidTy() && !I.hasName())
831 CreateFunctionSlot(&I);
833 // We allow direct calls to any llvm.foo function here, because the
834 // target may not be linked into the optimizer.
835 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
836 // Add all the call attributes to the table.
837 AttributeSet Attrs = CI->getAttributes().getFnAttributes();
838 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
839 CreateAttributeSetSlot(Attrs);
840 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
841 // Add all the call attributes to the table.
842 AttributeSet Attrs = II->getAttributes().getFnAttributes();
843 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
844 CreateAttributeSetSlot(Attrs);
849 FunctionProcessed = true;
851 ST_DEBUG("end processFunction!\n");
854 void SlotTracker::processFunctionMetadata(const Function &F) {
855 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
856 F.getAllMetadata(MDs);
858 CreateMetadataSlot(MD.second);
862 processInstructionMetadata(I);
866 void SlotTracker::processInstructionMetadata(const Instruction &I) {
867 // Process metadata used directly by intrinsics.
868 if (const CallInst *CI = dyn_cast<CallInst>(&I))
869 if (Function *F = CI->getCalledFunction())
870 if (F->isIntrinsic())
871 for (auto &Op : I.operands())
872 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
873 if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
874 CreateMetadataSlot(N);
876 // Process metadata attached to this instruction.
877 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
878 I.getAllMetadata(MDs);
880 CreateMetadataSlot(MD.second);
883 /// Clean up after incorporating a function. This is the only way to get out of
884 /// the function incorporation state that affects get*Slot/Create*Slot. Function
885 /// incorporation state is indicated by TheFunction != 0.
886 void SlotTracker::purgeFunction() {
887 ST_DEBUG("begin purgeFunction!\n");
888 fMap.clear(); // Simply discard the function level map
889 TheFunction = nullptr;
890 FunctionProcessed = false;
891 ST_DEBUG("end purgeFunction!\n");
894 /// getGlobalSlot - Get the slot number of a global value.
895 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
896 // Check for uninitialized state and do lazy initialization.
899 // Find the value in the module map
900 ValueMap::iterator MI = mMap.find(V);
901 return MI == mMap.end() ? -1 : (int)MI->second;
904 /// getMetadataSlot - Get the slot number of a MDNode.
905 int SlotTracker::getMetadataSlot(const MDNode *N) {
906 // Check for uninitialized state and do lazy initialization.
909 // Find the MDNode in the module map
910 mdn_iterator MI = mdnMap.find(N);
911 return MI == mdnMap.end() ? -1 : (int)MI->second;
915 /// getLocalSlot - Get the slot number for a value that is local to a function.
916 int SlotTracker::getLocalSlot(const Value *V) {
917 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
919 // Check for uninitialized state and do lazy initialization.
922 ValueMap::iterator FI = fMap.find(V);
923 return FI == fMap.end() ? -1 : (int)FI->second;
926 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
927 // Check for uninitialized state and do lazy initialization.
930 // Find the AttributeSet in the module map.
931 as_iterator AI = asMap.find(AS);
932 return AI == asMap.end() ? -1 : (int)AI->second;
935 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
936 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
937 assert(V && "Can't insert a null Value into SlotTracker!");
938 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
939 assert(!V->hasName() && "Doesn't need a slot!");
941 unsigned DestSlot = mNext++;
944 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
946 // G = Global, F = Function, A = Alias, o = other
947 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
948 (isa<Function>(V) ? 'F' :
949 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
952 /// CreateSlot - Create a new slot for the specified value if it has no name.
953 void SlotTracker::CreateFunctionSlot(const Value *V) {
954 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
956 unsigned DestSlot = fNext++;
959 // G = Global, F = Function, o = other
960 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
961 DestSlot << " [o]\n");
964 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
965 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
966 assert(N && "Can't insert a null Value into SlotTracker!");
968 unsigned DestSlot = mdnNext;
969 if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
973 // Recursively add any MDNodes referenced by operands.
974 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
975 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
976 CreateMetadataSlot(Op);
979 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
980 assert(AS.hasAttributes(AttributeSet::FunctionIndex) &&
981 "Doesn't need a slot!");
983 as_iterator I = asMap.find(AS);
984 if (I != asMap.end())
987 unsigned DestSlot = asNext++;
988 asMap[AS] = DestSlot;
991 //===----------------------------------------------------------------------===//
992 // AsmWriter Implementation
993 //===----------------------------------------------------------------------===//
995 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
996 TypePrinting *TypePrinter,
997 SlotTracker *Machine,
998 const Module *Context);
1000 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1001 TypePrinting *TypePrinter,
1002 SlotTracker *Machine, const Module *Context,
1003 bool FromValue = false);
1005 static const char *getPredicateText(unsigned predicate) {
1006 const char * pred = "unknown";
1007 switch (predicate) {
1008 case FCmpInst::FCMP_FALSE: pred = "false"; break;
1009 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
1010 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
1011 case FCmpInst::FCMP_OGE: pred = "oge"; break;
1012 case FCmpInst::FCMP_OLT: pred = "olt"; break;
1013 case FCmpInst::FCMP_OLE: pred = "ole"; break;
1014 case FCmpInst::FCMP_ONE: pred = "one"; break;
1015 case FCmpInst::FCMP_ORD: pred = "ord"; break;
1016 case FCmpInst::FCMP_UNO: pred = "uno"; break;
1017 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
1018 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
1019 case FCmpInst::FCMP_UGE: pred = "uge"; break;
1020 case FCmpInst::FCMP_ULT: pred = "ult"; break;
1021 case FCmpInst::FCMP_ULE: pred = "ule"; break;
1022 case FCmpInst::FCMP_UNE: pred = "une"; break;
1023 case FCmpInst::FCMP_TRUE: pred = "true"; break;
1024 case ICmpInst::ICMP_EQ: pred = "eq"; break;
1025 case ICmpInst::ICMP_NE: pred = "ne"; break;
1026 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
1027 case ICmpInst::ICMP_SGE: pred = "sge"; break;
1028 case ICmpInst::ICMP_SLT: pred = "slt"; break;
1029 case ICmpInst::ICMP_SLE: pred = "sle"; break;
1030 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
1031 case ICmpInst::ICMP_UGE: pred = "uge"; break;
1032 case ICmpInst::ICMP_ULT: pred = "ult"; break;
1033 case ICmpInst::ICMP_ULE: pred = "ule"; break;
1038 static void writeAtomicRMWOperation(raw_ostream &Out,
1039 AtomicRMWInst::BinOp Op) {
1041 default: Out << " <unknown operation " << Op << ">"; break;
1042 case AtomicRMWInst::Xchg: Out << " xchg"; break;
1043 case AtomicRMWInst::Add: Out << " add"; break;
1044 case AtomicRMWInst::Sub: Out << " sub"; break;
1045 case AtomicRMWInst::And: Out << " and"; break;
1046 case AtomicRMWInst::Nand: Out << " nand"; break;
1047 case AtomicRMWInst::Or: Out << " or"; break;
1048 case AtomicRMWInst::Xor: Out << " xor"; break;
1049 case AtomicRMWInst::Max: Out << " max"; break;
1050 case AtomicRMWInst::Min: Out << " min"; break;
1051 case AtomicRMWInst::UMax: Out << " umax"; break;
1052 case AtomicRMWInst::UMin: Out << " umin"; break;
1056 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1057 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
1058 // Unsafe algebra implies all the others, no need to write them all out
1059 if (FPO->hasUnsafeAlgebra())
1062 if (FPO->hasNoNaNs())
1064 if (FPO->hasNoInfs())
1066 if (FPO->hasNoSignedZeros())
1068 if (FPO->hasAllowReciprocal())
1073 if (const OverflowingBinaryOperator *OBO =
1074 dyn_cast<OverflowingBinaryOperator>(U)) {
1075 if (OBO->hasNoUnsignedWrap())
1077 if (OBO->hasNoSignedWrap())
1079 } else if (const PossiblyExactOperator *Div =
1080 dyn_cast<PossiblyExactOperator>(U)) {
1083 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1084 if (GEP->isInBounds())
1089 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1090 TypePrinting &TypePrinter,
1091 SlotTracker *Machine,
1092 const Module *Context) {
1093 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1094 if (CI->getType()->isIntegerTy(1)) {
1095 Out << (CI->getZExtValue() ? "true" : "false");
1098 Out << CI->getValue();
1102 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1103 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
1104 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
1105 // We would like to output the FP constant value in exponential notation,
1106 // but we cannot do this if doing so will lose precision. Check here to
1107 // make sure that we only output it in exponential format if we can parse
1108 // the value back and get the same value.
1111 bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
1112 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
1113 bool isInf = CFP->getValueAPF().isInfinity();
1114 bool isNaN = CFP->getValueAPF().isNaN();
1115 if (!isHalf && !isInf && !isNaN) {
1116 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
1117 CFP->getValueAPF().convertToFloat();
1118 SmallString<128> StrVal;
1119 raw_svector_ostream(StrVal) << Val;
1121 // Check to make sure that the stringized number is not some string like
1122 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
1123 // that the string matches the "[-+]?[0-9]" regex.
1125 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1126 ((StrVal[0] == '-' || StrVal[0] == '+') &&
1127 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
1128 // Reparse stringized version!
1129 if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
1135 // Otherwise we could not reparse it to exactly the same value, so we must
1136 // output the string in hexadecimal format! Note that loading and storing
1137 // floating point types changes the bits of NaNs on some hosts, notably
1138 // x86, so we must not use these types.
1139 static_assert(sizeof(double) == sizeof(uint64_t),
1140 "assuming that double is 64 bits!");
1142 APFloat apf = CFP->getValueAPF();
1143 // Halves and floats are represented in ASCII IR as double, convert.
1145 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1148 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
1153 // Either half, or some form of long double.
1154 // These appear as a magic letter identifying the type, then a
1155 // fixed number of hex digits.
1157 // Bit position, in the current word, of the next nibble to print.
1160 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
1162 // api needed to prevent premature destruction
1163 APInt api = CFP->getValueAPF().bitcastToAPInt();
1164 const uint64_t* p = api.getRawData();
1165 uint64_t word = p[1];
1167 int width = api.getBitWidth();
1168 for (int j=0; j<width; j+=4, shiftcount-=4) {
1169 unsigned int nibble = (word>>shiftcount) & 15;
1171 Out << (unsigned char)(nibble + '0');
1173 Out << (unsigned char)(nibble - 10 + 'A');
1174 if (shiftcount == 0 && j+4 < width) {
1178 shiftcount = width-j-4;
1182 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
1185 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
1188 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
1192 llvm_unreachable("Unsupported floating point type");
1193 // api needed to prevent premature destruction
1194 APInt api = CFP->getValueAPF().bitcastToAPInt();
1195 const uint64_t* p = api.getRawData();
1197 int width = api.getBitWidth();
1198 for (int j=0; j<width; j+=4, shiftcount-=4) {
1199 unsigned int nibble = (word>>shiftcount) & 15;
1201 Out << (unsigned char)(nibble + '0');
1203 Out << (unsigned char)(nibble - 10 + 'A');
1204 if (shiftcount == 0 && j+4 < width) {
1208 shiftcount = width-j-4;
1214 if (isa<ConstantAggregateZero>(CV)) {
1215 Out << "zeroinitializer";
1219 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1220 Out << "blockaddress(";
1221 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
1224 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
1230 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1231 Type *ETy = CA->getType()->getElementType();
1233 TypePrinter.print(ETy, Out);
1235 WriteAsOperandInternal(Out, CA->getOperand(0),
1236 &TypePrinter, Machine,
1238 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1240 TypePrinter.print(ETy, Out);
1242 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
1249 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1250 // As a special case, print the array as a string if it is an array of
1251 // i8 with ConstantInt values.
1252 if (CA->isString()) {
1254 PrintEscapedString(CA->getAsString(), Out);
1259 Type *ETy = CA->getType()->getElementType();
1261 TypePrinter.print(ETy, Out);
1263 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
1264 &TypePrinter, Machine,
1266 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1268 TypePrinter.print(ETy, Out);
1270 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
1278 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1279 if (CS->getType()->isPacked())
1282 unsigned N = CS->getNumOperands();
1285 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1288 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1291 for (unsigned i = 1; i < N; i++) {
1293 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1296 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1303 if (CS->getType()->isPacked())
1308 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1309 Type *ETy = CV->getType()->getVectorElementType();
1311 TypePrinter.print(ETy, Out);
1313 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
1315 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
1317 TypePrinter.print(ETy, Out);
1319 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1326 if (isa<ConstantPointerNull>(CV)) {
1331 if (isa<UndefValue>(CV)) {
1336 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1337 Out << CE->getOpcodeName();
1338 WriteOptimizationInfo(Out, CE);
1339 if (CE->isCompare())
1340 Out << ' ' << getPredicateText(CE->getPredicate());
1343 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1344 TypePrinter.print(GEP->getSourceElementType(), Out);
1348 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1349 TypePrinter.print((*OI)->getType(), Out);
1351 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1352 if (OI+1 != CE->op_end())
1356 if (CE->hasIndices()) {
1357 ArrayRef<unsigned> Indices = CE->getIndices();
1358 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1359 Out << ", " << Indices[i];
1364 TypePrinter.print(CE->getType(), Out);
1371 Out << "<placeholder or erroneous Constant>";
1374 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1375 TypePrinting *TypePrinter, SlotTracker *Machine,
1376 const Module *Context) {
1378 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1379 const Metadata *MD = Node->getOperand(mi);
1382 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1383 Value *V = MDV->getValue();
1384 TypePrinter->print(V->getType(), Out);
1386 WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
1388 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1398 struct FieldSeparator {
1401 FieldSeparator(const char *Sep = ", ") : Skip(true), Sep(Sep) {}
1403 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1408 return OS << FS.Sep;
1410 struct MDFieldPrinter {
1413 TypePrinting *TypePrinter;
1414 SlotTracker *Machine;
1415 const Module *Context;
1417 explicit MDFieldPrinter(raw_ostream &Out)
1418 : Out(Out), TypePrinter(nullptr), Machine(nullptr), Context(nullptr) {}
1419 MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
1420 SlotTracker *Machine, const Module *Context)
1421 : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
1423 void printTag(const DINode *N);
1424 void printString(StringRef Name, StringRef Value,
1425 bool ShouldSkipEmpty = true);
1426 void printMetadata(StringRef Name, const Metadata *MD,
1427 bool ShouldSkipNull = true);
1428 template <class IntTy>
1429 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1430 void printBool(StringRef Name, bool Value);
1431 void printDIFlags(StringRef Name, unsigned Flags);
1432 template <class IntTy, class Stringifier>
1433 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1434 bool ShouldSkipZero = true);
1438 void MDFieldPrinter::printTag(const DINode *N) {
1439 Out << FS << "tag: ";
1440 if (const char *Tag = dwarf::TagString(N->getTag()))
1446 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1447 bool ShouldSkipEmpty) {
1448 if (ShouldSkipEmpty && Value.empty())
1451 Out << FS << Name << ": \"";
1452 PrintEscapedString(Value, Out);
1456 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1457 TypePrinting *TypePrinter,
1458 SlotTracker *Machine,
1459 const Module *Context) {
1464 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1467 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1468 bool ShouldSkipNull) {
1469 if (ShouldSkipNull && !MD)
1472 Out << FS << Name << ": ";
1473 writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
1476 template <class IntTy>
1477 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1478 if (ShouldSkipZero && !Int)
1481 Out << FS << Name << ": " << Int;
1484 void MDFieldPrinter::printBool(StringRef Name, bool Value) {
1485 Out << FS << Name << ": " << (Value ? "true" : "false");
1488 void MDFieldPrinter::printDIFlags(StringRef Name, unsigned Flags) {
1492 Out << FS << Name << ": ";
1494 SmallVector<unsigned, 8> SplitFlags;
1495 unsigned Extra = DINode::splitFlags(Flags, SplitFlags);
1497 FieldSeparator FlagsFS(" | ");
1498 for (unsigned F : SplitFlags) {
1499 const char *StringF = DINode::getFlagString(F);
1500 assert(StringF && "Expected valid flag");
1501 Out << FlagsFS << StringF;
1503 if (Extra || SplitFlags.empty())
1504 Out << FlagsFS << Extra;
1507 template <class IntTy, class Stringifier>
1508 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1509 Stringifier toString, bool ShouldSkipZero) {
1513 Out << FS << Name << ": ";
1514 if (const char *S = toString(Value))
1520 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1521 TypePrinting *TypePrinter, SlotTracker *Machine,
1522 const Module *Context) {
1523 Out << "!GenericDINode(";
1524 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1525 Printer.printTag(N);
1526 Printer.printString("header", N->getHeader());
1527 if (N->getNumDwarfOperands()) {
1528 Out << Printer.FS << "operands: {";
1530 for (auto &I : N->dwarf_operands()) {
1532 writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
1539 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1540 TypePrinting *TypePrinter, SlotTracker *Machine,
1541 const Module *Context) {
1542 Out << "!DILocation(";
1543 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1544 // Always output the line, since 0 is a relevant and important value for it.
1545 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1546 Printer.printInt("column", DL->getColumn());
1547 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1548 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
1552 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1553 TypePrinting *, SlotTracker *, const Module *) {
1554 Out << "!DISubrange(";
1555 MDFieldPrinter Printer(Out);
1556 Printer.printInt("count", N->getCount(), /* ShouldSkipZero */ false);
1557 Printer.printInt("lowerBound", N->getLowerBound());
1561 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1562 TypePrinting *, SlotTracker *, const Module *) {
1563 Out << "!DIEnumerator(";
1564 MDFieldPrinter Printer(Out);
1565 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1566 Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
1570 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1571 TypePrinting *, SlotTracker *, const Module *) {
1572 Out << "!DIBasicType(";
1573 MDFieldPrinter Printer(Out);
1574 if (N->getTag() != dwarf::DW_TAG_base_type)
1575 Printer.printTag(N);
1576 Printer.printString("name", N->getName());
1577 Printer.printInt("size", N->getSizeInBits());
1578 Printer.printInt("align", N->getAlignInBits());
1579 Printer.printDwarfEnum("encoding", N->getEncoding(),
1580 dwarf::AttributeEncodingString);
1584 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
1585 TypePrinting *TypePrinter, SlotTracker *Machine,
1586 const Module *Context) {
1587 Out << "!DIDerivedType(";
1588 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1589 Printer.printTag(N);
1590 Printer.printString("name", N->getName());
1591 Printer.printMetadata("scope", N->getRawScope());
1592 Printer.printMetadata("file", N->getRawFile());
1593 Printer.printInt("line", N->getLine());
1594 Printer.printMetadata("baseType", N->getRawBaseType(),
1595 /* ShouldSkipNull */ false);
1596 Printer.printInt("size", N->getSizeInBits());
1597 Printer.printInt("align", N->getAlignInBits());
1598 Printer.printInt("offset", N->getOffsetInBits());
1599 Printer.printDIFlags("flags", N->getFlags());
1600 Printer.printMetadata("extraData", N->getRawExtraData());
1604 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
1605 TypePrinting *TypePrinter,
1606 SlotTracker *Machine, const Module *Context) {
1607 Out << "!DICompositeType(";
1608 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1609 Printer.printTag(N);
1610 Printer.printString("name", N->getName());
1611 Printer.printMetadata("scope", N->getRawScope());
1612 Printer.printMetadata("file", N->getRawFile());
1613 Printer.printInt("line", N->getLine());
1614 Printer.printMetadata("baseType", N->getRawBaseType());
1615 Printer.printInt("size", N->getSizeInBits());
1616 Printer.printInt("align", N->getAlignInBits());
1617 Printer.printInt("offset", N->getOffsetInBits());
1618 Printer.printDIFlags("flags", N->getFlags());
1619 Printer.printMetadata("elements", N->getRawElements());
1620 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
1621 dwarf::LanguageString);
1622 Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
1623 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1624 Printer.printString("identifier", N->getIdentifier());
1628 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
1629 TypePrinting *TypePrinter,
1630 SlotTracker *Machine, const Module *Context) {
1631 Out << "!DISubroutineType(";
1632 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1633 Printer.printDIFlags("flags", N->getFlags());
1634 Printer.printMetadata("types", N->getRawTypeArray(),
1635 /* ShouldSkipNull */ false);
1639 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
1640 SlotTracker *, const Module *) {
1642 MDFieldPrinter Printer(Out);
1643 Printer.printString("filename", N->getFilename(),
1644 /* ShouldSkipEmpty */ false);
1645 Printer.printString("directory", N->getDirectory(),
1646 /* ShouldSkipEmpty */ false);
1650 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
1651 TypePrinting *TypePrinter, SlotTracker *Machine,
1652 const Module *Context) {
1653 Out << "!DICompileUnit(";
1654 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1655 Printer.printDwarfEnum("language", N->getSourceLanguage(),
1656 dwarf::LanguageString, /* ShouldSkipZero */ false);
1657 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1658 Printer.printString("producer", N->getProducer());
1659 Printer.printBool("isOptimized", N->isOptimized());
1660 Printer.printString("flags", N->getFlags());
1661 Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
1662 /* ShouldSkipZero */ false);
1663 Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
1664 Printer.printInt("emissionKind", N->getEmissionKind(),
1665 /* ShouldSkipZero */ false);
1666 Printer.printMetadata("enums", N->getRawEnumTypes());
1667 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
1668 Printer.printMetadata("subprograms", N->getRawSubprograms());
1669 Printer.printMetadata("globals", N->getRawGlobalVariables());
1670 Printer.printMetadata("imports", N->getRawImportedEntities());
1671 Printer.printInt("dwoId", N->getDWOId());
1675 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
1676 TypePrinting *TypePrinter, SlotTracker *Machine,
1677 const Module *Context) {
1678 Out << "!DISubprogram(";
1679 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1680 Printer.printString("name", N->getName());
1681 Printer.printString("linkageName", N->getLinkageName());
1682 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1683 Printer.printMetadata("file", N->getRawFile());
1684 Printer.printInt("line", N->getLine());
1685 Printer.printMetadata("type", N->getRawType());
1686 Printer.printBool("isLocal", N->isLocalToUnit());
1687 Printer.printBool("isDefinition", N->isDefinition());
1688 Printer.printInt("scopeLine", N->getScopeLine());
1689 Printer.printMetadata("containingType", N->getRawContainingType());
1690 Printer.printDwarfEnum("virtuality", N->getVirtuality(),
1691 dwarf::VirtualityString);
1692 Printer.printInt("virtualIndex", N->getVirtualIndex());
1693 Printer.printDIFlags("flags", N->getFlags());
1694 Printer.printBool("isOptimized", N->isOptimized());
1695 Printer.printMetadata("function", N->getRawFunction());
1696 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1697 Printer.printMetadata("declaration", N->getRawDeclaration());
1698 Printer.printMetadata("variables", N->getRawVariables());
1702 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
1703 TypePrinting *TypePrinter, SlotTracker *Machine,
1704 const Module *Context) {
1705 Out << "!DILexicalBlock(";
1706 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1707 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1708 Printer.printMetadata("file", N->getRawFile());
1709 Printer.printInt("line", N->getLine());
1710 Printer.printInt("column", N->getColumn());
1714 static void writeDILexicalBlockFile(raw_ostream &Out,
1715 const DILexicalBlockFile *N,
1716 TypePrinting *TypePrinter,
1717 SlotTracker *Machine,
1718 const Module *Context) {
1719 Out << "!DILexicalBlockFile(";
1720 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1721 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1722 Printer.printMetadata("file", N->getRawFile());
1723 Printer.printInt("discriminator", N->getDiscriminator(),
1724 /* ShouldSkipZero */ false);
1728 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
1729 TypePrinting *TypePrinter, SlotTracker *Machine,
1730 const Module *Context) {
1731 Out << "!DINamespace(";
1732 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1733 Printer.printString("name", N->getName());
1734 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1735 Printer.printMetadata("file", N->getRawFile());
1736 Printer.printInt("line", N->getLine());
1740 static void writeDIModule(raw_ostream &Out, const DIModule *N,
1741 TypePrinting *TypePrinter, SlotTracker *Machine,
1742 const Module *Context) {
1743 Out << "!DIModule(";
1744 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1745 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1746 Printer.printString("name", N->getName());
1747 Printer.printString("configMacros", N->getConfigurationMacros());
1748 Printer.printString("includePath", N->getIncludePath());
1749 Printer.printString("isysroot", N->getISysRoot());
1754 static void writeDITemplateTypeParameter(raw_ostream &Out,
1755 const DITemplateTypeParameter *N,
1756 TypePrinting *TypePrinter,
1757 SlotTracker *Machine,
1758 const Module *Context) {
1759 Out << "!DITemplateTypeParameter(";
1760 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1761 Printer.printString("name", N->getName());
1762 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
1766 static void writeDITemplateValueParameter(raw_ostream &Out,
1767 const DITemplateValueParameter *N,
1768 TypePrinting *TypePrinter,
1769 SlotTracker *Machine,
1770 const Module *Context) {
1771 Out << "!DITemplateValueParameter(";
1772 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1773 if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
1774 Printer.printTag(N);
1775 Printer.printString("name", N->getName());
1776 Printer.printMetadata("type", N->getRawType());
1777 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
1781 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
1782 TypePrinting *TypePrinter,
1783 SlotTracker *Machine, const Module *Context) {
1784 Out << "!DIGlobalVariable(";
1785 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1786 Printer.printString("name", N->getName());
1787 Printer.printString("linkageName", N->getLinkageName());
1788 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1789 Printer.printMetadata("file", N->getRawFile());
1790 Printer.printInt("line", N->getLine());
1791 Printer.printMetadata("type", N->getRawType());
1792 Printer.printBool("isLocal", N->isLocalToUnit());
1793 Printer.printBool("isDefinition", N->isDefinition());
1794 Printer.printMetadata("variable", N->getRawVariable());
1795 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
1799 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
1800 TypePrinting *TypePrinter,
1801 SlotTracker *Machine, const Module *Context) {
1802 Out << "!DILocalVariable(";
1803 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1804 Printer.printString("name", N->getName());
1805 Printer.printInt("arg", N->getArg());
1806 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1807 Printer.printMetadata("file", N->getRawFile());
1808 Printer.printInt("line", N->getLine());
1809 Printer.printMetadata("type", N->getRawType());
1810 Printer.printDIFlags("flags", N->getFlags());
1814 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
1815 TypePrinting *TypePrinter, SlotTracker *Machine,
1816 const Module *Context) {
1817 Out << "!DIExpression(";
1820 for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
1821 const char *OpStr = dwarf::OperationEncodingString(I->getOp());
1822 assert(OpStr && "Expected valid opcode");
1825 for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
1826 Out << FS << I->getArg(A);
1829 for (const auto &I : N->getElements())
1835 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
1836 TypePrinting *TypePrinter, SlotTracker *Machine,
1837 const Module *Context) {
1838 Out << "!DIObjCProperty(";
1839 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1840 Printer.printString("name", N->getName());
1841 Printer.printMetadata("file", N->getRawFile());
1842 Printer.printInt("line", N->getLine());
1843 Printer.printString("setter", N->getSetterName());
1844 Printer.printString("getter", N->getGetterName());
1845 Printer.printInt("attributes", N->getAttributes());
1846 Printer.printMetadata("type", N->getRawType());
1850 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
1851 TypePrinting *TypePrinter,
1852 SlotTracker *Machine, const Module *Context) {
1853 Out << "!DIImportedEntity(";
1854 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1855 Printer.printTag(N);
1856 Printer.printString("name", N->getName());
1857 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1858 Printer.printMetadata("entity", N->getRawEntity());
1859 Printer.printInt("line", N->getLine());
1864 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1865 TypePrinting *TypePrinter,
1866 SlotTracker *Machine,
1867 const Module *Context) {
1868 if (Node->isDistinct())
1870 else if (Node->isTemporary())
1871 Out << "<temporary!> "; // Handle broken code.
1873 switch (Node->getMetadataID()) {
1875 llvm_unreachable("Expected uniquable MDNode");
1876 #define HANDLE_MDNODE_LEAF(CLASS) \
1877 case Metadata::CLASS##Kind: \
1878 write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \
1880 #include "llvm/IR/Metadata.def"
1884 // Full implementation of printing a Value as an operand with support for
1885 // TypePrinting, etc.
1886 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1887 TypePrinting *TypePrinter,
1888 SlotTracker *Machine,
1889 const Module *Context) {
1891 PrintLLVMName(Out, V);
1895 const Constant *CV = dyn_cast<Constant>(V);
1896 if (CV && !isa<GlobalValue>(CV)) {
1897 assert(TypePrinter && "Constants require TypePrinting!");
1898 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1902 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1904 if (IA->hasSideEffects())
1905 Out << "sideeffect ";
1906 if (IA->isAlignStack())
1907 Out << "alignstack ";
1908 // We don't emit the AD_ATT dialect as it's the assumed default.
1909 if (IA->getDialect() == InlineAsm::AD_Intel)
1910 Out << "inteldialect ";
1912 PrintEscapedString(IA->getAsmString(), Out);
1914 PrintEscapedString(IA->getConstraintString(), Out);
1919 if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
1920 WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
1921 Context, /* FromValue */ true);
1927 // If we have a SlotTracker, use it.
1929 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1930 Slot = Machine->getGlobalSlot(GV);
1933 Slot = Machine->getLocalSlot(V);
1935 // If the local value didn't succeed, then we may be referring to a value
1936 // from a different function. Translate it, as this can happen when using
1937 // address of blocks.
1939 if ((Machine = createSlotTracker(V))) {
1940 Slot = Machine->getLocalSlot(V);
1944 } else if ((Machine = createSlotTracker(V))) {
1945 // Otherwise, create one to get the # and then destroy it.
1946 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1947 Slot = Machine->getGlobalSlot(GV);
1950 Slot = Machine->getLocalSlot(V);
1959 Out << Prefix << Slot;
1964 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1965 TypePrinting *TypePrinter,
1966 SlotTracker *Machine, const Module *Context,
1968 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1969 std::unique_ptr<SlotTracker> MachineStorage;
1971 MachineStorage = make_unique<SlotTracker>(Context);
1972 Machine = MachineStorage.get();
1974 int Slot = Machine->getMetadataSlot(N);
1976 // Give the pointer value instead of "badref", since this comes up all
1977 // the time when debugging.
1978 Out << "<" << N << ">";
1984 if (const MDString *MDS = dyn_cast<MDString>(MD)) {
1986 PrintEscapedString(MDS->getString(), Out);
1991 auto *V = cast<ValueAsMetadata>(MD);
1992 assert(TypePrinter && "TypePrinter required for metadata values");
1993 assert((FromValue || !isa<LocalAsMetadata>(V)) &&
1994 "Unexpected function-local metadata outside of value argument");
1996 TypePrinter->print(V->getValue()->getType(), Out);
1998 WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
2002 class AssemblyWriter {
2003 formatted_raw_ostream &Out;
2004 const Module *TheModule;
2005 std::unique_ptr<SlotTracker> SlotTrackerStorage;
2006 SlotTracker &Machine;
2007 TypePrinting TypePrinter;
2008 AssemblyAnnotationWriter *AnnotationWriter;
2009 SetVector<const Comdat *> Comdats;
2011 bool ShouldPreserveUseListOrder;
2012 UseListOrderStack UseListOrders;
2013 SmallVector<StringRef, 8> MDNames;
2016 /// Construct an AssemblyWriter with an external SlotTracker
2017 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
2018 AssemblyAnnotationWriter *AAW, bool IsForDebug,
2019 bool ShouldPreserveUseListOrder = false);
2021 void printMDNodeBody(const MDNode *MD);
2022 void printNamedMDNode(const NamedMDNode *NMD);
2024 void printModule(const Module *M);
2026 void writeOperand(const Value *Op, bool PrintType);
2027 void writeParamOperand(const Value *Operand, AttributeSet Attrs,unsigned Idx);
2028 void writeOperandBundles(ImmutableCallSite CS);
2029 void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
2030 void writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2031 AtomicOrdering FailureOrdering,
2032 SynchronizationScope SynchScope);
2034 void writeAllMDNodes();
2035 void writeMDNode(unsigned Slot, const MDNode *Node);
2036 void writeAllAttributeGroups();
2038 void printTypeIdentities();
2039 void printGlobal(const GlobalVariable *GV);
2040 void printAlias(const GlobalAlias *GV);
2041 void printComdat(const Comdat *C);
2042 void printFunction(const Function *F);
2043 void printArgument(const Argument *FA, AttributeSet Attrs, unsigned Idx);
2044 void printBasicBlock(const BasicBlock *BB);
2045 void printInstructionLine(const Instruction &I);
2046 void printInstruction(const Instruction &I);
2048 void printUseListOrder(const UseListOrder &Order);
2049 void printUseLists(const Function *F);
2052 /// \brief Print out metadata attachments.
2053 void printMetadataAttachments(
2054 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2055 StringRef Separator);
2057 // printInfoComment - Print a little comment after the instruction indicating
2058 // which slot it occupies.
2059 void printInfoComment(const Value &V);
2061 // printGCRelocateComment - print comment after call to the gc.relocate
2062 // intrinsic indicating base and derived pointer names.
2063 void printGCRelocateComment(const Value &V);
2067 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2068 const Module *M, AssemblyAnnotationWriter *AAW,
2069 bool IsForDebug, bool ShouldPreserveUseListOrder)
2070 : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW),
2071 IsForDebug(IsForDebug),
2072 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2075 TypePrinter.incorporateTypes(*TheModule);
2076 for (const Function &F : *TheModule)
2077 if (const Comdat *C = F.getComdat())
2079 for (const GlobalVariable &GV : TheModule->globals())
2080 if (const Comdat *C = GV.getComdat())
2084 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2086 Out << "<null operand!>";
2090 TypePrinter.print(Operand->getType(), Out);
2093 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2096 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
2097 SynchronizationScope SynchScope) {
2098 if (Ordering == NotAtomic)
2101 switch (SynchScope) {
2102 case SingleThread: Out << " singlethread"; break;
2103 case CrossThread: break;
2107 default: Out << " <bad ordering " << int(Ordering) << ">"; break;
2108 case Unordered: Out << " unordered"; break;
2109 case Monotonic: Out << " monotonic"; break;
2110 case Acquire: Out << " acquire"; break;
2111 case Release: Out << " release"; break;
2112 case AcquireRelease: Out << " acq_rel"; break;
2113 case SequentiallyConsistent: Out << " seq_cst"; break;
2117 void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2118 AtomicOrdering FailureOrdering,
2119 SynchronizationScope SynchScope) {
2120 assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic);
2122 switch (SynchScope) {
2123 case SingleThread: Out << " singlethread"; break;
2124 case CrossThread: break;
2127 switch (SuccessOrdering) {
2128 default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break;
2129 case Unordered: Out << " unordered"; break;
2130 case Monotonic: Out << " monotonic"; break;
2131 case Acquire: Out << " acquire"; break;
2132 case Release: Out << " release"; break;
2133 case AcquireRelease: Out << " acq_rel"; break;
2134 case SequentiallyConsistent: Out << " seq_cst"; break;
2137 switch (FailureOrdering) {
2138 default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break;
2139 case Unordered: Out << " unordered"; break;
2140 case Monotonic: Out << " monotonic"; break;
2141 case Acquire: Out << " acquire"; break;
2142 case Release: Out << " release"; break;
2143 case AcquireRelease: Out << " acq_rel"; break;
2144 case SequentiallyConsistent: Out << " seq_cst"; break;
2148 void AssemblyWriter::writeParamOperand(const Value *Operand,
2149 AttributeSet Attrs, unsigned Idx) {
2151 Out << "<null operand!>";
2156 TypePrinter.print(Operand->getType(), Out);
2157 // Print parameter attributes list
2158 if (Attrs.hasAttributes(Idx))
2159 Out << ' ' << Attrs.getAsString(Idx);
2161 // Print the operand
2162 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2165 void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS) {
2166 if (!CS.hasOperandBundles())
2171 bool FirstBundle = true;
2172 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2173 OperandBundleUse BU = CS.getOperandBundle(i);
2177 FirstBundle = false;
2180 PrintEscapedString(BU.Tag, Out);
2185 bool FirstInput = true;
2186 for (const auto &Input : BU.Inputs) {
2191 TypePrinter.print(Input->getType(), Out);
2193 WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
2202 void AssemblyWriter::printModule(const Module *M) {
2203 Machine.initialize();
2205 if (ShouldPreserveUseListOrder)
2206 UseListOrders = predictUseListOrder(M);
2208 if (!M->getModuleIdentifier().empty() &&
2209 // Don't print the ID if it will start a new line (which would
2210 // require a comment char before it).
2211 M->getModuleIdentifier().find('\n') == std::string::npos)
2212 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2214 const std::string &DL = M->getDataLayoutStr();
2216 Out << "target datalayout = \"" << DL << "\"\n";
2217 if (!M->getTargetTriple().empty())
2218 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2220 if (!M->getModuleInlineAsm().empty()) {
2223 // Split the string into lines, to make it easier to read the .ll file.
2224 StringRef Asm = M->getModuleInlineAsm();
2227 std::tie(Front, Asm) = Asm.split('\n');
2229 // We found a newline, print the portion of the asm string from the
2230 // last newline up to this newline.
2231 Out << "module asm \"";
2232 PrintEscapedString(Front, Out);
2234 } while (!Asm.empty());
2237 printTypeIdentities();
2239 // Output all comdats.
2240 if (!Comdats.empty())
2242 for (const Comdat *C : Comdats) {
2244 if (C != Comdats.back())
2248 // Output all globals.
2249 if (!M->global_empty()) Out << '\n';
2250 for (const GlobalVariable &GV : M->globals()) {
2251 printGlobal(&GV); Out << '\n';
2254 // Output all aliases.
2255 if (!M->alias_empty()) Out << "\n";
2256 for (const GlobalAlias &GA : M->aliases())
2259 // Output global use-lists.
2260 printUseLists(nullptr);
2262 // Output all of the functions.
2263 for (const Function &F : *M)
2265 assert(UseListOrders.empty() && "All use-lists should have been consumed");
2267 // Output all attribute groups.
2268 if (!Machine.as_empty()) {
2270 writeAllAttributeGroups();
2273 // Output named metadata.
2274 if (!M->named_metadata_empty()) Out << '\n';
2276 for (const NamedMDNode &Node : M->named_metadata())
2277 printNamedMDNode(&Node);
2280 if (!Machine.mdn_empty()) {
2286 static void printMetadataIdentifier(StringRef Name,
2287 formatted_raw_ostream &Out) {
2289 Out << "<empty name> ";
2291 if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
2292 Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
2295 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
2296 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
2297 unsigned char C = Name[i];
2298 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
2299 C == '.' || C == '_')
2302 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
2307 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
2309 printMetadataIdentifier(NMD->getName(), Out);
2311 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2314 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
2323 static void PrintLinkage(GlobalValue::LinkageTypes LT,
2324 formatted_raw_ostream &Out) {
2326 case GlobalValue::ExternalLinkage: break;
2327 case GlobalValue::PrivateLinkage: Out << "private "; break;
2328 case GlobalValue::InternalLinkage: Out << "internal "; break;
2329 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
2330 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
2331 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
2332 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
2333 case GlobalValue::CommonLinkage: Out << "common "; break;
2334 case GlobalValue::AppendingLinkage: Out << "appending "; break;
2335 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
2336 case GlobalValue::AvailableExternallyLinkage:
2337 Out << "available_externally ";
2342 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
2343 formatted_raw_ostream &Out) {
2345 case GlobalValue::DefaultVisibility: break;
2346 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
2347 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
2351 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
2352 formatted_raw_ostream &Out) {
2354 case GlobalValue::DefaultStorageClass: break;
2355 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
2356 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
2360 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
2361 formatted_raw_ostream &Out) {
2363 case GlobalVariable::NotThreadLocal:
2365 case GlobalVariable::GeneralDynamicTLSModel:
2366 Out << "thread_local ";
2368 case GlobalVariable::LocalDynamicTLSModel:
2369 Out << "thread_local(localdynamic) ";
2371 case GlobalVariable::InitialExecTLSModel:
2372 Out << "thread_local(initialexec) ";
2374 case GlobalVariable::LocalExecTLSModel:
2375 Out << "thread_local(localexec) ";
2380 static void maybePrintComdat(formatted_raw_ostream &Out,
2381 const GlobalObject &GO) {
2382 const Comdat *C = GO.getComdat();
2386 if (isa<GlobalVariable>(GO))
2390 if (GO.getName() == C->getName())
2394 PrintLLVMName(Out, C->getName(), ComdatPrefix);
2398 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
2399 if (GV->isMaterializable())
2400 Out << "; Materializable\n";
2402 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
2405 if (!GV->hasInitializer() && GV->hasExternalLinkage())
2408 PrintLinkage(GV->getLinkage(), Out);
2409 PrintVisibility(GV->getVisibility(), Out);
2410 PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
2411 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
2412 if (GV->hasUnnamedAddr())
2413 Out << "unnamed_addr ";
2415 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
2416 Out << "addrspace(" << AddressSpace << ") ";
2417 if (GV->isExternallyInitialized()) Out << "externally_initialized ";
2418 Out << (GV->isConstant() ? "constant " : "global ");
2419 TypePrinter.print(GV->getType()->getElementType(), Out);
2421 if (GV->hasInitializer()) {
2423 writeOperand(GV->getInitializer(), false);
2426 if (GV->hasSection()) {
2427 Out << ", section \"";
2428 PrintEscapedString(GV->getSection(), Out);
2431 maybePrintComdat(Out, *GV);
2432 if (GV->getAlignment())
2433 Out << ", align " << GV->getAlignment();
2435 printInfoComment(*GV);
2438 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
2439 if (GA->isMaterializable())
2440 Out << "; Materializable\n";
2442 WriteAsOperandInternal(Out, GA, &TypePrinter, &Machine, GA->getParent());
2445 PrintLinkage(GA->getLinkage(), Out);
2446 PrintVisibility(GA->getVisibility(), Out);
2447 PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
2448 PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
2449 if (GA->hasUnnamedAddr())
2450 Out << "unnamed_addr ";
2454 TypePrinter.print(GA->getValueType(), Out);
2458 const Constant *Aliasee = GA->getAliasee();
2461 TypePrinter.print(GA->getType(), Out);
2462 Out << " <<NULL ALIASEE>>";
2464 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
2467 printInfoComment(*GA);
2471 void AssemblyWriter::printComdat(const Comdat *C) {
2475 void AssemblyWriter::printTypeIdentities() {
2476 if (TypePrinter.NumberedTypes.empty() &&
2477 TypePrinter.NamedTypes.empty())
2482 // We know all the numbers that each type is used and we know that it is a
2483 // dense assignment. Convert the map to an index table.
2484 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
2485 for (DenseMap<StructType*, unsigned>::iterator I =
2486 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
2488 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
2489 NumberedTypes[I->second] = I->first;
2492 // Emit all numbered types.
2493 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
2494 Out << '%' << i << " = type ";
2496 // Make sure we print out at least one level of the type structure, so
2497 // that we do not get %2 = type %2
2498 TypePrinter.printStructBody(NumberedTypes[i], Out);
2502 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
2503 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
2506 // Make sure we print out at least one level of the type structure, so
2507 // that we do not get %FILE = type %FILE
2508 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
2513 /// printFunction - Print all aspects of a function.
2515 void AssemblyWriter::printFunction(const Function *F) {
2516 // Print out the return type and name.
2519 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
2521 if (F->isMaterializable())
2522 Out << "; Materializable\n";
2524 const AttributeSet &Attrs = F->getAttributes();
2525 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
2526 AttributeSet AS = Attrs.getFnAttributes();
2527 std::string AttrStr;
2530 for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
2531 if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
2534 for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
2536 Attribute Attr = *I;
2537 if (!Attr.isStringAttribute()) {
2538 if (!AttrStr.empty()) AttrStr += ' ';
2539 AttrStr += Attr.getAsString();
2543 if (!AttrStr.empty())
2544 Out << "; Function Attrs: " << AttrStr << '\n';
2547 if (F->isDeclaration())
2552 PrintLinkage(F->getLinkage(), Out);
2553 PrintVisibility(F->getVisibility(), Out);
2554 PrintDLLStorageClass(F->getDLLStorageClass(), Out);
2556 // Print the calling convention.
2557 if (F->getCallingConv() != CallingConv::C) {
2558 PrintCallingConv(F->getCallingConv(), Out);
2562 FunctionType *FT = F->getFunctionType();
2563 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
2564 Out << Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
2565 TypePrinter.print(F->getReturnType(), Out);
2567 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
2569 Machine.incorporateFunction(F);
2571 // Loop over the arguments, printing them...
2572 if (F->isDeclaration() && !IsForDebug) {
2573 // We're only interested in the type here - don't print argument names.
2574 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
2575 // Insert commas as we go... the first arg doesn't get a comma
2579 TypePrinter.print(FT->getParamType(I), Out);
2581 if (Attrs.hasAttributes(I + 1))
2582 Out << ' ' << Attrs.getAsString(I + 1);
2585 // The arguments are meaningful here, print them in detail.
2587 for (const Argument &Arg : F->args()) {
2588 // Insert commas as we go... the first arg doesn't get a comma
2591 printArgument(&Arg, Attrs, Idx++);
2595 // Finish printing arguments...
2596 if (FT->isVarArg()) {
2597 if (FT->getNumParams()) Out << ", ";
2598 Out << "..."; // Output varargs portion of signature!
2601 if (F->hasUnnamedAddr())
2602 Out << " unnamed_addr";
2603 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
2604 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
2605 if (F->hasSection()) {
2606 Out << " section \"";
2607 PrintEscapedString(F->getSection(), Out);
2610 maybePrintComdat(Out, *F);
2611 if (F->getAlignment())
2612 Out << " align " << F->getAlignment();
2614 Out << " gc \"" << F->getGC() << '"';
2615 if (F->hasPrefixData()) {
2617 writeOperand(F->getPrefixData(), true);
2619 if (F->hasPrologueData()) {
2620 Out << " prologue ";
2621 writeOperand(F->getPrologueData(), true);
2623 if (F->hasPersonalityFn()) {
2624 Out << " personality ";
2625 writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
2628 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2629 F->getAllMetadata(MDs);
2630 printMetadataAttachments(MDs, " ");
2632 if (F->isDeclaration()) {
2636 // Output all of the function's basic blocks.
2637 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
2638 printBasicBlock(&*I);
2640 // Output the function's use-lists.
2646 Machine.purgeFunction();
2649 /// printArgument - This member is called for every argument that is passed into
2650 /// the function. Simply print it out
2652 void AssemblyWriter::printArgument(const Argument *Arg,
2653 AttributeSet Attrs, unsigned Idx) {
2655 TypePrinter.print(Arg->getType(), Out);
2657 // Output parameter attributes list
2658 if (Attrs.hasAttributes(Idx))
2659 Out << ' ' << Attrs.getAsString(Idx);
2661 // Output name, if available...
2662 if (Arg->hasName()) {
2664 PrintLLVMName(Out, Arg);
2668 /// printBasicBlock - This member is called for each basic block in a method.
2670 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
2671 if (BB->hasName()) { // Print out the label if it exists...
2673 PrintLLVMName(Out, BB->getName(), LabelPrefix);
2675 } else if (!BB->use_empty()) { // Don't print block # of no uses...
2676 Out << "\n; <label>:";
2677 int Slot = Machine.getLocalSlot(BB);
2684 if (!BB->getParent()) {
2685 Out.PadToColumn(50);
2686 Out << "; Error: Block without parent!";
2687 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
2688 // Output predecessors for the block.
2689 Out.PadToColumn(50);
2691 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
2694 Out << " No predecessors!";
2697 writeOperand(*PI, false);
2698 for (++PI; PI != PE; ++PI) {
2700 writeOperand(*PI, false);
2707 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
2709 // Output all of the instructions in the basic block...
2710 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2711 printInstructionLine(*I);
2714 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
2717 /// printInstructionLine - Print an instruction and a newline character.
2718 void AssemblyWriter::printInstructionLine(const Instruction &I) {
2719 printInstruction(I);
2723 /// printGCRelocateComment - print comment after call to the gc.relocate
2724 /// intrinsic indicating base and derived pointer names.
2725 void AssemblyWriter::printGCRelocateComment(const Value &V) {
2726 assert(isGCRelocate(&V));
2727 GCRelocateOperands GCOps(cast<Instruction>(&V));
2730 writeOperand(GCOps.getBasePtr(), false);
2732 writeOperand(GCOps.getDerivedPtr(), false);
2736 /// printInfoComment - Print a little comment after the instruction indicating
2737 /// which slot it occupies.
2739 void AssemblyWriter::printInfoComment(const Value &V) {
2740 if (isGCRelocate(&V))
2741 printGCRelocateComment(V);
2743 if (AnnotationWriter)
2744 AnnotationWriter->printInfoComment(V, Out);
2747 // This member is called for each Instruction in a function..
2748 void AssemblyWriter::printInstruction(const Instruction &I) {
2749 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
2751 // Print out indentation for an instruction.
2754 // Print out name if it exists...
2756 PrintLLVMName(Out, &I);
2758 } else if (!I.getType()->isVoidTy()) {
2759 // Print out the def slot taken.
2760 int SlotNum = Machine.getLocalSlot(&I);
2762 Out << "<badref> = ";
2764 Out << '%' << SlotNum << " = ";
2767 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2768 if (CI->isMustTailCall())
2770 else if (CI->isTailCall())
2774 // Print out the opcode...
2775 Out << I.getOpcodeName();
2777 // If this is an atomic load or store, print out the atomic marker.
2778 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
2779 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
2782 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
2785 // If this is a volatile operation, print out the volatile marker.
2786 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
2787 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
2788 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
2789 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
2792 // Print out optimization information.
2793 WriteOptimizationInfo(Out, &I);
2795 // Print out the compare instruction predicates
2796 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
2797 Out << ' ' << getPredicateText(CI->getPredicate());
2799 // Print out the atomicrmw operation
2800 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
2801 writeAtomicRMWOperation(Out, RMWI->getOperation());
2803 // Print out the type of the operands...
2804 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
2806 // Special case conditional branches to swizzle the condition out to the front
2807 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
2808 const BranchInst &BI(cast<BranchInst>(I));
2810 writeOperand(BI.getCondition(), true);
2812 writeOperand(BI.getSuccessor(0), true);
2814 writeOperand(BI.getSuccessor(1), true);
2816 } else if (isa<SwitchInst>(I)) {
2817 const SwitchInst& SI(cast<SwitchInst>(I));
2818 // Special case switch instruction to get formatting nice and correct.
2820 writeOperand(SI.getCondition(), true);
2822 writeOperand(SI.getDefaultDest(), true);
2824 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
2827 writeOperand(i.getCaseValue(), true);
2829 writeOperand(i.getCaseSuccessor(), true);
2832 } else if (isa<IndirectBrInst>(I)) {
2833 // Special case indirectbr instruction to get formatting nice and correct.
2835 writeOperand(Operand, true);
2838 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2841 writeOperand(I.getOperand(i), true);
2844 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
2846 TypePrinter.print(I.getType(), Out);
2849 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
2850 if (op) Out << ", ";
2852 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
2853 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
2855 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
2857 writeOperand(I.getOperand(0), true);
2858 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
2860 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
2862 writeOperand(I.getOperand(0), true); Out << ", ";
2863 writeOperand(I.getOperand(1), true);
2864 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
2866 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
2868 TypePrinter.print(I.getType(), Out);
2869 if (LPI->isCleanup() || LPI->getNumClauses() != 0)
2872 if (LPI->isCleanup())
2875 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
2876 if (i != 0 || LPI->isCleanup()) Out << "\n";
2877 if (LPI->isCatch(i))
2882 writeOperand(LPI->getClause(i), true);
2884 } else if (const auto *CPI = dyn_cast<CatchPadInst>(&I)) {
2886 for (unsigned Op = 0, NumOps = CPI->getNumArgOperands(); Op < NumOps;
2890 writeOperand(CPI->getArgOperand(Op), /*PrintType=*/true);
2893 writeOperand(CPI->getNormalDest(), /*PrintType=*/true);
2895 writeOperand(CPI->getUnwindDest(), /*PrintType=*/true);
2896 } else if (const auto *TPI = dyn_cast<TerminatePadInst>(&I)) {
2898 for (unsigned Op = 0, NumOps = TPI->getNumArgOperands(); Op < NumOps;
2902 writeOperand(TPI->getArgOperand(Op), /*PrintType=*/true);
2905 if (TPI->hasUnwindDest())
2906 writeOperand(TPI->getUnwindDest(), /*PrintType=*/true);
2909 } else if (const auto *CPI = dyn_cast<CleanupPadInst>(&I)) {
2911 for (unsigned Op = 0, NumOps = CPI->getNumOperands(); Op < NumOps; ++Op) {
2914 writeOperand(CPI->getOperand(Op), /*PrintType=*/true);
2917 } else if (isa<ReturnInst>(I) && !Operand) {
2919 } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
2921 writeOperand(CRI->getCatchPad(), /*PrintType=*/false);
2924 writeOperand(CRI->getSuccessor(), /*PrintType=*/true);
2925 } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
2927 writeOperand(CRI->getCleanupPad(), /*PrintType=*/false);
2930 if (CRI->hasUnwindDest())
2931 writeOperand(CRI->getUnwindDest(), /*PrintType=*/true);
2934 } else if (const auto *CEPI = dyn_cast<CatchEndPadInst>(&I)) {
2936 if (CEPI->hasUnwindDest())
2937 writeOperand(CEPI->getUnwindDest(), /*PrintType=*/true);
2940 } else if (const auto *CEPI = dyn_cast<CleanupEndPadInst>(&I)) {
2942 writeOperand(CEPI->getCleanupPad(), /*PrintType=*/false);
2945 if (CEPI->hasUnwindDest())
2946 writeOperand(CEPI->getUnwindDest(), /*PrintType=*/true);
2949 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2950 // Print the calling convention being used.
2951 if (CI->getCallingConv() != CallingConv::C) {
2953 PrintCallingConv(CI->getCallingConv(), Out);
2956 Operand = CI->getCalledValue();
2957 FunctionType *FTy = cast<FunctionType>(CI->getFunctionType());
2958 Type *RetTy = FTy->getReturnType();
2959 const AttributeSet &PAL = CI->getAttributes();
2961 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
2962 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
2964 // If possible, print out the short form of the call instruction. We can
2965 // only do this if the first argument is a pointer to a nonvararg function,
2966 // and if the return type is not a pointer to a function.
2969 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
2971 writeOperand(Operand, false);
2973 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
2976 writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
2979 // Emit an ellipsis if this is a musttail call in a vararg function. This
2980 // is only to aid readability, musttail calls forward varargs by default.
2981 if (CI->isMustTailCall() && CI->getParent() &&
2982 CI->getParent()->getParent() &&
2983 CI->getParent()->getParent()->isVarArg())
2987 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
2988 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
2990 writeOperandBundles(CI);
2992 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
2993 Operand = II->getCalledValue();
2994 FunctionType *FTy = cast<FunctionType>(II->getFunctionType());
2995 Type *RetTy = FTy->getReturnType();
2996 const AttributeSet &PAL = II->getAttributes();
2998 // Print the calling convention being used.
2999 if (II->getCallingConv() != CallingConv::C) {
3001 PrintCallingConv(II->getCallingConv(), Out);
3004 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
3005 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
3007 // If possible, print out the short form of the invoke instruction. We can
3008 // only do this if the first argument is a pointer to a nonvararg function,
3009 // and if the return type is not a pointer to a function.
3012 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3014 writeOperand(Operand, false);
3016 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
3019 writeParamOperand(II->getArgOperand(op), PAL, op + 1);
3023 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
3024 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3026 writeOperandBundles(II);
3029 writeOperand(II->getNormalDest(), true);
3031 writeOperand(II->getUnwindDest(), true);
3033 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
3035 if (AI->isUsedWithInAlloca())
3037 TypePrinter.print(AI->getAllocatedType(), Out);
3039 // Explicitly write the array size if the code is broken, if it's an array
3040 // allocation, or if the type is not canonical for scalar allocations. The
3041 // latter case prevents the type from mutating when round-tripping through
3043 if (!AI->getArraySize() || AI->isArrayAllocation() ||
3044 !AI->getArraySize()->getType()->isIntegerTy(32)) {
3046 writeOperand(AI->getArraySize(), true);
3048 if (AI->getAlignment()) {
3049 Out << ", align " << AI->getAlignment();
3051 } else if (isa<CastInst>(I)) {
3054 writeOperand(Operand, true); // Work with broken code
3057 TypePrinter.print(I.getType(), Out);
3058 } else if (isa<VAArgInst>(I)) {
3061 writeOperand(Operand, true); // Work with broken code
3064 TypePrinter.print(I.getType(), Out);
3065 } else if (Operand) { // Print the normal way.
3066 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
3068 TypePrinter.print(GEP->getSourceElementType(), Out);
3070 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
3072 TypePrinter.print(LI->getType(), Out);
3076 // PrintAllTypes - Instructions who have operands of all the same type
3077 // omit the type from all but the first operand. If the instruction has
3078 // different type operands (for example br), then they are all printed.
3079 bool PrintAllTypes = false;
3080 Type *TheType = Operand->getType();
3082 // Select, Store and ShuffleVector always print all types.
3083 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
3084 || isa<ReturnInst>(I)) {
3085 PrintAllTypes = true;
3087 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
3088 Operand = I.getOperand(i);
3089 // note that Operand shouldn't be null, but the test helps make dump()
3090 // more tolerant of malformed IR
3091 if (Operand && Operand->getType() != TheType) {
3092 PrintAllTypes = true; // We have differing types! Print them all!
3098 if (!PrintAllTypes) {
3100 TypePrinter.print(TheType, Out);
3104 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
3106 writeOperand(I.getOperand(i), PrintAllTypes);
3110 // Print atomic ordering/alignment for memory operations
3111 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
3113 writeAtomic(LI->getOrdering(), LI->getSynchScope());
3114 if (LI->getAlignment())
3115 Out << ", align " << LI->getAlignment();
3116 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
3118 writeAtomic(SI->getOrdering(), SI->getSynchScope());
3119 if (SI->getAlignment())
3120 Out << ", align " << SI->getAlignment();
3121 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
3122 writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
3123 CXI->getSynchScope());
3124 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
3125 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
3126 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
3127 writeAtomic(FI->getOrdering(), FI->getSynchScope());
3130 // Print Metadata info.
3131 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
3132 I.getAllMetadata(InstMD);
3133 printMetadataAttachments(InstMD, ", ");
3135 // Print a nice comment.
3136 printInfoComment(I);
3139 void AssemblyWriter::printMetadataAttachments(
3140 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
3141 StringRef Separator) {
3145 if (MDNames.empty())
3146 TheModule->getMDKindNames(MDNames);
3148 for (const auto &I : MDs) {
3149 unsigned Kind = I.first;
3151 if (Kind < MDNames.size()) {
3153 printMetadataIdentifier(MDNames[Kind], Out);
3155 Out << "!<unknown kind #" << Kind << ">";
3157 WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
3161 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
3162 Out << '!' << Slot << " = ";
3163 printMDNodeBody(Node);
3167 void AssemblyWriter::writeAllMDNodes() {
3168 SmallVector<const MDNode *, 16> Nodes;
3169 Nodes.resize(Machine.mdn_size());
3170 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
3172 Nodes[I->second] = cast<MDNode>(I->first);
3174 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
3175 writeMDNode(i, Nodes[i]);
3179 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
3180 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
3183 void AssemblyWriter::writeAllAttributeGroups() {
3184 std::vector<std::pair<AttributeSet, unsigned> > asVec;
3185 asVec.resize(Machine.as_size());
3187 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
3189 asVec[I->second] = *I;
3191 for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
3192 I = asVec.begin(), E = asVec.end(); I != E; ++I)
3193 Out << "attributes #" << I->second << " = { "
3194 << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
3197 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
3198 bool IsInFunction = Machine.getFunction();
3202 Out << "uselistorder";
3203 if (const BasicBlock *BB =
3204 IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
3206 writeOperand(BB->getParent(), false);
3208 writeOperand(BB, false);
3211 writeOperand(Order.V, true);
3215 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3216 Out << Order.Shuffle[0];
3217 for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
3218 Out << ", " << Order.Shuffle[I];
3222 void AssemblyWriter::printUseLists(const Function *F) {
3224 [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
3229 Out << "\n; uselistorder directives\n";
3231 printUseListOrder(UseListOrders.back());
3232 UseListOrders.pop_back();
3236 //===----------------------------------------------------------------------===//
3237 // External Interface declarations
3238 //===----------------------------------------------------------------------===//
3240 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
3241 bool ShouldPreserveUseListOrder, bool IsForDebug) const {
3242 SlotTracker SlotTable(this);
3243 formatted_raw_ostream OS(ROS);
3244 AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
3245 ShouldPreserveUseListOrder);
3246 W.printModule(this);
3249 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
3250 SlotTracker SlotTable(getParent());
3251 formatted_raw_ostream OS(ROS);
3252 AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
3253 W.printNamedMDNode(this);
3256 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
3257 PrintLLVMName(ROS, getName(), ComdatPrefix);
3258 ROS << " = comdat ";
3260 switch (getSelectionKind()) {
3264 case Comdat::ExactMatch:
3265 ROS << "exactmatch";
3267 case Comdat::Largest:
3270 case Comdat::NoDuplicates:
3271 ROS << "noduplicates";
3273 case Comdat::SameSize:
3281 void Type::print(raw_ostream &OS, bool /*IsForDebug*/) const {
3283 TP.print(const_cast<Type*>(this), OS);
3285 // If the type is a named struct type, print the body as well.
3286 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
3287 if (!STy->isLiteral()) {
3289 TP.printStructBody(STy, OS);
3293 static bool isReferencingMDNode(const Instruction &I) {
3294 if (const auto *CI = dyn_cast<CallInst>(&I))
3295 if (Function *F = CI->getCalledFunction())
3296 if (F->isIntrinsic())
3297 for (auto &Op : I.operands())
3298 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
3299 if (isa<MDNode>(V->getMetadata()))
3304 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
3305 bool ShouldInitializeAllMetadata = false;
3306 if (auto *I = dyn_cast<Instruction>(this))
3307 ShouldInitializeAllMetadata = isReferencingMDNode(*I);
3308 else if (isa<Function>(this) || isa<MetadataAsValue>(this))
3309 ShouldInitializeAllMetadata = true;
3311 ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
3312 print(ROS, MST, IsForDebug);
3315 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
3316 bool IsForDebug) const {
3317 formatted_raw_ostream OS(ROS);
3318 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
3319 SlotTracker &SlotTable =
3320 MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
3321 auto incorporateFunction = [&](const Function *F) {
3323 MST.incorporateFunction(*F);
3326 if (const Instruction *I = dyn_cast<Instruction>(this)) {
3327 incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
3328 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
3329 W.printInstruction(*I);
3330 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
3331 incorporateFunction(BB->getParent());
3332 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
3333 W.printBasicBlock(BB);
3334 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
3335 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
3336 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
3338 else if (const Function *F = dyn_cast<Function>(GV))
3341 W.printAlias(cast<GlobalAlias>(GV));
3342 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
3343 V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
3344 } else if (const Constant *C = dyn_cast<Constant>(this)) {
3345 TypePrinting TypePrinter;
3346 TypePrinter.print(C->getType(), OS);
3348 WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
3349 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
3350 this->printAsOperand(OS, /* PrintType */ true, MST);
3352 llvm_unreachable("Unknown value to print out!");
3356 /// Print without a type, skipping the TypePrinting object.
3358 /// \return \c true iff printing was successful.
3359 static bool printWithoutType(const Value &V, raw_ostream &O,
3360 SlotTracker *Machine, const Module *M) {
3361 if (V.hasName() || isa<GlobalValue>(V) ||
3362 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
3363 WriteAsOperandInternal(O, &V, nullptr, Machine, M);
3369 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
3370 ModuleSlotTracker &MST) {
3371 TypePrinting TypePrinter;
3372 if (const Module *M = MST.getModule())
3373 TypePrinter.incorporateTypes(*M);
3375 TypePrinter.print(V.getType(), O);
3379 WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
3383 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3384 const Module *M) const {
3386 M = getModuleFromVal(this);
3389 if (printWithoutType(*this, O, nullptr, M))
3392 SlotTracker Machine(
3393 M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
3394 ModuleSlotTracker MST(Machine, M);
3395 printAsOperandImpl(*this, O, PrintType, MST);
3398 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3399 ModuleSlotTracker &MST) const {
3401 if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
3404 printAsOperandImpl(*this, O, PrintType, MST);
3407 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
3408 ModuleSlotTracker &MST, const Module *M,
3409 bool OnlyAsOperand) {
3410 formatted_raw_ostream OS(ROS);
3412 TypePrinting TypePrinter;
3414 TypePrinter.incorporateTypes(*M);
3416 WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
3417 /* FromValue */ true);
3419 auto *N = dyn_cast<MDNode>(&MD);
3420 if (OnlyAsOperand || !N)
3424 WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
3427 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
3428 ModuleSlotTracker MST(M, isa<MDNode>(this));
3429 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3432 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
3433 const Module *M) const {
3434 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3437 void Metadata::print(raw_ostream &OS, const Module *M,
3438 bool /*IsForDebug*/) const {
3439 ModuleSlotTracker MST(M, isa<MDNode>(this));
3440 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3443 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
3444 const Module *M, bool /*IsForDebug*/) const {
3445 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3448 // Value::dump - allow easy printing of Values from the debugger.
3450 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3452 // Type::dump - allow easy printing of Types from the debugger.
3454 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3456 // Module::dump() - Allow printing of Modules from the debugger.
3458 void Module::dump() const {
3459 print(dbgs(), nullptr,
3460 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
3463 // \brief Allow printing of Comdats from the debugger.
3465 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3467 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
3469 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3472 void Metadata::dump() const { dump(nullptr); }
3475 void Metadata::dump(const Module *M) const {
3476 print(dbgs(), M, /*IsForDebug=*/true);