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 "AsmWriter.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/STLExtras.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/Operator.h"
34 #include "llvm/IR/TypeFinder.h"
35 #include "llvm/IR/ValueSymbolTable.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/Dwarf.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/FormattedStream.h"
40 #include "llvm/Support/MathExtras.h"
45 // Make virtual table appear in this compilation unit.
46 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
48 //===----------------------------------------------------------------------===//
50 //===----------------------------------------------------------------------===//
52 static const Module *getModuleFromVal(const Value *V) {
53 if (const Argument *MA = dyn_cast<Argument>(V))
54 return MA->getParent() ? MA->getParent()->getParent() : nullptr;
56 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
57 return BB->getParent() ? BB->getParent()->getParent() : nullptr;
59 if (const Instruction *I = dyn_cast<Instruction>(V)) {
60 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
61 return M ? M->getParent() : nullptr;
64 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
65 return GV->getParent();
69 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
71 default: Out << "cc" << cc; break;
72 case CallingConv::Fast: Out << "fastcc"; break;
73 case CallingConv::Cold: Out << "coldcc"; break;
74 case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
75 case CallingConv::AnyReg: Out << "anyregcc"; break;
76 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
77 case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
78 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
79 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
80 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
81 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
82 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
83 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
84 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
85 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
86 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
87 case CallingConv::PTX_Device: Out << "ptx_device"; break;
88 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
89 case CallingConv::X86_64_Win64: Out << "x86_64_win64cc"; break;
90 case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
91 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
95 // PrintEscapedString - Print each character of the specified string, escaping
96 // it if it is not printable or if it is an escape char.
97 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
98 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
99 unsigned char C = Name[i];
100 if (isprint(C) && C != '\\' && C != '"')
103 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
115 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
116 /// prefixed with % (if the string only contains simple characters) or is
117 /// surrounded with ""'s (if it has special chars in it). Print it out.
118 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
119 assert(!Name.empty() && "Cannot get empty name!");
121 case NoPrefix: break;
122 case GlobalPrefix: OS << '@'; break;
123 case ComdatPrefix: OS << '$'; break;
124 case LabelPrefix: break;
125 case LocalPrefix: OS << '%'; break;
128 // Scan the name to see if it needs quotes first.
129 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
131 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
132 // By making this unsigned, the value passed in to isalnum will always be
133 // in the range 0-255. This is important when building with MSVC because
134 // its implementation will assert. This situation can arise when dealing
135 // with UTF-8 multibyte characters.
136 unsigned char C = Name[i];
137 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
145 // If we didn't need any quotes, just write out the name in one blast.
151 // Okay, we need quotes. Output the quotes and escape any scary characters as
154 PrintEscapedString(Name, OS);
158 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
159 /// prefixed with % (if the string only contains simple characters) or is
160 /// surrounded with ""'s (if it has special chars in it). Print it out.
161 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
162 PrintLLVMName(OS, V->getName(),
163 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
169 void TypePrinting::incorporateTypes(const Module &M) {
170 NamedTypes.run(M, false);
172 // The list of struct types we got back includes all the struct types, split
173 // the unnamed ones out to a numbering and remove the anonymous structs.
174 unsigned NextNumber = 0;
176 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
177 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
178 StructType *STy = *I;
180 // Ignore anonymous types.
181 if (STy->isLiteral())
184 if (STy->getName().empty())
185 NumberedTypes[STy] = NextNumber++;
190 NamedTypes.erase(NextToUse, NamedTypes.end());
194 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
195 /// use of type names or up references to shorten the type name where possible.
196 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
197 switch (Ty->getTypeID()) {
198 case Type::VoidTyID: OS << "void"; return;
199 case Type::HalfTyID: OS << "half"; return;
200 case Type::FloatTyID: OS << "float"; return;
201 case Type::DoubleTyID: OS << "double"; return;
202 case Type::X86_FP80TyID: OS << "x86_fp80"; return;
203 case Type::FP128TyID: OS << "fp128"; return;
204 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
205 case Type::LabelTyID: OS << "label"; return;
206 case Type::MetadataTyID: OS << "metadata"; return;
207 case Type::X86_MMXTyID: OS << "x86_mmx"; return;
208 case Type::IntegerTyID:
209 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
212 case Type::FunctionTyID: {
213 FunctionType *FTy = cast<FunctionType>(Ty);
214 print(FTy->getReturnType(), OS);
216 for (FunctionType::param_iterator I = FTy->param_begin(),
217 E = FTy->param_end(); I != E; ++I) {
218 if (I != FTy->param_begin())
222 if (FTy->isVarArg()) {
223 if (FTy->getNumParams()) OS << ", ";
229 case Type::StructTyID: {
230 StructType *STy = cast<StructType>(Ty);
232 if (STy->isLiteral())
233 return printStructBody(STy, OS);
235 if (!STy->getName().empty())
236 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
238 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
239 if (I != NumberedTypes.end())
240 OS << '%' << I->second;
241 else // Not enumerated, print the hex address.
242 OS << "%\"type " << STy << '\"';
245 case Type::PointerTyID: {
246 PointerType *PTy = cast<PointerType>(Ty);
247 print(PTy->getElementType(), OS);
248 if (unsigned AddressSpace = PTy->getAddressSpace())
249 OS << " addrspace(" << AddressSpace << ')';
253 case Type::ArrayTyID: {
254 ArrayType *ATy = cast<ArrayType>(Ty);
255 OS << '[' << ATy->getNumElements() << " x ";
256 print(ATy->getElementType(), OS);
260 case Type::VectorTyID: {
261 VectorType *PTy = cast<VectorType>(Ty);
262 OS << "<" << PTy->getNumElements() << " x ";
263 print(PTy->getElementType(), OS);
268 llvm_unreachable("Invalid TypeID");
271 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
272 if (STy->isOpaque()) {
280 if (STy->getNumElements() == 0) {
283 StructType::element_iterator I = STy->element_begin();
286 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
297 //===----------------------------------------------------------------------===//
298 // SlotTracker Class: Enumerate slot numbers for unnamed values
299 //===----------------------------------------------------------------------===//
300 /// This class provides computation of slot numbers for LLVM Assembly writing.
304 /// ValueMap - A mapping of Values to slot numbers.
305 typedef DenseMap<const Value*, unsigned> ValueMap;
308 /// TheModule - The module for which we are holding slot numbers.
309 const Module* TheModule;
311 /// TheFunction - The function for which we are holding slot numbers.
312 const Function* TheFunction;
313 bool FunctionProcessed;
315 /// mMap - The slot map for the module level data.
319 /// fMap - The slot map for the function level data.
323 /// mdnMap - Map for MDNodes.
324 DenseMap<const MDNode*, unsigned> mdnMap;
327 /// asMap - The slot map for attribute sets.
328 DenseMap<AttributeSet, unsigned> asMap;
331 /// Construct from a module
332 explicit SlotTracker(const Module *M);
333 /// Construct from a function, starting out in incorp state.
334 explicit SlotTracker(const Function *F);
336 /// Return the slot number of the specified value in it's type
337 /// plane. If something is not in the SlotTracker, return -1.
338 int getLocalSlot(const Value *V);
339 int getGlobalSlot(const GlobalValue *V);
340 int getMetadataSlot(const MDNode *N);
341 int getAttributeGroupSlot(AttributeSet AS);
343 /// If you'd like to deal with a function instead of just a module, use
344 /// this method to get its data into the SlotTracker.
345 void incorporateFunction(const Function *F) {
347 FunctionProcessed = false;
350 /// After calling incorporateFunction, use this method to remove the
351 /// most recently incorporated function from the SlotTracker. This
352 /// will reset the state of the machine back to just the module contents.
353 void purgeFunction();
355 /// MDNode map iterators.
356 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
357 mdn_iterator mdn_begin() { return mdnMap.begin(); }
358 mdn_iterator mdn_end() { return mdnMap.end(); }
359 unsigned mdn_size() const { return mdnMap.size(); }
360 bool mdn_empty() const { return mdnMap.empty(); }
362 /// AttributeSet map iterators.
363 typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
364 as_iterator as_begin() { return asMap.begin(); }
365 as_iterator as_end() { return asMap.end(); }
366 unsigned as_size() const { return asMap.size(); }
367 bool as_empty() const { return asMap.empty(); }
369 /// This function does the actual initialization.
370 inline void initialize();
372 // Implementation Details
374 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
375 void CreateModuleSlot(const GlobalValue *V);
377 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
378 void CreateMetadataSlot(const MDNode *N);
380 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
381 void CreateFunctionSlot(const Value *V);
383 /// \brief Insert the specified AttributeSet into the slot table.
384 void CreateAttributeSetSlot(AttributeSet AS);
386 /// Add all of the module level global variables (and their initializers)
387 /// and function declarations, but not the contents of those functions.
388 void processModule();
390 /// Add all of the functions arguments, basic blocks, and instructions.
391 void processFunction();
393 SlotTracker(const SlotTracker &) LLVM_DELETED_FUNCTION;
394 void operator=(const SlotTracker &) LLVM_DELETED_FUNCTION;
397 SlotTracker *createSlotTracker(const Module *M) {
398 return new SlotTracker(M);
401 static SlotTracker *createSlotTracker(const Value *V) {
402 if (const Argument *FA = dyn_cast<Argument>(V))
403 return new SlotTracker(FA->getParent());
405 if (const Instruction *I = dyn_cast<Instruction>(V))
407 return new SlotTracker(I->getParent()->getParent());
409 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
410 return new SlotTracker(BB->getParent());
412 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
413 return new SlotTracker(GV->getParent());
415 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
416 return new SlotTracker(GA->getParent());
418 if (const Function *Func = dyn_cast<Function>(V))
419 return new SlotTracker(Func);
421 if (const MDNode *MD = dyn_cast<MDNode>(V)) {
422 if (!MD->isFunctionLocal())
423 return new SlotTracker(MD->getFunction());
425 return new SlotTracker((Function *)nullptr);
432 #define ST_DEBUG(X) dbgs() << X
437 // Module level constructor. Causes the contents of the Module (sans functions)
438 // to be added to the slot table.
439 SlotTracker::SlotTracker(const Module *M)
440 : TheModule(M), TheFunction(nullptr), FunctionProcessed(false),
441 mNext(0), fNext(0), mdnNext(0), asNext(0) {
444 // Function level constructor. Causes the contents of the Module and the one
445 // function provided to be added to the slot table.
446 SlotTracker::SlotTracker(const Function *F)
447 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
448 FunctionProcessed(false), mNext(0), fNext(0), mdnNext(0), asNext(0) {
451 inline void SlotTracker::initialize() {
454 TheModule = nullptr; ///< Prevent re-processing next time we're called.
457 if (TheFunction && !FunctionProcessed)
461 // Iterate through all the global variables, functions, and global
462 // variable initializers and create slots for them.
463 void SlotTracker::processModule() {
464 ST_DEBUG("begin processModule!\n");
466 // Add all of the unnamed global variables to the value table.
467 for (Module::const_global_iterator I = TheModule->global_begin(),
468 E = TheModule->global_end(); I != E; ++I) {
473 // Add metadata used by named metadata.
474 for (Module::const_named_metadata_iterator
475 I = TheModule->named_metadata_begin(),
476 E = TheModule->named_metadata_end(); I != E; ++I) {
477 const NamedMDNode *NMD = I;
478 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
479 CreateMetadataSlot(NMD->getOperand(i));
482 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
485 // Add all the unnamed functions to the table.
488 // Add all the function attributes to the table.
489 // FIXME: Add attributes of other objects?
490 AttributeSet FnAttrs = I->getAttributes().getFnAttributes();
491 if (FnAttrs.hasAttributes(AttributeSet::FunctionIndex))
492 CreateAttributeSetSlot(FnAttrs);
495 ST_DEBUG("end processModule!\n");
498 // Process the arguments, basic blocks, and instructions of a function.
499 void SlotTracker::processFunction() {
500 ST_DEBUG("begin processFunction!\n");
503 // Add all the function arguments with no names.
504 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
505 AE = TheFunction->arg_end(); AI != AE; ++AI)
507 CreateFunctionSlot(AI);
509 ST_DEBUG("Inserting Instructions:\n");
511 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
513 // Add all of the basic blocks and instructions with no names.
514 for (Function::const_iterator BB = TheFunction->begin(),
515 E = TheFunction->end(); BB != E; ++BB) {
517 CreateFunctionSlot(BB);
519 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
521 if (!I->getType()->isVoidTy() && !I->hasName())
522 CreateFunctionSlot(I);
524 // Intrinsics can directly use metadata. We allow direct calls to any
525 // llvm.foo function here, because the target may not be linked into the
527 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
528 if (Function *F = CI->getCalledFunction())
529 if (F->isIntrinsic())
530 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
531 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
532 CreateMetadataSlot(N);
534 // Add all the call attributes to the table.
535 AttributeSet Attrs = CI->getAttributes().getFnAttributes();
536 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
537 CreateAttributeSetSlot(Attrs);
538 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(I)) {
539 // Add all the call attributes to the table.
540 AttributeSet Attrs = II->getAttributes().getFnAttributes();
541 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
542 CreateAttributeSetSlot(Attrs);
545 // Process metadata attached with this instruction.
546 I->getAllMetadata(MDForInst);
547 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
548 CreateMetadataSlot(MDForInst[i].second);
553 FunctionProcessed = true;
555 ST_DEBUG("end processFunction!\n");
558 /// Clean up after incorporating a function. This is the only way to get out of
559 /// the function incorporation state that affects get*Slot/Create*Slot. Function
560 /// incorporation state is indicated by TheFunction != 0.
561 void SlotTracker::purgeFunction() {
562 ST_DEBUG("begin purgeFunction!\n");
563 fMap.clear(); // Simply discard the function level map
564 TheFunction = nullptr;
565 FunctionProcessed = false;
566 ST_DEBUG("end purgeFunction!\n");
569 /// getGlobalSlot - Get the slot number of a global value.
570 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
571 // Check for uninitialized state and do lazy initialization.
574 // Find the value in the module map
575 ValueMap::iterator MI = mMap.find(V);
576 return MI == mMap.end() ? -1 : (int)MI->second;
579 /// getMetadataSlot - Get the slot number of a MDNode.
580 int SlotTracker::getMetadataSlot(const MDNode *N) {
581 // Check for uninitialized state and do lazy initialization.
584 // Find the MDNode in the module map
585 mdn_iterator MI = mdnMap.find(N);
586 return MI == mdnMap.end() ? -1 : (int)MI->second;
590 /// getLocalSlot - Get the slot number for a value that is local to a function.
591 int SlotTracker::getLocalSlot(const Value *V) {
592 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
594 // Check for uninitialized state and do lazy initialization.
597 ValueMap::iterator FI = fMap.find(V);
598 return FI == fMap.end() ? -1 : (int)FI->second;
601 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
602 // Check for uninitialized state and do lazy initialization.
605 // Find the AttributeSet in the module map.
606 as_iterator AI = asMap.find(AS);
607 return AI == asMap.end() ? -1 : (int)AI->second;
610 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
611 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
612 assert(V && "Can't insert a null Value into SlotTracker!");
613 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
614 assert(!V->hasName() && "Doesn't need a slot!");
616 unsigned DestSlot = mNext++;
619 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
621 // G = Global, F = Function, A = Alias, o = other
622 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
623 (isa<Function>(V) ? 'F' :
624 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
627 /// CreateSlot - Create a new slot for the specified value if it has no name.
628 void SlotTracker::CreateFunctionSlot(const Value *V) {
629 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
631 unsigned DestSlot = fNext++;
634 // G = Global, F = Function, o = other
635 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
636 DestSlot << " [o]\n");
639 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
640 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
641 assert(N && "Can't insert a null Value into SlotTracker!");
643 // Don't insert if N is a function-local metadata, these are always printed
645 if (!N->isFunctionLocal()) {
646 mdn_iterator I = mdnMap.find(N);
647 if (I != mdnMap.end())
650 unsigned DestSlot = mdnNext++;
651 mdnMap[N] = DestSlot;
654 // Recursively add any MDNodes referenced by operands.
655 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
656 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
657 CreateMetadataSlot(Op);
660 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
661 assert(AS.hasAttributes(AttributeSet::FunctionIndex) &&
662 "Doesn't need a slot!");
664 as_iterator I = asMap.find(AS);
665 if (I != asMap.end())
668 unsigned DestSlot = asNext++;
669 asMap[AS] = DestSlot;
672 //===----------------------------------------------------------------------===//
673 // AsmWriter Implementation
674 //===----------------------------------------------------------------------===//
676 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
677 TypePrinting *TypePrinter,
678 SlotTracker *Machine,
679 const Module *Context);
681 static const char *getPredicateText(unsigned predicate) {
682 const char * pred = "unknown";
684 case FCmpInst::FCMP_FALSE: pred = "false"; break;
685 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
686 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
687 case FCmpInst::FCMP_OGE: pred = "oge"; break;
688 case FCmpInst::FCMP_OLT: pred = "olt"; break;
689 case FCmpInst::FCMP_OLE: pred = "ole"; break;
690 case FCmpInst::FCMP_ONE: pred = "one"; break;
691 case FCmpInst::FCMP_ORD: pred = "ord"; break;
692 case FCmpInst::FCMP_UNO: pred = "uno"; break;
693 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
694 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
695 case FCmpInst::FCMP_UGE: pred = "uge"; break;
696 case FCmpInst::FCMP_ULT: pred = "ult"; break;
697 case FCmpInst::FCMP_ULE: pred = "ule"; break;
698 case FCmpInst::FCMP_UNE: pred = "une"; break;
699 case FCmpInst::FCMP_TRUE: pred = "true"; break;
700 case ICmpInst::ICMP_EQ: pred = "eq"; break;
701 case ICmpInst::ICMP_NE: pred = "ne"; break;
702 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
703 case ICmpInst::ICMP_SGE: pred = "sge"; break;
704 case ICmpInst::ICMP_SLT: pred = "slt"; break;
705 case ICmpInst::ICMP_SLE: pred = "sle"; break;
706 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
707 case ICmpInst::ICMP_UGE: pred = "uge"; break;
708 case ICmpInst::ICMP_ULT: pred = "ult"; break;
709 case ICmpInst::ICMP_ULE: pred = "ule"; break;
714 static void writeAtomicRMWOperation(raw_ostream &Out,
715 AtomicRMWInst::BinOp Op) {
717 default: Out << " <unknown operation " << Op << ">"; break;
718 case AtomicRMWInst::Xchg: Out << " xchg"; break;
719 case AtomicRMWInst::Add: Out << " add"; break;
720 case AtomicRMWInst::Sub: Out << " sub"; break;
721 case AtomicRMWInst::And: Out << " and"; break;
722 case AtomicRMWInst::Nand: Out << " nand"; break;
723 case AtomicRMWInst::Or: Out << " or"; break;
724 case AtomicRMWInst::Xor: Out << " xor"; break;
725 case AtomicRMWInst::Max: Out << " max"; break;
726 case AtomicRMWInst::Min: Out << " min"; break;
727 case AtomicRMWInst::UMax: Out << " umax"; break;
728 case AtomicRMWInst::UMin: Out << " umin"; break;
732 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
733 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
734 // Unsafe algebra implies all the others, no need to write them all out
735 if (FPO->hasUnsafeAlgebra())
738 if (FPO->hasNoNaNs())
740 if (FPO->hasNoInfs())
742 if (FPO->hasNoSignedZeros())
744 if (FPO->hasAllowReciprocal())
749 if (const OverflowingBinaryOperator *OBO =
750 dyn_cast<OverflowingBinaryOperator>(U)) {
751 if (OBO->hasNoUnsignedWrap())
753 if (OBO->hasNoSignedWrap())
755 } else if (const PossiblyExactOperator *Div =
756 dyn_cast<PossiblyExactOperator>(U)) {
759 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
760 if (GEP->isInBounds())
765 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
766 TypePrinting &TypePrinter,
767 SlotTracker *Machine,
768 const Module *Context) {
769 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
770 if (CI->getType()->isIntegerTy(1)) {
771 Out << (CI->getZExtValue() ? "true" : "false");
774 Out << CI->getValue();
778 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
779 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
780 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
781 // We would like to output the FP constant value in exponential notation,
782 // but we cannot do this if doing so will lose precision. Check here to
783 // make sure that we only output it in exponential format if we can parse
784 // the value back and get the same value.
787 bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
788 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
789 bool isInf = CFP->getValueAPF().isInfinity();
790 bool isNaN = CFP->getValueAPF().isNaN();
791 if (!isHalf && !isInf && !isNaN) {
792 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
793 CFP->getValueAPF().convertToFloat();
794 SmallString<128> StrVal;
795 raw_svector_ostream(StrVal) << Val;
797 // Check to make sure that the stringized number is not some string like
798 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
799 // that the string matches the "[-+]?[0-9]" regex.
801 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
802 ((StrVal[0] == '-' || StrVal[0] == '+') &&
803 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
804 // Reparse stringized version!
805 if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
811 // Otherwise we could not reparse it to exactly the same value, so we must
812 // output the string in hexadecimal format! Note that loading and storing
813 // floating point types changes the bits of NaNs on some hosts, notably
814 // x86, so we must not use these types.
815 static_assert(sizeof(double) == sizeof(uint64_t),
816 "assuming that double is 64 bits!");
818 APFloat apf = CFP->getValueAPF();
819 // Halves and floats are represented in ASCII IR as double, convert.
821 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
824 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
829 // Either half, or some form of long double.
830 // These appear as a magic letter identifying the type, then a
831 // fixed number of hex digits.
833 // Bit position, in the current word, of the next nibble to print.
836 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
838 // api needed to prevent premature destruction
839 APInt api = CFP->getValueAPF().bitcastToAPInt();
840 const uint64_t* p = api.getRawData();
841 uint64_t word = p[1];
843 int width = api.getBitWidth();
844 for (int j=0; j<width; j+=4, shiftcount-=4) {
845 unsigned int nibble = (word>>shiftcount) & 15;
847 Out << (unsigned char)(nibble + '0');
849 Out << (unsigned char)(nibble - 10 + 'A');
850 if (shiftcount == 0 && j+4 < width) {
854 shiftcount = width-j-4;
858 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
861 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
864 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
868 llvm_unreachable("Unsupported floating point type");
869 // api needed to prevent premature destruction
870 APInt api = CFP->getValueAPF().bitcastToAPInt();
871 const uint64_t* p = api.getRawData();
873 int width = api.getBitWidth();
874 for (int j=0; j<width; j+=4, shiftcount-=4) {
875 unsigned int nibble = (word>>shiftcount) & 15;
877 Out << (unsigned char)(nibble + '0');
879 Out << (unsigned char)(nibble - 10 + 'A');
880 if (shiftcount == 0 && j+4 < width) {
884 shiftcount = width-j-4;
890 if (isa<ConstantAggregateZero>(CV)) {
891 Out << "zeroinitializer";
895 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
896 Out << "blockaddress(";
897 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
900 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
906 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
907 Type *ETy = CA->getType()->getElementType();
909 TypePrinter.print(ETy, Out);
911 WriteAsOperandInternal(Out, CA->getOperand(0),
912 &TypePrinter, Machine,
914 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
916 TypePrinter.print(ETy, Out);
918 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
925 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
926 // As a special case, print the array as a string if it is an array of
927 // i8 with ConstantInt values.
928 if (CA->isString()) {
930 PrintEscapedString(CA->getAsString(), Out);
935 Type *ETy = CA->getType()->getElementType();
937 TypePrinter.print(ETy, Out);
939 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
940 &TypePrinter, Machine,
942 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
944 TypePrinter.print(ETy, Out);
946 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
954 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
955 if (CS->getType()->isPacked())
958 unsigned N = CS->getNumOperands();
961 TypePrinter.print(CS->getOperand(0)->getType(), Out);
964 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
967 for (unsigned i = 1; i < N; i++) {
969 TypePrinter.print(CS->getOperand(i)->getType(), Out);
972 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
979 if (CS->getType()->isPacked())
984 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
985 Type *ETy = CV->getType()->getVectorElementType();
987 TypePrinter.print(ETy, Out);
989 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
991 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
993 TypePrinter.print(ETy, Out);
995 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1002 if (isa<ConstantPointerNull>(CV)) {
1007 if (isa<UndefValue>(CV)) {
1012 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1013 Out << CE->getOpcodeName();
1014 WriteOptimizationInfo(Out, CE);
1015 if (CE->isCompare())
1016 Out << ' ' << getPredicateText(CE->getPredicate());
1019 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1020 TypePrinter.print((*OI)->getType(), Out);
1022 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1023 if (OI+1 != CE->op_end())
1027 if (CE->hasIndices()) {
1028 ArrayRef<unsigned> Indices = CE->getIndices();
1029 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1030 Out << ", " << Indices[i];
1035 TypePrinter.print(CE->getType(), Out);
1042 Out << "<placeholder or erroneous Constant>";
1045 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1046 TypePrinting *TypePrinter,
1047 SlotTracker *Machine,
1048 const Module *Context) {
1050 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1051 const Value *V = Node->getOperand(mi);
1055 TypePrinter->print(V->getType(), Out);
1057 WriteAsOperandInternal(Out, Node->getOperand(mi),
1058 TypePrinter, Machine, Context);
1067 // Full implementation of printing a Value as an operand with support for
1068 // TypePrinting, etc.
1069 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1070 TypePrinting *TypePrinter,
1071 SlotTracker *Machine,
1072 const Module *Context) {
1074 PrintLLVMName(Out, V);
1078 const Constant *CV = dyn_cast<Constant>(V);
1079 if (CV && !isa<GlobalValue>(CV)) {
1080 assert(TypePrinter && "Constants require TypePrinting!");
1081 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1085 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1087 if (IA->hasSideEffects())
1088 Out << "sideeffect ";
1089 if (IA->isAlignStack())
1090 Out << "alignstack ";
1091 // We don't emit the AD_ATT dialect as it's the assumed default.
1092 if (IA->getDialect() == InlineAsm::AD_Intel)
1093 Out << "inteldialect ";
1095 PrintEscapedString(IA->getAsmString(), Out);
1097 PrintEscapedString(IA->getConstraintString(), Out);
1102 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1103 if (N->isFunctionLocal()) {
1104 // Print metadata inline, not via slot reference number.
1105 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
1110 if (N->isFunctionLocal())
1111 Machine = new SlotTracker(N->getFunction());
1113 Machine = new SlotTracker(Context);
1115 int Slot = Machine->getMetadataSlot(N);
1123 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1125 PrintEscapedString(MDS->getString(), Out);
1132 // If we have a SlotTracker, use it.
1134 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1135 Slot = Machine->getGlobalSlot(GV);
1138 Slot = Machine->getLocalSlot(V);
1140 // If the local value didn't succeed, then we may be referring to a value
1141 // from a different function. Translate it, as this can happen when using
1142 // address of blocks.
1144 if ((Machine = createSlotTracker(V))) {
1145 Slot = Machine->getLocalSlot(V);
1149 } else if ((Machine = createSlotTracker(V))) {
1150 // Otherwise, create one to get the # and then destroy it.
1151 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1152 Slot = Machine->getGlobalSlot(GV);
1155 Slot = Machine->getLocalSlot(V);
1164 Out << Prefix << Slot;
1169 void AssemblyWriter::init() {
1172 TypePrinter.incorporateTypes(*TheModule);
1173 for (const Function &F : *TheModule)
1174 if (const Comdat *C = F.getComdat())
1176 for (const GlobalVariable &GV : TheModule->globals())
1177 if (const Comdat *C = GV.getComdat())
1182 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1184 AssemblyAnnotationWriter *AAW)
1185 : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW) {
1189 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, const Module *M,
1190 AssemblyAnnotationWriter *AAW)
1191 : Out(o), TheModule(M), ModuleSlotTracker(createSlotTracker(M)),
1192 Machine(*ModuleSlotTracker), AnnotationWriter(AAW) {
1196 AssemblyWriter::~AssemblyWriter() { }
1198 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1200 Out << "<null operand!>";
1204 TypePrinter.print(Operand->getType(), Out);
1207 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1210 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
1211 SynchronizationScope SynchScope) {
1212 if (Ordering == NotAtomic)
1215 switch (SynchScope) {
1216 case SingleThread: Out << " singlethread"; break;
1217 case CrossThread: break;
1221 default: Out << " <bad ordering " << int(Ordering) << ">"; break;
1222 case Unordered: Out << " unordered"; break;
1223 case Monotonic: Out << " monotonic"; break;
1224 case Acquire: Out << " acquire"; break;
1225 case Release: Out << " release"; break;
1226 case AcquireRelease: Out << " acq_rel"; break;
1227 case SequentiallyConsistent: Out << " seq_cst"; break;
1231 void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
1232 AtomicOrdering FailureOrdering,
1233 SynchronizationScope SynchScope) {
1234 assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic);
1236 switch (SynchScope) {
1237 case SingleThread: Out << " singlethread"; break;
1238 case CrossThread: break;
1241 switch (SuccessOrdering) {
1242 default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break;
1243 case Unordered: Out << " unordered"; break;
1244 case Monotonic: Out << " monotonic"; break;
1245 case Acquire: Out << " acquire"; break;
1246 case Release: Out << " release"; break;
1247 case AcquireRelease: Out << " acq_rel"; break;
1248 case SequentiallyConsistent: Out << " seq_cst"; break;
1251 switch (FailureOrdering) {
1252 default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break;
1253 case Unordered: Out << " unordered"; break;
1254 case Monotonic: Out << " monotonic"; break;
1255 case Acquire: Out << " acquire"; break;
1256 case Release: Out << " release"; break;
1257 case AcquireRelease: Out << " acq_rel"; break;
1258 case SequentiallyConsistent: Out << " seq_cst"; break;
1262 void AssemblyWriter::writeParamOperand(const Value *Operand,
1263 AttributeSet Attrs, unsigned Idx) {
1265 Out << "<null operand!>";
1270 TypePrinter.print(Operand->getType(), Out);
1271 // Print parameter attributes list
1272 if (Attrs.hasAttributes(Idx))
1273 Out << ' ' << Attrs.getAsString(Idx);
1275 // Print the operand
1276 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1279 void AssemblyWriter::printModule(const Module *M) {
1280 Machine.initialize();
1282 if (!M->getModuleIdentifier().empty() &&
1283 // Don't print the ID if it will start a new line (which would
1284 // require a comment char before it).
1285 M->getModuleIdentifier().find('\n') == std::string::npos)
1286 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1288 const std::string &DL = M->getDataLayoutStr();
1290 Out << "target datalayout = \"" << DL << "\"\n";
1291 if (!M->getTargetTriple().empty())
1292 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1294 if (!M->getModuleInlineAsm().empty()) {
1295 // Split the string into lines, to make it easier to read the .ll file.
1296 std::string Asm = M->getModuleInlineAsm();
1298 size_t NewLine = Asm.find_first_of('\n', CurPos);
1300 while (NewLine != std::string::npos) {
1301 // We found a newline, print the portion of the asm string from the
1302 // last newline up to this newline.
1303 Out << "module asm \"";
1304 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1308 NewLine = Asm.find_first_of('\n', CurPos);
1310 std::string rest(Asm.begin()+CurPos, Asm.end());
1311 if (!rest.empty()) {
1312 Out << "module asm \"";
1313 PrintEscapedString(rest, Out);
1318 printTypeIdentities();
1320 // Output all comdats.
1321 if (!Comdats.empty())
1323 for (const Comdat *C : Comdats) {
1325 if (C != Comdats.back())
1329 // Output all globals.
1330 if (!M->global_empty()) Out << '\n';
1331 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1333 printGlobal(I); Out << '\n';
1336 // Output all aliases.
1337 if (!M->alias_empty()) Out << "\n";
1338 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1342 // Output all of the functions.
1343 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1346 // Output all attribute groups.
1347 if (!Machine.as_empty()) {
1349 writeAllAttributeGroups();
1352 // Output named metadata.
1353 if (!M->named_metadata_empty()) Out << '\n';
1355 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1356 E = M->named_metadata_end(); I != E; ++I)
1357 printNamedMDNode(I);
1360 if (!Machine.mdn_empty()) {
1366 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1368 StringRef Name = NMD->getName();
1370 Out << "<empty name> ";
1372 if (isalpha(static_cast<unsigned char>(Name[0])) ||
1373 Name[0] == '-' || Name[0] == '$' ||
1374 Name[0] == '.' || Name[0] == '_')
1377 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
1378 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
1379 unsigned char C = Name[i];
1380 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
1381 C == '.' || C == '_')
1384 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1388 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1390 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
1400 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1401 formatted_raw_ostream &Out) {
1403 case GlobalValue::ExternalLinkage: break;
1404 case GlobalValue::PrivateLinkage: Out << "private "; break;
1405 case GlobalValue::InternalLinkage: Out << "internal "; break;
1406 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1407 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1408 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1409 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1410 case GlobalValue::CommonLinkage: Out << "common "; break;
1411 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1412 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1413 case GlobalValue::AvailableExternallyLinkage:
1414 Out << "available_externally ";
1420 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1421 formatted_raw_ostream &Out) {
1423 case GlobalValue::DefaultVisibility: break;
1424 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1425 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1429 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
1430 formatted_raw_ostream &Out) {
1432 case GlobalValue::DefaultStorageClass: break;
1433 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
1434 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
1438 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
1439 formatted_raw_ostream &Out) {
1441 case GlobalVariable::NotThreadLocal:
1443 case GlobalVariable::GeneralDynamicTLSModel:
1444 Out << "thread_local ";
1446 case GlobalVariable::LocalDynamicTLSModel:
1447 Out << "thread_local(localdynamic) ";
1449 case GlobalVariable::InitialExecTLSModel:
1450 Out << "thread_local(initialexec) ";
1452 case GlobalVariable::LocalExecTLSModel:
1453 Out << "thread_local(localexec) ";
1458 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1459 if (GV->isMaterializable())
1460 Out << "; Materializable\n";
1462 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
1465 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1468 PrintLinkage(GV->getLinkage(), Out);
1469 PrintVisibility(GV->getVisibility(), Out);
1470 PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
1471 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
1472 if (GV->hasUnnamedAddr())
1473 Out << "unnamed_addr ";
1475 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1476 Out << "addrspace(" << AddressSpace << ") ";
1477 if (GV->isExternallyInitialized()) Out << "externally_initialized ";
1478 Out << (GV->isConstant() ? "constant " : "global ");
1479 TypePrinter.print(GV->getType()->getElementType(), Out);
1481 if (GV->hasInitializer()) {
1483 writeOperand(GV->getInitializer(), false);
1486 if (GV->hasSection()) {
1487 Out << ", section \"";
1488 PrintEscapedString(GV->getSection(), Out);
1491 if (GV->hasComdat()) {
1493 PrintLLVMName(Out, GV->getComdat()->getName(), ComdatPrefix);
1495 if (GV->getAlignment())
1496 Out << ", align " << GV->getAlignment();
1498 printInfoComment(*GV);
1501 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1502 if (GA->isMaterializable())
1503 Out << "; Materializable\n";
1505 // Don't crash when dumping partially built GA
1507 Out << "<<nameless>> = ";
1509 PrintLLVMName(Out, GA);
1512 PrintVisibility(GA->getVisibility(), Out);
1513 PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
1514 PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
1515 if (GA->hasUnnamedAddr())
1516 Out << "unnamed_addr ";
1520 PrintLinkage(GA->getLinkage(), Out);
1522 const Constant *Aliasee = GA->getAliasee();
1525 TypePrinter.print(GA->getType(), Out);
1526 Out << " <<NULL ALIASEE>>";
1528 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
1531 if (GA->hasComdat()) {
1533 PrintLLVMName(Out, GA->getComdat()->getName(), ComdatPrefix);
1536 printInfoComment(*GA);
1540 void AssemblyWriter::printComdat(const Comdat *C) {
1544 void AssemblyWriter::printTypeIdentities() {
1545 if (TypePrinter.NumberedTypes.empty() &&
1546 TypePrinter.NamedTypes.empty())
1551 // We know all the numbers that each type is used and we know that it is a
1552 // dense assignment. Convert the map to an index table.
1553 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
1554 for (DenseMap<StructType*, unsigned>::iterator I =
1555 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
1557 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
1558 NumberedTypes[I->second] = I->first;
1561 // Emit all numbered types.
1562 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1563 Out << '%' << i << " = type ";
1565 // Make sure we print out at least one level of the type structure, so
1566 // that we do not get %2 = type %2
1567 TypePrinter.printStructBody(NumberedTypes[i], Out);
1571 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
1572 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
1575 // Make sure we print out at least one level of the type structure, so
1576 // that we do not get %FILE = type %FILE
1577 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
1582 /// printFunction - Print all aspects of a function.
1584 void AssemblyWriter::printFunction(const Function *F) {
1585 // Print out the return type and name.
1588 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1590 if (F->isMaterializable())
1591 Out << "; Materializable\n";
1593 const AttributeSet &Attrs = F->getAttributes();
1594 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
1595 AttributeSet AS = Attrs.getFnAttributes();
1596 std::string AttrStr;
1599 for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
1600 if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
1603 for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
1605 Attribute Attr = *I;
1606 if (!Attr.isStringAttribute()) {
1607 if (!AttrStr.empty()) AttrStr += ' ';
1608 AttrStr += Attr.getAsString();
1612 if (!AttrStr.empty())
1613 Out << "; Function Attrs: " << AttrStr << '\n';
1616 if (F->isDeclaration())
1621 PrintLinkage(F->getLinkage(), Out);
1622 PrintVisibility(F->getVisibility(), Out);
1623 PrintDLLStorageClass(F->getDLLStorageClass(), Out);
1625 // Print the calling convention.
1626 if (F->getCallingConv() != CallingConv::C) {
1627 PrintCallingConv(F->getCallingConv(), Out);
1631 FunctionType *FT = F->getFunctionType();
1632 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
1633 Out << Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
1634 TypePrinter.print(F->getReturnType(), Out);
1636 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1638 Machine.incorporateFunction(F);
1640 // Loop over the arguments, printing them...
1643 if (!F->isDeclaration()) {
1644 // If this isn't a declaration, print the argument names as well.
1645 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1647 // Insert commas as we go... the first arg doesn't get a comma
1648 if (I != F->arg_begin()) Out << ", ";
1649 printArgument(I, Attrs, Idx);
1653 // Otherwise, print the types from the function type.
1654 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1655 // Insert commas as we go... the first arg doesn't get a comma
1659 TypePrinter.print(FT->getParamType(i), Out);
1661 if (Attrs.hasAttributes(i+1))
1662 Out << ' ' << Attrs.getAsString(i+1);
1666 // Finish printing arguments...
1667 if (FT->isVarArg()) {
1668 if (FT->getNumParams()) Out << ", ";
1669 Out << "..."; // Output varargs portion of signature!
1672 if (F->hasUnnamedAddr())
1673 Out << " unnamed_addr";
1674 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
1675 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
1676 if (F->hasSection()) {
1677 Out << " section \"";
1678 PrintEscapedString(F->getSection(), Out);
1681 if (F->hasComdat()) {
1683 PrintLLVMName(Out, F->getComdat()->getName(), ComdatPrefix);
1685 if (F->getAlignment())
1686 Out << " align " << F->getAlignment();
1688 Out << " gc \"" << F->getGC() << '"';
1689 if (F->hasPrefixData()) {
1691 writeOperand(F->getPrefixData(), true);
1693 if (F->isDeclaration()) {
1697 // Output all of the function's basic blocks.
1698 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1704 Machine.purgeFunction();
1707 /// printArgument - This member is called for every argument that is passed into
1708 /// the function. Simply print it out
1710 void AssemblyWriter::printArgument(const Argument *Arg,
1711 AttributeSet Attrs, unsigned Idx) {
1713 TypePrinter.print(Arg->getType(), Out);
1715 // Output parameter attributes list
1716 if (Attrs.hasAttributes(Idx))
1717 Out << ' ' << Attrs.getAsString(Idx);
1719 // Output name, if available...
1720 if (Arg->hasName()) {
1722 PrintLLVMName(Out, Arg);
1726 /// printBasicBlock - This member is called for each basic block in a method.
1728 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1729 if (BB->hasName()) { // Print out the label if it exists...
1731 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1733 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1734 Out << "\n; <label>:";
1735 int Slot = Machine.getLocalSlot(BB);
1742 if (!BB->getParent()) {
1743 Out.PadToColumn(50);
1744 Out << "; Error: Block without parent!";
1745 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1746 // Output predecessors for the block.
1747 Out.PadToColumn(50);
1749 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1752 Out << " No predecessors!";
1755 writeOperand(*PI, false);
1756 for (++PI; PI != PE; ++PI) {
1758 writeOperand(*PI, false);
1765 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1767 // Output all of the instructions in the basic block...
1768 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1769 printInstructionLine(*I);
1772 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1775 /// printInstructionLine - Print an instruction and a newline character.
1776 void AssemblyWriter::printInstructionLine(const Instruction &I) {
1777 printInstruction(I);
1781 /// printInfoComment - Print a little comment after the instruction indicating
1782 /// which slot it occupies.
1784 void AssemblyWriter::printInfoComment(const Value &V) {
1785 if (AnnotationWriter)
1786 AnnotationWriter->printInfoComment(V, Out);
1789 // This member is called for each Instruction in a function..
1790 void AssemblyWriter::printInstruction(const Instruction &I) {
1791 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1793 // Print out indentation for an instruction.
1796 // Print out name if it exists...
1798 PrintLLVMName(Out, &I);
1800 } else if (!I.getType()->isVoidTy()) {
1801 // Print out the def slot taken.
1802 int SlotNum = Machine.getLocalSlot(&I);
1804 Out << "<badref> = ";
1806 Out << '%' << SlotNum << " = ";
1809 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1810 if (CI->isMustTailCall())
1812 else if (CI->isTailCall())
1816 // Print out the opcode...
1817 Out << I.getOpcodeName();
1819 // If this is an atomic load or store, print out the atomic marker.
1820 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
1821 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
1824 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
1827 // If this is a volatile operation, print out the volatile marker.
1828 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1829 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
1830 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
1831 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
1834 // Print out optimization information.
1835 WriteOptimizationInfo(Out, &I);
1837 // Print out the compare instruction predicates
1838 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1839 Out << ' ' << getPredicateText(CI->getPredicate());
1841 // Print out the atomicrmw operation
1842 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
1843 writeAtomicRMWOperation(Out, RMWI->getOperation());
1845 // Print out the type of the operands...
1846 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
1848 // Special case conditional branches to swizzle the condition out to the front
1849 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1850 const BranchInst &BI(cast<BranchInst>(I));
1852 writeOperand(BI.getCondition(), true);
1854 writeOperand(BI.getSuccessor(0), true);
1856 writeOperand(BI.getSuccessor(1), true);
1858 } else if (isa<SwitchInst>(I)) {
1859 const SwitchInst& SI(cast<SwitchInst>(I));
1860 // Special case switch instruction to get formatting nice and correct.
1862 writeOperand(SI.getCondition(), true);
1864 writeOperand(SI.getDefaultDest(), true);
1866 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1869 writeOperand(i.getCaseValue(), true);
1871 writeOperand(i.getCaseSuccessor(), true);
1874 } else if (isa<IndirectBrInst>(I)) {
1875 // Special case indirectbr instruction to get formatting nice and correct.
1877 writeOperand(Operand, true);
1880 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1883 writeOperand(I.getOperand(i), true);
1886 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
1888 TypePrinter.print(I.getType(), Out);
1891 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
1892 if (op) Out << ", ";
1894 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
1895 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
1897 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1899 writeOperand(I.getOperand(0), true);
1900 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1902 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1904 writeOperand(I.getOperand(0), true); Out << ", ";
1905 writeOperand(I.getOperand(1), true);
1906 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1908 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
1910 TypePrinter.print(I.getType(), Out);
1911 Out << " personality ";
1912 writeOperand(I.getOperand(0), true); Out << '\n';
1914 if (LPI->isCleanup())
1917 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
1918 if (i != 0 || LPI->isCleanup()) Out << "\n";
1919 if (LPI->isCatch(i))
1924 writeOperand(LPI->getClause(i), true);
1926 } else if (isa<ReturnInst>(I) && !Operand) {
1928 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1929 // Print the calling convention being used.
1930 if (CI->getCallingConv() != CallingConv::C) {
1932 PrintCallingConv(CI->getCallingConv(), Out);
1935 Operand = CI->getCalledValue();
1936 PointerType *PTy = cast<PointerType>(Operand->getType());
1937 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1938 Type *RetTy = FTy->getReturnType();
1939 const AttributeSet &PAL = CI->getAttributes();
1941 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
1942 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
1944 // If possible, print out the short form of the call instruction. We can
1945 // only do this if the first argument is a pointer to a nonvararg function,
1946 // and if the return type is not a pointer to a function.
1949 if (!FTy->isVarArg() &&
1950 (!RetTy->isPointerTy() ||
1951 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1952 TypePrinter.print(RetTy, Out);
1954 writeOperand(Operand, false);
1956 writeOperand(Operand, true);
1959 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1962 writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
1965 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
1966 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
1967 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1968 Operand = II->getCalledValue();
1969 PointerType *PTy = cast<PointerType>(Operand->getType());
1970 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1971 Type *RetTy = FTy->getReturnType();
1972 const AttributeSet &PAL = II->getAttributes();
1974 // Print the calling convention being used.
1975 if (II->getCallingConv() != CallingConv::C) {
1977 PrintCallingConv(II->getCallingConv(), Out);
1980 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
1981 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
1983 // If possible, print out the short form of the invoke instruction. We can
1984 // only do this if the first argument is a pointer to a nonvararg function,
1985 // and if the return type is not a pointer to a function.
1988 if (!FTy->isVarArg() &&
1989 (!RetTy->isPointerTy() ||
1990 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1991 TypePrinter.print(RetTy, Out);
1993 writeOperand(Operand, false);
1995 writeOperand(Operand, true);
1998 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
2001 writeParamOperand(II->getArgOperand(op), PAL, op + 1);
2005 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
2006 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
2009 writeOperand(II->getNormalDest(), true);
2011 writeOperand(II->getUnwindDest(), true);
2013 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
2015 if (AI->isUsedWithInAlloca())
2017 TypePrinter.print(AI->getAllocatedType(), Out);
2018 if (!AI->getArraySize() || AI->isArrayAllocation()) {
2020 writeOperand(AI->getArraySize(), true);
2022 if (AI->getAlignment()) {
2023 Out << ", align " << AI->getAlignment();
2025 } else if (isa<CastInst>(I)) {
2028 writeOperand(Operand, true); // Work with broken code
2031 TypePrinter.print(I.getType(), Out);
2032 } else if (isa<VAArgInst>(I)) {
2035 writeOperand(Operand, true); // Work with broken code
2038 TypePrinter.print(I.getType(), Out);
2039 } else if (Operand) { // Print the normal way.
2041 // PrintAllTypes - Instructions who have operands of all the same type
2042 // omit the type from all but the first operand. If the instruction has
2043 // different type operands (for example br), then they are all printed.
2044 bool PrintAllTypes = false;
2045 Type *TheType = Operand->getType();
2047 // Select, Store and ShuffleVector always print all types.
2048 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
2049 || isa<ReturnInst>(I)) {
2050 PrintAllTypes = true;
2052 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
2053 Operand = I.getOperand(i);
2054 // note that Operand shouldn't be null, but the test helps make dump()
2055 // more tolerant of malformed IR
2056 if (Operand && Operand->getType() != TheType) {
2057 PrintAllTypes = true; // We have differing types! Print them all!
2063 if (!PrintAllTypes) {
2065 TypePrinter.print(TheType, Out);
2069 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
2071 writeOperand(I.getOperand(i), PrintAllTypes);
2075 // Print atomic ordering/alignment for memory operations
2076 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
2078 writeAtomic(LI->getOrdering(), LI->getSynchScope());
2079 if (LI->getAlignment())
2080 Out << ", align " << LI->getAlignment();
2081 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
2083 writeAtomic(SI->getOrdering(), SI->getSynchScope());
2084 if (SI->getAlignment())
2085 Out << ", align " << SI->getAlignment();
2086 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
2087 writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
2088 CXI->getSynchScope());
2089 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
2090 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
2091 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
2092 writeAtomic(FI->getOrdering(), FI->getSynchScope());
2095 // Print Metadata info.
2096 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
2097 I.getAllMetadata(InstMD);
2098 if (!InstMD.empty()) {
2099 SmallVector<StringRef, 8> MDNames;
2100 I.getType()->getContext().getMDKindNames(MDNames);
2101 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
2102 unsigned Kind = InstMD[i].first;
2103 if (Kind < MDNames.size()) {
2104 Out << ", !" << MDNames[Kind];
2106 Out << ", !<unknown kind #" << Kind << ">";
2109 WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
2113 printInfoComment(I);
2116 static void WriteMDNodeComment(const MDNode *Node,
2117 formatted_raw_ostream &Out) {
2118 if (Node->getNumOperands() < 1)
2121 Value *Op = Node->getOperand(0);
2122 if (!Op || !isa<ConstantInt>(Op) || cast<ConstantInt>(Op)->getBitWidth() < 32)
2125 DIDescriptor Desc(Node);
2129 unsigned Tag = Desc.getTag();
2130 Out.PadToColumn(50);
2131 if (dwarf::TagString(Tag)) {
2134 } else if (Tag == dwarf::DW_TAG_user_base) {
2135 Out << "; [ DW_TAG_user_base ]";
2139 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
2140 Out << '!' << Slot << " = metadata ";
2141 printMDNodeBody(Node);
2144 void AssemblyWriter::writeAllMDNodes() {
2145 SmallVector<const MDNode *, 16> Nodes;
2146 Nodes.resize(Machine.mdn_size());
2147 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2149 Nodes[I->second] = cast<MDNode>(I->first);
2151 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2152 writeMDNode(i, Nodes[i]);
2156 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2157 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
2158 WriteMDNodeComment(Node, Out);
2162 void AssemblyWriter::writeAllAttributeGroups() {
2163 std::vector<std::pair<AttributeSet, unsigned> > asVec;
2164 asVec.resize(Machine.as_size());
2166 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
2168 asVec[I->second] = *I;
2170 for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
2171 I = asVec.begin(), E = asVec.end(); I != E; ++I)
2172 Out << "attributes #" << I->second << " = { "
2173 << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
2178 //===----------------------------------------------------------------------===//
2179 // External Interface declarations
2180 //===----------------------------------------------------------------------===//
2182 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2183 SlotTracker SlotTable(this);
2184 formatted_raw_ostream OS(ROS);
2185 AssemblyWriter W(OS, SlotTable, this, AAW);
2186 W.printModule(this);
2189 void NamedMDNode::print(raw_ostream &ROS) const {
2190 SlotTracker SlotTable(getParent());
2191 formatted_raw_ostream OS(ROS);
2192 AssemblyWriter W(OS, SlotTable, getParent(), nullptr);
2193 W.printNamedMDNode(this);
2196 void Comdat::print(raw_ostream &ROS) const {
2197 PrintLLVMName(ROS, getName(), ComdatPrefix);
2198 ROS << " = comdat ";
2200 switch (getSelectionKind()) {
2204 case Comdat::ExactMatch:
2205 ROS << "exactmatch";
2207 case Comdat::Largest:
2210 case Comdat::NoDuplicates:
2211 ROS << "noduplicates";
2213 case Comdat::SameSize:
2221 void Type::print(raw_ostream &OS) const {
2223 TP.print(const_cast<Type*>(this), OS);
2225 // If the type is a named struct type, print the body as well.
2226 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
2227 if (!STy->isLiteral()) {
2229 TP.printStructBody(STy, OS);
2233 void Value::print(raw_ostream &ROS) const {
2234 formatted_raw_ostream OS(ROS);
2235 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2236 const Function *F = I->getParent() ? I->getParent()->getParent() : nullptr;
2237 SlotTracker SlotTable(F);
2238 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr);
2239 W.printInstruction(*I);
2240 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2241 SlotTracker SlotTable(BB->getParent());
2242 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr);
2243 W.printBasicBlock(BB);
2244 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2245 SlotTracker SlotTable(GV->getParent());
2246 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr);
2247 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2249 else if (const Function *F = dyn_cast<Function>(GV))
2252 W.printAlias(cast<GlobalAlias>(GV));
2253 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2254 const Function *F = N->getFunction();
2255 SlotTracker SlotTable(F);
2256 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : nullptr, nullptr);
2257 W.printMDNodeBody(N);
2258 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2259 TypePrinting TypePrinter;
2260 TypePrinter.print(C->getType(), OS);
2262 WriteConstantInternal(OS, C, TypePrinter, nullptr, nullptr);
2263 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2264 isa<Argument>(this)) {
2265 this->printAsOperand(OS);
2267 llvm_unreachable("Unknown value to print out!");
2271 void Value::printAsOperand(raw_ostream &O, bool PrintType, const Module *M) const {
2272 // Fast path: Don't construct and populate a TypePrinting object if we
2273 // won't be needing any types printed.
2275 ((!isa<Constant>(this) && !isa<MDNode>(this)) ||
2276 hasName() || isa<GlobalValue>(this))) {
2277 WriteAsOperandInternal(O, this, nullptr, nullptr, M);
2282 M = getModuleFromVal(this);
2284 TypePrinting TypePrinter;
2286 TypePrinter.incorporateTypes(*M);
2288 TypePrinter.print(getType(), O);
2292 WriteAsOperandInternal(O, this, &TypePrinter, nullptr, M);
2295 // Value::dump - allow easy printing of Values from the debugger.
2296 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2298 // Type::dump - allow easy printing of Types from the debugger.
2299 void Type::dump() const { print(dbgs()); }
2301 // Module::dump() - Allow printing of Modules from the debugger.
2302 void Module::dump() const { print(dbgs(), nullptr); }
2304 // \brief Allow printing of Comdats from the debugger.
2305 void Comdat::dump() const { print(dbgs()); }
2307 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
2308 void NamedMDNode::dump() const { print(dbgs()); }