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);
152 void calcTypeName(const Type *Ty, SmallVectorImpl<const Type *> &TypeStack,
153 std::string &Result);
155 } // end anonymous namespace.
157 TypePrinting::TypePrinting(const Module *M, raw_ostream &os) : OS(os) {
160 // If the module has a symbol table, take all global types and stuff their
161 // names into the TypeNames map.
162 const TypeSymbolTable &ST = M->getTypeSymbolTable();
163 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
165 const Type *Ty = cast<Type>(TI->second);
167 // As a heuristic, don't insert pointer to primitive types, because
168 // they are used too often to have a single useful name.
169 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
170 const Type *PETy = PTy->getElementType();
171 if ((PETy->isPrimitiveType() || PETy->isInteger()) &&
172 !isa<OpaqueType>(PETy))
176 // Get the name as a string and insert it into TypeNames.
178 raw_string_ostream NameOS(NameStr);
179 PrintLLVMName(NameOS, TI->first.c_str(), TI->first.length(), LocalPrefix);
180 TypeNames.insert(std::make_pair(Ty, NameOS.str()));
184 void TypePrinting::calcTypeName(const Type *Ty,
185 SmallVectorImpl<const Type *> &TypeStack,
186 std::string &Result) {
187 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
188 Result += Ty->getDescription(); // Base case
192 // Check to see if the type is named.
193 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
194 if (I != TypeNames.end()) {
199 if (isa<OpaqueType>(Ty)) {
204 // Check to see if the Type is already on the stack...
205 unsigned Slot = 0, CurSize = TypeStack.size();
206 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
208 // This is another base case for the recursion. In this case, we know
209 // that we have looped back to a type that we have previously visited.
210 // Generate the appropriate upreference to handle this.
211 if (Slot < CurSize) {
212 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
216 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
218 switch (Ty->getTypeID()) {
219 case Type::FunctionTyID: {
220 const FunctionType *FTy = cast<FunctionType>(Ty);
221 calcTypeName(FTy->getReturnType(), TypeStack, Result);
223 for (FunctionType::param_iterator I = FTy->param_begin(),
224 E = FTy->param_end(); I != E; ++I) {
225 if (I != FTy->param_begin())
227 calcTypeName(*I, TypeStack, Result);
229 if (FTy->isVarArg()) {
230 if (FTy->getNumParams()) Result += ", ";
236 case Type::StructTyID: {
237 const StructType *STy = cast<StructType>(Ty);
241 for (StructType::element_iterator I = STy->element_begin(),
242 E = STy->element_end(); I != E; ++I) {
243 calcTypeName(*I, TypeStack, Result);
244 if (next(I) != STy->element_end())
253 case Type::PointerTyID: {
254 const PointerType *PTy = cast<PointerType>(Ty);
255 calcTypeName(PTy->getElementType(), TypeStack, Result);
256 if (unsigned AddressSpace = PTy->getAddressSpace())
257 Result += " addrspace(" + utostr(AddressSpace) + ")";
261 case Type::ArrayTyID: {
262 const ArrayType *ATy = cast<ArrayType>(Ty);
263 Result += "[" + utostr(ATy->getNumElements()) + " x ";
264 calcTypeName(ATy->getElementType(), TypeStack, Result);
268 case Type::VectorTyID: {
269 const VectorType *PTy = cast<VectorType>(Ty);
270 Result += "<" + utostr(PTy->getNumElements()) + " x ";
271 calcTypeName(PTy->getElementType(), TypeStack, Result);
275 case Type::OpaqueTyID:
279 Result += "<unrecognized-type>";
283 TypeStack.pop_back(); // Remove self from stack...
286 /// printTypeInt - The internal guts of printing out a type that has a
287 /// potentially named portion.
289 void TypePrinting::print(const Type *Ty) {
290 // Primitive types always print out their description, regardless of whether
291 // they have been named or not.
292 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
293 OS << Ty->getDescription();
297 // Check to see if the type is named.
298 std::map<const Type*, std::string>::iterator I = TypeNames.find(Ty);
299 if (I != TypeNames.end()) {
304 // Otherwise we have a type that has not been named but is a derived type.
305 // Carefully recurse the type hierarchy to print out any contained symbolic
307 SmallVector<const Type *, 16> TypeStack;
308 std::string TypeName;
309 calcTypeName(Ty, TypeStack, TypeName);
310 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
314 /// printAtLeastOneLevel - Print out one level of the possibly complex type
315 /// without considering any symbolic types that we may have equal to it.
316 void TypePrinting::printAtLeastOneLevel(const Type *Ty) {
317 // FIXME: Just call calcTypeName!
318 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
319 print(FTy->getReturnType());
321 for (FunctionType::param_iterator I = FTy->param_begin(),
322 E = FTy->param_end(); I != E; ++I) {
323 if (I != FTy->param_begin())
327 if (FTy->isVarArg()) {
328 if (FTy->getNumParams()) OS << ", ";
335 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
339 for (StructType::element_iterator I = STy->element_begin(),
340 E = STy->element_end(); I != E; ++I) {
341 if (I != STy->element_begin())
351 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
352 print(PTy->getElementType());
353 if (unsigned AddressSpace = PTy->getAddressSpace())
354 OS << " addrspace(" << AddressSpace << ")";
359 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
360 OS << '[' << ATy->getNumElements() << " x ";
361 print(ATy->getElementType());
366 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
367 OS << '<' << PTy->getNumElements() << " x ";
368 print(PTy->getElementType());
373 if (isa<OpaqueType>(Ty)) {
378 if (!Ty->isPrimitiveType() && !isa<IntegerType>(Ty))
379 OS << "<unknown derived type>";
386 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
387 /// type, iff there is an entry in the modules symbol table for the specified
388 /// type or one of it's component types. This is slower than a simple x << Type
390 void llvm::WriteTypeSymbolic(raw_ostream &Out, const Type *Ty, const Module *M){
391 // FIXME: Remove this space.
394 // If they want us to print out a type, but there is no context, we can't
395 // print it symbolically.
397 Out << Ty->getDescription();
399 TypePrinting(M, Out).print(Ty);
403 // std::ostream adaptor.
404 void llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
406 raw_os_ostream RO(Out);
407 WriteTypeSymbolic(RO, Ty, M);
411 //===----------------------------------------------------------------------===//
412 // SlotTracker Class: Enumerate slot numbers for unnamed values
413 //===----------------------------------------------------------------------===//
417 /// This class provides computation of slot numbers for LLVM Assembly writing.
421 /// ValueMap - A mapping of Values to slot numbers
422 typedef DenseMap<const Value*, unsigned> ValueMap;
425 /// TheModule - The module for which we are holding slot numbers
426 const Module* TheModule;
428 /// TheFunction - The function for which we are holding slot numbers
429 const Function* TheFunction;
430 bool FunctionProcessed;
432 /// mMap - The TypePlanes map for the module level data
436 /// fMap - The TypePlanes map for the function level data
441 /// Construct from a module
442 explicit SlotTracker(const Module *M);
443 /// Construct from a function, starting out in incorp state.
444 explicit SlotTracker(const Function *F);
446 /// Return the slot number of the specified value in it's type
447 /// plane. If something is not in the SlotTracker, return -1.
448 int getLocalSlot(const Value *V);
449 int getGlobalSlot(const GlobalValue *V);
451 /// If you'd like to deal with a function instead of just a module, use
452 /// this method to get its data into the SlotTracker.
453 void incorporateFunction(const Function *F) {
455 FunctionProcessed = false;
458 /// After calling incorporateFunction, use this method to remove the
459 /// most recently incorporated function from the SlotTracker. This
460 /// will reset the state of the machine back to just the module contents.
461 void purgeFunction();
463 // Implementation Details
465 /// This function does the actual initialization.
466 inline void initialize();
468 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
469 void CreateModuleSlot(const GlobalValue *V);
471 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
472 void CreateFunctionSlot(const Value *V);
474 /// Add all of the module level global variables (and their initializers)
475 /// and function declarations, but not the contents of those functions.
476 void processModule();
478 /// Add all of the functions arguments, basic blocks, and instructions
479 void processFunction();
481 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
482 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
485 } // end anonymous namespace
488 static SlotTracker *createSlotTracker(const Value *V) {
489 if (const Argument *FA = dyn_cast<Argument>(V))
490 return new SlotTracker(FA->getParent());
492 if (const Instruction *I = dyn_cast<Instruction>(V))
493 return new SlotTracker(I->getParent()->getParent());
495 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
496 return new SlotTracker(BB->getParent());
498 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
499 return new SlotTracker(GV->getParent());
501 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
502 return new SlotTracker(GA->getParent());
504 if (const Function *Func = dyn_cast<Function>(V))
505 return new SlotTracker(Func);
511 #define ST_DEBUG(X) cerr << X
516 // Module level constructor. Causes the contents of the Module (sans functions)
517 // to be added to the slot table.
518 SlotTracker::SlotTracker(const Module *M)
519 : TheModule(M), TheFunction(0), FunctionProcessed(false), mNext(0), fNext(0) {
522 // Function level constructor. Causes the contents of the Module and the one
523 // function provided to be added to the slot table.
524 SlotTracker::SlotTracker(const Function *F)
525 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
529 inline void SlotTracker::initialize() {
532 TheModule = 0; ///< Prevent re-processing next time we're called.
535 if (TheFunction && !FunctionProcessed)
539 // Iterate through all the global variables, functions, and global
540 // variable initializers and create slots for them.
541 void SlotTracker::processModule() {
542 ST_DEBUG("begin processModule!\n");
544 // Add all of the unnamed global variables to the value table.
545 for (Module::const_global_iterator I = TheModule->global_begin(),
546 E = TheModule->global_end(); I != E; ++I)
550 // Add all the unnamed functions to the table.
551 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
556 ST_DEBUG("end processModule!\n");
560 // Process the arguments, basic blocks, and instructions of a function.
561 void SlotTracker::processFunction() {
562 ST_DEBUG("begin processFunction!\n");
565 // Add all the function arguments with no names.
566 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
567 AE = TheFunction->arg_end(); AI != AE; ++AI)
569 CreateFunctionSlot(AI);
571 ST_DEBUG("Inserting Instructions:\n");
573 // Add all of the basic blocks and instructions with no names.
574 for (Function::const_iterator BB = TheFunction->begin(),
575 E = TheFunction->end(); BB != E; ++BB) {
577 CreateFunctionSlot(BB);
578 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
579 if (I->getType() != Type::VoidTy && !I->hasName())
580 CreateFunctionSlot(I);
583 FunctionProcessed = true;
585 ST_DEBUG("end processFunction!\n");
588 /// Clean up after incorporating a function. This is the only way to get out of
589 /// the function incorporation state that affects get*Slot/Create*Slot. Function
590 /// incorporation state is indicated by TheFunction != 0.
591 void SlotTracker::purgeFunction() {
592 ST_DEBUG("begin purgeFunction!\n");
593 fMap.clear(); // Simply discard the function level map
595 FunctionProcessed = false;
596 ST_DEBUG("end purgeFunction!\n");
599 /// getGlobalSlot - Get the slot number of a global value.
600 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
601 // Check for uninitialized state and do lazy initialization.
604 // Find the type plane in the module map
605 ValueMap::iterator MI = mMap.find(V);
606 return MI == mMap.end() ? -1 : (int)MI->second;
610 /// getLocalSlot - Get the slot number for a value that is local to a function.
611 int SlotTracker::getLocalSlot(const Value *V) {
612 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
614 // Check for uninitialized state and do lazy initialization.
617 ValueMap::iterator FI = fMap.find(V);
618 return FI == fMap.end() ? -1 : (int)FI->second;
622 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
623 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
624 assert(V && "Can't insert a null Value into SlotTracker!");
625 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
626 assert(!V->hasName() && "Doesn't need a slot!");
628 unsigned DestSlot = mNext++;
631 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
633 // G = Global, F = Function, A = Alias, o = other
634 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
635 (isa<Function>(V) ? 'F' :
636 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
640 /// CreateSlot - Create a new slot for the specified value if it has no name.
641 void SlotTracker::CreateFunctionSlot(const Value *V) {
642 assert(V->getType() != Type::VoidTy && !V->hasName() &&
643 "Doesn't need a slot!");
645 unsigned DestSlot = fNext++;
648 // G = Global, F = Function, o = other
649 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
650 DestSlot << " [o]\n");
655 //===----------------------------------------------------------------------===//
656 // AsmWriter Implementation
657 //===----------------------------------------------------------------------===//
659 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
660 TypePrinting &TypePrinter,
661 SlotTracker *Machine);
665 static const char *getPredicateText(unsigned predicate) {
666 const char * pred = "unknown";
668 case FCmpInst::FCMP_FALSE: pred = "false"; break;
669 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
670 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
671 case FCmpInst::FCMP_OGE: pred = "oge"; break;
672 case FCmpInst::FCMP_OLT: pred = "olt"; break;
673 case FCmpInst::FCMP_OLE: pred = "ole"; break;
674 case FCmpInst::FCMP_ONE: pred = "one"; break;
675 case FCmpInst::FCMP_ORD: pred = "ord"; break;
676 case FCmpInst::FCMP_UNO: pred = "uno"; break;
677 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
678 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
679 case FCmpInst::FCMP_UGE: pred = "uge"; break;
680 case FCmpInst::FCMP_ULT: pred = "ult"; break;
681 case FCmpInst::FCMP_ULE: pred = "ule"; break;
682 case FCmpInst::FCMP_UNE: pred = "une"; break;
683 case FCmpInst::FCMP_TRUE: pred = "true"; break;
684 case ICmpInst::ICMP_EQ: pred = "eq"; break;
685 case ICmpInst::ICMP_NE: pred = "ne"; break;
686 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
687 case ICmpInst::ICMP_SGE: pred = "sge"; break;
688 case ICmpInst::ICMP_SLT: pred = "slt"; break;
689 case ICmpInst::ICMP_SLE: pred = "sle"; break;
690 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
691 case ICmpInst::ICMP_UGE: pred = "uge"; break;
692 case ICmpInst::ICMP_ULT: pred = "ult"; break;
693 case ICmpInst::ICMP_ULE: pred = "ule"; break;
698 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
699 TypePrinting &TypePrinter, SlotTracker *Machine) {
700 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
701 if (CI->getType() == Type::Int1Ty) {
702 Out << (CI->getZExtValue() ? "true" : "false");
705 Out << CI->getValue();
709 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
710 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
711 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
712 // We would like to output the FP constant value in exponential notation,
713 // but we cannot do this if doing so will lose precision. Check here to
714 // make sure that we only output it in exponential format if we can parse
715 // the value back and get the same value.
718 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
719 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
720 CFP->getValueAPF().convertToFloat();
721 std::string StrVal = ftostr(CFP->getValueAPF());
723 // Check to make sure that the stringized number is not some string like
724 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
725 // that the string matches the "[-+]?[0-9]" regex.
727 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
728 ((StrVal[0] == '-' || StrVal[0] == '+') &&
729 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
730 // Reparse stringized version!
731 if (atof(StrVal.c_str()) == Val) {
736 // Otherwise we could not reparse it to exactly the same value, so we must
737 // output the string in hexadecimal format! Note that loading and storing
738 // floating point types changes the bits of NaNs on some hosts, notably
739 // x86, so we must not use these types.
740 assert(sizeof(double) == sizeof(uint64_t) &&
741 "assuming that double is 64 bits!");
743 APFloat apf = CFP->getValueAPF();
744 // Floats are represented in ASCII IR as double, convert.
746 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
749 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
754 // Some form of long double. These appear as a magic letter identifying
755 // the type, then a fixed number of hex digits.
757 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended)
759 else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
761 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
764 assert(0 && "Unsupported floating point type");
765 // api needed to prevent premature destruction
766 APInt api = CFP->getValueAPF().bitcastToAPInt();
767 const uint64_t* p = api.getRawData();
770 int width = api.getBitWidth();
771 for (int j=0; j<width; j+=4, shiftcount-=4) {
772 unsigned int nibble = (word>>shiftcount) & 15;
774 Out << (unsigned char)(nibble + '0');
776 Out << (unsigned char)(nibble - 10 + 'A');
777 if (shiftcount == 0 && j+4 < width) {
781 shiftcount = width-j-4;
787 if (isa<ConstantAggregateZero>(CV)) {
788 Out << "zeroinitializer";
792 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
793 // As a special case, print the array as a string if it is an array of
794 // i8 with ConstantInt values.
796 const Type *ETy = CA->getType()->getElementType();
797 if (CA->isString()) {
799 PrintEscapedString(CA->getAsString(), Out);
801 } else { // Cannot output in string format...
803 if (CA->getNumOperands()) {
804 TypePrinter.print(ETy);
806 WriteAsOperandInternal(Out, CA->getOperand(0),
807 TypePrinter, Machine);
808 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
810 TypePrinter.print(ETy);
812 WriteAsOperandInternal(Out, CA->getOperand(i), TypePrinter, Machine);
820 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
821 if (CS->getType()->isPacked())
824 unsigned N = CS->getNumOperands();
827 TypePrinter.print(CS->getOperand(0)->getType());
830 WriteAsOperandInternal(Out, CS->getOperand(0), TypePrinter, Machine);
832 for (unsigned i = 1; i < N; i++) {
834 TypePrinter.print(CS->getOperand(i)->getType());
837 WriteAsOperandInternal(Out, CS->getOperand(i), TypePrinter, Machine);
843 if (CS->getType()->isPacked())
848 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
849 const Type *ETy = CP->getType()->getElementType();
850 assert(CP->getNumOperands() > 0 &&
851 "Number of operands for a PackedConst must be > 0");
853 TypePrinter.print(ETy);
855 WriteAsOperandInternal(Out, CP->getOperand(0), TypePrinter, Machine);
856 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
858 TypePrinter.print(ETy);
860 WriteAsOperandInternal(Out, CP->getOperand(i), TypePrinter, Machine);
866 if (isa<ConstantPointerNull>(CV)) {
871 if (isa<UndefValue>(CV)) {
876 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
877 Out << CE->getOpcodeName();
879 Out << ' ' << getPredicateText(CE->getPredicate());
882 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
883 TypePrinter.print((*OI)->getType());
885 WriteAsOperandInternal(Out, *OI, TypePrinter, Machine);
886 if (OI+1 != CE->op_end())
890 if (CE->hasIndices()) {
891 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
892 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
893 Out << ", " << Indices[i];
898 TypePrinter.print(CE->getType());
905 Out << "<placeholder or erroneous Constant>";
909 /// WriteAsOperand - Write the name of the specified value out to the specified
910 /// ostream. This can be useful when you just want to print int %reg126, not
911 /// the whole instruction that generated it.
913 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
914 TypePrinting &TypePrinter,
915 SlotTracker *Machine) {
917 PrintLLVMName(Out, V);
921 const Constant *CV = dyn_cast<Constant>(V);
922 if (CV && !isa<GlobalValue>(CV)) {
923 WriteConstantInt(Out, CV, TypePrinter, Machine);
927 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
929 if (IA->hasSideEffects())
930 Out << "sideeffect ";
932 PrintEscapedString(IA->getAsmString(), Out);
934 PrintEscapedString(IA->getConstraintString(), Out);
942 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
943 Slot = Machine->getGlobalSlot(GV);
946 Slot = Machine->getLocalSlot(V);
949 Machine = createSlotTracker(V);
951 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
952 Slot = Machine->getGlobalSlot(GV);
955 Slot = Machine->getLocalSlot(V);
964 Out << Prefix << Slot;
969 /// WriteAsOperand - Write the name of the specified value out to the specified
970 /// ostream. This can be useful when you just want to print int %reg126, not
971 /// the whole instruction that generated it.
973 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
974 const Module *Context) {
975 raw_os_ostream OS(Out);
976 WriteAsOperand(OS, V, PrintType, Context);
979 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
980 const Module *Context) {
981 if (Context == 0) Context = getModuleFromVal(V);
983 TypePrinting TypePrinter(Context, Out);
985 TypePrinter.print(V->getType());
989 WriteAsOperandInternal(Out, V, TypePrinter, 0);
995 class AssemblyWriter {
997 SlotTracker &Machine;
998 const Module *TheModule;
999 TypePrinting TypePrinter;
1000 AssemblyAnnotationWriter *AnnotationWriter;
1002 inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
1003 AssemblyAnnotationWriter *AAW)
1004 : Out(o), Machine(Mac), TheModule(M), TypePrinter(M, Out),
1005 AnnotationWriter(AAW) {
1008 void write(const Module *M) { printModule(M); }
1010 void write(const GlobalValue *G) {
1011 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
1013 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
1015 else if (const Function *F = dyn_cast<Function>(G))
1018 assert(0 && "Unknown global");
1021 void write(const BasicBlock *BB) { printBasicBlock(BB); }
1022 void write(const Instruction *I) { printInstruction(*I); }
1023 // void write(const Type *Ty) { printType(Ty); }
1025 void writeOperand(const Value *Op, bool PrintType);
1026 void writeParamOperand(const Value *Operand, Attributes Attrs);
1028 const Module* getModule() { return TheModule; }
1031 void printModule(const Module *M);
1032 void printTypeSymbolTable(const TypeSymbolTable &ST);
1033 void printGlobal(const GlobalVariable *GV);
1034 void printAlias(const GlobalAlias *GV);
1035 void printFunction(const Function *F);
1036 void printArgument(const Argument *FA, Attributes Attrs);
1037 void printBasicBlock(const BasicBlock *BB);
1038 void printInstruction(const Instruction &I);
1040 // printType - Go to extreme measures to attempt to print out a short,
1041 // symbolic version of a type name.
1043 void printType(const Type *Ty) {
1044 TypePrinter.print(Ty);
1047 // printInfoComment - Print a little comment after the instruction indicating
1048 // which slot it occupies.
1049 void printInfoComment(const Value &V);
1051 } // end of llvm namespace
1054 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1056 Out << "<null operand!>";
1059 printType(Operand->getType());
1062 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1066 void AssemblyWriter::writeParamOperand(const Value *Operand,
1069 Out << "<null operand!>";
1072 printType(Operand->getType());
1073 // Print parameter attributes list
1074 if (Attrs != Attribute::None)
1075 Out << ' ' << Attribute::getAsString(Attrs);
1077 // Print the operand
1078 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1082 void AssemblyWriter::printModule(const Module *M) {
1083 if (!M->getModuleIdentifier().empty() &&
1084 // Don't print the ID if it will start a new line (which would
1085 // require a comment char before it).
1086 M->getModuleIdentifier().find('\n') == std::string::npos)
1087 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1089 if (!M->getDataLayout().empty())
1090 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1091 if (!M->getTargetTriple().empty())
1092 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1094 if (!M->getModuleInlineAsm().empty()) {
1095 // Split the string into lines, to make it easier to read the .ll file.
1096 std::string Asm = M->getModuleInlineAsm();
1098 size_t NewLine = Asm.find_first_of('\n', CurPos);
1099 while (NewLine != std::string::npos) {
1100 // We found a newline, print the portion of the asm string from the
1101 // last newline up to this newline.
1102 Out << "module asm \"";
1103 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1107 NewLine = Asm.find_first_of('\n', CurPos);
1109 Out << "module asm \"";
1110 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1114 // Loop over the dependent libraries and emit them.
1115 Module::lib_iterator LI = M->lib_begin();
1116 Module::lib_iterator LE = M->lib_end();
1118 Out << "deplibs = [ ";
1120 Out << '"' << *LI << '"';
1128 // Loop over the symbol table, emitting all named constants.
1129 printTypeSymbolTable(M->getTypeSymbolTable());
1131 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1135 // Output all aliases.
1136 if (!M->alias_empty()) Out << "\n";
1137 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1141 // Output all of the functions.
1142 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1146 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1148 case GlobalValue::PrivateLinkage: Out << "private "; break;
1149 case GlobalValue::InternalLinkage: Out << "internal "; break;
1150 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
1151 case GlobalValue::WeakLinkage: Out << "weak "; break;
1152 case GlobalValue::CommonLinkage: Out << "common "; break;
1153 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1154 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1155 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1156 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1157 case GlobalValue::ExternalLinkage: break;
1158 case GlobalValue::GhostLinkage:
1159 Out << "GhostLinkage not allowed in AsmWriter!\n";
1165 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1168 default: assert(0 && "Invalid visibility style!");
1169 case GlobalValue::DefaultVisibility: break;
1170 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1171 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1175 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1176 if (GV->hasName()) {
1177 PrintLLVMName(Out, GV);
1181 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1184 PrintLinkage(GV->getLinkage(), Out);
1185 PrintVisibility(GV->getVisibility(), Out);
1187 if (GV->isThreadLocal()) Out << "thread_local ";
1188 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1189 Out << "addrspace(" << AddressSpace << ") ";
1190 Out << (GV->isConstant() ? "constant " : "global ");
1191 printType(GV->getType()->getElementType());
1193 if (GV->hasInitializer()) {
1195 writeOperand(GV->getInitializer(), false);
1198 if (GV->hasSection())
1199 Out << ", section \"" << GV->getSection() << '"';
1200 if (GV->getAlignment())
1201 Out << ", align " << GV->getAlignment();
1203 printInfoComment(*GV);
1207 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1208 // Don't crash when dumping partially built GA
1210 Out << "<<nameless>> = ";
1212 PrintLLVMName(Out, GA);
1215 PrintVisibility(GA->getVisibility(), Out);
1219 PrintLinkage(GA->getLinkage(), Out);
1221 const Constant *Aliasee = GA->getAliasee();
1223 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1224 printType(GV->getType());
1226 PrintLLVMName(Out, GV);
1227 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1228 printType(F->getFunctionType());
1231 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1232 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1233 printType(GA->getType());
1235 PrintLLVMName(Out, GA);
1237 const ConstantExpr *CE = 0;
1238 if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
1239 (CE->getOpcode() == Instruction::BitCast)) {
1240 writeOperand(CE, false);
1242 assert(0 && "Unsupported aliasee");
1245 printInfoComment(*GA);
1249 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1251 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1254 PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1257 // Make sure we print out at least one level of the type structure, so
1258 // that we do not get %FILE = type %FILE
1259 TypePrinter.printAtLeastOneLevel(TI->second);
1264 /// printFunction - Print all aspects of a function.
1266 void AssemblyWriter::printFunction(const Function *F) {
1267 // Print out the return type and name.
1270 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1272 if (F->isDeclaration())
1277 PrintLinkage(F->getLinkage(), Out);
1278 PrintVisibility(F->getVisibility(), Out);
1280 // Print the calling convention.
1281 switch (F->getCallingConv()) {
1282 case CallingConv::C: break; // default
1283 case CallingConv::Fast: Out << "fastcc "; break;
1284 case CallingConv::Cold: Out << "coldcc "; break;
1285 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1286 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1287 default: Out << "cc" << F->getCallingConv() << " "; break;
1290 const FunctionType *FT = F->getFunctionType();
1291 const AttrListPtr &Attrs = F->getAttributes();
1292 Attributes RetAttrs = Attrs.getRetAttributes();
1293 if (RetAttrs != Attribute::None)
1294 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1295 printType(F->getReturnType());
1297 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1299 Machine.incorporateFunction(F);
1301 // Loop over the arguments, printing them...
1304 if (!F->isDeclaration()) {
1305 // If this isn't a declaration, print the argument names as well.
1306 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1308 // Insert commas as we go... the first arg doesn't get a comma
1309 if (I != F->arg_begin()) Out << ", ";
1310 printArgument(I, Attrs.getParamAttributes(Idx));
1314 // Otherwise, print the types from the function type.
1315 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1316 // Insert commas as we go... the first arg doesn't get a comma
1320 printType(FT->getParamType(i));
1322 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1323 if (ArgAttrs != Attribute::None)
1324 Out << ' ' << Attribute::getAsString(ArgAttrs);
1328 // Finish printing arguments...
1329 if (FT->isVarArg()) {
1330 if (FT->getNumParams()) Out << ", ";
1331 Out << "..."; // Output varargs portion of signature!
1334 Attributes FnAttrs = Attrs.getFnAttributes();
1335 if (FnAttrs != Attribute::None)
1336 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1337 if (F->hasSection())
1338 Out << " section \"" << F->getSection() << '"';
1339 if (F->getAlignment())
1340 Out << " align " << F->getAlignment();
1342 Out << " gc \"" << F->getGC() << '"';
1343 if (F->isDeclaration()) {
1348 // Output all of its basic blocks... for the function
1349 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1355 Machine.purgeFunction();
1358 /// printArgument - This member is called for every argument that is passed into
1359 /// the function. Simply print it out
1361 void AssemblyWriter::printArgument(const Argument *Arg,
1364 printType(Arg->getType());
1366 // Output parameter attributes list
1367 if (Attrs != Attribute::None)
1368 Out << ' ' << Attribute::getAsString(Attrs);
1370 // Output name, if available...
1371 if (Arg->hasName()) {
1373 PrintLLVMName(Out, Arg);
1377 /// printBasicBlock - This member is called for each basic block in a method.
1379 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1380 if (BB->hasName()) { // Print out the label if it exists...
1382 PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1384 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1385 Out << "\n; <label>:";
1386 int Slot = Machine.getLocalSlot(BB);
1393 if (BB->getParent() == 0)
1394 Out << "\t\t; Error: Block without parent!";
1395 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1396 // Output predecessors for the block...
1398 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1401 Out << " No predecessors!";
1404 writeOperand(*PI, false);
1405 for (++PI; PI != PE; ++PI) {
1407 writeOperand(*PI, false);
1414 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1416 // Output all of the instructions in the basic block...
1417 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1418 printInstruction(*I);
1420 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1424 /// printInfoComment - Print a little comment after the instruction indicating
1425 /// which slot it occupies.
1427 void AssemblyWriter::printInfoComment(const Value &V) {
1428 if (V.getType() != Type::VoidTy) {
1430 printType(V.getType());
1433 if (!V.hasName() && !isa<Instruction>(V)) {
1435 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1436 SlotNum = Machine.getGlobalSlot(GV);
1438 SlotNum = Machine.getLocalSlot(&V);
1442 Out << ':' << SlotNum; // Print out the def slot taken.
1444 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1448 // This member is called for each Instruction in a function..
1449 void AssemblyWriter::printInstruction(const Instruction &I) {
1450 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1454 // Print out name if it exists...
1456 PrintLLVMName(Out, &I);
1458 } else if (I.getType() != Type::VoidTy) {
1459 // Print out the def slot taken.
1460 int SlotNum = Machine.getLocalSlot(&I);
1462 Out << "<badref> = ";
1464 Out << '%' << SlotNum << " = ";
1467 // If this is a volatile load or store, print out the volatile marker.
1468 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1469 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1471 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1472 // If this is a call, check if it's a tail call.
1476 // Print out the opcode...
1477 Out << I.getOpcodeName();
1479 // Print out the compare instruction predicates
1480 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1481 Out << ' ' << getPredicateText(CI->getPredicate());
1483 // Print out the type of the operands...
1484 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1486 // Special case conditional branches to swizzle the condition out to the front
1487 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1488 BranchInst &BI(cast<BranchInst>(I));
1490 writeOperand(BI.getCondition(), true);
1492 writeOperand(BI.getSuccessor(0), true);
1494 writeOperand(BI.getSuccessor(1), true);
1496 } else if (isa<SwitchInst>(I)) {
1497 // Special case switch statement to get formatting nice and correct...
1499 writeOperand(Operand , true);
1501 writeOperand(I.getOperand(1), true);
1504 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1506 writeOperand(I.getOperand(op ), true);
1508 writeOperand(I.getOperand(op+1), true);
1511 } else if (isa<PHINode>(I)) {
1513 printType(I.getType());
1516 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1517 if (op) Out << ", ";
1519 writeOperand(I.getOperand(op ), false); Out << ", ";
1520 writeOperand(I.getOperand(op+1), false); Out << " ]";
1522 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1524 writeOperand(I.getOperand(0), true);
1525 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1527 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1529 writeOperand(I.getOperand(0), true); Out << ", ";
1530 writeOperand(I.getOperand(1), true);
1531 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1533 } else if (isa<ReturnInst>(I) && !Operand) {
1535 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1536 // Print the calling convention being used.
1537 switch (CI->getCallingConv()) {
1538 case CallingConv::C: break; // default
1539 case CallingConv::Fast: Out << " fastcc"; break;
1540 case CallingConv::Cold: Out << " coldcc"; break;
1541 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1542 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1543 default: Out << " cc" << CI->getCallingConv(); break;
1546 const PointerType *PTy = cast<PointerType>(Operand->getType());
1547 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1548 const Type *RetTy = FTy->getReturnType();
1549 const AttrListPtr &PAL = CI->getAttributes();
1551 if (PAL.getRetAttributes() != Attribute::None)
1552 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1554 // If possible, print out the short form of the call instruction. We can
1555 // only do this if the first argument is a pointer to a nonvararg function,
1556 // and if the return type is not a pointer to a function.
1559 if (!FTy->isVarArg() &&
1560 (!isa<PointerType>(RetTy) ||
1561 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1564 writeOperand(Operand, false);
1566 writeOperand(Operand, true);
1569 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1572 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1575 if (PAL.getFnAttributes() != Attribute::None)
1576 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1577 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1578 const PointerType *PTy = cast<PointerType>(Operand->getType());
1579 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1580 const Type *RetTy = FTy->getReturnType();
1581 const AttrListPtr &PAL = II->getAttributes();
1583 // Print the calling convention being used.
1584 switch (II->getCallingConv()) {
1585 case CallingConv::C: break; // default
1586 case CallingConv::Fast: Out << " fastcc"; break;
1587 case CallingConv::Cold: Out << " coldcc"; break;
1588 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1589 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1590 default: Out << " cc" << II->getCallingConv(); break;
1593 if (PAL.getRetAttributes() != Attribute::None)
1594 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1596 // If possible, print out the short form of the invoke instruction. We can
1597 // only do this if the first argument is a pointer to a nonvararg function,
1598 // and if the return type is not a pointer to a function.
1601 if (!FTy->isVarArg() &&
1602 (!isa<PointerType>(RetTy) ||
1603 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1606 writeOperand(Operand, false);
1608 writeOperand(Operand, true);
1611 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1614 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1618 if (PAL.getFnAttributes() != Attribute::None)
1619 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1621 Out << "\n\t\t\tto ";
1622 writeOperand(II->getNormalDest(), true);
1624 writeOperand(II->getUnwindDest(), true);
1626 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1628 printType(AI->getType()->getElementType());
1629 if (AI->isArrayAllocation()) {
1631 writeOperand(AI->getArraySize(), true);
1633 if (AI->getAlignment()) {
1634 Out << ", align " << AI->getAlignment();
1636 } else if (isa<CastInst>(I)) {
1639 writeOperand(Operand, true); // Work with broken code
1642 printType(I.getType());
1643 } else if (isa<VAArgInst>(I)) {
1646 writeOperand(Operand, true); // Work with broken code
1649 printType(I.getType());
1650 } else if (Operand) { // Print the normal way...
1652 // PrintAllTypes - Instructions who have operands of all the same type
1653 // omit the type from all but the first operand. If the instruction has
1654 // different type operands (for example br), then they are all printed.
1655 bool PrintAllTypes = false;
1656 const Type *TheType = Operand->getType();
1658 // Select, Store and ShuffleVector always print all types.
1659 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1660 || isa<ReturnInst>(I)) {
1661 PrintAllTypes = true;
1663 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1664 Operand = I.getOperand(i);
1665 // note that Operand shouldn't be null, but the test helps make dump()
1666 // more tolerant of malformed IR
1667 if (Operand && Operand->getType() != TheType) {
1668 PrintAllTypes = true; // We have differing types! Print them all!
1674 if (!PrintAllTypes) {
1680 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1682 writeOperand(I.getOperand(i), PrintAllTypes);
1686 // Print post operand alignment for load/store
1687 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1688 Out << ", align " << cast<LoadInst>(I).getAlignment();
1689 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1690 Out << ", align " << cast<StoreInst>(I).getAlignment();
1693 printInfoComment(I);
1698 //===----------------------------------------------------------------------===//
1699 // External Interface declarations
1700 //===----------------------------------------------------------------------===//
1702 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1703 raw_os_ostream OS(o);
1706 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1707 SlotTracker SlotTable(this);
1708 AssemblyWriter W(OS, SlotTable, this, AAW);
1712 void Type::print(std::ostream &o) const {
1713 raw_os_ostream OS(o);
1717 void Type::print(raw_ostream &o) const {
1721 o << getDescription();
1724 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1726 OS << "printing a <null> value\n";
1730 if (const Instruction *I = dyn_cast<Instruction>(this)) {
1731 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1732 SlotTracker SlotTable(F);
1733 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1735 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1736 SlotTracker SlotTable(BB->getParent());
1737 AssemblyWriter W(OS, SlotTable,
1738 BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1740 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1741 SlotTracker SlotTable(GV->getParent());
1742 AssemblyWriter W(OS, SlotTable, GV->getParent(), 0);
1744 } else if (const Constant *C = dyn_cast<Constant>(this)) {
1745 OS << C->getType()->getDescription() << ' ';
1746 TypePrinting TypePrinter(0, OS);
1747 WriteConstantInt(OS, C, TypePrinter, 0);
1748 } else if (const Argument *A = dyn_cast<Argument>(this)) {
1749 WriteAsOperand(OS, this, true,
1750 A->getParent() ? A->getParent()->getParent() : 0);
1751 } else if (isa<InlineAsm>(this)) {
1752 WriteAsOperand(OS, this, true, 0);
1754 assert(0 && "Unknown value to print out!");
1758 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
1759 raw_os_ostream OS(O);
1763 // Value::dump - allow easy printing of Values from the debugger.
1764 void Value::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1766 // Type::dump - allow easy printing of Types from the debugger.
1767 void Type::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1769 // Type::dump - allow easy printing of Types from the debugger.
1770 // This one uses type names from the given context module
1771 void Type::dump(const Module *Context) const {
1772 WriteTypeSymbolic(errs(), this, Context);
1777 // Module::dump() - Allow printing of Modules from the debugger.
1778 void Module::dump() const { print(errs(), 0); errs().flush(); }