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/Format.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/raw_ostream.h"
50 // Make virtual table appear in this compilation unit.
51 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
53 //===----------------------------------------------------------------------===//
55 //===----------------------------------------------------------------------===//
59 DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
61 unsigned size() const { return IDs.size(); }
62 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
63 std::pair<unsigned, bool> lookup(const Value *V) const {
66 void index(const Value *V) {
67 // Explicitly sequence get-size and insert-value operations to avoid UB.
68 unsigned ID = IDs.size() + 1;
74 static void orderValue(const Value *V, OrderMap &OM) {
75 if (OM.lookup(V).first)
78 if (const Constant *C = dyn_cast<Constant>(V))
79 if (C->getNumOperands() && !isa<GlobalValue>(C))
80 for (const Value *Op : C->operands())
81 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
84 // Note: we cannot cache this lookup above, since inserting into the map
85 // changes the map's size, and thus affects the other IDs.
89 static OrderMap orderModule(const Module *M) {
90 // This needs to match the order used by ValueEnumerator::ValueEnumerator()
91 // and ValueEnumerator::incorporateFunction().
94 for (const GlobalVariable &G : M->globals()) {
95 if (G.hasInitializer())
96 if (!isa<GlobalValue>(G.getInitializer()))
97 orderValue(G.getInitializer(), OM);
100 for (const GlobalAlias &A : M->aliases()) {
101 if (!isa<GlobalValue>(A.getAliasee()))
102 orderValue(A.getAliasee(), OM);
105 for (const Function &F : *M) {
106 for (const Use &U : F.operands())
107 if (!isa<GlobalValue>(U.get()))
108 orderValue(U.get(), OM);
112 if (F.isDeclaration())
115 for (const Argument &A : F.args())
117 for (const BasicBlock &BB : F) {
119 for (const Instruction &I : BB) {
120 for (const Value *Op : I.operands())
121 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
131 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
132 unsigned ID, const OrderMap &OM,
133 UseListOrderStack &Stack) {
134 // Predict use-list order for this one.
135 typedef std::pair<const Use *, unsigned> Entry;
136 SmallVector<Entry, 64> List;
137 for (const Use &U : V->uses())
138 // Check if this user will be serialized.
139 if (OM.lookup(U.getUser()).first)
140 List.push_back(std::make_pair(&U, List.size()));
143 // We may have lost some users.
147 !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
148 if (auto *BA = dyn_cast<BlockAddress>(V))
149 ID = OM.lookup(BA->getBasicBlock()).first;
150 std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
151 const Use *LU = L.first;
152 const Use *RU = R.first;
156 auto LID = OM.lookup(LU->getUser()).first;
157 auto RID = OM.lookup(RU->getUser()).first;
159 // If ID is 4, then expect: 7 6 5 1 2 3.
173 // LID and RID are equal, so we have different operands of the same user.
174 // Assume operands are added in order for all instructions.
177 return LU->getOperandNo() < RU->getOperandNo();
178 return LU->getOperandNo() > RU->getOperandNo();
182 List.begin(), List.end(),
183 [](const Entry &L, const Entry &R) { return L.second < R.second; }))
184 // Order is already correct.
187 // Store the shuffle.
188 Stack.emplace_back(V, F, List.size());
189 assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
190 for (size_t I = 0, E = List.size(); I != E; ++I)
191 Stack.back().Shuffle[I] = List[I].second;
194 static void predictValueUseListOrder(const Value *V, const Function *F,
195 OrderMap &OM, UseListOrderStack &Stack) {
196 auto &IDPair = OM[V];
197 assert(IDPair.first && "Unmapped value");
199 // Already predicted.
202 // Do the actual prediction.
203 IDPair.second = true;
204 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
205 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
207 // Recursive descent into constants.
208 if (const Constant *C = dyn_cast<Constant>(V))
209 if (C->getNumOperands()) // Visit GlobalValues.
210 for (const Value *Op : C->operands())
211 if (isa<Constant>(Op)) // Visit GlobalValues.
212 predictValueUseListOrder(Op, F, OM, Stack);
215 static UseListOrderStack predictUseListOrder(const Module *M) {
216 OrderMap OM = orderModule(M);
218 // Use-list orders need to be serialized after all the users have been added
219 // to a value, or else the shuffles will be incomplete. Store them per
220 // function in a stack.
222 // Aside from function order, the order of values doesn't matter much here.
223 UseListOrderStack Stack;
225 // We want to visit the functions backward now so we can list function-local
226 // constants in the last Function they're used in. Module-level constants
227 // have already been visited above.
228 for (const Function &F : make_range(M->rbegin(), M->rend())) {
229 if (F.isDeclaration())
231 for (const BasicBlock &BB : F)
232 predictValueUseListOrder(&BB, &F, OM, Stack);
233 for (const Argument &A : F.args())
234 predictValueUseListOrder(&A, &F, OM, Stack);
235 for (const BasicBlock &BB : F)
236 for (const Instruction &I : BB)
237 for (const Value *Op : I.operands())
238 if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
239 predictValueUseListOrder(Op, &F, OM, Stack);
240 for (const BasicBlock &BB : F)
241 for (const Instruction &I : BB)
242 predictValueUseListOrder(&I, &F, OM, Stack);
245 // Visit globals last.
246 for (const GlobalVariable &G : M->globals())
247 predictValueUseListOrder(&G, nullptr, OM, Stack);
248 for (const Function &F : *M)
249 predictValueUseListOrder(&F, nullptr, OM, Stack);
250 for (const GlobalAlias &A : M->aliases())
251 predictValueUseListOrder(&A, nullptr, OM, Stack);
252 for (const GlobalVariable &G : M->globals())
253 if (G.hasInitializer())
254 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
255 for (const GlobalAlias &A : M->aliases())
256 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
257 for (const Function &F : *M)
258 for (const Use &U : F.operands())
259 predictValueUseListOrder(U.get(), nullptr, OM, Stack);
264 static const Module *getModuleFromVal(const Value *V) {
265 if (const Argument *MA = dyn_cast<Argument>(V))
266 return MA->getParent() ? MA->getParent()->getParent() : nullptr;
268 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
269 return BB->getParent() ? BB->getParent()->getParent() : nullptr;
271 if (const Instruction *I = dyn_cast<Instruction>(V)) {
272 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
273 return M ? M->getParent() : nullptr;
276 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
277 return GV->getParent();
279 if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
280 for (const User *U : MAV->users())
281 if (isa<Instruction>(U))
282 if (const Module *M = getModuleFromVal(U))
290 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
292 default: Out << "cc" << cc; break;
293 case CallingConv::Fast: Out << "fastcc"; break;
294 case CallingConv::Cold: Out << "coldcc"; break;
295 case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
296 case CallingConv::AnyReg: Out << "anyregcc"; break;
297 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
298 case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
299 case CallingConv::CXX_FAST_TLS: Out << "cxx_fast_tlscc"; break;
300 case CallingConv::GHC: Out << "ghccc"; break;
301 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
302 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
303 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
304 case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
305 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
306 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
307 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
308 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
309 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
310 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
311 case CallingConv::PTX_Device: Out << "ptx_device"; break;
312 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
313 case CallingConv::X86_64_Win64: Out << "x86_64_win64cc"; break;
314 case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
315 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
316 case CallingConv::HHVM: Out << "hhvmcc"; break;
317 case CallingConv::HHVM_C: Out << "hhvm_ccc"; break;
321 // PrintEscapedString - Print each character of the specified string, escaping
322 // it if it is not printable or if it is an escape char.
323 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
324 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
325 unsigned char C = Name[i];
326 if (isprint(C) && C != '\\' && C != '"')
329 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
341 void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
342 assert(!Name.empty() && "Cannot get empty name!");
344 // Scan the name to see if it needs quotes first.
345 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
347 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
348 // By making this unsigned, the value passed in to isalnum will always be
349 // in the range 0-255. This is important when building with MSVC because
350 // its implementation will assert. This situation can arise when dealing
351 // with UTF-8 multibyte characters.
352 unsigned char C = Name[i];
353 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
361 // If we didn't need any quotes, just write out the name in one blast.
367 // Okay, we need quotes. Output the quotes and escape any scary characters as
370 PrintEscapedString(Name, OS);
374 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
375 /// (if the string only contains simple characters) or is surrounded with ""'s
376 /// (if it has special chars in it). Print it out.
377 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
393 printLLVMNameWithoutPrefix(OS, Name);
396 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
397 /// (if the string only contains simple characters) or is surrounded with ""'s
398 /// (if it has special chars in it). Print it out.
399 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
400 PrintLLVMName(OS, V->getName(),
401 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
407 TypePrinting(const TypePrinting &) = delete;
408 void operator=(const TypePrinting&) = delete;
411 /// NamedTypes - The named types that are used by the current module.
412 TypeFinder NamedTypes;
414 /// NumberedTypes - The numbered types, along with their value.
415 DenseMap<StructType*, unsigned> NumberedTypes;
417 TypePrinting() = default;
419 void incorporateTypes(const Module &M);
421 void print(Type *Ty, raw_ostream &OS);
423 void printStructBody(StructType *Ty, raw_ostream &OS);
427 void TypePrinting::incorporateTypes(const Module &M) {
428 NamedTypes.run(M, false);
430 // The list of struct types we got back includes all the struct types, split
431 // the unnamed ones out to a numbering and remove the anonymous structs.
432 unsigned NextNumber = 0;
434 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
435 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
436 StructType *STy = *I;
438 // Ignore anonymous types.
439 if (STy->isLiteral())
442 if (STy->getName().empty())
443 NumberedTypes[STy] = NextNumber++;
448 NamedTypes.erase(NextToUse, NamedTypes.end());
452 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
453 /// use of type names or up references to shorten the type name where possible.
454 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
455 switch (Ty->getTypeID()) {
456 case Type::VoidTyID: OS << "void"; return;
457 case Type::HalfTyID: OS << "half"; return;
458 case Type::FloatTyID: OS << "float"; return;
459 case Type::DoubleTyID: OS << "double"; return;
460 case Type::X86_FP80TyID: OS << "x86_fp80"; return;
461 case Type::FP128TyID: OS << "fp128"; return;
462 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
463 case Type::LabelTyID: OS << "label"; return;
464 case Type::MetadataTyID: OS << "metadata"; return;
465 case Type::X86_MMXTyID: OS << "x86_mmx"; return;
466 case Type::TokenTyID: OS << "token"; return;
467 case Type::IntegerTyID:
468 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
471 case Type::FunctionTyID: {
472 FunctionType *FTy = cast<FunctionType>(Ty);
473 print(FTy->getReturnType(), OS);
475 for (FunctionType::param_iterator I = FTy->param_begin(),
476 E = FTy->param_end(); I != E; ++I) {
477 if (I != FTy->param_begin())
481 if (FTy->isVarArg()) {
482 if (FTy->getNumParams()) OS << ", ";
488 case Type::StructTyID: {
489 StructType *STy = cast<StructType>(Ty);
491 if (STy->isLiteral())
492 return printStructBody(STy, OS);
494 if (!STy->getName().empty())
495 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
497 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
498 if (I != NumberedTypes.end())
499 OS << '%' << I->second;
500 else // Not enumerated, print the hex address.
501 OS << "%\"type " << STy << '\"';
504 case Type::PointerTyID: {
505 PointerType *PTy = cast<PointerType>(Ty);
506 print(PTy->getElementType(), OS);
507 if (unsigned AddressSpace = PTy->getAddressSpace())
508 OS << " addrspace(" << AddressSpace << ')';
512 case Type::ArrayTyID: {
513 ArrayType *ATy = cast<ArrayType>(Ty);
514 OS << '[' << ATy->getNumElements() << " x ";
515 print(ATy->getElementType(), OS);
519 case Type::VectorTyID: {
520 VectorType *PTy = cast<VectorType>(Ty);
521 OS << "<" << PTy->getNumElements() << " x ";
522 print(PTy->getElementType(), OS);
527 llvm_unreachable("Invalid TypeID");
530 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
531 if (STy->isOpaque()) {
539 if (STy->getNumElements() == 0) {
542 StructType::element_iterator I = STy->element_begin();
545 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
557 //===----------------------------------------------------------------------===//
558 // SlotTracker Class: Enumerate slot numbers for unnamed values
559 //===----------------------------------------------------------------------===//
560 /// This class provides computation of slot numbers for LLVM Assembly writing.
564 /// ValueMap - A mapping of Values to slot numbers.
565 typedef DenseMap<const Value*, unsigned> ValueMap;
568 /// TheModule - The module for which we are holding slot numbers.
569 const Module* TheModule;
571 /// TheFunction - The function for which we are holding slot numbers.
572 const Function* TheFunction;
573 bool FunctionProcessed;
574 bool ShouldInitializeAllMetadata;
576 /// mMap - The slot map for the module level data.
580 /// fMap - The slot map for the function level data.
584 /// mdnMap - Map for MDNodes.
585 DenseMap<const MDNode*, unsigned> mdnMap;
588 /// asMap - The slot map for attribute sets.
589 DenseMap<AttributeSet, unsigned> asMap;
592 /// Construct from a module.
594 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
595 /// functions, giving correct numbering for metadata referenced only from
596 /// within a function (even if no functions have been initialized).
597 explicit SlotTracker(const Module *M,
598 bool ShouldInitializeAllMetadata = false);
599 /// Construct from a function, starting out in incorp state.
601 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
602 /// functions, giving correct numbering for metadata referenced only from
603 /// within a function (even if no functions have been initialized).
604 explicit SlotTracker(const Function *F,
605 bool ShouldInitializeAllMetadata = false);
607 /// Return the slot number of the specified value in it's type
608 /// plane. If something is not in the SlotTracker, return -1.
609 int getLocalSlot(const Value *V);
610 int getGlobalSlot(const GlobalValue *V);
611 int getMetadataSlot(const MDNode *N);
612 int getAttributeGroupSlot(AttributeSet AS);
614 /// If you'd like to deal with a function instead of just a module, use
615 /// this method to get its data into the SlotTracker.
616 void incorporateFunction(const Function *F) {
618 FunctionProcessed = false;
621 const Function *getFunction() const { return TheFunction; }
623 /// After calling incorporateFunction, use this method to remove the
624 /// most recently incorporated function from the SlotTracker. This
625 /// will reset the state of the machine back to just the module contents.
626 void purgeFunction();
628 /// MDNode map iterators.
629 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
630 mdn_iterator mdn_begin() { return mdnMap.begin(); }
631 mdn_iterator mdn_end() { return mdnMap.end(); }
632 unsigned mdn_size() const { return mdnMap.size(); }
633 bool mdn_empty() const { return mdnMap.empty(); }
635 /// AttributeSet map iterators.
636 typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
637 as_iterator as_begin() { return asMap.begin(); }
638 as_iterator as_end() { return asMap.end(); }
639 unsigned as_size() const { return asMap.size(); }
640 bool as_empty() const { return asMap.empty(); }
642 /// This function does the actual initialization.
643 inline void initialize();
645 // Implementation Details
647 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
648 void CreateModuleSlot(const GlobalValue *V);
650 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
651 void CreateMetadataSlot(const MDNode *N);
653 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
654 void CreateFunctionSlot(const Value *V);
656 /// \brief Insert the specified AttributeSet into the slot table.
657 void CreateAttributeSetSlot(AttributeSet AS);
659 /// Add all of the module level global variables (and their initializers)
660 /// and function declarations, but not the contents of those functions.
661 void processModule();
663 /// Add all of the functions arguments, basic blocks, and instructions.
664 void processFunction();
666 /// Add all of the metadata from a function.
667 void processFunctionMetadata(const Function &F);
669 /// Add all of the metadata from an instruction.
670 void processInstructionMetadata(const Instruction &I);
672 SlotTracker(const SlotTracker &) = delete;
673 void operator=(const SlotTracker &) = delete;
677 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
679 : M(M), F(F), Machine(&Machine) {}
681 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
682 bool ShouldInitializeAllMetadata)
683 : MachineStorage(M ? new SlotTracker(M, ShouldInitializeAllMetadata)
685 M(M), Machine(MachineStorage.get()) {}
687 ModuleSlotTracker::~ModuleSlotTracker() {}
689 void ModuleSlotTracker::incorporateFunction(const Function &F) {
693 // Nothing to do if this is the right function already.
697 Machine->purgeFunction();
698 Machine->incorporateFunction(&F);
702 int ModuleSlotTracker::getLocalSlot(const Value *V) {
703 assert(F && "No function incorporated");
704 return Machine->getLocalSlot(V);
707 static SlotTracker *createSlotTracker(const Value *V) {
708 if (const Argument *FA = dyn_cast<Argument>(V))
709 return new SlotTracker(FA->getParent());
711 if (const Instruction *I = dyn_cast<Instruction>(V))
713 return new SlotTracker(I->getParent()->getParent());
715 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
716 return new SlotTracker(BB->getParent());
718 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
719 return new SlotTracker(GV->getParent());
721 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
722 return new SlotTracker(GA->getParent());
724 if (const Function *Func = dyn_cast<Function>(V))
725 return new SlotTracker(Func);
731 #define ST_DEBUG(X) dbgs() << X
736 // Module level constructor. Causes the contents of the Module (sans functions)
737 // to be added to the slot table.
738 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
739 : TheModule(M), TheFunction(nullptr), FunctionProcessed(false),
740 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
741 fNext(0), mdnNext(0), asNext(0) {}
743 // Function level constructor. Causes the contents of the Module and the one
744 // function provided to be added to the slot table.
745 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
746 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
747 FunctionProcessed(false),
748 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
749 fNext(0), mdnNext(0), asNext(0) {}
751 inline void SlotTracker::initialize() {
754 TheModule = nullptr; ///< Prevent re-processing next time we're called.
757 if (TheFunction && !FunctionProcessed)
761 // Iterate through all the global variables, functions, and global
762 // variable initializers and create slots for them.
763 void SlotTracker::processModule() {
764 ST_DEBUG("begin processModule!\n");
766 // Add all of the unnamed global variables to the value table.
767 for (const GlobalVariable &Var : TheModule->globals()) {
769 CreateModuleSlot(&Var);
772 for (const GlobalAlias &A : TheModule->aliases()) {
774 CreateModuleSlot(&A);
777 // Add metadata used by named metadata.
778 for (const NamedMDNode &NMD : TheModule->named_metadata()) {
779 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
780 CreateMetadataSlot(NMD.getOperand(i));
783 for (const Function &F : *TheModule) {
785 // Add all the unnamed functions to the table.
786 CreateModuleSlot(&F);
788 if (ShouldInitializeAllMetadata)
789 processFunctionMetadata(F);
791 // Add all the function attributes to the table.
792 // FIXME: Add attributes of other objects?
793 AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
794 if (FnAttrs.hasAttributes(AttributeSet::FunctionIndex))
795 CreateAttributeSetSlot(FnAttrs);
798 ST_DEBUG("end processModule!\n");
801 // Process the arguments, basic blocks, and instructions of a function.
802 void SlotTracker::processFunction() {
803 ST_DEBUG("begin processFunction!\n");
806 // Process function metadata if it wasn't hit at the module-level.
807 if (!ShouldInitializeAllMetadata)
808 processFunctionMetadata(*TheFunction);
810 // Add all the function arguments with no names.
811 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
812 AE = TheFunction->arg_end(); AI != AE; ++AI)
814 CreateFunctionSlot(&*AI);
816 ST_DEBUG("Inserting Instructions:\n");
818 // Add all of the basic blocks and instructions with no names.
819 for (auto &BB : *TheFunction) {
821 CreateFunctionSlot(&BB);
824 if (!I.getType()->isVoidTy() && !I.hasName())
825 CreateFunctionSlot(&I);
827 // We allow direct calls to any llvm.foo function here, because the
828 // target may not be linked into the optimizer.
829 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
830 // Add all the call attributes to the table.
831 AttributeSet Attrs = CI->getAttributes().getFnAttributes();
832 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
833 CreateAttributeSetSlot(Attrs);
834 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
835 // Add all the call attributes to the table.
836 AttributeSet Attrs = II->getAttributes().getFnAttributes();
837 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
838 CreateAttributeSetSlot(Attrs);
843 FunctionProcessed = true;
845 ST_DEBUG("end processFunction!\n");
848 void SlotTracker::processFunctionMetadata(const Function &F) {
849 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
850 F.getAllMetadata(MDs);
852 CreateMetadataSlot(MD.second);
856 processInstructionMetadata(I);
860 void SlotTracker::processInstructionMetadata(const Instruction &I) {
861 // Process metadata used directly by intrinsics.
862 if (const CallInst *CI = dyn_cast<CallInst>(&I))
863 if (Function *F = CI->getCalledFunction())
864 if (F->isIntrinsic())
865 for (auto &Op : I.operands())
866 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
867 if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
868 CreateMetadataSlot(N);
870 // Process metadata attached to this instruction.
871 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
872 I.getAllMetadata(MDs);
874 CreateMetadataSlot(MD.second);
877 /// Clean up after incorporating a function. This is the only way to get out of
878 /// the function incorporation state that affects get*Slot/Create*Slot. Function
879 /// incorporation state is indicated by TheFunction != 0.
880 void SlotTracker::purgeFunction() {
881 ST_DEBUG("begin purgeFunction!\n");
882 fMap.clear(); // Simply discard the function level map
883 TheFunction = nullptr;
884 FunctionProcessed = false;
885 ST_DEBUG("end purgeFunction!\n");
888 /// getGlobalSlot - Get the slot number of a global value.
889 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
890 // Check for uninitialized state and do lazy initialization.
893 // Find the value in the module map
894 ValueMap::iterator MI = mMap.find(V);
895 return MI == mMap.end() ? -1 : (int)MI->second;
898 /// getMetadataSlot - Get the slot number of a MDNode.
899 int SlotTracker::getMetadataSlot(const MDNode *N) {
900 // Check for uninitialized state and do lazy initialization.
903 // Find the MDNode in the module map
904 mdn_iterator MI = mdnMap.find(N);
905 return MI == mdnMap.end() ? -1 : (int)MI->second;
909 /// getLocalSlot - Get the slot number for a value that is local to a function.
910 int SlotTracker::getLocalSlot(const Value *V) {
911 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
913 // Check for uninitialized state and do lazy initialization.
916 ValueMap::iterator FI = fMap.find(V);
917 return FI == fMap.end() ? -1 : (int)FI->second;
920 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
921 // Check for uninitialized state and do lazy initialization.
924 // Find the AttributeSet in the module map.
925 as_iterator AI = asMap.find(AS);
926 return AI == asMap.end() ? -1 : (int)AI->second;
929 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
930 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
931 assert(V && "Can't insert a null Value into SlotTracker!");
932 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
933 assert(!V->hasName() && "Doesn't need a slot!");
935 unsigned DestSlot = mNext++;
938 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
940 // G = Global, F = Function, A = Alias, o = other
941 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
942 (isa<Function>(V) ? 'F' :
943 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
946 /// CreateSlot - Create a new slot for the specified value if it has no name.
947 void SlotTracker::CreateFunctionSlot(const Value *V) {
948 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
950 unsigned DestSlot = fNext++;
953 // G = Global, F = Function, o = other
954 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
955 DestSlot << " [o]\n");
958 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
959 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
960 assert(N && "Can't insert a null Value into SlotTracker!");
962 unsigned DestSlot = mdnNext;
963 if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
967 // Recursively add any MDNodes referenced by operands.
968 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
969 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
970 CreateMetadataSlot(Op);
973 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
974 assert(AS.hasAttributes(AttributeSet::FunctionIndex) &&
975 "Doesn't need a slot!");
977 as_iterator I = asMap.find(AS);
978 if (I != asMap.end())
981 unsigned DestSlot = asNext++;
982 asMap[AS] = DestSlot;
985 //===----------------------------------------------------------------------===//
986 // AsmWriter Implementation
987 //===----------------------------------------------------------------------===//
989 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
990 TypePrinting *TypePrinter,
991 SlotTracker *Machine,
992 const Module *Context);
994 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
995 TypePrinting *TypePrinter,
996 SlotTracker *Machine, const Module *Context,
997 bool FromValue = false);
999 static const char *getPredicateText(unsigned predicate) {
1000 const char * pred = "unknown";
1001 switch (predicate) {
1002 case FCmpInst::FCMP_FALSE: pred = "false"; break;
1003 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
1004 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
1005 case FCmpInst::FCMP_OGE: pred = "oge"; break;
1006 case FCmpInst::FCMP_OLT: pred = "olt"; break;
1007 case FCmpInst::FCMP_OLE: pred = "ole"; break;
1008 case FCmpInst::FCMP_ONE: pred = "one"; break;
1009 case FCmpInst::FCMP_ORD: pred = "ord"; break;
1010 case FCmpInst::FCMP_UNO: pred = "uno"; break;
1011 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
1012 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
1013 case FCmpInst::FCMP_UGE: pred = "uge"; break;
1014 case FCmpInst::FCMP_ULT: pred = "ult"; break;
1015 case FCmpInst::FCMP_ULE: pred = "ule"; break;
1016 case FCmpInst::FCMP_UNE: pred = "une"; break;
1017 case FCmpInst::FCMP_TRUE: pred = "true"; break;
1018 case ICmpInst::ICMP_EQ: pred = "eq"; break;
1019 case ICmpInst::ICMP_NE: pred = "ne"; break;
1020 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
1021 case ICmpInst::ICMP_SGE: pred = "sge"; break;
1022 case ICmpInst::ICMP_SLT: pred = "slt"; break;
1023 case ICmpInst::ICMP_SLE: pred = "sle"; break;
1024 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
1025 case ICmpInst::ICMP_UGE: pred = "uge"; break;
1026 case ICmpInst::ICMP_ULT: pred = "ult"; break;
1027 case ICmpInst::ICMP_ULE: pred = "ule"; break;
1032 static void writeAtomicRMWOperation(raw_ostream &Out,
1033 AtomicRMWInst::BinOp Op) {
1035 default: Out << " <unknown operation " << Op << ">"; break;
1036 case AtomicRMWInst::Xchg: Out << " xchg"; break;
1037 case AtomicRMWInst::Add: Out << " add"; break;
1038 case AtomicRMWInst::Sub: Out << " sub"; break;
1039 case AtomicRMWInst::And: Out << " and"; break;
1040 case AtomicRMWInst::Nand: Out << " nand"; break;
1041 case AtomicRMWInst::Or: Out << " or"; break;
1042 case AtomicRMWInst::Xor: Out << " xor"; break;
1043 case AtomicRMWInst::Max: Out << " max"; break;
1044 case AtomicRMWInst::Min: Out << " min"; break;
1045 case AtomicRMWInst::UMax: Out << " umax"; break;
1046 case AtomicRMWInst::UMin: Out << " umin"; break;
1050 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1051 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
1052 // Unsafe algebra implies all the others, no need to write them all out
1053 if (FPO->hasUnsafeAlgebra())
1056 if (FPO->hasNoNaNs())
1058 if (FPO->hasNoInfs())
1060 if (FPO->hasNoSignedZeros())
1062 if (FPO->hasAllowReciprocal())
1067 if (const OverflowingBinaryOperator *OBO =
1068 dyn_cast<OverflowingBinaryOperator>(U)) {
1069 if (OBO->hasNoUnsignedWrap())
1071 if (OBO->hasNoSignedWrap())
1073 } else if (const PossiblyExactOperator *Div =
1074 dyn_cast<PossiblyExactOperator>(U)) {
1077 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1078 if (GEP->isInBounds())
1083 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1084 TypePrinting &TypePrinter,
1085 SlotTracker *Machine,
1086 const Module *Context) {
1087 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1088 if (CI->getType()->isIntegerTy(1)) {
1089 Out << (CI->getZExtValue() ? "true" : "false");
1092 Out << CI->getValue();
1096 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1097 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
1098 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
1099 // We would like to output the FP constant value in exponential notation,
1100 // but we cannot do this if doing so will lose precision. Check here to
1101 // make sure that we only output it in exponential format if we can parse
1102 // the value back and get the same value.
1105 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
1106 bool isInf = CFP->getValueAPF().isInfinity();
1107 bool isNaN = CFP->getValueAPF().isNaN();
1108 if (!isInf && !isNaN) {
1109 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
1110 CFP->getValueAPF().convertToFloat();
1111 SmallString<128> StrVal;
1112 raw_svector_ostream(StrVal) << Val;
1114 // Check to make sure that the stringized number is not some string like
1115 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
1116 // that the string matches the "[-+]?[0-9]" regex.
1118 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1119 ((StrVal[0] == '-' || StrVal[0] == '+') &&
1120 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
1121 // Reparse stringized version!
1122 if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
1128 // Otherwise we could not reparse it to exactly the same value, so we must
1129 // output the string in hexadecimal format! Note that loading and storing
1130 // floating point types changes the bits of NaNs on some hosts, notably
1131 // x86, so we must not use these types.
1132 static_assert(sizeof(double) == sizeof(uint64_t),
1133 "assuming that double is 64 bits!");
1134 APFloat apf = CFP->getValueAPF();
1135 // Floats are represented in ASCII IR as double, convert.
1137 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1139 Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
1143 // Either half, or some form of long double.
1144 // These appear as a magic letter identifying the type, then a
1145 // fixed number of hex digits.
1147 APInt API = CFP->getValueAPF().bitcastToAPInt();
1148 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
1150 Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
1152 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1155 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
1157 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1159 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1161 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
1163 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1165 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1167 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
1169 Out << format_hex_no_prefix(API.getZExtValue(), 4,
1172 llvm_unreachable("Unsupported floating point type");
1176 if (isa<ConstantAggregateZero>(CV)) {
1177 Out << "zeroinitializer";
1181 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1182 Out << "blockaddress(";
1183 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
1186 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
1192 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1193 Type *ETy = CA->getType()->getElementType();
1195 TypePrinter.print(ETy, Out);
1197 WriteAsOperandInternal(Out, CA->getOperand(0),
1198 &TypePrinter, Machine,
1200 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1202 TypePrinter.print(ETy, Out);
1204 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
1211 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1212 // As a special case, print the array as a string if it is an array of
1213 // i8 with ConstantInt values.
1214 if (CA->isString()) {
1216 PrintEscapedString(CA->getAsString(), Out);
1221 Type *ETy = CA->getType()->getElementType();
1223 TypePrinter.print(ETy, Out);
1225 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
1226 &TypePrinter, Machine,
1228 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1230 TypePrinter.print(ETy, Out);
1232 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
1240 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1241 if (CS->getType()->isPacked())
1244 unsigned N = CS->getNumOperands();
1247 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1250 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1253 for (unsigned i = 1; i < N; i++) {
1255 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1258 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1265 if (CS->getType()->isPacked())
1270 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1271 Type *ETy = CV->getType()->getVectorElementType();
1273 TypePrinter.print(ETy, Out);
1275 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
1277 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
1279 TypePrinter.print(ETy, Out);
1281 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1288 if (isa<ConstantPointerNull>(CV)) {
1293 if (isa<ConstantTokenNone>(CV)) {
1298 if (isa<UndefValue>(CV)) {
1303 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1304 Out << CE->getOpcodeName();
1305 WriteOptimizationInfo(Out, CE);
1306 if (CE->isCompare())
1307 Out << ' ' << getPredicateText(CE->getPredicate());
1310 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1311 TypePrinter.print(GEP->getSourceElementType(), Out);
1315 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1316 TypePrinter.print((*OI)->getType(), Out);
1318 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1319 if (OI+1 != CE->op_end())
1323 if (CE->hasIndices()) {
1324 ArrayRef<unsigned> Indices = CE->getIndices();
1325 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1326 Out << ", " << Indices[i];
1331 TypePrinter.print(CE->getType(), Out);
1338 Out << "<placeholder or erroneous Constant>";
1341 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1342 TypePrinting *TypePrinter, SlotTracker *Machine,
1343 const Module *Context) {
1345 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1346 const Metadata *MD = Node->getOperand(mi);
1349 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1350 Value *V = MDV->getValue();
1351 TypePrinter->print(V->getType(), Out);
1353 WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
1355 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1365 struct FieldSeparator {
1368 FieldSeparator(const char *Sep = ", ") : Skip(true), Sep(Sep) {}
1370 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1375 return OS << FS.Sep;
1377 struct MDFieldPrinter {
1380 TypePrinting *TypePrinter;
1381 SlotTracker *Machine;
1382 const Module *Context;
1384 explicit MDFieldPrinter(raw_ostream &Out)
1385 : Out(Out), TypePrinter(nullptr), Machine(nullptr), Context(nullptr) {}
1386 MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
1387 SlotTracker *Machine, const Module *Context)
1388 : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
1390 void printTag(const DINode *N);
1391 void printMacinfoType(const DIMacroNode *N);
1392 void printString(StringRef Name, StringRef Value,
1393 bool ShouldSkipEmpty = true);
1394 void printMetadata(StringRef Name, const Metadata *MD,
1395 bool ShouldSkipNull = true);
1396 template <class IntTy>
1397 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1398 void printBool(StringRef Name, bool Value);
1399 void printDIFlags(StringRef Name, unsigned Flags);
1400 template <class IntTy, class Stringifier>
1401 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1402 bool ShouldSkipZero = true);
1406 void MDFieldPrinter::printTag(const DINode *N) {
1407 Out << FS << "tag: ";
1408 if (const char *Tag = dwarf::TagString(N->getTag()))
1414 void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
1415 Out << FS << "type: ";
1416 if (const char *Type = dwarf::MacinfoString(N->getMacinfoType()))
1419 Out << N->getMacinfoType();
1422 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1423 bool ShouldSkipEmpty) {
1424 if (ShouldSkipEmpty && Value.empty())
1427 Out << FS << Name << ": \"";
1428 PrintEscapedString(Value, Out);
1432 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1433 TypePrinting *TypePrinter,
1434 SlotTracker *Machine,
1435 const Module *Context) {
1440 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1443 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1444 bool ShouldSkipNull) {
1445 if (ShouldSkipNull && !MD)
1448 Out << FS << Name << ": ";
1449 writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
1452 template <class IntTy>
1453 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1454 if (ShouldSkipZero && !Int)
1457 Out << FS << Name << ": " << Int;
1460 void MDFieldPrinter::printBool(StringRef Name, bool Value) {
1461 Out << FS << Name << ": " << (Value ? "true" : "false");
1464 void MDFieldPrinter::printDIFlags(StringRef Name, unsigned Flags) {
1468 Out << FS << Name << ": ";
1470 SmallVector<unsigned, 8> SplitFlags;
1471 unsigned Extra = DINode::splitFlags(Flags, SplitFlags);
1473 FieldSeparator FlagsFS(" | ");
1474 for (unsigned F : SplitFlags) {
1475 const char *StringF = DINode::getFlagString(F);
1476 assert(StringF && "Expected valid flag");
1477 Out << FlagsFS << StringF;
1479 if (Extra || SplitFlags.empty())
1480 Out << FlagsFS << Extra;
1483 template <class IntTy, class Stringifier>
1484 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1485 Stringifier toString, bool ShouldSkipZero) {
1489 Out << FS << Name << ": ";
1490 if (const char *S = toString(Value))
1496 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1497 TypePrinting *TypePrinter, SlotTracker *Machine,
1498 const Module *Context) {
1499 Out << "!GenericDINode(";
1500 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1501 Printer.printTag(N);
1502 Printer.printString("header", N->getHeader());
1503 if (N->getNumDwarfOperands()) {
1504 Out << Printer.FS << "operands: {";
1506 for (auto &I : N->dwarf_operands()) {
1508 writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
1515 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1516 TypePrinting *TypePrinter, SlotTracker *Machine,
1517 const Module *Context) {
1518 Out << "!DILocation(";
1519 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1520 // Always output the line, since 0 is a relevant and important value for it.
1521 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1522 Printer.printInt("column", DL->getColumn());
1523 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1524 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
1528 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1529 TypePrinting *, SlotTracker *, const Module *) {
1530 Out << "!DISubrange(";
1531 MDFieldPrinter Printer(Out);
1532 Printer.printInt("count", N->getCount(), /* ShouldSkipZero */ false);
1533 Printer.printInt("lowerBound", N->getLowerBound());
1537 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1538 TypePrinting *, SlotTracker *, const Module *) {
1539 Out << "!DIEnumerator(";
1540 MDFieldPrinter Printer(Out);
1541 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1542 Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
1546 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1547 TypePrinting *, SlotTracker *, const Module *) {
1548 Out << "!DIBasicType(";
1549 MDFieldPrinter Printer(Out);
1550 if (N->getTag() != dwarf::DW_TAG_base_type)
1551 Printer.printTag(N);
1552 Printer.printString("name", N->getName());
1553 Printer.printInt("size", N->getSizeInBits());
1554 Printer.printInt("align", N->getAlignInBits());
1555 Printer.printDwarfEnum("encoding", N->getEncoding(),
1556 dwarf::AttributeEncodingString);
1560 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
1561 TypePrinting *TypePrinter, SlotTracker *Machine,
1562 const Module *Context) {
1563 Out << "!DIDerivedType(";
1564 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1565 Printer.printTag(N);
1566 Printer.printString("name", N->getName());
1567 Printer.printMetadata("scope", N->getRawScope());
1568 Printer.printMetadata("file", N->getRawFile());
1569 Printer.printInt("line", N->getLine());
1570 Printer.printMetadata("baseType", N->getRawBaseType(),
1571 /* ShouldSkipNull */ false);
1572 Printer.printInt("size", N->getSizeInBits());
1573 Printer.printInt("align", N->getAlignInBits());
1574 Printer.printInt("offset", N->getOffsetInBits());
1575 Printer.printDIFlags("flags", N->getFlags());
1576 Printer.printMetadata("extraData", N->getRawExtraData());
1580 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
1581 TypePrinting *TypePrinter,
1582 SlotTracker *Machine, const Module *Context) {
1583 Out << "!DICompositeType(";
1584 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1585 Printer.printTag(N);
1586 Printer.printString("name", N->getName());
1587 Printer.printMetadata("scope", N->getRawScope());
1588 Printer.printMetadata("file", N->getRawFile());
1589 Printer.printInt("line", N->getLine());
1590 Printer.printMetadata("baseType", N->getRawBaseType());
1591 Printer.printInt("size", N->getSizeInBits());
1592 Printer.printInt("align", N->getAlignInBits());
1593 Printer.printInt("offset", N->getOffsetInBits());
1594 Printer.printDIFlags("flags", N->getFlags());
1595 Printer.printMetadata("elements", N->getRawElements());
1596 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
1597 dwarf::LanguageString);
1598 Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
1599 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1600 Printer.printString("identifier", N->getIdentifier());
1604 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
1605 TypePrinting *TypePrinter,
1606 SlotTracker *Machine, const Module *Context) {
1607 Out << "!DISubroutineType(";
1608 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1609 Printer.printDIFlags("flags", N->getFlags());
1610 Printer.printMetadata("types", N->getRawTypeArray(),
1611 /* ShouldSkipNull */ false);
1615 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
1616 SlotTracker *, const Module *) {
1618 MDFieldPrinter Printer(Out);
1619 Printer.printString("filename", N->getFilename(),
1620 /* ShouldSkipEmpty */ false);
1621 Printer.printString("directory", N->getDirectory(),
1622 /* ShouldSkipEmpty */ false);
1626 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
1627 TypePrinting *TypePrinter, SlotTracker *Machine,
1628 const Module *Context) {
1629 Out << "!DICompileUnit(";
1630 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1631 Printer.printDwarfEnum("language", N->getSourceLanguage(),
1632 dwarf::LanguageString, /* ShouldSkipZero */ false);
1633 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1634 Printer.printString("producer", N->getProducer());
1635 Printer.printBool("isOptimized", N->isOptimized());
1636 Printer.printString("flags", N->getFlags());
1637 Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
1638 /* ShouldSkipZero */ false);
1639 Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
1640 Printer.printInt("emissionKind", N->getEmissionKind(),
1641 /* ShouldSkipZero */ false);
1642 Printer.printMetadata("enums", N->getRawEnumTypes());
1643 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
1644 Printer.printMetadata("subprograms", N->getRawSubprograms());
1645 Printer.printMetadata("globals", N->getRawGlobalVariables());
1646 Printer.printMetadata("imports", N->getRawImportedEntities());
1647 Printer.printMetadata("macros", N->getRawMacros());
1648 Printer.printInt("dwoId", N->getDWOId());
1652 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
1653 TypePrinting *TypePrinter, SlotTracker *Machine,
1654 const Module *Context) {
1655 Out << "!DISubprogram(";
1656 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1657 Printer.printString("name", N->getName());
1658 Printer.printString("linkageName", N->getLinkageName());
1659 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1660 Printer.printMetadata("file", N->getRawFile());
1661 Printer.printInt("line", N->getLine());
1662 Printer.printMetadata("type", N->getRawType());
1663 Printer.printBool("isLocal", N->isLocalToUnit());
1664 Printer.printBool("isDefinition", N->isDefinition());
1665 Printer.printInt("scopeLine", N->getScopeLine());
1666 Printer.printMetadata("containingType", N->getRawContainingType());
1667 Printer.printDwarfEnum("virtuality", N->getVirtuality(),
1668 dwarf::VirtualityString);
1669 Printer.printInt("virtualIndex", N->getVirtualIndex());
1670 Printer.printDIFlags("flags", N->getFlags());
1671 Printer.printBool("isOptimized", N->isOptimized());
1672 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1673 Printer.printMetadata("declaration", N->getRawDeclaration());
1674 Printer.printMetadata("variables", N->getRawVariables());
1678 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
1679 TypePrinting *TypePrinter, SlotTracker *Machine,
1680 const Module *Context) {
1681 Out << "!DILexicalBlock(";
1682 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1683 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1684 Printer.printMetadata("file", N->getRawFile());
1685 Printer.printInt("line", N->getLine());
1686 Printer.printInt("column", N->getColumn());
1690 static void writeDILexicalBlockFile(raw_ostream &Out,
1691 const DILexicalBlockFile *N,
1692 TypePrinting *TypePrinter,
1693 SlotTracker *Machine,
1694 const Module *Context) {
1695 Out << "!DILexicalBlockFile(";
1696 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1697 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1698 Printer.printMetadata("file", N->getRawFile());
1699 Printer.printInt("discriminator", N->getDiscriminator(),
1700 /* ShouldSkipZero */ false);
1704 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
1705 TypePrinting *TypePrinter, SlotTracker *Machine,
1706 const Module *Context) {
1707 Out << "!DINamespace(";
1708 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1709 Printer.printString("name", N->getName());
1710 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1711 Printer.printMetadata("file", N->getRawFile());
1712 Printer.printInt("line", N->getLine());
1716 static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
1717 TypePrinting *TypePrinter, SlotTracker *Machine,
1718 const Module *Context) {
1720 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1721 Printer.printMacinfoType(N);
1722 Printer.printInt("line", N->getLine());
1723 Printer.printString("name", N->getName());
1724 Printer.printString("value", N->getValue());
1728 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
1729 TypePrinting *TypePrinter, SlotTracker *Machine,
1730 const Module *Context) {
1731 Out << "!DIMacroFile(";
1732 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1733 Printer.printInt("line", N->getLine());
1734 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1735 Printer.printMetadata("nodes", N->getRawElements());
1739 static void writeDIModule(raw_ostream &Out, const DIModule *N,
1740 TypePrinting *TypePrinter, SlotTracker *Machine,
1741 const Module *Context) {
1742 Out << "!DIModule(";
1743 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1744 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1745 Printer.printString("name", N->getName());
1746 Printer.printString("configMacros", N->getConfigurationMacros());
1747 Printer.printString("includePath", N->getIncludePath());
1748 Printer.printString("isysroot", N->getISysRoot());
1753 static void writeDITemplateTypeParameter(raw_ostream &Out,
1754 const DITemplateTypeParameter *N,
1755 TypePrinting *TypePrinter,
1756 SlotTracker *Machine,
1757 const Module *Context) {
1758 Out << "!DITemplateTypeParameter(";
1759 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1760 Printer.printString("name", N->getName());
1761 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
1765 static void writeDITemplateValueParameter(raw_ostream &Out,
1766 const DITemplateValueParameter *N,
1767 TypePrinting *TypePrinter,
1768 SlotTracker *Machine,
1769 const Module *Context) {
1770 Out << "!DITemplateValueParameter(";
1771 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1772 if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
1773 Printer.printTag(N);
1774 Printer.printString("name", N->getName());
1775 Printer.printMetadata("type", N->getRawType());
1776 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
1780 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
1781 TypePrinting *TypePrinter,
1782 SlotTracker *Machine, const Module *Context) {
1783 Out << "!DIGlobalVariable(";
1784 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1785 Printer.printString("name", N->getName());
1786 Printer.printString("linkageName", N->getLinkageName());
1787 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1788 Printer.printMetadata("file", N->getRawFile());
1789 Printer.printInt("line", N->getLine());
1790 Printer.printMetadata("type", N->getRawType());
1791 Printer.printBool("isLocal", N->isLocalToUnit());
1792 Printer.printBool("isDefinition", N->isDefinition());
1793 Printer.printMetadata("variable", N->getRawVariable());
1794 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
1798 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
1799 TypePrinting *TypePrinter,
1800 SlotTracker *Machine, const Module *Context) {
1801 Out << "!DILocalVariable(";
1802 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1803 Printer.printString("name", N->getName());
1804 Printer.printInt("arg", N->getArg());
1805 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1806 Printer.printMetadata("file", N->getRawFile());
1807 Printer.printInt("line", N->getLine());
1808 Printer.printMetadata("type", N->getRawType());
1809 Printer.printDIFlags("flags", N->getFlags());
1813 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
1814 TypePrinting *TypePrinter, SlotTracker *Machine,
1815 const Module *Context) {
1816 Out << "!DIExpression(";
1819 for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
1820 const char *OpStr = dwarf::OperationEncodingString(I->getOp());
1821 assert(OpStr && "Expected valid opcode");
1824 for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
1825 Out << FS << I->getArg(A);
1828 for (const auto &I : N->getElements())
1834 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
1835 TypePrinting *TypePrinter, SlotTracker *Machine,
1836 const Module *Context) {
1837 Out << "!DIObjCProperty(";
1838 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1839 Printer.printString("name", N->getName());
1840 Printer.printMetadata("file", N->getRawFile());
1841 Printer.printInt("line", N->getLine());
1842 Printer.printString("setter", N->getSetterName());
1843 Printer.printString("getter", N->getGetterName());
1844 Printer.printInt("attributes", N->getAttributes());
1845 Printer.printMetadata("type", N->getRawType());
1849 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
1850 TypePrinting *TypePrinter,
1851 SlotTracker *Machine, const Module *Context) {
1852 Out << "!DIImportedEntity(";
1853 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1854 Printer.printTag(N);
1855 Printer.printString("name", N->getName());
1856 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1857 Printer.printMetadata("entity", N->getRawEntity());
1858 Printer.printInt("line", N->getLine());
1863 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1864 TypePrinting *TypePrinter,
1865 SlotTracker *Machine,
1866 const Module *Context) {
1867 if (Node->isDistinct())
1869 else if (Node->isTemporary())
1870 Out << "<temporary!> "; // Handle broken code.
1872 switch (Node->getMetadataID()) {
1874 llvm_unreachable("Expected uniquable MDNode");
1875 #define HANDLE_MDNODE_LEAF(CLASS) \
1876 case Metadata::CLASS##Kind: \
1877 write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \
1879 #include "llvm/IR/Metadata.def"
1883 // Full implementation of printing a Value as an operand with support for
1884 // TypePrinting, etc.
1885 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1886 TypePrinting *TypePrinter,
1887 SlotTracker *Machine,
1888 const Module *Context) {
1890 PrintLLVMName(Out, V);
1894 const Constant *CV = dyn_cast<Constant>(V);
1895 if (CV && !isa<GlobalValue>(CV)) {
1896 assert(TypePrinter && "Constants require TypePrinting!");
1897 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1901 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1903 if (IA->hasSideEffects())
1904 Out << "sideeffect ";
1905 if (IA->isAlignStack())
1906 Out << "alignstack ";
1907 // We don't emit the AD_ATT dialect as it's the assumed default.
1908 if (IA->getDialect() == InlineAsm::AD_Intel)
1909 Out << "inteldialect ";
1911 PrintEscapedString(IA->getAsmString(), Out);
1913 PrintEscapedString(IA->getConstraintString(), Out);
1918 if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
1919 WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
1920 Context, /* FromValue */ true);
1926 // If we have a SlotTracker, use it.
1928 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1929 Slot = Machine->getGlobalSlot(GV);
1932 Slot = Machine->getLocalSlot(V);
1934 // If the local value didn't succeed, then we may be referring to a value
1935 // from a different function. Translate it, as this can happen when using
1936 // address of blocks.
1938 if ((Machine = createSlotTracker(V))) {
1939 Slot = Machine->getLocalSlot(V);
1943 } else if ((Machine = createSlotTracker(V))) {
1944 // Otherwise, create one to get the # and then destroy it.
1945 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1946 Slot = Machine->getGlobalSlot(GV);
1949 Slot = Machine->getLocalSlot(V);
1958 Out << Prefix << Slot;
1963 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1964 TypePrinting *TypePrinter,
1965 SlotTracker *Machine, const Module *Context,
1967 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1968 std::unique_ptr<SlotTracker> MachineStorage;
1970 MachineStorage = make_unique<SlotTracker>(Context);
1971 Machine = MachineStorage.get();
1973 int Slot = Machine->getMetadataSlot(N);
1975 // Give the pointer value instead of "badref", since this comes up all
1976 // the time when debugging.
1977 Out << "<" << N << ">";
1983 if (const MDString *MDS = dyn_cast<MDString>(MD)) {
1985 PrintEscapedString(MDS->getString(), Out);
1990 auto *V = cast<ValueAsMetadata>(MD);
1991 assert(TypePrinter && "TypePrinter required for metadata values");
1992 assert((FromValue || !isa<LocalAsMetadata>(V)) &&
1993 "Unexpected function-local metadata outside of value argument");
1995 TypePrinter->print(V->getValue()->getType(), Out);
1997 WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
2001 class AssemblyWriter {
2002 formatted_raw_ostream &Out;
2003 const Module *TheModule;
2004 std::unique_ptr<SlotTracker> SlotTrackerStorage;
2005 SlotTracker &Machine;
2006 TypePrinting TypePrinter;
2007 AssemblyAnnotationWriter *AnnotationWriter;
2008 SetVector<const Comdat *> Comdats;
2010 bool ShouldPreserveUseListOrder;
2011 UseListOrderStack UseListOrders;
2012 SmallVector<StringRef, 8> MDNames;
2015 /// Construct an AssemblyWriter with an external SlotTracker
2016 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
2017 AssemblyAnnotationWriter *AAW, bool IsForDebug,
2018 bool ShouldPreserveUseListOrder = false);
2020 void printMDNodeBody(const MDNode *MD);
2021 void printNamedMDNode(const NamedMDNode *NMD);
2023 void printModule(const Module *M);
2025 void writeOperand(const Value *Op, bool PrintType);
2026 void writeParamOperand(const Value *Operand, AttributeSet Attrs,unsigned Idx);
2027 void writeOperandBundles(ImmutableCallSite CS);
2028 void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
2029 void writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2030 AtomicOrdering FailureOrdering,
2031 SynchronizationScope SynchScope);
2033 void writeAllMDNodes();
2034 void writeMDNode(unsigned Slot, const MDNode *Node);
2035 void writeAllAttributeGroups();
2037 void printTypeIdentities();
2038 void printGlobal(const GlobalVariable *GV);
2039 void printAlias(const GlobalAlias *GV);
2040 void printComdat(const Comdat *C);
2041 void printFunction(const Function *F);
2042 void printArgument(const Argument *FA, AttributeSet Attrs, unsigned Idx);
2043 void printBasicBlock(const BasicBlock *BB);
2044 void printInstructionLine(const Instruction &I);
2045 void printInstruction(const Instruction &I);
2047 void printUseListOrder(const UseListOrder &Order);
2048 void printUseLists(const Function *F);
2051 /// \brief Print out metadata attachments.
2052 void printMetadataAttachments(
2053 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2054 StringRef Separator);
2056 // printInfoComment - Print a little comment after the instruction indicating
2057 // which slot it occupies.
2058 void printInfoComment(const Value &V);
2060 // printGCRelocateComment - print comment after call to the gc.relocate
2061 // intrinsic indicating base and derived pointer names.
2062 void printGCRelocateComment(const Value &V);
2066 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2067 const Module *M, AssemblyAnnotationWriter *AAW,
2068 bool IsForDebug, bool ShouldPreserveUseListOrder)
2069 : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW),
2070 IsForDebug(IsForDebug),
2071 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2074 TypePrinter.incorporateTypes(*TheModule);
2075 for (const Function &F : *TheModule)
2076 if (const Comdat *C = F.getComdat())
2078 for (const GlobalVariable &GV : TheModule->globals())
2079 if (const Comdat *C = GV.getComdat())
2083 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2085 Out << "<null operand!>";
2089 TypePrinter.print(Operand->getType(), Out);
2092 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2095 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
2096 SynchronizationScope SynchScope) {
2097 if (Ordering == NotAtomic)
2100 switch (SynchScope) {
2101 case SingleThread: Out << " singlethread"; break;
2102 case CrossThread: break;
2106 default: Out << " <bad ordering " << int(Ordering) << ">"; break;
2107 case Unordered: Out << " unordered"; break;
2108 case Monotonic: Out << " monotonic"; break;
2109 case Acquire: Out << " acquire"; break;
2110 case Release: Out << " release"; break;
2111 case AcquireRelease: Out << " acq_rel"; break;
2112 case SequentiallyConsistent: Out << " seq_cst"; break;
2116 void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2117 AtomicOrdering FailureOrdering,
2118 SynchronizationScope SynchScope) {
2119 assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic);
2121 switch (SynchScope) {
2122 case SingleThread: Out << " singlethread"; break;
2123 case CrossThread: break;
2126 switch (SuccessOrdering) {
2127 default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break;
2128 case Unordered: Out << " unordered"; break;
2129 case Monotonic: Out << " monotonic"; break;
2130 case Acquire: Out << " acquire"; break;
2131 case Release: Out << " release"; break;
2132 case AcquireRelease: Out << " acq_rel"; break;
2133 case SequentiallyConsistent: Out << " seq_cst"; break;
2136 switch (FailureOrdering) {
2137 default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break;
2138 case Unordered: Out << " unordered"; break;
2139 case Monotonic: Out << " monotonic"; break;
2140 case Acquire: Out << " acquire"; break;
2141 case Release: Out << " release"; break;
2142 case AcquireRelease: Out << " acq_rel"; break;
2143 case SequentiallyConsistent: Out << " seq_cst"; break;
2147 void AssemblyWriter::writeParamOperand(const Value *Operand,
2148 AttributeSet Attrs, unsigned Idx) {
2150 Out << "<null operand!>";
2155 TypePrinter.print(Operand->getType(), Out);
2156 // Print parameter attributes list
2157 if (Attrs.hasAttributes(Idx))
2158 Out << ' ' << Attrs.getAsString(Idx);
2160 // Print the operand
2161 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2164 void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS) {
2165 if (!CS.hasOperandBundles())
2170 bool FirstBundle = true;
2171 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2172 OperandBundleUse BU = CS.getOperandBundleAt(i);
2176 FirstBundle = false;
2179 PrintEscapedString(BU.getTagName(), Out);
2184 bool FirstInput = true;
2185 for (const auto &Input : BU.Inputs) {
2190 TypePrinter.print(Input->getType(), Out);
2192 WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
2201 void AssemblyWriter::printModule(const Module *M) {
2202 Machine.initialize();
2204 if (ShouldPreserveUseListOrder)
2205 UseListOrders = predictUseListOrder(M);
2207 if (!M->getModuleIdentifier().empty() &&
2208 // Don't print the ID if it will start a new line (which would
2209 // require a comment char before it).
2210 M->getModuleIdentifier().find('\n') == std::string::npos)
2211 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2213 const std::string &DL = M->getDataLayoutStr();
2215 Out << "target datalayout = \"" << DL << "\"\n";
2216 if (!M->getTargetTriple().empty())
2217 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2219 if (!M->getModuleInlineAsm().empty()) {
2222 // Split the string into lines, to make it easier to read the .ll file.
2223 StringRef Asm = M->getModuleInlineAsm();
2226 std::tie(Front, Asm) = Asm.split('\n');
2228 // We found a newline, print the portion of the asm string from the
2229 // last newline up to this newline.
2230 Out << "module asm \"";
2231 PrintEscapedString(Front, Out);
2233 } while (!Asm.empty());
2236 printTypeIdentities();
2238 // Output all comdats.
2239 if (!Comdats.empty())
2241 for (const Comdat *C : Comdats) {
2243 if (C != Comdats.back())
2247 // Output all globals.
2248 if (!M->global_empty()) Out << '\n';
2249 for (const GlobalVariable &GV : M->globals()) {
2250 printGlobal(&GV); Out << '\n';
2253 // Output all aliases.
2254 if (!M->alias_empty()) Out << "\n";
2255 for (const GlobalAlias &GA : M->aliases())
2258 // Output global use-lists.
2259 printUseLists(nullptr);
2261 // Output all of the functions.
2262 for (const Function &F : *M)
2264 assert(UseListOrders.empty() && "All use-lists should have been consumed");
2266 // Output all attribute groups.
2267 if (!Machine.as_empty()) {
2269 writeAllAttributeGroups();
2272 // Output named metadata.
2273 if (!M->named_metadata_empty()) Out << '\n';
2275 for (const NamedMDNode &Node : M->named_metadata())
2276 printNamedMDNode(&Node);
2279 if (!Machine.mdn_empty()) {
2285 static void printMetadataIdentifier(StringRef Name,
2286 formatted_raw_ostream &Out) {
2288 Out << "<empty name> ";
2290 if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
2291 Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
2294 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
2295 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
2296 unsigned char C = Name[i];
2297 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
2298 C == '.' || C == '_')
2301 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
2306 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
2308 printMetadataIdentifier(NMD->getName(), Out);
2310 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2313 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
2322 static void PrintLinkage(GlobalValue::LinkageTypes LT,
2323 formatted_raw_ostream &Out) {
2325 case GlobalValue::ExternalLinkage: break;
2326 case GlobalValue::PrivateLinkage: Out << "private "; break;
2327 case GlobalValue::InternalLinkage: Out << "internal "; break;
2328 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
2329 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
2330 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
2331 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
2332 case GlobalValue::CommonLinkage: Out << "common "; break;
2333 case GlobalValue::AppendingLinkage: Out << "appending "; break;
2334 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
2335 case GlobalValue::AvailableExternallyLinkage:
2336 Out << "available_externally ";
2341 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
2342 formatted_raw_ostream &Out) {
2344 case GlobalValue::DefaultVisibility: break;
2345 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
2346 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
2350 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
2351 formatted_raw_ostream &Out) {
2353 case GlobalValue::DefaultStorageClass: break;
2354 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
2355 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
2359 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
2360 formatted_raw_ostream &Out) {
2362 case GlobalVariable::NotThreadLocal:
2364 case GlobalVariable::GeneralDynamicTLSModel:
2365 Out << "thread_local ";
2367 case GlobalVariable::LocalDynamicTLSModel:
2368 Out << "thread_local(localdynamic) ";
2370 case GlobalVariable::InitialExecTLSModel:
2371 Out << "thread_local(initialexec) ";
2373 case GlobalVariable::LocalExecTLSModel:
2374 Out << "thread_local(localexec) ";
2379 static void maybePrintComdat(formatted_raw_ostream &Out,
2380 const GlobalObject &GO) {
2381 const Comdat *C = GO.getComdat();
2385 if (isa<GlobalVariable>(GO))
2389 if (GO.getName() == C->getName())
2393 PrintLLVMName(Out, C->getName(), ComdatPrefix);
2397 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
2398 if (GV->isMaterializable())
2399 Out << "; Materializable\n";
2401 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
2404 if (!GV->hasInitializer() && GV->hasExternalLinkage())
2407 PrintLinkage(GV->getLinkage(), Out);
2408 PrintVisibility(GV->getVisibility(), Out);
2409 PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
2410 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
2411 if (GV->hasUnnamedAddr())
2412 Out << "unnamed_addr ";
2414 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
2415 Out << "addrspace(" << AddressSpace << ") ";
2416 if (GV->isExternallyInitialized()) Out << "externally_initialized ";
2417 Out << (GV->isConstant() ? "constant " : "global ");
2418 TypePrinter.print(GV->getType()->getElementType(), Out);
2420 if (GV->hasInitializer()) {
2422 writeOperand(GV->getInitializer(), false);
2425 if (GV->hasSection()) {
2426 Out << ", section \"";
2427 PrintEscapedString(GV->getSection(), Out);
2430 maybePrintComdat(Out, *GV);
2431 if (GV->getAlignment())
2432 Out << ", align " << GV->getAlignment();
2434 printInfoComment(*GV);
2437 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
2438 if (GA->isMaterializable())
2439 Out << "; Materializable\n";
2441 WriteAsOperandInternal(Out, GA, &TypePrinter, &Machine, GA->getParent());
2444 PrintLinkage(GA->getLinkage(), Out);
2445 PrintVisibility(GA->getVisibility(), Out);
2446 PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
2447 PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
2448 if (GA->hasUnnamedAddr())
2449 Out << "unnamed_addr ";
2453 TypePrinter.print(GA->getValueType(), Out);
2457 const Constant *Aliasee = GA->getAliasee();
2460 TypePrinter.print(GA->getType(), Out);
2461 Out << " <<NULL ALIASEE>>";
2463 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
2466 printInfoComment(*GA);
2470 void AssemblyWriter::printComdat(const Comdat *C) {
2474 void AssemblyWriter::printTypeIdentities() {
2475 if (TypePrinter.NumberedTypes.empty() &&
2476 TypePrinter.NamedTypes.empty())
2481 // We know all the numbers that each type is used and we know that it is a
2482 // dense assignment. Convert the map to an index table.
2483 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
2484 for (DenseMap<StructType*, unsigned>::iterator I =
2485 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
2487 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
2488 NumberedTypes[I->second] = I->first;
2491 // Emit all numbered types.
2492 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
2493 Out << '%' << i << " = type ";
2495 // Make sure we print out at least one level of the type structure, so
2496 // that we do not get %2 = type %2
2497 TypePrinter.printStructBody(NumberedTypes[i], Out);
2501 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
2502 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
2505 // Make sure we print out at least one level of the type structure, so
2506 // that we do not get %FILE = type %FILE
2507 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
2512 /// printFunction - Print all aspects of a function.
2514 void AssemblyWriter::printFunction(const Function *F) {
2515 // Print out the return type and name.
2518 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
2520 if (F->isMaterializable())
2521 Out << "; Materializable\n";
2523 const AttributeSet &Attrs = F->getAttributes();
2524 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
2525 AttributeSet AS = Attrs.getFnAttributes();
2526 std::string AttrStr;
2529 for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
2530 if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
2533 for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
2535 Attribute Attr = *I;
2536 if (!Attr.isStringAttribute()) {
2537 if (!AttrStr.empty()) AttrStr += ' ';
2538 AttrStr += Attr.getAsString();
2542 if (!AttrStr.empty())
2543 Out << "; Function Attrs: " << AttrStr << '\n';
2546 if (F->isDeclaration())
2551 PrintLinkage(F->getLinkage(), Out);
2552 PrintVisibility(F->getVisibility(), Out);
2553 PrintDLLStorageClass(F->getDLLStorageClass(), Out);
2555 // Print the calling convention.
2556 if (F->getCallingConv() != CallingConv::C) {
2557 PrintCallingConv(F->getCallingConv(), Out);
2561 FunctionType *FT = F->getFunctionType();
2562 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
2563 Out << Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
2564 TypePrinter.print(F->getReturnType(), Out);
2566 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
2568 Machine.incorporateFunction(F);
2570 // Loop over the arguments, printing them...
2571 if (F->isDeclaration() && !IsForDebug) {
2572 // We're only interested in the type here - don't print argument names.
2573 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
2574 // Insert commas as we go... the first arg doesn't get a comma
2578 TypePrinter.print(FT->getParamType(I), Out);
2580 if (Attrs.hasAttributes(I + 1))
2581 Out << ' ' << Attrs.getAsString(I + 1);
2584 // The arguments are meaningful here, print them in detail.
2586 for (const Argument &Arg : F->args()) {
2587 // Insert commas as we go... the first arg doesn't get a comma
2590 printArgument(&Arg, Attrs, Idx++);
2594 // Finish printing arguments...
2595 if (FT->isVarArg()) {
2596 if (FT->getNumParams()) Out << ", ";
2597 Out << "..."; // Output varargs portion of signature!
2600 if (F->hasUnnamedAddr())
2601 Out << " unnamed_addr";
2602 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
2603 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
2604 if (F->hasSection()) {
2605 Out << " section \"";
2606 PrintEscapedString(F->getSection(), Out);
2609 maybePrintComdat(Out, *F);
2610 if (F->getAlignment())
2611 Out << " align " << F->getAlignment();
2613 Out << " gc \"" << F->getGC() << '"';
2614 if (F->hasPrefixData()) {
2616 writeOperand(F->getPrefixData(), true);
2618 if (F->hasPrologueData()) {
2619 Out << " prologue ";
2620 writeOperand(F->getPrologueData(), true);
2622 if (F->hasPersonalityFn()) {
2623 Out << " personality ";
2624 writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
2627 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2628 F->getAllMetadata(MDs);
2629 printMetadataAttachments(MDs, " ");
2631 if (F->isDeclaration()) {
2635 // Output all of the function's basic blocks.
2636 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
2637 printBasicBlock(&*I);
2639 // Output the function's use-lists.
2645 Machine.purgeFunction();
2648 /// printArgument - This member is called for every argument that is passed into
2649 /// the function. Simply print it out
2651 void AssemblyWriter::printArgument(const Argument *Arg,
2652 AttributeSet Attrs, unsigned Idx) {
2654 TypePrinter.print(Arg->getType(), Out);
2656 // Output parameter attributes list
2657 if (Attrs.hasAttributes(Idx))
2658 Out << ' ' << Attrs.getAsString(Idx);
2660 // Output name, if available...
2661 if (Arg->hasName()) {
2663 PrintLLVMName(Out, Arg);
2667 /// printBasicBlock - This member is called for each basic block in a method.
2669 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
2670 if (BB->hasName()) { // Print out the label if it exists...
2672 PrintLLVMName(Out, BB->getName(), LabelPrefix);
2674 } else if (!BB->use_empty()) { // Don't print block # of no uses...
2675 Out << "\n; <label>:";
2676 int Slot = Machine.getLocalSlot(BB);
2683 if (!BB->getParent()) {
2684 Out.PadToColumn(50);
2685 Out << "; Error: Block without parent!";
2686 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
2687 // Output predecessors for the block.
2688 Out.PadToColumn(50);
2690 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
2693 Out << " No predecessors!";
2696 writeOperand(*PI, false);
2697 for (++PI; PI != PE; ++PI) {
2699 writeOperand(*PI, false);
2706 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
2708 // Output all of the instructions in the basic block...
2709 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2710 printInstructionLine(*I);
2713 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
2716 /// printInstructionLine - Print an instruction and a newline character.
2717 void AssemblyWriter::printInstructionLine(const Instruction &I) {
2718 printInstruction(I);
2722 /// printGCRelocateComment - print comment after call to the gc.relocate
2723 /// intrinsic indicating base and derived pointer names.
2724 void AssemblyWriter::printGCRelocateComment(const Value &V) {
2725 assert(isGCRelocate(&V));
2726 GCRelocateOperands GCOps(cast<Instruction>(&V));
2729 writeOperand(GCOps.getBasePtr(), false);
2731 writeOperand(GCOps.getDerivedPtr(), false);
2735 /// printInfoComment - Print a little comment after the instruction indicating
2736 /// which slot it occupies.
2738 void AssemblyWriter::printInfoComment(const Value &V) {
2739 if (isGCRelocate(&V))
2740 printGCRelocateComment(V);
2742 if (AnnotationWriter)
2743 AnnotationWriter->printInfoComment(V, Out);
2746 // This member is called for each Instruction in a function..
2747 void AssemblyWriter::printInstruction(const Instruction &I) {
2748 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
2750 // Print out indentation for an instruction.
2753 // Print out name if it exists...
2755 PrintLLVMName(Out, &I);
2757 } else if (!I.getType()->isVoidTy()) {
2758 // Print out the def slot taken.
2759 int SlotNum = Machine.getLocalSlot(&I);
2761 Out << "<badref> = ";
2763 Out << '%' << SlotNum << " = ";
2766 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2767 if (CI->isMustTailCall())
2769 else if (CI->isTailCall())
2771 else if (CI->isNoTailCall())
2775 // Print out the opcode...
2776 Out << I.getOpcodeName();
2778 // If this is an atomic load or store, print out the atomic marker.
2779 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
2780 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
2783 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
2786 // If this is a volatile operation, print out the volatile marker.
2787 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
2788 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
2789 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
2790 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
2793 // Print out optimization information.
2794 WriteOptimizationInfo(Out, &I);
2796 // Print out the compare instruction predicates
2797 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
2798 Out << ' ' << getPredicateText(CI->getPredicate());
2800 // Print out the atomicrmw operation
2801 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
2802 writeAtomicRMWOperation(Out, RMWI->getOperation());
2804 // Print out the type of the operands...
2805 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
2807 // Special case conditional branches to swizzle the condition out to the front
2808 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
2809 const BranchInst &BI(cast<BranchInst>(I));
2811 writeOperand(BI.getCondition(), true);
2813 writeOperand(BI.getSuccessor(0), true);
2815 writeOperand(BI.getSuccessor(1), true);
2817 } else if (isa<SwitchInst>(I)) {
2818 const SwitchInst& SI(cast<SwitchInst>(I));
2819 // Special case switch instruction to get formatting nice and correct.
2821 writeOperand(SI.getCondition(), true);
2823 writeOperand(SI.getDefaultDest(), true);
2825 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
2828 writeOperand(i.getCaseValue(), true);
2830 writeOperand(i.getCaseSuccessor(), true);
2833 } else if (isa<IndirectBrInst>(I)) {
2834 // Special case indirectbr instruction to get formatting nice and correct.
2836 writeOperand(Operand, true);
2839 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2842 writeOperand(I.getOperand(i), true);
2845 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
2847 TypePrinter.print(I.getType(), Out);
2850 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
2851 if (op) Out << ", ";
2853 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
2854 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
2856 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
2858 writeOperand(I.getOperand(0), true);
2859 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
2861 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
2863 writeOperand(I.getOperand(0), true); Out << ", ";
2864 writeOperand(I.getOperand(1), true);
2865 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
2867 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
2869 TypePrinter.print(I.getType(), Out);
2870 if (LPI->isCleanup() || LPI->getNumClauses() != 0)
2873 if (LPI->isCleanup())
2876 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
2877 if (i != 0 || LPI->isCleanup()) Out << "\n";
2878 if (LPI->isCatch(i))
2883 writeOperand(LPI->getClause(i), true);
2885 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
2887 writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
2890 for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
2893 writeOperand(PadBB, /*PrintType=*/true);
2897 if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
2898 writeOperand(UnwindDest, /*PrintType=*/true);
2901 } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
2903 writeOperand(FPI->getParentPad(), /*PrintType=*/false);
2905 for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps;
2909 writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
2912 } else if (isa<ReturnInst>(I) && !Operand) {
2914 } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
2916 writeOperand(CRI->getOperand(0), /*PrintType=*/false);
2919 writeOperand(CRI->getOperand(1), /*PrintType=*/true);
2920 } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
2922 writeOperand(CRI->getOperand(0), /*PrintType=*/false);
2925 if (CRI->hasUnwindDest())
2926 writeOperand(CRI->getOperand(1), /*PrintType=*/true);
2929 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2930 // Print the calling convention being used.
2931 if (CI->getCallingConv() != CallingConv::C) {
2933 PrintCallingConv(CI->getCallingConv(), Out);
2936 Operand = CI->getCalledValue();
2937 FunctionType *FTy = cast<FunctionType>(CI->getFunctionType());
2938 Type *RetTy = FTy->getReturnType();
2939 const AttributeSet &PAL = CI->getAttributes();
2941 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
2942 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
2944 // If possible, print out the short form of the call instruction. We can
2945 // only do this if the first argument is a pointer to a nonvararg function,
2946 // and if the return type is not a pointer to a function.
2949 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
2951 writeOperand(Operand, false);
2953 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
2956 writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
2959 // Emit an ellipsis if this is a musttail call in a vararg function. This
2960 // is only to aid readability, musttail calls forward varargs by default.
2961 if (CI->isMustTailCall() && CI->getParent() &&
2962 CI->getParent()->getParent() &&
2963 CI->getParent()->getParent()->isVarArg())
2967 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
2968 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
2970 writeOperandBundles(CI);
2972 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
2973 Operand = II->getCalledValue();
2974 FunctionType *FTy = cast<FunctionType>(II->getFunctionType());
2975 Type *RetTy = FTy->getReturnType();
2976 const AttributeSet &PAL = II->getAttributes();
2978 // Print the calling convention being used.
2979 if (II->getCallingConv() != CallingConv::C) {
2981 PrintCallingConv(II->getCallingConv(), Out);
2984 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
2985 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
2987 // If possible, print out the short form of the invoke instruction. We can
2988 // only do this if the first argument is a pointer to a nonvararg function,
2989 // and if the return type is not a pointer to a function.
2992 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
2994 writeOperand(Operand, false);
2996 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
2999 writeParamOperand(II->getArgOperand(op), PAL, op + 1);
3003 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
3004 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3006 writeOperandBundles(II);
3009 writeOperand(II->getNormalDest(), true);
3011 writeOperand(II->getUnwindDest(), true);
3013 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
3015 if (AI->isUsedWithInAlloca())
3017 TypePrinter.print(AI->getAllocatedType(), Out);
3019 // Explicitly write the array size if the code is broken, if it's an array
3020 // allocation, or if the type is not canonical for scalar allocations. The
3021 // latter case prevents the type from mutating when round-tripping through
3023 if (!AI->getArraySize() || AI->isArrayAllocation() ||
3024 !AI->getArraySize()->getType()->isIntegerTy(32)) {
3026 writeOperand(AI->getArraySize(), true);
3028 if (AI->getAlignment()) {
3029 Out << ", align " << AI->getAlignment();
3031 } else if (isa<CastInst>(I)) {
3034 writeOperand(Operand, true); // Work with broken code
3037 TypePrinter.print(I.getType(), Out);
3038 } else if (isa<VAArgInst>(I)) {
3041 writeOperand(Operand, true); // Work with broken code
3044 TypePrinter.print(I.getType(), Out);
3045 } else if (Operand) { // Print the normal way.
3046 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
3048 TypePrinter.print(GEP->getSourceElementType(), Out);
3050 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
3052 TypePrinter.print(LI->getType(), Out);
3056 // PrintAllTypes - Instructions who have operands of all the same type
3057 // omit the type from all but the first operand. If the instruction has
3058 // different type operands (for example br), then they are all printed.
3059 bool PrintAllTypes = false;
3060 Type *TheType = Operand->getType();
3062 // Select, Store and ShuffleVector always print all types.
3063 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
3064 || isa<ReturnInst>(I)) {
3065 PrintAllTypes = true;
3067 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
3068 Operand = I.getOperand(i);
3069 // note that Operand shouldn't be null, but the test helps make dump()
3070 // more tolerant of malformed IR
3071 if (Operand && Operand->getType() != TheType) {
3072 PrintAllTypes = true; // We have differing types! Print them all!
3078 if (!PrintAllTypes) {
3080 TypePrinter.print(TheType, Out);
3084 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
3086 writeOperand(I.getOperand(i), PrintAllTypes);
3090 // Print atomic ordering/alignment for memory operations
3091 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
3093 writeAtomic(LI->getOrdering(), LI->getSynchScope());
3094 if (LI->getAlignment())
3095 Out << ", align " << LI->getAlignment();
3096 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
3098 writeAtomic(SI->getOrdering(), SI->getSynchScope());
3099 if (SI->getAlignment())
3100 Out << ", align " << SI->getAlignment();
3101 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
3102 writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
3103 CXI->getSynchScope());
3104 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
3105 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
3106 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
3107 writeAtomic(FI->getOrdering(), FI->getSynchScope());
3110 // Print Metadata info.
3111 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
3112 I.getAllMetadata(InstMD);
3113 printMetadataAttachments(InstMD, ", ");
3115 // Print a nice comment.
3116 printInfoComment(I);
3119 void AssemblyWriter::printMetadataAttachments(
3120 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
3121 StringRef Separator) {
3125 if (MDNames.empty())
3126 TheModule->getMDKindNames(MDNames);
3128 for (const auto &I : MDs) {
3129 unsigned Kind = I.first;
3131 if (Kind < MDNames.size()) {
3133 printMetadataIdentifier(MDNames[Kind], Out);
3135 Out << "!<unknown kind #" << Kind << ">";
3137 WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
3141 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
3142 Out << '!' << Slot << " = ";
3143 printMDNodeBody(Node);
3147 void AssemblyWriter::writeAllMDNodes() {
3148 SmallVector<const MDNode *, 16> Nodes;
3149 Nodes.resize(Machine.mdn_size());
3150 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
3152 Nodes[I->second] = cast<MDNode>(I->first);
3154 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
3155 writeMDNode(i, Nodes[i]);
3159 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
3160 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
3163 void AssemblyWriter::writeAllAttributeGroups() {
3164 std::vector<std::pair<AttributeSet, unsigned> > asVec;
3165 asVec.resize(Machine.as_size());
3167 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
3169 asVec[I->second] = *I;
3171 for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
3172 I = asVec.begin(), E = asVec.end(); I != E; ++I)
3173 Out << "attributes #" << I->second << " = { "
3174 << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
3177 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
3178 bool IsInFunction = Machine.getFunction();
3182 Out << "uselistorder";
3183 if (const BasicBlock *BB =
3184 IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
3186 writeOperand(BB->getParent(), false);
3188 writeOperand(BB, false);
3191 writeOperand(Order.V, true);
3195 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3196 Out << Order.Shuffle[0];
3197 for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
3198 Out << ", " << Order.Shuffle[I];
3202 void AssemblyWriter::printUseLists(const Function *F) {
3204 [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
3209 Out << "\n; uselistorder directives\n";
3211 printUseListOrder(UseListOrders.back());
3212 UseListOrders.pop_back();
3216 //===----------------------------------------------------------------------===//
3217 // External Interface declarations
3218 //===----------------------------------------------------------------------===//
3220 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
3221 bool ShouldPreserveUseListOrder, bool IsForDebug) const {
3222 SlotTracker SlotTable(this);
3223 formatted_raw_ostream OS(ROS);
3224 AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
3225 ShouldPreserveUseListOrder);
3226 W.printModule(this);
3229 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
3230 SlotTracker SlotTable(getParent());
3231 formatted_raw_ostream OS(ROS);
3232 AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
3233 W.printNamedMDNode(this);
3236 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
3237 PrintLLVMName(ROS, getName(), ComdatPrefix);
3238 ROS << " = comdat ";
3240 switch (getSelectionKind()) {
3244 case Comdat::ExactMatch:
3245 ROS << "exactmatch";
3247 case Comdat::Largest:
3250 case Comdat::NoDuplicates:
3251 ROS << "noduplicates";
3253 case Comdat::SameSize:
3261 void Type::print(raw_ostream &OS, bool /*IsForDebug*/) const {
3263 TP.print(const_cast<Type*>(this), OS);
3265 // If the type is a named struct type, print the body as well.
3266 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
3267 if (!STy->isLiteral()) {
3269 TP.printStructBody(STy, OS);
3273 static bool isReferencingMDNode(const Instruction &I) {
3274 if (const auto *CI = dyn_cast<CallInst>(&I))
3275 if (Function *F = CI->getCalledFunction())
3276 if (F->isIntrinsic())
3277 for (auto &Op : I.operands())
3278 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
3279 if (isa<MDNode>(V->getMetadata()))
3284 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
3285 bool ShouldInitializeAllMetadata = false;
3286 if (auto *I = dyn_cast<Instruction>(this))
3287 ShouldInitializeAllMetadata = isReferencingMDNode(*I);
3288 else if (isa<Function>(this) || isa<MetadataAsValue>(this))
3289 ShouldInitializeAllMetadata = true;
3291 ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
3292 print(ROS, MST, IsForDebug);
3295 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
3296 bool IsForDebug) const {
3297 formatted_raw_ostream OS(ROS);
3298 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
3299 SlotTracker &SlotTable =
3300 MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
3301 auto incorporateFunction = [&](const Function *F) {
3303 MST.incorporateFunction(*F);
3306 if (const Instruction *I = dyn_cast<Instruction>(this)) {
3307 incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
3308 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
3309 W.printInstruction(*I);
3310 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
3311 incorporateFunction(BB->getParent());
3312 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
3313 W.printBasicBlock(BB);
3314 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
3315 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
3316 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
3318 else if (const Function *F = dyn_cast<Function>(GV))
3321 W.printAlias(cast<GlobalAlias>(GV));
3322 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
3323 V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
3324 } else if (const Constant *C = dyn_cast<Constant>(this)) {
3325 TypePrinting TypePrinter;
3326 TypePrinter.print(C->getType(), OS);
3328 WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
3329 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
3330 this->printAsOperand(OS, /* PrintType */ true, MST);
3332 llvm_unreachable("Unknown value to print out!");
3336 /// Print without a type, skipping the TypePrinting object.
3338 /// \return \c true iff printing was successful.
3339 static bool printWithoutType(const Value &V, raw_ostream &O,
3340 SlotTracker *Machine, const Module *M) {
3341 if (V.hasName() || isa<GlobalValue>(V) ||
3342 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
3343 WriteAsOperandInternal(O, &V, nullptr, Machine, M);
3349 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
3350 ModuleSlotTracker &MST) {
3351 TypePrinting TypePrinter;
3352 if (const Module *M = MST.getModule())
3353 TypePrinter.incorporateTypes(*M);
3355 TypePrinter.print(V.getType(), O);
3359 WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
3363 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3364 const Module *M) const {
3366 M = getModuleFromVal(this);
3369 if (printWithoutType(*this, O, nullptr, M))
3372 SlotTracker Machine(
3373 M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
3374 ModuleSlotTracker MST(Machine, M);
3375 printAsOperandImpl(*this, O, PrintType, MST);
3378 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3379 ModuleSlotTracker &MST) const {
3381 if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
3384 printAsOperandImpl(*this, O, PrintType, MST);
3387 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
3388 ModuleSlotTracker &MST, const Module *M,
3389 bool OnlyAsOperand) {
3390 formatted_raw_ostream OS(ROS);
3392 TypePrinting TypePrinter;
3394 TypePrinter.incorporateTypes(*M);
3396 WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
3397 /* FromValue */ true);
3399 auto *N = dyn_cast<MDNode>(&MD);
3400 if (OnlyAsOperand || !N)
3404 WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
3407 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
3408 ModuleSlotTracker MST(M, isa<MDNode>(this));
3409 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3412 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
3413 const Module *M) const {
3414 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3417 void Metadata::print(raw_ostream &OS, const Module *M,
3418 bool /*IsForDebug*/) const {
3419 ModuleSlotTracker MST(M, isa<MDNode>(this));
3420 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3423 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
3424 const Module *M, bool /*IsForDebug*/) const {
3425 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3428 // Value::dump - allow easy printing of Values from the debugger.
3430 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3432 // Type::dump - allow easy printing of Types from the debugger.
3434 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3436 // Module::dump() - Allow printing of Modules from the debugger.
3438 void Module::dump() const {
3439 print(dbgs(), nullptr,
3440 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
3443 // \brief Allow printing of Comdats from the debugger.
3445 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3447 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
3449 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3452 void Metadata::dump() const { dump(nullptr); }
3455 void Metadata::dump(const Module *M) const {
3456 print(dbgs(), M, /*IsForDebug=*/true);