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/Assembly/Writer.h
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/Assembly/AsmAnnotationWriter.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instruction.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Module.h"
27 #include "llvm/ValueSymbolTable.h"
28 #include "llvm/TypeSymbolTable.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
39 // Make virtual table appear in this compilation unit.
40 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
42 //===----------------------------------------------------------------------===//
44 //===----------------------------------------------------------------------===//
46 static const Module *getModuleFromVal(const Value *V) {
47 if (const Argument *MA = dyn_cast<Argument>(V))
48 return MA->getParent() ? MA->getParent()->getParent() : 0;
50 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
51 return BB->getParent() ? BB->getParent()->getParent() : 0;
53 if (const Instruction *I = dyn_cast<Instruction>(V)) {
54 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
55 return M ? M->getParent() : 0;
58 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
59 return GV->getParent();
63 // PrintEscapedString - Print each character of the specified string, escaping
64 // it if it is not printable or if it is an escape char.
65 static void PrintEscapedString(const char *Str, unsigned Length,
67 for (unsigned i = 0; i != Length; ++i) {
68 unsigned char C = Str[i];
69 if (isprint(C) && C != '\\' && C != '"' && isprint(C))
72 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
76 // PrintEscapedString - Print each character of the specified string, escaping
77 // it if it is not printable or if it is an escape char.
78 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
79 PrintEscapedString(Str.c_str(), Str.size(), Out);
89 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
90 /// prefixed with % (if the string only contains simple characters) or is
91 /// surrounded with ""'s (if it has special chars in it). Print it out.
92 static void PrintLLVMName(raw_ostream &OS, const char *NameStr,
93 unsigned NameLen, PrefixType Prefix) {
94 assert(NameStr && "Cannot get empty name!");
96 default: assert(0 && "Bad prefix!");
98 case GlobalPrefix: OS << '@'; break;
99 case LabelPrefix: break;
100 case LocalPrefix: OS << '%'; break;
103 // Scan the name to see if it needs quotes first.
104 bool NeedsQuotes = isdigit(NameStr[0]);
106 for (unsigned i = 0; i != NameLen; ++i) {
108 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
115 // If we didn't need any quotes, just write out the name in one blast.
117 OS.write(NameStr, NameLen);
121 // Okay, we need quotes. Output the quotes and escape any scary characters as
124 PrintEscapedString(NameStr, NameLen, OS);
128 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
129 /// prefixed with % (if the string only contains simple characters) or is
130 /// surrounded with ""'s (if it has special chars in it). Print it out.
131 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
132 PrintLLVMName(OS, V->getNameStart(), V->getNameLen(),
133 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
136 //===----------------------------------------------------------------------===//
137 // TypePrinting Class: Type printing machinery
138 //===----------------------------------------------------------------------===//
141 /// TypePrinting - Type printing machinery.
143 std::map<const Type *, std::string> TypeNames;
146 TypePrinting(const Module *M, raw_ostream &os);
148 void print(const Type *Ty);
149 void printAtLeastOneLevel(const Type *Ty);
151 } // end anonymous namespace.
153 TypePrinting::TypePrinting(const Module *M, raw_ostream &os) : OS(os) {
156 // If the module has a symbol table, take all global types and stuff their
157 // names into the TypeNames map.
158 const TypeSymbolTable &ST = M->getTypeSymbolTable();
159 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
161 const Type *Ty = cast<Type>(TI->second);
163 // As a heuristic, don't insert pointer to primitive types, because
164 // they are used too often to have a single useful name.
165 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
166 const Type *PETy = PTy->getElementType();
167 if ((PETy->isPrimitiveType() || PETy->isInteger()) &&
168 !isa<OpaqueType>(PETy))
173 raw_string_ostream NameOS(NameStr);
174 PrintLLVMName(NameOS, TI->first.c_str(), TI->first.length(), LocalPrefix);
175 TypeNames.insert(std::make_pair(Ty, NameOS.str()));
179 static void calcTypeName(const Type *Ty,
180 std::vector<const Type *> &TypeStack,
181 std::map<const Type *, std::string> &TypeNames,
182 std::string &Result) {
183 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
184 Result += Ty->getDescription(); // Base case
188 // Check to see if the type is named.
189 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
190 if (I != TypeNames.end()) {
195 if (isa<OpaqueType>(Ty)) {
200 // Check to see if the Type is already on the stack...
201 unsigned Slot = 0, CurSize = TypeStack.size();
202 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
204 // This is another base case for the recursion. In this case, we know
205 // that we have looped back to a type that we have previously visited.
206 // Generate the appropriate upreference to handle this.
207 if (Slot < CurSize) {
208 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
212 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
214 switch (Ty->getTypeID()) {
215 case Type::IntegerTyID: {
216 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
217 Result += "i" + utostr(BitWidth);
220 case Type::FunctionTyID: {
221 const FunctionType *FTy = cast<FunctionType>(Ty);
222 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
224 for (FunctionType::param_iterator I = FTy->param_begin(),
225 E = FTy->param_end(); I != E; ++I) {
226 if (I != FTy->param_begin())
228 calcTypeName(*I, TypeStack, TypeNames, Result);
230 if (FTy->isVarArg()) {
231 if (FTy->getNumParams()) Result += ", ";
237 case Type::StructTyID: {
238 const StructType *STy = cast<StructType>(Ty);
242 for (StructType::element_iterator I = STy->element_begin(),
243 E = STy->element_end(); I != E; ++I) {
244 calcTypeName(*I, TypeStack, TypeNames, Result);
245 if (next(I) != STy->element_end())
254 case Type::PointerTyID: {
255 const PointerType *PTy = cast<PointerType>(Ty);
256 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
257 if (unsigned AddressSpace = PTy->getAddressSpace())
258 Result += " addrspace(" + utostr(AddressSpace) + ")";
262 case Type::ArrayTyID: {
263 const ArrayType *ATy = cast<ArrayType>(Ty);
264 Result += "[" + utostr(ATy->getNumElements()) + " x ";
265 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
269 case Type::VectorTyID: {
270 const VectorType *PTy = cast<VectorType>(Ty);
271 Result += "<" + utostr(PTy->getNumElements()) + " x ";
272 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
276 case Type::OpaqueTyID:
280 Result += "<unrecognized-type>";
284 TypeStack.pop_back(); // Remove self from stack...
287 /// printTypeInt - The internal guts of printing out a type that has a
288 /// potentially named portion.
290 void TypePrinting::print(const Type *Ty) {
291 // Primitive types always print out their description, regardless of whether
292 // they have been named or not.
293 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
294 OS << Ty->getDescription();
298 // Check to see if the type is named.
299 std::map<const Type*, std::string>::iterator I = TypeNames.find(Ty);
300 if (I != TypeNames.end()) {
305 // Otherwise we have a type that has not been named but is a derived type.
306 // Carefully recurse the type hierarchy to print out any contained symbolic
308 std::vector<const Type *> TypeStack;
309 std::string TypeName;
310 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
311 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
315 /// printAtLeastOneLevel - Print out one level of the possibly complex type
316 /// without considering any symbolic types that we may have equal to it.
317 void TypePrinting::printAtLeastOneLevel(const Type *Ty) {
318 // FIXME: Just call calcTypeName!
319 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
320 print(FTy->getReturnType());
322 for (FunctionType::param_iterator I = FTy->param_begin(),
323 E = FTy->param_end(); I != E; ++I) {
324 if (I != FTy->param_begin())
328 if (FTy->isVarArg()) {
329 if (FTy->getNumParams()) OS << ", ";
336 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
340 for (StructType::element_iterator I = STy->element_begin(),
341 E = STy->element_end(); I != E; ++I) {
342 if (I != STy->element_begin())
352 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
353 print(PTy->getElementType());
354 if (unsigned AddressSpace = PTy->getAddressSpace())
355 OS << " addrspace(" << AddressSpace << ")";
360 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
361 OS << '[' << ATy->getNumElements() << " x ";
362 print(ATy->getElementType());
367 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
368 OS << '<' << PTy->getNumElements() << " x ";
369 print(PTy->getElementType());
374 if (isa<OpaqueType>(Ty)) {
379 if (!Ty->isPrimitiveType() && !isa<IntegerType>(Ty))
380 OS << "<unknown derived type>";
387 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
388 /// type, iff there is an entry in the modules symbol table for the specified
389 /// type or one of it's component types. This is slower than a simple x << Type
391 void llvm::WriteTypeSymbolic(raw_ostream &Out, const Type *Ty, const Module *M){
392 // FIXME: Remove this space.
395 // If they want us to print out a type, but there is no context, we can't
396 // print it symbolically.
398 Out << Ty->getDescription();
400 TypePrinting(M, Out).print(Ty);
404 // std::ostream adaptor.
405 void llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
407 raw_os_ostream RO(Out);
408 WriteTypeSymbolic(RO, Ty, M);
412 //===----------------------------------------------------------------------===//
413 // SlotTracker Class: Enumerate slot numbers for unnamed values
414 //===----------------------------------------------------------------------===//
418 /// This class provides computation of slot numbers for LLVM Assembly writing.
422 /// ValueMap - A mapping of Values to slot numbers
423 typedef DenseMap<const Value*, unsigned> ValueMap;
426 /// TheModule - The module for which we are holding slot numbers
427 const Module* TheModule;
429 /// TheFunction - The function for which we are holding slot numbers
430 const Function* TheFunction;
431 bool FunctionProcessed;
433 /// mMap - The TypePlanes map for the module level data
437 /// fMap - The TypePlanes map for the function level data
442 /// Construct from a module
443 explicit SlotTracker(const Module *M);
444 /// Construct from a function, starting out in incorp state.
445 explicit SlotTracker(const Function *F);
447 /// Return the slot number of the specified value in it's type
448 /// plane. If something is not in the SlotTracker, return -1.
449 int getLocalSlot(const Value *V);
450 int getGlobalSlot(const GlobalValue *V);
452 /// If you'd like to deal with a function instead of just a module, use
453 /// this method to get its data into the SlotTracker.
454 void incorporateFunction(const Function *F) {
456 FunctionProcessed = false;
459 /// After calling incorporateFunction, use this method to remove the
460 /// most recently incorporated function from the SlotTracker. This
461 /// will reset the state of the machine back to just the module contents.
462 void purgeFunction();
464 // Implementation Details
466 /// This function does the actual initialization.
467 inline void initialize();
469 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
470 void CreateModuleSlot(const GlobalValue *V);
472 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
473 void CreateFunctionSlot(const Value *V);
475 /// Add all of the module level global variables (and their initializers)
476 /// and function declarations, but not the contents of those functions.
477 void processModule();
479 /// Add all of the functions arguments, basic blocks, and instructions
480 void processFunction();
482 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
483 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
486 } // end anonymous namespace
489 static SlotTracker *createSlotTracker(const Value *V) {
490 if (const Argument *FA = dyn_cast<Argument>(V))
491 return new SlotTracker(FA->getParent());
493 if (const Instruction *I = dyn_cast<Instruction>(V))
494 return new SlotTracker(I->getParent()->getParent());
496 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
497 return new SlotTracker(BB->getParent());
499 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
500 return new SlotTracker(GV->getParent());
502 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
503 return new SlotTracker(GA->getParent());
505 if (const Function *Func = dyn_cast<Function>(V))
506 return new SlotTracker(Func);
512 #define ST_DEBUG(X) cerr << X
517 // Module level constructor. Causes the contents of the Module (sans functions)
518 // to be added to the slot table.
519 SlotTracker::SlotTracker(const Module *M)
520 : TheModule(M), TheFunction(0), FunctionProcessed(false), mNext(0), fNext(0) {
523 // Function level constructor. Causes the contents of the Module and the one
524 // function provided to be added to the slot table.
525 SlotTracker::SlotTracker(const Function *F)
526 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
530 inline void SlotTracker::initialize() {
533 TheModule = 0; ///< Prevent re-processing next time we're called.
536 if (TheFunction && !FunctionProcessed)
540 // Iterate through all the global variables, functions, and global
541 // variable initializers and create slots for them.
542 void SlotTracker::processModule() {
543 ST_DEBUG("begin processModule!\n");
545 // Add all of the unnamed global variables to the value table.
546 for (Module::const_global_iterator I = TheModule->global_begin(),
547 E = TheModule->global_end(); I != E; ++I)
551 // Add all the unnamed functions to the table.
552 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
557 ST_DEBUG("end processModule!\n");
561 // Process the arguments, basic blocks, and instructions of a function.
562 void SlotTracker::processFunction() {
563 ST_DEBUG("begin processFunction!\n");
566 // Add all the function arguments with no names.
567 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
568 AE = TheFunction->arg_end(); AI != AE; ++AI)
570 CreateFunctionSlot(AI);
572 ST_DEBUG("Inserting Instructions:\n");
574 // Add all of the basic blocks and instructions with no names.
575 for (Function::const_iterator BB = TheFunction->begin(),
576 E = TheFunction->end(); BB != E; ++BB) {
578 CreateFunctionSlot(BB);
579 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
580 if (I->getType() != Type::VoidTy && !I->hasName())
581 CreateFunctionSlot(I);
584 FunctionProcessed = true;
586 ST_DEBUG("end processFunction!\n");
589 /// Clean up after incorporating a function. This is the only way to get out of
590 /// the function incorporation state that affects get*Slot/Create*Slot. Function
591 /// incorporation state is indicated by TheFunction != 0.
592 void SlotTracker::purgeFunction() {
593 ST_DEBUG("begin purgeFunction!\n");
594 fMap.clear(); // Simply discard the function level map
596 FunctionProcessed = false;
597 ST_DEBUG("end purgeFunction!\n");
600 /// getGlobalSlot - Get the slot number of a global value.
601 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
602 // Check for uninitialized state and do lazy initialization.
605 // Find the type plane in the module map
606 ValueMap::iterator MI = mMap.find(V);
607 return MI == mMap.end() ? -1 : (int)MI->second;
611 /// getLocalSlot - Get the slot number for a value that is local to a function.
612 int SlotTracker::getLocalSlot(const Value *V) {
613 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
615 // Check for uninitialized state and do lazy initialization.
618 ValueMap::iterator FI = fMap.find(V);
619 return FI == fMap.end() ? -1 : (int)FI->second;
623 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
624 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
625 assert(V && "Can't insert a null Value into SlotTracker!");
626 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
627 assert(!V->hasName() && "Doesn't need a slot!");
629 unsigned DestSlot = mNext++;
632 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
634 // G = Global, F = Function, A = Alias, o = other
635 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
636 (isa<Function>(V) ? 'F' :
637 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
641 /// CreateSlot - Create a new slot for the specified value if it has no name.
642 void SlotTracker::CreateFunctionSlot(const Value *V) {
643 assert(V->getType() != Type::VoidTy && !V->hasName() &&
644 "Doesn't need a slot!");
646 unsigned DestSlot = fNext++;
649 // G = Global, F = Function, o = other
650 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
651 DestSlot << " [o]\n");
656 //===----------------------------------------------------------------------===//
657 // AsmWriter Implementation
658 //===----------------------------------------------------------------------===//
660 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
661 TypePrinting &TypePrinter,
662 SlotTracker *Machine);
666 static const char *getPredicateText(unsigned predicate) {
667 const char * pred = "unknown";
669 case FCmpInst::FCMP_FALSE: pred = "false"; break;
670 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
671 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
672 case FCmpInst::FCMP_OGE: pred = "oge"; break;
673 case FCmpInst::FCMP_OLT: pred = "olt"; break;
674 case FCmpInst::FCMP_OLE: pred = "ole"; break;
675 case FCmpInst::FCMP_ONE: pred = "one"; break;
676 case FCmpInst::FCMP_ORD: pred = "ord"; break;
677 case FCmpInst::FCMP_UNO: pred = "uno"; break;
678 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
679 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
680 case FCmpInst::FCMP_UGE: pred = "uge"; break;
681 case FCmpInst::FCMP_ULT: pred = "ult"; break;
682 case FCmpInst::FCMP_ULE: pred = "ule"; break;
683 case FCmpInst::FCMP_UNE: pred = "une"; break;
684 case FCmpInst::FCMP_TRUE: pred = "true"; break;
685 case ICmpInst::ICMP_EQ: pred = "eq"; break;
686 case ICmpInst::ICMP_NE: pred = "ne"; break;
687 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
688 case ICmpInst::ICMP_SGE: pred = "sge"; break;
689 case ICmpInst::ICMP_SLT: pred = "slt"; break;
690 case ICmpInst::ICMP_SLE: pred = "sle"; break;
691 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
692 case ICmpInst::ICMP_UGE: pred = "uge"; break;
693 case ICmpInst::ICMP_ULT: pred = "ult"; break;
694 case ICmpInst::ICMP_ULE: pred = "ule"; break;
699 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
700 TypePrinting &TypePrinter, SlotTracker *Machine) {
701 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
702 if (CI->getType() == Type::Int1Ty) {
703 Out << (CI->getZExtValue() ? "true" : "false");
706 Out << CI->getValue();
710 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
711 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
712 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
713 // We would like to output the FP constant value in exponential notation,
714 // but we cannot do this if doing so will lose precision. Check here to
715 // make sure that we only output it in exponential format if we can parse
716 // the value back and get the same value.
719 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
720 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
721 CFP->getValueAPF().convertToFloat();
722 std::string StrVal = ftostr(CFP->getValueAPF());
724 // Check to make sure that the stringized number is not some string like
725 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
726 // that the string matches the "[-+]?[0-9]" regex.
728 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
729 ((StrVal[0] == '-' || StrVal[0] == '+') &&
730 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
731 // Reparse stringized version!
732 if (atof(StrVal.c_str()) == Val) {
737 // Otherwise we could not reparse it to exactly the same value, so we must
738 // output the string in hexadecimal format! Note that loading and storing
739 // floating point types changes the bits of NaNs on some hosts, notably
740 // x86, so we must not use these types.
741 assert(sizeof(double) == sizeof(uint64_t) &&
742 "assuming that double is 64 bits!");
744 APFloat apf = CFP->getValueAPF();
745 // Floats are represented in ASCII IR as double, convert.
747 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
750 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
755 // Some form of long double. These appear as a magic letter identifying
756 // the type, then a fixed number of hex digits.
758 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended)
760 else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
762 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
765 assert(0 && "Unsupported floating point type");
766 // api needed to prevent premature destruction
767 APInt api = CFP->getValueAPF().bitcastToAPInt();
768 const uint64_t* p = api.getRawData();
771 int width = api.getBitWidth();
772 for (int j=0; j<width; j+=4, shiftcount-=4) {
773 unsigned int nibble = (word>>shiftcount) & 15;
775 Out << (unsigned char)(nibble + '0');
777 Out << (unsigned char)(nibble - 10 + 'A');
778 if (shiftcount == 0 && j+4 < width) {
782 shiftcount = width-j-4;
788 if (isa<ConstantAggregateZero>(CV)) {
789 Out << "zeroinitializer";
793 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
794 // As a special case, print the array as a string if it is an array of
795 // i8 with ConstantInt values.
797 const Type *ETy = CA->getType()->getElementType();
798 if (CA->isString()) {
800 PrintEscapedString(CA->getAsString(), Out);
802 } else { // Cannot output in string format...
804 if (CA->getNumOperands()) {
805 TypePrinter.print(ETy);
807 WriteAsOperandInternal(Out, CA->getOperand(0),
808 TypePrinter, Machine);
809 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
811 TypePrinter.print(ETy);
813 WriteAsOperandInternal(Out, CA->getOperand(i), TypePrinter, Machine);
821 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
822 if (CS->getType()->isPacked())
825 unsigned N = CS->getNumOperands();
828 TypePrinter.print(CS->getOperand(0)->getType());
831 WriteAsOperandInternal(Out, CS->getOperand(0), TypePrinter, Machine);
833 for (unsigned i = 1; i < N; i++) {
835 TypePrinter.print(CS->getOperand(i)->getType());
838 WriteAsOperandInternal(Out, CS->getOperand(i), TypePrinter, Machine);
844 if (CS->getType()->isPacked())
849 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
850 const Type *ETy = CP->getType()->getElementType();
851 assert(CP->getNumOperands() > 0 &&
852 "Number of operands for a PackedConst must be > 0");
854 TypePrinter.print(ETy);
856 WriteAsOperandInternal(Out, CP->getOperand(0), TypePrinter, Machine);
857 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
859 TypePrinter.print(ETy);
861 WriteAsOperandInternal(Out, CP->getOperand(i), TypePrinter, Machine);
867 if (isa<ConstantPointerNull>(CV)) {
872 if (isa<UndefValue>(CV)) {
877 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
878 Out << CE->getOpcodeName();
880 Out << ' ' << getPredicateText(CE->getPredicate());
883 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
884 TypePrinter.print((*OI)->getType());
886 WriteAsOperandInternal(Out, *OI, TypePrinter, Machine);
887 if (OI+1 != CE->op_end())
891 if (CE->hasIndices()) {
892 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
893 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
894 Out << ", " << Indices[i];
899 TypePrinter.print(CE->getType());
906 Out << "<placeholder or erroneous Constant>";
910 /// WriteAsOperand - Write the name of the specified value out to the specified
911 /// ostream. This can be useful when you just want to print int %reg126, not
912 /// the whole instruction that generated it.
914 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
915 TypePrinting &TypePrinter,
916 SlotTracker *Machine) {
918 PrintLLVMName(Out, V);
922 const Constant *CV = dyn_cast<Constant>(V);
923 if (CV && !isa<GlobalValue>(CV)) {
924 WriteConstantInt(Out, CV, TypePrinter, Machine);
928 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
930 if (IA->hasSideEffects())
931 Out << "sideeffect ";
933 PrintEscapedString(IA->getAsmString(), Out);
935 PrintEscapedString(IA->getConstraintString(), Out);
943 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
944 Slot = Machine->getGlobalSlot(GV);
947 Slot = Machine->getLocalSlot(V);
950 Machine = createSlotTracker(V);
952 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
953 Slot = Machine->getGlobalSlot(GV);
956 Slot = Machine->getLocalSlot(V);
965 Out << Prefix << Slot;
970 /// WriteAsOperand - Write the name of the specified value out to the specified
971 /// ostream. This can be useful when you just want to print int %reg126, not
972 /// the whole instruction that generated it.
974 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
975 const Module *Context) {
976 raw_os_ostream OS(Out);
977 WriteAsOperand(OS, V, PrintType, Context);
980 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
981 const Module *Context) {
982 if (Context == 0) Context = getModuleFromVal(V);
984 TypePrinting TypePrinter(Context, Out);
986 TypePrinter.print(V->getType());
990 WriteAsOperandInternal(Out, V, TypePrinter, 0);
996 class AssemblyWriter {
998 SlotTracker &Machine;
999 const Module *TheModule;
1000 TypePrinting TypePrinter;
1001 AssemblyAnnotationWriter *AnnotationWriter;
1003 inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
1004 AssemblyAnnotationWriter *AAW)
1005 : Out(o), Machine(Mac), TheModule(M), TypePrinter(M, Out),
1006 AnnotationWriter(AAW) {
1009 void write(const Module *M) { printModule(M); }
1011 void write(const GlobalValue *G) {
1012 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
1014 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
1016 else if (const Function *F = dyn_cast<Function>(G))
1019 assert(0 && "Unknown global");
1022 void write(const BasicBlock *BB) { printBasicBlock(BB); }
1023 void write(const Instruction *I) { printInstruction(*I); }
1024 // void write(const Type *Ty) { printType(Ty); }
1026 void writeOperand(const Value *Op, bool PrintType);
1027 void writeParamOperand(const Value *Operand, Attributes Attrs);
1029 const Module* getModule() { return TheModule; }
1032 void printModule(const Module *M);
1033 void printTypeSymbolTable(const TypeSymbolTable &ST);
1034 void printGlobal(const GlobalVariable *GV);
1035 void printAlias(const GlobalAlias *GV);
1036 void printFunction(const Function *F);
1037 void printArgument(const Argument *FA, Attributes Attrs);
1038 void printBasicBlock(const BasicBlock *BB);
1039 void printInstruction(const Instruction &I);
1041 // printType - Go to extreme measures to attempt to print out a short,
1042 // symbolic version of a type name.
1044 void printType(const Type *Ty) {
1045 TypePrinter.print(Ty);
1048 // printInfoComment - Print a little comment after the instruction indicating
1049 // which slot it occupies.
1050 void printInfoComment(const Value &V);
1052 } // end of llvm namespace
1055 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1057 Out << "<null operand!>";
1060 printType(Operand->getType());
1063 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1067 void AssemblyWriter::writeParamOperand(const Value *Operand,
1070 Out << "<null operand!>";
1073 printType(Operand->getType());
1074 // Print parameter attributes list
1075 if (Attrs != Attribute::None)
1076 Out << ' ' << Attribute::getAsString(Attrs);
1078 // Print the operand
1079 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1083 void AssemblyWriter::printModule(const Module *M) {
1084 if (!M->getModuleIdentifier().empty() &&
1085 // Don't print the ID if it will start a new line (which would
1086 // require a comment char before it).
1087 M->getModuleIdentifier().find('\n') == std::string::npos)
1088 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1090 if (!M->getDataLayout().empty())
1091 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1092 if (!M->getTargetTriple().empty())
1093 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1095 if (!M->getModuleInlineAsm().empty()) {
1096 // Split the string into lines, to make it easier to read the .ll file.
1097 std::string Asm = M->getModuleInlineAsm();
1099 size_t NewLine = Asm.find_first_of('\n', CurPos);
1100 while (NewLine != std::string::npos) {
1101 // We found a newline, print the portion of the asm string from the
1102 // last newline up to this newline.
1103 Out << "module asm \"";
1104 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1108 NewLine = Asm.find_first_of('\n', CurPos);
1110 Out << "module asm \"";
1111 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1115 // Loop over the dependent libraries and emit them.
1116 Module::lib_iterator LI = M->lib_begin();
1117 Module::lib_iterator LE = M->lib_end();
1119 Out << "deplibs = [ ";
1121 Out << '"' << *LI << '"';
1129 // Loop over the symbol table, emitting all named constants.
1130 printTypeSymbolTable(M->getTypeSymbolTable());
1132 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1136 // Output all aliases.
1137 if (!M->alias_empty()) Out << "\n";
1138 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1142 // Output all of the functions.
1143 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1147 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1149 case GlobalValue::PrivateLinkage: Out << "private "; break;
1150 case GlobalValue::InternalLinkage: Out << "internal "; break;
1151 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
1152 case GlobalValue::WeakLinkage: Out << "weak "; break;
1153 case GlobalValue::CommonLinkage: Out << "common "; break;
1154 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1155 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1156 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1157 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1158 case GlobalValue::ExternalLinkage: break;
1159 case GlobalValue::GhostLinkage:
1160 Out << "GhostLinkage not allowed in AsmWriter!\n";
1166 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1169 default: assert(0 && "Invalid visibility style!");
1170 case GlobalValue::DefaultVisibility: break;
1171 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1172 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1176 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1177 if (GV->hasName()) {
1178 PrintLLVMName(Out, GV);
1182 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1185 PrintLinkage(GV->getLinkage(), Out);
1186 PrintVisibility(GV->getVisibility(), Out);
1188 if (GV->isThreadLocal()) Out << "thread_local ";
1189 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1190 Out << "addrspace(" << AddressSpace << ") ";
1191 Out << (GV->isConstant() ? "constant " : "global ");
1192 printType(GV->getType()->getElementType());
1194 if (GV->hasInitializer()) {
1196 writeOperand(GV->getInitializer(), false);
1199 if (GV->hasSection())
1200 Out << ", section \"" << GV->getSection() << '"';
1201 if (GV->getAlignment())
1202 Out << ", align " << GV->getAlignment();
1204 printInfoComment(*GV);
1208 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1209 // Don't crash when dumping partially built GA
1211 Out << "<<nameless>> = ";
1213 PrintLLVMName(Out, GA);
1216 PrintVisibility(GA->getVisibility(), Out);
1220 PrintLinkage(GA->getLinkage(), Out);
1222 const Constant *Aliasee = GA->getAliasee();
1224 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1225 printType(GV->getType());
1227 PrintLLVMName(Out, GV);
1228 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1229 printType(F->getFunctionType());
1232 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1233 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1234 printType(GA->getType());
1236 PrintLLVMName(Out, GA);
1238 const ConstantExpr *CE = 0;
1239 if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
1240 (CE->getOpcode() == Instruction::BitCast)) {
1241 writeOperand(CE, false);
1243 assert(0 && "Unsupported aliasee");
1246 printInfoComment(*GA);
1250 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1252 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1255 PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1258 // Make sure we print out at least one level of the type structure, so
1259 // that we do not get %FILE = type %FILE
1260 TypePrinter.printAtLeastOneLevel(TI->second);
1265 /// printFunction - Print all aspects of a function.
1267 void AssemblyWriter::printFunction(const Function *F) {
1268 // Print out the return type and name.
1271 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1273 if (F->isDeclaration())
1278 PrintLinkage(F->getLinkage(), Out);
1279 PrintVisibility(F->getVisibility(), Out);
1281 // Print the calling convention.
1282 switch (F->getCallingConv()) {
1283 case CallingConv::C: break; // default
1284 case CallingConv::Fast: Out << "fastcc "; break;
1285 case CallingConv::Cold: Out << "coldcc "; break;
1286 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1287 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1288 default: Out << "cc" << F->getCallingConv() << " "; break;
1291 const FunctionType *FT = F->getFunctionType();
1292 const AttrListPtr &Attrs = F->getAttributes();
1293 Attributes RetAttrs = Attrs.getRetAttributes();
1294 if (RetAttrs != Attribute::None)
1295 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1296 printType(F->getReturnType());
1298 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1300 Machine.incorporateFunction(F);
1302 // Loop over the arguments, printing them...
1305 if (!F->isDeclaration()) {
1306 // If this isn't a declaration, print the argument names as well.
1307 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1309 // Insert commas as we go... the first arg doesn't get a comma
1310 if (I != F->arg_begin()) Out << ", ";
1311 printArgument(I, Attrs.getParamAttributes(Idx));
1315 // Otherwise, print the types from the function type.
1316 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1317 // Insert commas as we go... the first arg doesn't get a comma
1321 printType(FT->getParamType(i));
1323 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1324 if (ArgAttrs != Attribute::None)
1325 Out << ' ' << Attribute::getAsString(ArgAttrs);
1329 // Finish printing arguments...
1330 if (FT->isVarArg()) {
1331 if (FT->getNumParams()) Out << ", ";
1332 Out << "..."; // Output varargs portion of signature!
1335 Attributes FnAttrs = Attrs.getFnAttributes();
1336 if (FnAttrs != Attribute::None)
1337 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1338 if (F->hasSection())
1339 Out << " section \"" << F->getSection() << '"';
1340 if (F->getAlignment())
1341 Out << " align " << F->getAlignment();
1343 Out << " gc \"" << F->getGC() << '"';
1344 if (F->isDeclaration()) {
1349 // Output all of its basic blocks... for the function
1350 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1356 Machine.purgeFunction();
1359 /// printArgument - This member is called for every argument that is passed into
1360 /// the function. Simply print it out
1362 void AssemblyWriter::printArgument(const Argument *Arg,
1365 printType(Arg->getType());
1367 // Output parameter attributes list
1368 if (Attrs != Attribute::None)
1369 Out << ' ' << Attribute::getAsString(Attrs);
1371 // Output name, if available...
1372 if (Arg->hasName()) {
1374 PrintLLVMName(Out, Arg);
1378 /// printBasicBlock - This member is called for each basic block in a method.
1380 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1381 if (BB->hasName()) { // Print out the label if it exists...
1383 PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1385 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1386 Out << "\n; <label>:";
1387 int Slot = Machine.getLocalSlot(BB);
1394 if (BB->getParent() == 0)
1395 Out << "\t\t; Error: Block without parent!";
1396 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1397 // Output predecessors for the block...
1399 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1402 Out << " No predecessors!";
1405 writeOperand(*PI, false);
1406 for (++PI; PI != PE; ++PI) {
1408 writeOperand(*PI, false);
1415 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1417 // Output all of the instructions in the basic block...
1418 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1419 printInstruction(*I);
1421 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1425 /// printInfoComment - Print a little comment after the instruction indicating
1426 /// which slot it occupies.
1428 void AssemblyWriter::printInfoComment(const Value &V) {
1429 if (V.getType() != Type::VoidTy) {
1431 printType(V.getType());
1434 if (!V.hasName() && !isa<Instruction>(V)) {
1436 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1437 SlotNum = Machine.getGlobalSlot(GV);
1439 SlotNum = Machine.getLocalSlot(&V);
1443 Out << ':' << SlotNum; // Print out the def slot taken.
1445 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1449 // This member is called for each Instruction in a function..
1450 void AssemblyWriter::printInstruction(const Instruction &I) {
1451 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1455 // Print out name if it exists...
1457 PrintLLVMName(Out, &I);
1459 } else if (I.getType() != Type::VoidTy) {
1460 // Print out the def slot taken.
1461 int SlotNum = Machine.getLocalSlot(&I);
1463 Out << "<badref> = ";
1465 Out << '%' << SlotNum << " = ";
1468 // If this is a volatile load or store, print out the volatile marker.
1469 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1470 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1472 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1473 // If this is a call, check if it's a tail call.
1477 // Print out the opcode...
1478 Out << I.getOpcodeName();
1480 // Print out the compare instruction predicates
1481 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1482 Out << ' ' << getPredicateText(CI->getPredicate());
1484 // Print out the type of the operands...
1485 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1487 // Special case conditional branches to swizzle the condition out to the front
1488 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1489 BranchInst &BI(cast<BranchInst>(I));
1491 writeOperand(BI.getCondition(), true);
1493 writeOperand(BI.getSuccessor(0), true);
1495 writeOperand(BI.getSuccessor(1), true);
1497 } else if (isa<SwitchInst>(I)) {
1498 // Special case switch statement to get formatting nice and correct...
1500 writeOperand(Operand , true);
1502 writeOperand(I.getOperand(1), true);
1505 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1507 writeOperand(I.getOperand(op ), true);
1509 writeOperand(I.getOperand(op+1), true);
1512 } else if (isa<PHINode>(I)) {
1514 printType(I.getType());
1517 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1518 if (op) Out << ", ";
1520 writeOperand(I.getOperand(op ), false); Out << ", ";
1521 writeOperand(I.getOperand(op+1), false); Out << " ]";
1523 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1525 writeOperand(I.getOperand(0), true);
1526 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1528 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1530 writeOperand(I.getOperand(0), true); Out << ", ";
1531 writeOperand(I.getOperand(1), true);
1532 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1534 } else if (isa<ReturnInst>(I) && !Operand) {
1536 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1537 // Print the calling convention being used.
1538 switch (CI->getCallingConv()) {
1539 case CallingConv::C: break; // default
1540 case CallingConv::Fast: Out << " fastcc"; break;
1541 case CallingConv::Cold: Out << " coldcc"; break;
1542 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1543 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1544 default: Out << " cc" << CI->getCallingConv(); break;
1547 const PointerType *PTy = cast<PointerType>(Operand->getType());
1548 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1549 const Type *RetTy = FTy->getReturnType();
1550 const AttrListPtr &PAL = CI->getAttributes();
1552 if (PAL.getRetAttributes() != Attribute::None)
1553 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1555 // If possible, print out the short form of the call instruction. We can
1556 // only do this if the first argument is a pointer to a nonvararg function,
1557 // and if the return type is not a pointer to a function.
1560 if (!FTy->isVarArg() &&
1561 (!isa<PointerType>(RetTy) ||
1562 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1565 writeOperand(Operand, false);
1567 writeOperand(Operand, true);
1570 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1573 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1576 if (PAL.getFnAttributes() != Attribute::None)
1577 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1578 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1579 const PointerType *PTy = cast<PointerType>(Operand->getType());
1580 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1581 const Type *RetTy = FTy->getReturnType();
1582 const AttrListPtr &PAL = II->getAttributes();
1584 // Print the calling convention being used.
1585 switch (II->getCallingConv()) {
1586 case CallingConv::C: break; // default
1587 case CallingConv::Fast: Out << " fastcc"; break;
1588 case CallingConv::Cold: Out << " coldcc"; break;
1589 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1590 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1591 default: Out << " cc" << II->getCallingConv(); break;
1594 if (PAL.getRetAttributes() != Attribute::None)
1595 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1597 // If possible, print out the short form of the invoke instruction. We can
1598 // only do this if the first argument is a pointer to a nonvararg function,
1599 // and if the return type is not a pointer to a function.
1602 if (!FTy->isVarArg() &&
1603 (!isa<PointerType>(RetTy) ||
1604 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1607 writeOperand(Operand, false);
1609 writeOperand(Operand, true);
1612 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1615 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1619 if (PAL.getFnAttributes() != Attribute::None)
1620 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1622 Out << "\n\t\t\tto ";
1623 writeOperand(II->getNormalDest(), true);
1625 writeOperand(II->getUnwindDest(), true);
1627 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1629 printType(AI->getType()->getElementType());
1630 if (AI->isArrayAllocation()) {
1632 writeOperand(AI->getArraySize(), true);
1634 if (AI->getAlignment()) {
1635 Out << ", align " << AI->getAlignment();
1637 } else if (isa<CastInst>(I)) {
1640 writeOperand(Operand, true); // Work with broken code
1643 printType(I.getType());
1644 } else if (isa<VAArgInst>(I)) {
1647 writeOperand(Operand, true); // Work with broken code
1650 printType(I.getType());
1651 } else if (Operand) { // Print the normal way...
1653 // PrintAllTypes - Instructions who have operands of all the same type
1654 // omit the type from all but the first operand. If the instruction has
1655 // different type operands (for example br), then they are all printed.
1656 bool PrintAllTypes = false;
1657 const Type *TheType = Operand->getType();
1659 // Select, Store and ShuffleVector always print all types.
1660 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1661 || isa<ReturnInst>(I)) {
1662 PrintAllTypes = true;
1664 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1665 Operand = I.getOperand(i);
1666 // note that Operand shouldn't be null, but the test helps make dump()
1667 // more tolerant of malformed IR
1668 if (Operand && Operand->getType() != TheType) {
1669 PrintAllTypes = true; // We have differing types! Print them all!
1675 if (!PrintAllTypes) {
1681 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1683 writeOperand(I.getOperand(i), PrintAllTypes);
1687 // Print post operand alignment for load/store
1688 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1689 Out << ", align " << cast<LoadInst>(I).getAlignment();
1690 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1691 Out << ", align " << cast<StoreInst>(I).getAlignment();
1694 printInfoComment(I);
1699 //===----------------------------------------------------------------------===//
1700 // External Interface declarations
1701 //===----------------------------------------------------------------------===//
1703 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1704 raw_os_ostream OS(o);
1707 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1708 SlotTracker SlotTable(this);
1709 AssemblyWriter W(OS, SlotTable, this, AAW);
1713 void Type::print(std::ostream &o) const {
1714 raw_os_ostream OS(o);
1718 void Type::print(raw_ostream &o) const {
1722 o << getDescription();
1725 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1727 OS << "printing a <null> value\n";
1731 if (const Instruction *I = dyn_cast<Instruction>(this)) {
1732 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1733 SlotTracker SlotTable(F);
1734 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1736 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1737 SlotTracker SlotTable(BB->getParent());
1738 AssemblyWriter W(OS, SlotTable,
1739 BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1741 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1742 SlotTracker SlotTable(GV->getParent());
1743 AssemblyWriter W(OS, SlotTable, GV->getParent(), 0);
1745 } else if (const Constant *C = dyn_cast<Constant>(this)) {
1746 OS << C->getType()->getDescription() << ' ';
1747 TypePrinting TypePrinter(0, OS);
1748 WriteConstantInt(OS, C, TypePrinter, 0);
1749 } else if (const Argument *A = dyn_cast<Argument>(this)) {
1750 WriteAsOperand(OS, this, true,
1751 A->getParent() ? A->getParent()->getParent() : 0);
1752 } else if (isa<InlineAsm>(this)) {
1753 WriteAsOperand(OS, this, true, 0);
1755 assert(0 && "Unknown value to print out!");
1759 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
1760 raw_os_ostream OS(O);
1764 // Value::dump - allow easy printing of Values from the debugger.
1765 void Value::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1767 // Type::dump - allow easy printing of Types from the debugger.
1768 void Type::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1770 // Type::dump - allow easy printing of Types from the debugger.
1771 // This one uses type names from the given context module
1772 void Type::dump(const Module *Context) const {
1773 WriteTypeSymbolic(errs(), this, Context);
1778 // Module::dump() - Allow printing of Modules from the debugger.
1779 void Module::dump() const { print(errs(), 0); errs().flush(); }