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/DebugInfo.h"
23 #include "llvm/IR/AssemblyAnnotationWriter.h"
24 #include "llvm/IR/CallingConv.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/IRPrintingPasses.h"
28 #include "llvm/IR/InlineAsm.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Operator.h"
33 #include "llvm/IR/TypeFinder.h"
34 #include "llvm/IR/ValueSymbolTable.h"
35 #include "llvm/Support/CFG.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() : 0;
56 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
57 return BB->getParent() ? BB->getParent()->getParent() : 0;
59 if (const Instruction *I = dyn_cast<Instruction>(V)) {
60 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
61 return M ? M->getParent() : 0;
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::X86_CDeclMethod:Out << "x86_cdeclmethodcc"; break;
82 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
83 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
84 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
85 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
86 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
87 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
88 case CallingConv::PTX_Device: Out << "ptx_device"; break;
89 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
90 case CallingConv::X86_64_Win64: Out << "x86_64_win64cc"; break;
91 case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
92 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
96 // PrintEscapedString - Print each character of the specified string, escaping
97 // it if it is not printable or if it is an escape char.
98 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
99 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
100 unsigned char C = Name[i];
101 if (isprint(C) && C != '\\' && C != '"')
104 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 LabelPrefix: break;
124 case LocalPrefix: OS << '%'; break;
127 // Scan the name to see if it needs quotes first.
128 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
130 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
131 // By making this unsigned, the value passed in to isalnum will always be
132 // in the range 0-255. This is important when building with MSVC because
133 // its implementation will assert. This situation can arise when dealing
134 // with UTF-8 multibyte characters.
135 unsigned char C = Name[i];
136 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
144 // If we didn't need any quotes, just write out the name in one blast.
150 // Okay, we need quotes. Output the quotes and escape any scary characters as
153 PrintEscapedString(Name, OS);
157 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
158 /// prefixed with % (if the string only contains simple characters) or is
159 /// surrounded with ""'s (if it has special chars in it). Print it out.
160 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
161 PrintLLVMName(OS, V->getName(),
162 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
168 void TypePrinting::incorporateTypes(const Module &M) {
169 NamedTypes.run(M, false);
171 // The list of struct types we got back includes all the struct types, split
172 // the unnamed ones out to a numbering and remove the anonymous structs.
173 unsigned NextNumber = 0;
175 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
176 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
177 StructType *STy = *I;
179 // Ignore anonymous types.
180 if (STy->isLiteral())
183 if (STy->getName().empty())
184 NumberedTypes[STy] = NextNumber++;
189 NamedTypes.erase(NextToUse, NamedTypes.end());
193 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
194 /// use of type names or up references to shorten the type name where possible.
195 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
196 switch (Ty->getTypeID()) {
197 case Type::VoidTyID: OS << "void"; return;
198 case Type::HalfTyID: OS << "half"; return;
199 case Type::FloatTyID: OS << "float"; return;
200 case Type::DoubleTyID: OS << "double"; return;
201 case Type::X86_FP80TyID: OS << "x86_fp80"; return;
202 case Type::FP128TyID: OS << "fp128"; return;
203 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
204 case Type::LabelTyID: OS << "label"; return;
205 case Type::MetadataTyID: OS << "metadata"; return;
206 case Type::X86_MMXTyID: OS << "x86_mmx"; return;
207 case Type::IntegerTyID:
208 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
211 case Type::FunctionTyID: {
212 FunctionType *FTy = cast<FunctionType>(Ty);
213 print(FTy->getReturnType(), OS);
215 for (FunctionType::param_iterator I = FTy->param_begin(),
216 E = FTy->param_end(); I != E; ++I) {
217 if (I != FTy->param_begin())
221 if (FTy->isVarArg()) {
222 if (FTy->getNumParams()) OS << ", ";
228 case Type::StructTyID: {
229 StructType *STy = cast<StructType>(Ty);
231 if (STy->isLiteral())
232 return printStructBody(STy, OS);
234 if (!STy->getName().empty())
235 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
237 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
238 if (I != NumberedTypes.end())
239 OS << '%' << I->second;
240 else // Not enumerated, print the hex address.
241 OS << "%\"type " << STy << '\"';
244 case Type::PointerTyID: {
245 PointerType *PTy = cast<PointerType>(Ty);
246 print(PTy->getElementType(), OS);
247 if (unsigned AddressSpace = PTy->getAddressSpace())
248 OS << " addrspace(" << AddressSpace << ')';
252 case Type::ArrayTyID: {
253 ArrayType *ATy = cast<ArrayType>(Ty);
254 OS << '[' << ATy->getNumElements() << " x ";
255 print(ATy->getElementType(), OS);
259 case Type::VectorTyID: {
260 VectorType *PTy = cast<VectorType>(Ty);
261 OS << "<" << PTy->getNumElements() << " x ";
262 print(PTy->getElementType(), OS);
267 llvm_unreachable("Invalid TypeID");
270 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
271 if (STy->isOpaque()) {
279 if (STy->getNumElements() == 0) {
282 StructType::element_iterator I = STy->element_begin();
285 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
296 //===----------------------------------------------------------------------===//
297 // SlotTracker Class: Enumerate slot numbers for unnamed values
298 //===----------------------------------------------------------------------===//
299 /// This class provides computation of slot numbers for LLVM Assembly writing.
303 /// ValueMap - A mapping of Values to slot numbers.
304 typedef DenseMap<const Value*, unsigned> ValueMap;
307 /// TheModule - The module for which we are holding slot numbers.
308 const Module* TheModule;
310 /// TheFunction - The function for which we are holding slot numbers.
311 const Function* TheFunction;
312 bool FunctionProcessed;
314 /// mMap - The slot map for the module level data.
318 /// fMap - The slot map for the function level data.
322 /// mdnMap - Map for MDNodes.
323 DenseMap<const MDNode*, unsigned> mdnMap;
326 /// asMap - The slot map for attribute sets.
327 DenseMap<AttributeSet, unsigned> asMap;
330 /// Construct from a module
331 explicit SlotTracker(const Module *M);
332 /// Construct from a function, starting out in incorp state.
333 explicit SlotTracker(const Function *F);
335 /// Return the slot number of the specified value in it's type
336 /// plane. If something is not in the SlotTracker, return -1.
337 int getLocalSlot(const Value *V);
338 int getGlobalSlot(const GlobalValue *V);
339 int getMetadataSlot(const MDNode *N);
340 int getAttributeGroupSlot(AttributeSet AS);
342 /// If you'd like to deal with a function instead of just a module, use
343 /// this method to get its data into the SlotTracker.
344 void incorporateFunction(const Function *F) {
346 FunctionProcessed = false;
349 /// After calling incorporateFunction, use this method to remove the
350 /// most recently incorporated function from the SlotTracker. This
351 /// will reset the state of the machine back to just the module contents.
352 void purgeFunction();
354 /// MDNode map iterators.
355 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
356 mdn_iterator mdn_begin() { return mdnMap.begin(); }
357 mdn_iterator mdn_end() { return mdnMap.end(); }
358 unsigned mdn_size() const { return mdnMap.size(); }
359 bool mdn_empty() const { return mdnMap.empty(); }
361 /// AttributeSet map iterators.
362 typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
363 as_iterator as_begin() { return asMap.begin(); }
364 as_iterator as_end() { return asMap.end(); }
365 unsigned as_size() const { return asMap.size(); }
366 bool as_empty() const { return asMap.empty(); }
368 /// This function does the actual initialization.
369 inline void initialize();
371 // Implementation Details
373 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
374 void CreateModuleSlot(const GlobalValue *V);
376 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
377 void CreateMetadataSlot(const MDNode *N);
379 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
380 void CreateFunctionSlot(const Value *V);
382 /// \brief Insert the specified AttributeSet into the slot table.
383 void CreateAttributeSetSlot(AttributeSet AS);
385 /// Add all of the module level global variables (and their initializers)
386 /// and function declarations, but not the contents of those functions.
387 void processModule();
389 /// Add all of the functions arguments, basic blocks, and instructions.
390 void processFunction();
392 SlotTracker(const SlotTracker &) LLVM_DELETED_FUNCTION;
393 void operator=(const SlotTracker &) LLVM_DELETED_FUNCTION;
396 SlotTracker *createSlotTracker(const Module *M) {
397 return new SlotTracker(M);
400 static SlotTracker *createSlotTracker(const Value *V) {
401 if (const Argument *FA = dyn_cast<Argument>(V))
402 return new SlotTracker(FA->getParent());
404 if (const Instruction *I = dyn_cast<Instruction>(V))
406 return new SlotTracker(I->getParent()->getParent());
408 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
409 return new SlotTracker(BB->getParent());
411 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
412 return new SlotTracker(GV->getParent());
414 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
415 return new SlotTracker(GA->getParent());
417 if (const Function *Func = dyn_cast<Function>(V))
418 return new SlotTracker(Func);
420 if (const MDNode *MD = dyn_cast<MDNode>(V)) {
421 if (!MD->isFunctionLocal())
422 return new SlotTracker(MD->getFunction());
424 return new SlotTracker((Function *)0);
431 #define ST_DEBUG(X) dbgs() << X
436 // Module level constructor. Causes the contents of the Module (sans functions)
437 // to be added to the slot table.
438 SlotTracker::SlotTracker(const Module *M)
439 : TheModule(M), TheFunction(0), FunctionProcessed(false),
440 mNext(0), fNext(0), mdnNext(0), asNext(0) {
443 // Function level constructor. Causes the contents of the Module and the one
444 // function provided to be added to the slot table.
445 SlotTracker::SlotTracker(const Function *F)
446 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
447 mNext(0), fNext(0), mdnNext(0), asNext(0) {
450 inline void SlotTracker::initialize() {
453 TheModule = 0; ///< Prevent re-processing next time we're called.
456 if (TheFunction && !FunctionProcessed)
460 // Iterate through all the global variables, functions, and global
461 // variable initializers and create slots for them.
462 void SlotTracker::processModule() {
463 ST_DEBUG("begin processModule!\n");
465 // Add all of the unnamed global variables to the value table.
466 for (Module::const_global_iterator I = TheModule->global_begin(),
467 E = TheModule->global_end(); I != E; ++I) {
472 // Add metadata used by named metadata.
473 for (Module::const_named_metadata_iterator
474 I = TheModule->named_metadata_begin(),
475 E = TheModule->named_metadata_end(); I != E; ++I) {
476 const NamedMDNode *NMD = I;
477 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
478 CreateMetadataSlot(NMD->getOperand(i));
481 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
484 // Add all the unnamed functions to the table.
487 // Add all the function attributes to the table.
488 // FIXME: Add attributes of other objects?
489 AttributeSet FnAttrs = I->getAttributes().getFnAttributes();
490 if (FnAttrs.hasAttributes(AttributeSet::FunctionIndex))
491 CreateAttributeSetSlot(FnAttrs);
494 ST_DEBUG("end processModule!\n");
497 // Process the arguments, basic blocks, and instructions of a function.
498 void SlotTracker::processFunction() {
499 ST_DEBUG("begin processFunction!\n");
502 // Add all the function arguments with no names.
503 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
504 AE = TheFunction->arg_end(); AI != AE; ++AI)
506 CreateFunctionSlot(AI);
508 ST_DEBUG("Inserting Instructions:\n");
510 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
512 // Add all of the basic blocks and instructions with no names.
513 for (Function::const_iterator BB = TheFunction->begin(),
514 E = TheFunction->end(); BB != E; ++BB) {
516 CreateFunctionSlot(BB);
518 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
520 if (!I->getType()->isVoidTy() && !I->hasName())
521 CreateFunctionSlot(I);
523 // Intrinsics can directly use metadata. We allow direct calls to any
524 // llvm.foo function here, because the target may not be linked into the
526 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
527 if (Function *F = CI->getCalledFunction())
528 if (F->isIntrinsic())
529 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
530 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
531 CreateMetadataSlot(N);
533 // Add all the call attributes to the table.
534 AttributeSet Attrs = CI->getAttributes().getFnAttributes();
535 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
536 CreateAttributeSetSlot(Attrs);
537 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(I)) {
538 // Add all the call attributes to the table.
539 AttributeSet Attrs = II->getAttributes().getFnAttributes();
540 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
541 CreateAttributeSetSlot(Attrs);
544 // Process metadata attached with this instruction.
545 I->getAllMetadata(MDForInst);
546 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
547 CreateMetadataSlot(MDForInst[i].second);
552 FunctionProcessed = true;
554 ST_DEBUG("end processFunction!\n");
557 /// Clean up after incorporating a function. This is the only way to get out of
558 /// the function incorporation state that affects get*Slot/Create*Slot. Function
559 /// incorporation state is indicated by TheFunction != 0.
560 void SlotTracker::purgeFunction() {
561 ST_DEBUG("begin purgeFunction!\n");
562 fMap.clear(); // Simply discard the function level map
564 FunctionProcessed = false;
565 ST_DEBUG("end purgeFunction!\n");
568 /// getGlobalSlot - Get the slot number of a global value.
569 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
570 // Check for uninitialized state and do lazy initialization.
573 // Find the value in the module map
574 ValueMap::iterator MI = mMap.find(V);
575 return MI == mMap.end() ? -1 : (int)MI->second;
578 /// getMetadataSlot - Get the slot number of a MDNode.
579 int SlotTracker::getMetadataSlot(const MDNode *N) {
580 // Check for uninitialized state and do lazy initialization.
583 // Find the MDNode in the module map
584 mdn_iterator MI = mdnMap.find(N);
585 return MI == mdnMap.end() ? -1 : (int)MI->second;
589 /// getLocalSlot - Get the slot number for a value that is local to a function.
590 int SlotTracker::getLocalSlot(const Value *V) {
591 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
593 // Check for uninitialized state and do lazy initialization.
596 ValueMap::iterator FI = fMap.find(V);
597 return FI == fMap.end() ? -1 : (int)FI->second;
600 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
601 // Check for uninitialized state and do lazy initialization.
604 // Find the AttributeSet in the module map.
605 as_iterator AI = asMap.find(AS);
606 return AI == asMap.end() ? -1 : (int)AI->second;
609 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
610 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
611 assert(V && "Can't insert a null Value into SlotTracker!");
612 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
613 assert(!V->hasName() && "Doesn't need a slot!");
615 unsigned DestSlot = mNext++;
618 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
620 // G = Global, F = Function, A = Alias, o = other
621 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
622 (isa<Function>(V) ? 'F' :
623 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
626 /// CreateSlot - Create a new slot for the specified value if it has no name.
627 void SlotTracker::CreateFunctionSlot(const Value *V) {
628 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
630 unsigned DestSlot = fNext++;
633 // G = Global, F = Function, o = other
634 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
635 DestSlot << " [o]\n");
638 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
639 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
640 assert(N && "Can't insert a null Value into SlotTracker!");
642 // Don't insert if N is a function-local metadata, these are always printed
644 if (!N->isFunctionLocal()) {
645 mdn_iterator I = mdnMap.find(N);
646 if (I != mdnMap.end())
649 unsigned DestSlot = mdnNext++;
650 mdnMap[N] = DestSlot;
653 // Recursively add any MDNodes referenced by operands.
654 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
655 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
656 CreateMetadataSlot(Op);
659 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
660 assert(AS.hasAttributes(AttributeSet::FunctionIndex) &&
661 "Doesn't need a slot!");
663 as_iterator I = asMap.find(AS);
664 if (I != asMap.end())
667 unsigned DestSlot = asNext++;
668 asMap[AS] = DestSlot;
671 //===----------------------------------------------------------------------===//
672 // AsmWriter Implementation
673 //===----------------------------------------------------------------------===//
675 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
676 TypePrinting *TypePrinter,
677 SlotTracker *Machine,
678 const Module *Context);
680 static const char *getPredicateText(unsigned predicate) {
681 const char * pred = "unknown";
683 case FCmpInst::FCMP_FALSE: pred = "false"; break;
684 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
685 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
686 case FCmpInst::FCMP_OGE: pred = "oge"; break;
687 case FCmpInst::FCMP_OLT: pred = "olt"; break;
688 case FCmpInst::FCMP_OLE: pred = "ole"; break;
689 case FCmpInst::FCMP_ONE: pred = "one"; break;
690 case FCmpInst::FCMP_ORD: pred = "ord"; break;
691 case FCmpInst::FCMP_UNO: pred = "uno"; break;
692 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
693 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
694 case FCmpInst::FCMP_UGE: pred = "uge"; break;
695 case FCmpInst::FCMP_ULT: pred = "ult"; break;
696 case FCmpInst::FCMP_ULE: pred = "ule"; break;
697 case FCmpInst::FCMP_UNE: pred = "une"; break;
698 case FCmpInst::FCMP_TRUE: pred = "true"; break;
699 case ICmpInst::ICMP_EQ: pred = "eq"; break;
700 case ICmpInst::ICMP_NE: pred = "ne"; break;
701 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
702 case ICmpInst::ICMP_SGE: pred = "sge"; break;
703 case ICmpInst::ICMP_SLT: pred = "slt"; break;
704 case ICmpInst::ICMP_SLE: pred = "sle"; break;
705 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
706 case ICmpInst::ICMP_UGE: pred = "uge"; break;
707 case ICmpInst::ICMP_ULT: pred = "ult"; break;
708 case ICmpInst::ICMP_ULE: pred = "ule"; break;
713 static void writeAtomicRMWOperation(raw_ostream &Out,
714 AtomicRMWInst::BinOp Op) {
716 default: Out << " <unknown operation " << Op << ">"; break;
717 case AtomicRMWInst::Xchg: Out << " xchg"; break;
718 case AtomicRMWInst::Add: Out << " add"; break;
719 case AtomicRMWInst::Sub: Out << " sub"; break;
720 case AtomicRMWInst::And: Out << " and"; break;
721 case AtomicRMWInst::Nand: Out << " nand"; break;
722 case AtomicRMWInst::Or: Out << " or"; break;
723 case AtomicRMWInst::Xor: Out << " xor"; break;
724 case AtomicRMWInst::Max: Out << " max"; break;
725 case AtomicRMWInst::Min: Out << " min"; break;
726 case AtomicRMWInst::UMax: Out << " umax"; break;
727 case AtomicRMWInst::UMin: Out << " umin"; break;
731 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
732 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
733 // Unsafe algebra implies all the others, no need to write them all out
734 if (FPO->hasUnsafeAlgebra())
737 if (FPO->hasNoNaNs())
739 if (FPO->hasNoInfs())
741 if (FPO->hasNoSignedZeros())
743 if (FPO->hasAllowReciprocal())
748 if (const OverflowingBinaryOperator *OBO =
749 dyn_cast<OverflowingBinaryOperator>(U)) {
750 if (OBO->hasNoUnsignedWrap())
752 if (OBO->hasNoSignedWrap())
754 } else if (const PossiblyExactOperator *Div =
755 dyn_cast<PossiblyExactOperator>(U)) {
758 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
759 if (GEP->isInBounds())
764 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
765 TypePrinting &TypePrinter,
766 SlotTracker *Machine,
767 const Module *Context) {
768 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
769 if (CI->getType()->isIntegerTy(1)) {
770 Out << (CI->getZExtValue() ? "true" : "false");
773 Out << CI->getValue();
777 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
778 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
779 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
780 // We would like to output the FP constant value in exponential notation,
781 // but we cannot do this if doing so will lose precision. Check here to
782 // make sure that we only output it in exponential format if we can parse
783 // the value back and get the same value.
786 bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
787 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
788 bool isInf = CFP->getValueAPF().isInfinity();
789 bool isNaN = CFP->getValueAPF().isNaN();
790 if (!isHalf && !isInf && !isNaN) {
791 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
792 CFP->getValueAPF().convertToFloat();
793 SmallString<128> StrVal;
794 raw_svector_ostream(StrVal) << Val;
796 // Check to make sure that the stringized number is not some string like
797 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
798 // that the string matches the "[-+]?[0-9]" regex.
800 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
801 ((StrVal[0] == '-' || StrVal[0] == '+') &&
802 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
803 // Reparse stringized version!
804 if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
810 // Otherwise we could not reparse it to exactly the same value, so we must
811 // output the string in hexadecimal format! Note that loading and storing
812 // floating point types changes the bits of NaNs on some hosts, notably
813 // x86, so we must not use these types.
814 assert(sizeof(double) == sizeof(uint64_t) &&
815 "assuming that double is 64 bits!");
817 APFloat apf = CFP->getValueAPF();
818 // Halves and floats are represented in ASCII IR as double, convert.
820 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
823 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
828 // Either half, or some form of long double.
829 // These appear as a magic letter identifying the type, then a
830 // fixed number of hex digits.
832 // Bit position, in the current word, of the next nibble to print.
835 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
837 // api needed to prevent premature destruction
838 APInt api = CFP->getValueAPF().bitcastToAPInt();
839 const uint64_t* p = api.getRawData();
840 uint64_t word = p[1];
842 int width = api.getBitWidth();
843 for (int j=0; j<width; j+=4, shiftcount-=4) {
844 unsigned int nibble = (word>>shiftcount) & 15;
846 Out << (unsigned char)(nibble + '0');
848 Out << (unsigned char)(nibble - 10 + 'A');
849 if (shiftcount == 0 && j+4 < width) {
853 shiftcount = width-j-4;
857 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
860 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
863 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
867 llvm_unreachable("Unsupported floating point type");
868 // api needed to prevent premature destruction
869 APInt api = CFP->getValueAPF().bitcastToAPInt();
870 const uint64_t* p = api.getRawData();
872 int width = api.getBitWidth();
873 for (int j=0; j<width; j+=4, shiftcount-=4) {
874 unsigned int nibble = (word>>shiftcount) & 15;
876 Out << (unsigned char)(nibble + '0');
878 Out << (unsigned char)(nibble - 10 + 'A');
879 if (shiftcount == 0 && j+4 < width) {
883 shiftcount = width-j-4;
889 if (isa<ConstantAggregateZero>(CV)) {
890 Out << "zeroinitializer";
894 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
895 Out << "blockaddress(";
896 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
899 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
905 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
906 Type *ETy = CA->getType()->getElementType();
908 TypePrinter.print(ETy, Out);
910 WriteAsOperandInternal(Out, CA->getOperand(0),
911 &TypePrinter, Machine,
913 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
915 TypePrinter.print(ETy, Out);
917 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
924 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
925 // As a special case, print the array as a string if it is an array of
926 // i8 with ConstantInt values.
927 if (CA->isString()) {
929 PrintEscapedString(CA->getAsString(), Out);
934 Type *ETy = CA->getType()->getElementType();
936 TypePrinter.print(ETy, Out);
938 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
939 &TypePrinter, Machine,
941 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
943 TypePrinter.print(ETy, Out);
945 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
953 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
954 if (CS->getType()->isPacked())
957 unsigned N = CS->getNumOperands();
960 TypePrinter.print(CS->getOperand(0)->getType(), Out);
963 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
966 for (unsigned i = 1; i < N; i++) {
968 TypePrinter.print(CS->getOperand(i)->getType(), Out);
971 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
978 if (CS->getType()->isPacked())
983 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
984 Type *ETy = CV->getType()->getVectorElementType();
986 TypePrinter.print(ETy, Out);
988 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
990 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
992 TypePrinter.print(ETy, Out);
994 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1001 if (isa<ConstantPointerNull>(CV)) {
1006 if (isa<UndefValue>(CV)) {
1011 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1012 Out << CE->getOpcodeName();
1013 WriteOptimizationInfo(Out, CE);
1014 if (CE->isCompare())
1015 Out << ' ' << getPredicateText(CE->getPredicate());
1018 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1019 TypePrinter.print((*OI)->getType(), Out);
1021 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1022 if (OI+1 != CE->op_end())
1026 if (CE->hasIndices()) {
1027 ArrayRef<unsigned> Indices = CE->getIndices();
1028 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1029 Out << ", " << Indices[i];
1034 TypePrinter.print(CE->getType(), Out);
1041 Out << "<placeholder or erroneous Constant>";
1044 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1045 TypePrinting *TypePrinter,
1046 SlotTracker *Machine,
1047 const Module *Context) {
1049 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1050 const Value *V = Node->getOperand(mi);
1054 TypePrinter->print(V->getType(), Out);
1056 WriteAsOperandInternal(Out, Node->getOperand(mi),
1057 TypePrinter, Machine, Context);
1066 // Full implementation of printing a Value as an operand with support for
1067 // TypePrinting, etc.
1068 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1069 TypePrinting *TypePrinter,
1070 SlotTracker *Machine,
1071 const Module *Context) {
1073 PrintLLVMName(Out, V);
1077 const Constant *CV = dyn_cast<Constant>(V);
1078 if (CV && !isa<GlobalValue>(CV)) {
1079 assert(TypePrinter && "Constants require TypePrinting!");
1080 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1084 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1086 if (IA->hasSideEffects())
1087 Out << "sideeffect ";
1088 if (IA->isAlignStack())
1089 Out << "alignstack ";
1090 // We don't emit the AD_ATT dialect as it's the assumed default.
1091 if (IA->getDialect() == InlineAsm::AD_Intel)
1092 Out << "inteldialect ";
1094 PrintEscapedString(IA->getAsmString(), Out);
1096 PrintEscapedString(IA->getConstraintString(), Out);
1101 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1102 if (N->isFunctionLocal()) {
1103 // Print metadata inline, not via slot reference number.
1104 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
1109 if (N->isFunctionLocal())
1110 Machine = new SlotTracker(N->getFunction());
1112 Machine = new SlotTracker(Context);
1114 int Slot = Machine->getMetadataSlot(N);
1122 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1124 PrintEscapedString(MDS->getString(), Out);
1129 if (V->getValueID() == Value::PseudoSourceValueVal ||
1130 V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1137 // If we have a SlotTracker, use it.
1139 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1140 Slot = Machine->getGlobalSlot(GV);
1143 Slot = Machine->getLocalSlot(V);
1145 // If the local value didn't succeed, then we may be referring to a value
1146 // from a different function. Translate it, as this can happen when using
1147 // address of blocks.
1149 if ((Machine = createSlotTracker(V))) {
1150 Slot = Machine->getLocalSlot(V);
1154 } else if ((Machine = createSlotTracker(V))) {
1155 // Otherwise, create one to get the # and then destroy it.
1156 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1157 Slot = Machine->getGlobalSlot(GV);
1160 Slot = Machine->getLocalSlot(V);
1169 Out << Prefix << Slot;
1174 void AssemblyWriter::init() {
1176 TypePrinter.incorporateTypes(*TheModule);
1180 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1182 AssemblyAnnotationWriter *AAW)
1183 : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW) {
1187 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, const Module *M,
1188 AssemblyAnnotationWriter *AAW)
1189 : Out(o), TheModule(M), ModuleSlotTracker(createSlotTracker(M)),
1190 Machine(*ModuleSlotTracker), AnnotationWriter(AAW) {
1194 AssemblyWriter::~AssemblyWriter() { }
1196 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1198 Out << "<null operand!>";
1202 TypePrinter.print(Operand->getType(), Out);
1205 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1208 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
1209 SynchronizationScope SynchScope) {
1210 if (Ordering == NotAtomic)
1213 switch (SynchScope) {
1214 case SingleThread: Out << " singlethread"; break;
1215 case CrossThread: break;
1219 default: Out << " <bad ordering " << int(Ordering) << ">"; break;
1220 case Unordered: Out << " unordered"; break;
1221 case Monotonic: Out << " monotonic"; break;
1222 case Acquire: Out << " acquire"; break;
1223 case Release: Out << " release"; break;
1224 case AcquireRelease: Out << " acq_rel"; break;
1225 case SequentiallyConsistent: Out << " seq_cst"; break;
1229 void AssemblyWriter::writeParamOperand(const Value *Operand,
1230 AttributeSet Attrs, unsigned Idx) {
1232 Out << "<null operand!>";
1237 TypePrinter.print(Operand->getType(), Out);
1238 // Print parameter attributes list
1239 if (Attrs.hasAttributes(Idx))
1240 Out << ' ' << Attrs.getAsString(Idx);
1242 // Print the operand
1243 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1246 void AssemblyWriter::printModule(const Module *M) {
1247 Machine.initialize();
1249 if (!M->getModuleIdentifier().empty() &&
1250 // Don't print the ID if it will start a new line (which would
1251 // require a comment char before it).
1252 M->getModuleIdentifier().find('\n') == std::string::npos)
1253 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1255 if (!M->getDataLayout().empty())
1256 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1257 if (!M->getTargetTriple().empty())
1258 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1260 if (!M->getModuleInlineAsm().empty()) {
1261 // Split the string into lines, to make it easier to read the .ll file.
1262 std::string Asm = M->getModuleInlineAsm();
1264 size_t NewLine = Asm.find_first_of('\n', CurPos);
1266 while (NewLine != std::string::npos) {
1267 // We found a newline, print the portion of the asm string from the
1268 // last newline up to this newline.
1269 Out << "module asm \"";
1270 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1274 NewLine = Asm.find_first_of('\n', CurPos);
1276 std::string rest(Asm.begin()+CurPos, Asm.end());
1277 if (!rest.empty()) {
1278 Out << "module asm \"";
1279 PrintEscapedString(rest, Out);
1284 printTypeIdentities();
1286 // Output all globals.
1287 if (!M->global_empty()) Out << '\n';
1288 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1290 printGlobal(I); Out << '\n';
1293 // Output all aliases.
1294 if (!M->alias_empty()) Out << "\n";
1295 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1299 // Output all of the functions.
1300 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1303 // Output all attribute groups.
1304 if (!Machine.as_empty()) {
1306 writeAllAttributeGroups();
1309 // Output named metadata.
1310 if (!M->named_metadata_empty()) Out << '\n';
1312 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1313 E = M->named_metadata_end(); I != E; ++I)
1314 printNamedMDNode(I);
1317 if (!Machine.mdn_empty()) {
1323 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1325 StringRef Name = NMD->getName();
1327 Out << "<empty name> ";
1329 if (isalpha(static_cast<unsigned char>(Name[0])) ||
1330 Name[0] == '-' || Name[0] == '$' ||
1331 Name[0] == '.' || Name[0] == '_')
1334 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
1335 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
1336 unsigned char C = Name[i];
1337 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
1338 C == '.' || C == '_')
1341 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1345 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1347 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
1357 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1358 formatted_raw_ostream &Out) {
1360 case GlobalValue::ExternalLinkage: break;
1361 case GlobalValue::PrivateLinkage: Out << "private "; break;
1362 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1363 case GlobalValue::LinkerPrivateWeakLinkage:
1364 Out << "linker_private_weak ";
1366 case GlobalValue::InternalLinkage: Out << "internal "; break;
1367 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1368 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1369 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1370 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1371 case GlobalValue::CommonLinkage: Out << "common "; break;
1372 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1373 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1374 case GlobalValue::AvailableExternallyLinkage:
1375 Out << "available_externally ";
1381 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1382 formatted_raw_ostream &Out) {
1384 case GlobalValue::DefaultVisibility: break;
1385 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1386 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1390 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
1391 formatted_raw_ostream &Out) {
1393 case GlobalValue::DefaultStorageClass: break;
1394 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
1395 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
1399 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
1400 formatted_raw_ostream &Out) {
1402 case GlobalVariable::NotThreadLocal:
1404 case GlobalVariable::GeneralDynamicTLSModel:
1405 Out << "thread_local ";
1407 case GlobalVariable::LocalDynamicTLSModel:
1408 Out << "thread_local(localdynamic) ";
1410 case GlobalVariable::InitialExecTLSModel:
1411 Out << "thread_local(initialexec) ";
1413 case GlobalVariable::LocalExecTLSModel:
1414 Out << "thread_local(localexec) ";
1419 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1420 if (GV->isMaterializable())
1421 Out << "; Materializable\n";
1423 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
1426 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1429 PrintLinkage(GV->getLinkage(), Out);
1430 PrintVisibility(GV->getVisibility(), Out);
1431 PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
1432 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
1434 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1435 Out << "addrspace(" << AddressSpace << ") ";
1436 if (GV->hasUnnamedAddr()) Out << "unnamed_addr ";
1437 if (GV->isExternallyInitialized()) Out << "externally_initialized ";
1438 Out << (GV->isConstant() ? "constant " : "global ");
1439 TypePrinter.print(GV->getType()->getElementType(), Out);
1441 if (GV->hasInitializer()) {
1443 writeOperand(GV->getInitializer(), false);
1446 if (GV->hasSection()) {
1447 Out << ", section \"";
1448 PrintEscapedString(GV->getSection(), Out);
1451 if (GV->getAlignment())
1452 Out << ", align " << GV->getAlignment();
1454 printInfoComment(*GV);
1457 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1458 if (GA->isMaterializable())
1459 Out << "; Materializable\n";
1461 // Don't crash when dumping partially built GA
1463 Out << "<<nameless>> = ";
1465 PrintLLVMName(Out, GA);
1468 PrintVisibility(GA->getVisibility(), Out);
1469 PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
1473 PrintLinkage(GA->getLinkage(), Out);
1475 const Constant *Aliasee = GA->getAliasee();
1478 TypePrinter.print(GA->getType(), Out);
1479 Out << " <<NULL ALIASEE>>";
1481 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
1484 printInfoComment(*GA);
1488 void AssemblyWriter::printTypeIdentities() {
1489 if (TypePrinter.NumberedTypes.empty() &&
1490 TypePrinter.NamedTypes.empty())
1495 // We know all the numbers that each type is used and we know that it is a
1496 // dense assignment. Convert the map to an index table.
1497 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
1498 for (DenseMap<StructType*, unsigned>::iterator I =
1499 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
1501 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
1502 NumberedTypes[I->second] = I->first;
1505 // Emit all numbered types.
1506 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1507 Out << '%' << i << " = type ";
1509 // Make sure we print out at least one level of the type structure, so
1510 // that we do not get %2 = type %2
1511 TypePrinter.printStructBody(NumberedTypes[i], Out);
1515 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
1516 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
1519 // Make sure we print out at least one level of the type structure, so
1520 // that we do not get %FILE = type %FILE
1521 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
1526 /// printFunction - Print all aspects of a function.
1528 void AssemblyWriter::printFunction(const Function *F) {
1529 // Print out the return type and name.
1532 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1534 if (F->isMaterializable())
1535 Out << "; Materializable\n";
1537 const AttributeSet &Attrs = F->getAttributes();
1538 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
1539 AttributeSet AS = Attrs.getFnAttributes();
1540 std::string AttrStr;
1543 for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
1544 if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
1547 for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
1549 Attribute Attr = *I;
1550 if (!Attr.isStringAttribute()) {
1551 if (!AttrStr.empty()) AttrStr += ' ';
1552 AttrStr += Attr.getAsString();
1556 if (!AttrStr.empty())
1557 Out << "; Function Attrs: " << AttrStr << '\n';
1560 if (F->isDeclaration())
1565 PrintLinkage(F->getLinkage(), Out);
1566 PrintVisibility(F->getVisibility(), Out);
1567 PrintDLLStorageClass(F->getDLLStorageClass(), Out);
1569 // Print the calling convention.
1570 if (F->getCallingConv() != CallingConv::C) {
1571 PrintCallingConv(F->getCallingConv(), Out);
1575 FunctionType *FT = F->getFunctionType();
1576 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
1577 Out << Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
1578 TypePrinter.print(F->getReturnType(), Out);
1580 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1582 Machine.incorporateFunction(F);
1584 // Loop over the arguments, printing them...
1587 if (!F->isDeclaration()) {
1588 // If this isn't a declaration, print the argument names as well.
1589 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1591 // Insert commas as we go... the first arg doesn't get a comma
1592 if (I != F->arg_begin()) Out << ", ";
1593 printArgument(I, Attrs, Idx);
1597 // Otherwise, print the types from the function type.
1598 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1599 // Insert commas as we go... the first arg doesn't get a comma
1603 TypePrinter.print(FT->getParamType(i), Out);
1605 if (Attrs.hasAttributes(i+1))
1606 Out << ' ' << Attrs.getAsString(i+1);
1610 // Finish printing arguments...
1611 if (FT->isVarArg()) {
1612 if (FT->getNumParams()) Out << ", ";
1613 Out << "..."; // Output varargs portion of signature!
1616 if (F->hasUnnamedAddr())
1617 Out << " unnamed_addr";
1618 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
1619 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
1620 if (F->hasSection()) {
1621 Out << " section \"";
1622 PrintEscapedString(F->getSection(), Out);
1625 if (F->getAlignment())
1626 Out << " align " << F->getAlignment();
1628 Out << " gc \"" << F->getGC() << '"';
1629 if (F->hasPrefixData()) {
1631 writeOperand(F->getPrefixData(), true);
1633 if (F->isDeclaration()) {
1637 // Output all of the function's basic blocks.
1638 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1644 Machine.purgeFunction();
1647 /// printArgument - This member is called for every argument that is passed into
1648 /// the function. Simply print it out
1650 void AssemblyWriter::printArgument(const Argument *Arg,
1651 AttributeSet Attrs, unsigned Idx) {
1653 TypePrinter.print(Arg->getType(), Out);
1655 // Output parameter attributes list
1656 if (Attrs.hasAttributes(Idx))
1657 Out << ' ' << Attrs.getAsString(Idx);
1659 // Output name, if available...
1660 if (Arg->hasName()) {
1662 PrintLLVMName(Out, Arg);
1666 /// printBasicBlock - This member is called for each basic block in a method.
1668 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1669 if (BB->hasName()) { // Print out the label if it exists...
1671 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1673 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1674 Out << "\n; <label>:";
1675 int Slot = Machine.getLocalSlot(BB);
1682 if (BB->getParent() == 0) {
1683 Out.PadToColumn(50);
1684 Out << "; Error: Block without parent!";
1685 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1686 // Output predecessors for the block.
1687 Out.PadToColumn(50);
1689 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1692 Out << " No predecessors!";
1695 writeOperand(*PI, false);
1696 for (++PI; PI != PE; ++PI) {
1698 writeOperand(*PI, false);
1705 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1707 // Output all of the instructions in the basic block...
1708 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1709 printInstructionLine(*I);
1712 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1715 /// printInstructionLine - Print an instruction and a newline character.
1716 void AssemblyWriter::printInstructionLine(const Instruction &I) {
1717 printInstruction(I);
1721 /// printInfoComment - Print a little comment after the instruction indicating
1722 /// which slot it occupies.
1724 void AssemblyWriter::printInfoComment(const Value &V) {
1725 if (AnnotationWriter)
1726 AnnotationWriter->printInfoComment(V, Out);
1729 // This member is called for each Instruction in a function..
1730 void AssemblyWriter::printInstruction(const Instruction &I) {
1731 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1733 // Print out indentation for an instruction.
1736 // Print out name if it exists...
1738 PrintLLVMName(Out, &I);
1740 } else if (!I.getType()->isVoidTy()) {
1741 // Print out the def slot taken.
1742 int SlotNum = Machine.getLocalSlot(&I);
1744 Out << "<badref> = ";
1746 Out << '%' << SlotNum << " = ";
1749 if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall())
1752 // Print out the opcode...
1753 Out << I.getOpcodeName();
1755 // If this is an atomic load or store, print out the atomic marker.
1756 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
1757 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
1760 // If this is a volatile operation, print out the volatile marker.
1761 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1762 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
1763 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
1764 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
1767 // Print out optimization information.
1768 WriteOptimizationInfo(Out, &I);
1770 // Print out the compare instruction predicates
1771 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1772 Out << ' ' << getPredicateText(CI->getPredicate());
1774 // Print out the atomicrmw operation
1775 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
1776 writeAtomicRMWOperation(Out, RMWI->getOperation());
1778 // Print out the type of the operands...
1779 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1781 // Special case conditional branches to swizzle the condition out to the front
1782 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1783 const BranchInst &BI(cast<BranchInst>(I));
1785 writeOperand(BI.getCondition(), true);
1787 writeOperand(BI.getSuccessor(0), true);
1789 writeOperand(BI.getSuccessor(1), true);
1791 } else if (isa<SwitchInst>(I)) {
1792 const SwitchInst& SI(cast<SwitchInst>(I));
1793 // Special case switch instruction to get formatting nice and correct.
1795 writeOperand(SI.getCondition(), true);
1797 writeOperand(SI.getDefaultDest(), true);
1799 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1802 writeOperand(i.getCaseValue(), true);
1804 writeOperand(i.getCaseSuccessor(), true);
1807 } else if (isa<IndirectBrInst>(I)) {
1808 // Special case indirectbr instruction to get formatting nice and correct.
1810 writeOperand(Operand, true);
1813 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1816 writeOperand(I.getOperand(i), true);
1819 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
1821 TypePrinter.print(I.getType(), Out);
1824 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
1825 if (op) Out << ", ";
1827 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
1828 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
1830 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1832 writeOperand(I.getOperand(0), true);
1833 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1835 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1837 writeOperand(I.getOperand(0), true); Out << ", ";
1838 writeOperand(I.getOperand(1), true);
1839 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1841 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
1843 TypePrinter.print(I.getType(), Out);
1844 Out << " personality ";
1845 writeOperand(I.getOperand(0), true); Out << '\n';
1847 if (LPI->isCleanup())
1850 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
1851 if (i != 0 || LPI->isCleanup()) Out << "\n";
1852 if (LPI->isCatch(i))
1857 writeOperand(LPI->getClause(i), true);
1859 } else if (isa<ReturnInst>(I) && !Operand) {
1861 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1862 // Print the calling convention being used.
1863 if (CI->getCallingConv() != CallingConv::C) {
1865 PrintCallingConv(CI->getCallingConv(), Out);
1868 Operand = CI->getCalledValue();
1869 PointerType *PTy = cast<PointerType>(Operand->getType());
1870 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1871 Type *RetTy = FTy->getReturnType();
1872 const AttributeSet &PAL = CI->getAttributes();
1874 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
1875 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
1877 // If possible, print out the short form of the call instruction. We can
1878 // only do this if the first argument is a pointer to a nonvararg function,
1879 // and if the return type is not a pointer to a function.
1882 if (!FTy->isVarArg() &&
1883 (!RetTy->isPointerTy() ||
1884 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1885 TypePrinter.print(RetTy, Out);
1887 writeOperand(Operand, false);
1889 writeOperand(Operand, true);
1892 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1895 writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
1898 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
1899 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
1900 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1901 Operand = II->getCalledValue();
1902 PointerType *PTy = cast<PointerType>(Operand->getType());
1903 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1904 Type *RetTy = FTy->getReturnType();
1905 const AttributeSet &PAL = II->getAttributes();
1907 // Print the calling convention being used.
1908 if (II->getCallingConv() != CallingConv::C) {
1910 PrintCallingConv(II->getCallingConv(), Out);
1913 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
1914 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
1916 // If possible, print out the short form of the invoke instruction. We can
1917 // only do this if the first argument is a pointer to a nonvararg function,
1918 // and if the return type is not a pointer to a function.
1921 if (!FTy->isVarArg() &&
1922 (!RetTy->isPointerTy() ||
1923 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1924 TypePrinter.print(RetTy, Out);
1926 writeOperand(Operand, false);
1928 writeOperand(Operand, true);
1931 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
1934 writeParamOperand(II->getArgOperand(op), PAL, op + 1);
1938 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
1939 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
1942 writeOperand(II->getNormalDest(), true);
1944 writeOperand(II->getUnwindDest(), true);
1946 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1948 TypePrinter.print(AI->getAllocatedType(), Out);
1949 if (AI->isUsedWithInAlloca())
1950 Out << ", inalloca";
1951 if (!AI->getArraySize() || AI->isArrayAllocation()) {
1953 writeOperand(AI->getArraySize(), true);
1955 if (AI->getAlignment()) {
1956 Out << ", align " << AI->getAlignment();
1958 } else if (isa<CastInst>(I)) {
1961 writeOperand(Operand, true); // Work with broken code
1964 TypePrinter.print(I.getType(), Out);
1965 } else if (isa<VAArgInst>(I)) {
1968 writeOperand(Operand, true); // Work with broken code
1971 TypePrinter.print(I.getType(), Out);
1972 } else if (Operand) { // Print the normal way.
1974 // PrintAllTypes - Instructions who have operands of all the same type
1975 // omit the type from all but the first operand. If the instruction has
1976 // different type operands (for example br), then they are all printed.
1977 bool PrintAllTypes = false;
1978 Type *TheType = Operand->getType();
1980 // Select, Store and ShuffleVector always print all types.
1981 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1982 || isa<ReturnInst>(I)) {
1983 PrintAllTypes = true;
1985 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1986 Operand = I.getOperand(i);
1987 // note that Operand shouldn't be null, but the test helps make dump()
1988 // more tolerant of malformed IR
1989 if (Operand && Operand->getType() != TheType) {
1990 PrintAllTypes = true; // We have differing types! Print them all!
1996 if (!PrintAllTypes) {
1998 TypePrinter.print(TheType, Out);
2002 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
2004 writeOperand(I.getOperand(i), PrintAllTypes);
2008 // Print atomic ordering/alignment for memory operations
2009 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
2011 writeAtomic(LI->getOrdering(), LI->getSynchScope());
2012 if (LI->getAlignment())
2013 Out << ", align " << LI->getAlignment();
2014 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
2016 writeAtomic(SI->getOrdering(), SI->getSynchScope());
2017 if (SI->getAlignment())
2018 Out << ", align " << SI->getAlignment();
2019 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
2020 writeAtomic(CXI->getOrdering(), CXI->getSynchScope());
2021 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
2022 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
2023 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
2024 writeAtomic(FI->getOrdering(), FI->getSynchScope());
2027 // Print Metadata info.
2028 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
2029 I.getAllMetadata(InstMD);
2030 if (!InstMD.empty()) {
2031 SmallVector<StringRef, 8> MDNames;
2032 I.getType()->getContext().getMDKindNames(MDNames);
2033 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
2034 unsigned Kind = InstMD[i].first;
2035 if (Kind < MDNames.size()) {
2036 Out << ", !" << MDNames[Kind];
2038 Out << ", !<unknown kind #" << Kind << ">";
2041 WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
2045 printInfoComment(I);
2048 static void WriteMDNodeComment(const MDNode *Node,
2049 formatted_raw_ostream &Out) {
2050 if (Node->getNumOperands() < 1)
2053 Value *Op = Node->getOperand(0);
2054 if (!Op || !isa<ConstantInt>(Op) || cast<ConstantInt>(Op)->getBitWidth() < 32)
2057 DIDescriptor Desc(Node);
2061 unsigned Tag = Desc.getTag();
2062 Out.PadToColumn(50);
2063 if (dwarf::TagString(Tag)) {
2066 } else if (Tag == dwarf::DW_TAG_user_base) {
2067 Out << "; [ DW_TAG_user_base ]";
2071 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
2072 Out << '!' << Slot << " = metadata ";
2073 printMDNodeBody(Node);
2076 void AssemblyWriter::writeAllMDNodes() {
2077 SmallVector<const MDNode *, 16> Nodes;
2078 Nodes.resize(Machine.mdn_size());
2079 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2081 Nodes[I->second] = cast<MDNode>(I->first);
2083 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2084 writeMDNode(i, Nodes[i]);
2088 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2089 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
2090 WriteMDNodeComment(Node, Out);
2094 void AssemblyWriter::writeAllAttributeGroups() {
2095 std::vector<std::pair<AttributeSet, unsigned> > asVec;
2096 asVec.resize(Machine.as_size());
2098 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
2100 asVec[I->second] = *I;
2102 for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
2103 I = asVec.begin(), E = asVec.end(); I != E; ++I)
2104 Out << "attributes #" << I->second << " = { "
2105 << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
2110 //===----------------------------------------------------------------------===//
2111 // External Interface declarations
2112 //===----------------------------------------------------------------------===//
2114 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2115 SlotTracker SlotTable(this);
2116 formatted_raw_ostream OS(ROS);
2117 AssemblyWriter W(OS, SlotTable, this, AAW);
2118 W.printModule(this);
2121 void NamedMDNode::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2122 SlotTracker SlotTable(getParent());
2123 formatted_raw_ostream OS(ROS);
2124 AssemblyWriter W(OS, SlotTable, getParent(), AAW);
2125 W.printNamedMDNode(this);
2128 void Type::print(raw_ostream &OS) const {
2130 OS << "<null Type>";
2134 TP.print(const_cast<Type*>(this), OS);
2136 // If the type is a named struct type, print the body as well.
2137 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
2138 if (!STy->isLiteral()) {
2140 TP.printStructBody(STy, OS);
2144 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2146 ROS << "printing a <null> value\n";
2149 formatted_raw_ostream OS(ROS);
2150 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2151 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2152 SlotTracker SlotTable(F);
2153 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2154 W.printInstruction(*I);
2155 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2156 SlotTracker SlotTable(BB->getParent());
2157 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2158 W.printBasicBlock(BB);
2159 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2160 SlotTracker SlotTable(GV->getParent());
2161 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2162 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2164 else if (const Function *F = dyn_cast<Function>(GV))
2167 W.printAlias(cast<GlobalAlias>(GV));
2168 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2169 const Function *F = N->getFunction();
2170 SlotTracker SlotTable(F);
2171 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
2172 W.printMDNodeBody(N);
2173 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2174 TypePrinting TypePrinter;
2175 TypePrinter.print(C->getType(), OS);
2177 WriteConstantInternal(OS, C, TypePrinter, 0, 0);
2178 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2179 isa<Argument>(this)) {
2180 this->printAsOperand(OS);
2182 // Otherwise we don't know what it is. Call the virtual function to
2183 // allow a subclass to print itself.
2188 void Value::printAsOperand(raw_ostream &O, bool PrintType, const Module *M) const {
2189 // Fast path: Don't construct and populate a TypePrinting object if we
2190 // won't be needing any types printed.
2192 ((!isa<Constant>(this) && !isa<MDNode>(this)) ||
2193 hasName() || isa<GlobalValue>(this))) {
2194 WriteAsOperandInternal(O, this, 0, 0, M);
2199 M = getModuleFromVal(this);
2201 TypePrinting TypePrinter;
2203 TypePrinter.incorporateTypes(*M);
2205 TypePrinter.print(getType(), O);
2209 WriteAsOperandInternal(O, this, &TypePrinter, 0, M);
2212 // Value::printCustom - subclasses should override this to implement printing.
2213 void Value::printCustom(raw_ostream &OS) const {
2214 llvm_unreachable("Unknown value to print out!");
2217 // Value::dump - allow easy printing of Values from the debugger.
2218 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2220 // Type::dump - allow easy printing of Types from the debugger.
2221 void Type::dump() const { print(dbgs()); }
2223 // Module::dump() - Allow printing of Modules from the debugger.
2224 void Module::dump() const { print(dbgs(), 0); }
2226 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
2227 void NamedMDNode::dump() const { print(dbgs(), 0); }