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 //===----------------------------------------------------------------------===//
140 static std::map<const Type *, std::string> &getTypeNamesMap(void *M) {
141 return *static_cast<std::map<const Type *, std::string>*>(M);
144 void TypePrinting::clear() {
145 getTypeNamesMap(TypeNames).clear();
148 TypePrinting::TypePrinting(const Module *M) {
151 TypeNames = new std::map<const Type *, std::string>();
153 // If the module has a symbol table, take all global types and stuff their
154 // names into the TypeNames map.
155 const TypeSymbolTable &ST = M->getTypeSymbolTable();
156 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
158 const Type *Ty = cast<Type>(TI->second);
160 // As a heuristic, don't insert pointer to primitive types, because
161 // they are used too often to have a single useful name.
162 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
163 const Type *PETy = PTy->getElementType();
164 if ((PETy->isPrimitiveType() || PETy->isInteger()) &&
165 !isa<OpaqueType>(PETy))
169 // Likewise don't insert primitives either.
170 if (Ty->isInteger() || Ty->isPrimitiveType())
173 // Get the name as a string and insert it into TypeNames.
175 raw_string_ostream NameOS(NameStr);
176 PrintLLVMName(NameOS, TI->first.c_str(), TI->first.length(), LocalPrefix);
177 getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, NameOS.str()));
181 TypePrinting::~TypePrinting() {
182 delete &getTypeNamesMap(TypeNames);
185 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
186 /// use of type names or up references to shorten the type name where possible.
187 void TypePrinting::CalcTypeName(const Type *Ty,
188 SmallVectorImpl<const Type *> &TypeStack,
190 // Check to see if the type is named.
191 std::map<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
192 std::map<const Type *, std::string>::iterator I = TM.find(Ty);
194 // If the name wasn't temporarily removed use it.
195 !I->second.empty()) {
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 OS << '\\' << unsigned(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::VoidTyID: OS << "void"; break;
216 case Type::FloatTyID: OS << "float"; break;
217 case Type::DoubleTyID: OS << "double"; break;
218 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
219 case Type::FP128TyID: OS << "fp128"; break;
220 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
221 case Type::LabelTyID: OS << "label"; break;
222 case Type::IntegerTyID:
223 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
226 case Type::FunctionTyID: {
227 const FunctionType *FTy = cast<FunctionType>(Ty);
228 CalcTypeName(FTy->getReturnType(), TypeStack, OS);
230 for (FunctionType::param_iterator I = FTy->param_begin(),
231 E = FTy->param_end(); I != E; ++I) {
232 if (I != FTy->param_begin())
234 CalcTypeName(*I, TypeStack, OS);
236 if (FTy->isVarArg()) {
237 if (FTy->getNumParams()) OS << ", ";
243 case Type::StructTyID: {
244 const StructType *STy = cast<StructType>(Ty);
248 for (StructType::element_iterator I = STy->element_begin(),
249 E = STy->element_end(); I != E; ++I) {
250 CalcTypeName(*I, TypeStack, OS);
251 if (next(I) != STy->element_end())
260 case Type::PointerTyID: {
261 const PointerType *PTy = cast<PointerType>(Ty);
262 CalcTypeName(PTy->getElementType(), TypeStack, OS);
263 if (unsigned AddressSpace = PTy->getAddressSpace())
264 OS << " addrspace(" << AddressSpace << ')';
268 case Type::ArrayTyID: {
269 const ArrayType *ATy = cast<ArrayType>(Ty);
270 OS << '[' << ATy->getNumElements() << " x ";
271 CalcTypeName(ATy->getElementType(), TypeStack, OS);
275 case Type::VectorTyID: {
276 const VectorType *PTy = cast<VectorType>(Ty);
277 OS << "<" << PTy->getNumElements() << " x ";
278 CalcTypeName(PTy->getElementType(), TypeStack, OS);
282 case Type::OpaqueTyID:
286 OS << "<unrecognized-type>";
290 TypeStack.pop_back(); // Remove self from stack.
293 /// printTypeInt - The internal guts of printing out a type that has a
294 /// potentially named portion.
296 void TypePrinting::print(const Type *Ty, raw_ostream &OS) {
297 // Check to see if the type is named.
298 std::map<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
299 std::map<const Type*, std::string>::iterator I = TM.find(Ty);
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 SmallVector<const Type *, 16> TypeStack;
309 std::string TypeName;
311 raw_string_ostream TypeOS(TypeName);
312 CalcTypeName(Ty, TypeStack, TypeOS);
315 // Cache type name for later use.
316 TM.insert(std::make_pair(Ty, TypeOS.str()));
319 /// printAtLeastOneLevel - Print out one level of the possibly complex type
320 /// without considering any symbolic types that we may have equal to it.
321 void TypePrinting::printAtLeastOneLevel(const Type *Ty, raw_ostream &OS) {
322 // If the type does not have a name, then it is already guaranteed to print at
324 std::map<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
325 std::map<const Type*, std::string>::iterator I = TM.find(Ty);
327 return print(Ty, OS);
329 // Otherwise, temporarily remove the name and print it.
331 std::swap(OldName, I->second);
333 // Print the type without the name.
334 SmallVector<const Type *, 16> TypeStack;
335 CalcTypeName(Ty, TypeStack, OS);
338 std::swap(OldName, I->second);
342 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
343 /// type, iff there is an entry in the modules symbol table for the specified
344 /// type or one of it's component types.
346 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M){
347 TypePrinting(M).print(Ty, OS);
350 //===----------------------------------------------------------------------===//
351 // SlotTracker Class: Enumerate slot numbers for unnamed values
352 //===----------------------------------------------------------------------===//
356 /// This class provides computation of slot numbers for LLVM Assembly writing.
360 /// ValueMap - A mapping of Values to slot numbers
361 typedef DenseMap<const Value*, unsigned> ValueMap;
364 /// TheModule - The module for which we are holding slot numbers
365 const Module* TheModule;
367 /// TheFunction - The function for which we are holding slot numbers
368 const Function* TheFunction;
369 bool FunctionProcessed;
371 /// mMap - The TypePlanes map for the module level data
375 /// fMap - The TypePlanes map for the function level data
380 /// Construct from a module
381 explicit SlotTracker(const Module *M);
382 /// Construct from a function, starting out in incorp state.
383 explicit SlotTracker(const Function *F);
385 /// Return the slot number of the specified value in it's type
386 /// plane. If something is not in the SlotTracker, return -1.
387 int getLocalSlot(const Value *V);
388 int getGlobalSlot(const GlobalValue *V);
390 /// If you'd like to deal with a function instead of just a module, use
391 /// this method to get its data into the SlotTracker.
392 void incorporateFunction(const Function *F) {
394 FunctionProcessed = false;
397 /// After calling incorporateFunction, use this method to remove the
398 /// most recently incorporated function from the SlotTracker. This
399 /// will reset the state of the machine back to just the module contents.
400 void purgeFunction();
402 // Implementation Details
404 /// This function does the actual initialization.
405 inline void initialize();
407 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
408 void CreateModuleSlot(const GlobalValue *V);
410 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
411 void CreateFunctionSlot(const Value *V);
413 /// Add all of the module level global variables (and their initializers)
414 /// and function declarations, but not the contents of those functions.
415 void processModule();
417 /// Add all of the functions arguments, basic blocks, and instructions
418 void processFunction();
420 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
421 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
424 } // end anonymous namespace
427 static SlotTracker *createSlotTracker(const Value *V) {
428 if (const Argument *FA = dyn_cast<Argument>(V))
429 return new SlotTracker(FA->getParent());
431 if (const Instruction *I = dyn_cast<Instruction>(V))
432 return new SlotTracker(I->getParent()->getParent());
434 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
435 return new SlotTracker(BB->getParent());
437 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
438 return new SlotTracker(GV->getParent());
440 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
441 return new SlotTracker(GA->getParent());
443 if (const Function *Func = dyn_cast<Function>(V))
444 return new SlotTracker(Func);
450 #define ST_DEBUG(X) cerr << X
455 // Module level constructor. Causes the contents of the Module (sans functions)
456 // to be added to the slot table.
457 SlotTracker::SlotTracker(const Module *M)
458 : TheModule(M), TheFunction(0), FunctionProcessed(false), mNext(0), fNext(0) {
461 // Function level constructor. Causes the contents of the Module and the one
462 // function provided to be added to the slot table.
463 SlotTracker::SlotTracker(const Function *F)
464 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
468 inline void SlotTracker::initialize() {
471 TheModule = 0; ///< Prevent re-processing next time we're called.
474 if (TheFunction && !FunctionProcessed)
478 // Iterate through all the global variables, functions, and global
479 // variable initializers and create slots for them.
480 void SlotTracker::processModule() {
481 ST_DEBUG("begin processModule!\n");
483 // Add all of the unnamed global variables to the value table.
484 for (Module::const_global_iterator I = TheModule->global_begin(),
485 E = TheModule->global_end(); I != E; ++I)
489 // Add all the unnamed functions to the table.
490 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
495 ST_DEBUG("end processModule!\n");
499 // Process the arguments, basic blocks, and instructions of a function.
500 void SlotTracker::processFunction() {
501 ST_DEBUG("begin processFunction!\n");
504 // Add all the function arguments with no names.
505 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
506 AE = TheFunction->arg_end(); AI != AE; ++AI)
508 CreateFunctionSlot(AI);
510 ST_DEBUG("Inserting Instructions:\n");
512 // Add all of the basic blocks and instructions with no names.
513 for (Function::const_iterator BB = TheFunction->begin(),
514 E = TheFunction->end(); BB != E; ++BB) {
516 CreateFunctionSlot(BB);
517 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
518 if (I->getType() != Type::VoidTy && !I->hasName())
519 CreateFunctionSlot(I);
522 FunctionProcessed = true;
524 ST_DEBUG("end processFunction!\n");
527 /// Clean up after incorporating a function. This is the only way to get out of
528 /// the function incorporation state that affects get*Slot/Create*Slot. Function
529 /// incorporation state is indicated by TheFunction != 0.
530 void SlotTracker::purgeFunction() {
531 ST_DEBUG("begin purgeFunction!\n");
532 fMap.clear(); // Simply discard the function level map
534 FunctionProcessed = false;
535 ST_DEBUG("end purgeFunction!\n");
538 /// getGlobalSlot - Get the slot number of a global value.
539 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
540 // Check for uninitialized state and do lazy initialization.
543 // Find the type plane in the module map
544 ValueMap::iterator MI = mMap.find(V);
545 return MI == mMap.end() ? -1 : (int)MI->second;
549 /// getLocalSlot - Get the slot number for a value that is local to a function.
550 int SlotTracker::getLocalSlot(const Value *V) {
551 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
553 // Check for uninitialized state and do lazy initialization.
556 ValueMap::iterator FI = fMap.find(V);
557 return FI == fMap.end() ? -1 : (int)FI->second;
561 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
562 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
563 assert(V && "Can't insert a null Value into SlotTracker!");
564 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
565 assert(!V->hasName() && "Doesn't need a slot!");
567 unsigned DestSlot = mNext++;
570 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
572 // G = Global, F = Function, A = Alias, o = other
573 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
574 (isa<Function>(V) ? 'F' :
575 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
579 /// CreateSlot - Create a new slot for the specified value if it has no name.
580 void SlotTracker::CreateFunctionSlot(const Value *V) {
581 assert(V->getType() != Type::VoidTy && !V->hasName() &&
582 "Doesn't need a slot!");
584 unsigned DestSlot = fNext++;
587 // G = Global, F = Function, o = other
588 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
589 DestSlot << " [o]\n");
594 //===----------------------------------------------------------------------===//
595 // AsmWriter Implementation
596 //===----------------------------------------------------------------------===//
598 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
599 TypePrinting &TypePrinter,
600 SlotTracker *Machine);
604 static const char *getPredicateText(unsigned predicate) {
605 const char * pred = "unknown";
607 case FCmpInst::FCMP_FALSE: pred = "false"; break;
608 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
609 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
610 case FCmpInst::FCMP_OGE: pred = "oge"; break;
611 case FCmpInst::FCMP_OLT: pred = "olt"; break;
612 case FCmpInst::FCMP_OLE: pred = "ole"; break;
613 case FCmpInst::FCMP_ONE: pred = "one"; break;
614 case FCmpInst::FCMP_ORD: pred = "ord"; break;
615 case FCmpInst::FCMP_UNO: pred = "uno"; break;
616 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
617 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
618 case FCmpInst::FCMP_UGE: pred = "uge"; break;
619 case FCmpInst::FCMP_ULT: pred = "ult"; break;
620 case FCmpInst::FCMP_ULE: pred = "ule"; break;
621 case FCmpInst::FCMP_UNE: pred = "une"; break;
622 case FCmpInst::FCMP_TRUE: pred = "true"; break;
623 case ICmpInst::ICMP_EQ: pred = "eq"; break;
624 case ICmpInst::ICMP_NE: pred = "ne"; break;
625 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
626 case ICmpInst::ICMP_SGE: pred = "sge"; break;
627 case ICmpInst::ICMP_SLT: pred = "slt"; break;
628 case ICmpInst::ICMP_SLE: pred = "sle"; break;
629 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
630 case ICmpInst::ICMP_UGE: pred = "uge"; break;
631 case ICmpInst::ICMP_ULT: pred = "ult"; break;
632 case ICmpInst::ICMP_ULE: pred = "ule"; break;
637 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
638 TypePrinting &TypePrinter, SlotTracker *Machine) {
639 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
640 if (CI->getType() == Type::Int1Ty) {
641 Out << (CI->getZExtValue() ? "true" : "false");
644 Out << CI->getValue();
648 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
649 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
650 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
651 // We would like to output the FP constant value in exponential notation,
652 // but we cannot do this if doing so will lose precision. Check here to
653 // make sure that we only output it in exponential format if we can parse
654 // the value back and get the same value.
657 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
658 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
659 CFP->getValueAPF().convertToFloat();
660 std::string StrVal = ftostr(CFP->getValueAPF());
662 // Check to make sure that the stringized number is not some string like
663 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
664 // that the string matches the "[-+]?[0-9]" regex.
666 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
667 ((StrVal[0] == '-' || StrVal[0] == '+') &&
668 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
669 // Reparse stringized version!
670 if (atof(StrVal.c_str()) == Val) {
675 // Otherwise we could not reparse it to exactly the same value, so we must
676 // output the string in hexadecimal format! Note that loading and storing
677 // floating point types changes the bits of NaNs on some hosts, notably
678 // x86, so we must not use these types.
679 assert(sizeof(double) == sizeof(uint64_t) &&
680 "assuming that double is 64 bits!");
682 APFloat apf = CFP->getValueAPF();
683 // Floats are represented in ASCII IR as double, convert.
685 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
688 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
693 // Some form of long double. These appear as a magic letter identifying
694 // the type, then a fixed number of hex digits.
696 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended)
698 else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
700 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
703 assert(0 && "Unsupported floating point type");
704 // api needed to prevent premature destruction
705 APInt api = CFP->getValueAPF().bitcastToAPInt();
706 const uint64_t* p = api.getRawData();
709 int width = api.getBitWidth();
710 for (int j=0; j<width; j+=4, shiftcount-=4) {
711 unsigned int nibble = (word>>shiftcount) & 15;
713 Out << (unsigned char)(nibble + '0');
715 Out << (unsigned char)(nibble - 10 + 'A');
716 if (shiftcount == 0 && j+4 < width) {
720 shiftcount = width-j-4;
726 if (isa<ConstantAggregateZero>(CV)) {
727 Out << "zeroinitializer";
731 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
732 // As a special case, print the array as a string if it is an array of
733 // i8 with ConstantInt values.
735 const Type *ETy = CA->getType()->getElementType();
736 if (CA->isString()) {
738 PrintEscapedString(CA->getAsString(), Out);
740 } else { // Cannot output in string format...
742 if (CA->getNumOperands()) {
743 TypePrinter.print(ETy, Out);
745 WriteAsOperandInternal(Out, CA->getOperand(0),
746 TypePrinter, Machine);
747 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
749 TypePrinter.print(ETy, Out);
751 WriteAsOperandInternal(Out, CA->getOperand(i), TypePrinter, Machine);
759 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
760 if (CS->getType()->isPacked())
763 unsigned N = CS->getNumOperands();
766 TypePrinter.print(CS->getOperand(0)->getType(), Out);
769 WriteAsOperandInternal(Out, CS->getOperand(0), TypePrinter, Machine);
771 for (unsigned i = 1; i < N; i++) {
773 TypePrinter.print(CS->getOperand(i)->getType(), Out);
776 WriteAsOperandInternal(Out, CS->getOperand(i), TypePrinter, Machine);
782 if (CS->getType()->isPacked())
787 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
788 const Type *ETy = CP->getType()->getElementType();
789 assert(CP->getNumOperands() > 0 &&
790 "Number of operands for a PackedConst must be > 0");
792 TypePrinter.print(ETy, Out);
794 WriteAsOperandInternal(Out, CP->getOperand(0), TypePrinter, Machine);
795 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
797 TypePrinter.print(ETy, Out);
799 WriteAsOperandInternal(Out, CP->getOperand(i), TypePrinter, Machine);
805 if (isa<ConstantPointerNull>(CV)) {
810 if (isa<UndefValue>(CV)) {
815 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
816 Out << CE->getOpcodeName();
818 Out << ' ' << getPredicateText(CE->getPredicate());
821 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
822 TypePrinter.print((*OI)->getType(), Out);
824 WriteAsOperandInternal(Out, *OI, TypePrinter, Machine);
825 if (OI+1 != CE->op_end())
829 if (CE->hasIndices()) {
830 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
831 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
832 Out << ", " << Indices[i];
837 TypePrinter.print(CE->getType(), Out);
844 Out << "<placeholder or erroneous Constant>";
848 /// WriteAsOperand - Write the name of the specified value out to the specified
849 /// ostream. This can be useful when you just want to print int %reg126, not
850 /// the whole instruction that generated it.
852 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
853 TypePrinting &TypePrinter,
854 SlotTracker *Machine) {
856 PrintLLVMName(Out, V);
860 const Constant *CV = dyn_cast<Constant>(V);
861 if (CV && !isa<GlobalValue>(CV)) {
862 WriteConstantInt(Out, CV, TypePrinter, Machine);
866 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
868 if (IA->hasSideEffects())
869 Out << "sideeffect ";
871 PrintEscapedString(IA->getAsmString(), Out);
873 PrintEscapedString(IA->getConstraintString(), Out);
881 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
882 Slot = Machine->getGlobalSlot(GV);
885 Slot = Machine->getLocalSlot(V);
888 Machine = createSlotTracker(V);
890 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
891 Slot = Machine->getGlobalSlot(GV);
894 Slot = Machine->getLocalSlot(V);
903 Out << Prefix << Slot;
908 /// WriteAsOperand - Write the name of the specified value out to the specified
909 /// ostream. This can be useful when you just want to print int %reg126, not
910 /// the whole instruction that generated it.
912 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
913 const Module *Context) {
914 raw_os_ostream OS(Out);
915 WriteAsOperand(OS, V, PrintType, Context);
918 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
919 const Module *Context) {
920 if (Context == 0) Context = getModuleFromVal(V);
922 TypePrinting TypePrinter(Context);
924 TypePrinter.print(V->getType(), Out);
928 WriteAsOperandInternal(Out, V, TypePrinter, 0);
934 class AssemblyWriter {
936 SlotTracker &Machine;
937 const Module *TheModule;
938 TypePrinting TypePrinter;
939 AssemblyAnnotationWriter *AnnotationWriter;
941 inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
942 AssemblyAnnotationWriter *AAW)
943 : Out(o), Machine(Mac), TheModule(M), TypePrinter(M),
944 AnnotationWriter(AAW) {
947 void write(const Module *M) { printModule(M); }
949 void write(const GlobalValue *G) {
950 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
952 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
954 else if (const Function *F = dyn_cast<Function>(G))
957 assert(0 && "Unknown global");
960 void write(const BasicBlock *BB) { printBasicBlock(BB); }
961 void write(const Instruction *I) { printInstruction(*I); }
963 void writeOperand(const Value *Op, bool PrintType);
964 void writeParamOperand(const Value *Operand, Attributes Attrs);
966 const Module* getModule() { return TheModule; }
969 void printModule(const Module *M);
970 void printTypeSymbolTable(const TypeSymbolTable &ST);
971 void printGlobal(const GlobalVariable *GV);
972 void printAlias(const GlobalAlias *GV);
973 void printFunction(const Function *F);
974 void printArgument(const Argument *FA, Attributes Attrs);
975 void printBasicBlock(const BasicBlock *BB);
976 void printInstruction(const Instruction &I);
978 // printInfoComment - Print a little comment after the instruction indicating
979 // which slot it occupies.
980 void printInfoComment(const Value &V);
982 } // end of llvm namespace
985 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
987 Out << "<null operand!>";
990 TypePrinter.print(Operand->getType(), Out);
993 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
997 void AssemblyWriter::writeParamOperand(const Value *Operand,
1000 Out << "<null operand!>";
1003 TypePrinter.print(Operand->getType(), Out);
1004 // Print parameter attributes list
1005 if (Attrs != Attribute::None)
1006 Out << ' ' << Attribute::getAsString(Attrs);
1008 // Print the operand
1009 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1013 void AssemblyWriter::printModule(const Module *M) {
1014 if (!M->getModuleIdentifier().empty() &&
1015 // Don't print the ID if it will start a new line (which would
1016 // require a comment char before it).
1017 M->getModuleIdentifier().find('\n') == std::string::npos)
1018 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1020 if (!M->getDataLayout().empty())
1021 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1022 if (!M->getTargetTriple().empty())
1023 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1025 if (!M->getModuleInlineAsm().empty()) {
1026 // Split the string into lines, to make it easier to read the .ll file.
1027 std::string Asm = M->getModuleInlineAsm();
1029 size_t NewLine = Asm.find_first_of('\n', CurPos);
1030 while (NewLine != std::string::npos) {
1031 // We found a newline, print the portion of the asm string from the
1032 // last newline up to this newline.
1033 Out << "module asm \"";
1034 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1038 NewLine = Asm.find_first_of('\n', CurPos);
1040 Out << "module asm \"";
1041 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1045 // Loop over the dependent libraries and emit them.
1046 Module::lib_iterator LI = M->lib_begin();
1047 Module::lib_iterator LE = M->lib_end();
1049 Out << "deplibs = [ ";
1051 Out << '"' << *LI << '"';
1059 // Loop over the symbol table, emitting all named constants.
1060 printTypeSymbolTable(M->getTypeSymbolTable());
1062 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1066 // Output all aliases.
1067 if (!M->alias_empty()) Out << "\n";
1068 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1072 // Output all of the functions.
1073 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1077 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1079 case GlobalValue::PrivateLinkage: Out << "private "; break;
1080 case GlobalValue::InternalLinkage: Out << "internal "; break;
1081 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
1082 case GlobalValue::WeakLinkage: Out << "weak "; break;
1083 case GlobalValue::CommonLinkage: Out << "common "; break;
1084 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1085 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1086 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1087 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1088 case GlobalValue::ExternalLinkage: break;
1089 case GlobalValue::GhostLinkage:
1090 Out << "GhostLinkage not allowed in AsmWriter!\n";
1096 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1099 default: assert(0 && "Invalid visibility style!");
1100 case GlobalValue::DefaultVisibility: break;
1101 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1102 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1106 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1107 if (GV->hasName()) {
1108 PrintLLVMName(Out, GV);
1112 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1115 PrintLinkage(GV->getLinkage(), Out);
1116 PrintVisibility(GV->getVisibility(), Out);
1118 if (GV->isThreadLocal()) Out << "thread_local ";
1119 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1120 Out << "addrspace(" << AddressSpace << ") ";
1121 Out << (GV->isConstant() ? "constant " : "global ");
1122 TypePrinter.print(GV->getType()->getElementType(), Out);
1124 if (GV->hasInitializer()) {
1126 writeOperand(GV->getInitializer(), false);
1129 if (GV->hasSection())
1130 Out << ", section \"" << GV->getSection() << '"';
1131 if (GV->getAlignment())
1132 Out << ", align " << GV->getAlignment();
1134 printInfoComment(*GV);
1138 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1139 // Don't crash when dumping partially built GA
1141 Out << "<<nameless>> = ";
1143 PrintLLVMName(Out, GA);
1146 PrintVisibility(GA->getVisibility(), Out);
1150 PrintLinkage(GA->getLinkage(), Out);
1152 const Constant *Aliasee = GA->getAliasee();
1154 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1155 TypePrinter.print(GV->getType(), Out);
1157 PrintLLVMName(Out, GV);
1158 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1159 TypePrinter.print(F->getFunctionType(), Out);
1162 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1163 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1164 TypePrinter.print(GA->getType(), Out);
1166 PrintLLVMName(Out, GA);
1168 const ConstantExpr *CE = 0;
1169 if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
1170 (CE->getOpcode() == Instruction::BitCast)) {
1171 writeOperand(CE, false);
1173 assert(0 && "Unsupported aliasee");
1176 printInfoComment(*GA);
1180 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1182 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1185 PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1188 // Make sure we print out at least one level of the type structure, so
1189 // that we do not get %FILE = type %FILE
1190 TypePrinter.printAtLeastOneLevel(TI->second, Out);
1195 /// printFunction - Print all aspects of a function.
1197 void AssemblyWriter::printFunction(const Function *F) {
1198 // Print out the return type and name.
1201 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1203 if (F->isDeclaration())
1208 PrintLinkage(F->getLinkage(), Out);
1209 PrintVisibility(F->getVisibility(), Out);
1211 // Print the calling convention.
1212 switch (F->getCallingConv()) {
1213 case CallingConv::C: break; // default
1214 case CallingConv::Fast: Out << "fastcc "; break;
1215 case CallingConv::Cold: Out << "coldcc "; break;
1216 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1217 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1218 default: Out << "cc" << F->getCallingConv() << " "; break;
1221 const FunctionType *FT = F->getFunctionType();
1222 const AttrListPtr &Attrs = F->getAttributes();
1223 Attributes RetAttrs = Attrs.getRetAttributes();
1224 if (RetAttrs != Attribute::None)
1225 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1226 TypePrinter.print(F->getReturnType(), Out);
1228 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1230 Machine.incorporateFunction(F);
1232 // Loop over the arguments, printing them...
1235 if (!F->isDeclaration()) {
1236 // If this isn't a declaration, print the argument names as well.
1237 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1239 // Insert commas as we go... the first arg doesn't get a comma
1240 if (I != F->arg_begin()) Out << ", ";
1241 printArgument(I, Attrs.getParamAttributes(Idx));
1245 // Otherwise, print the types from the function type.
1246 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1247 // Insert commas as we go... the first arg doesn't get a comma
1251 TypePrinter.print(FT->getParamType(i), Out);
1253 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1254 if (ArgAttrs != Attribute::None)
1255 Out << ' ' << Attribute::getAsString(ArgAttrs);
1259 // Finish printing arguments...
1260 if (FT->isVarArg()) {
1261 if (FT->getNumParams()) Out << ", ";
1262 Out << "..."; // Output varargs portion of signature!
1265 Attributes FnAttrs = Attrs.getFnAttributes();
1266 if (FnAttrs != Attribute::None)
1267 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1268 if (F->hasSection())
1269 Out << " section \"" << F->getSection() << '"';
1270 if (F->getAlignment())
1271 Out << " align " << F->getAlignment();
1273 Out << " gc \"" << F->getGC() << '"';
1274 if (F->isDeclaration()) {
1279 // Output all of its basic blocks... for the function
1280 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1286 Machine.purgeFunction();
1289 /// printArgument - This member is called for every argument that is passed into
1290 /// the function. Simply print it out
1292 void AssemblyWriter::printArgument(const Argument *Arg,
1295 TypePrinter.print(Arg->getType(), Out);
1297 // Output parameter attributes list
1298 if (Attrs != Attribute::None)
1299 Out << ' ' << Attribute::getAsString(Attrs);
1301 // Output name, if available...
1302 if (Arg->hasName()) {
1304 PrintLLVMName(Out, Arg);
1308 /// printBasicBlock - This member is called for each basic block in a method.
1310 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1311 if (BB->hasName()) { // Print out the label if it exists...
1313 PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1315 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1316 Out << "\n; <label>:";
1317 int Slot = Machine.getLocalSlot(BB);
1324 if (BB->getParent() == 0)
1325 Out << "\t\t; Error: Block without parent!";
1326 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1327 // Output predecessors for the block...
1329 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1332 Out << " No predecessors!";
1335 writeOperand(*PI, false);
1336 for (++PI; PI != PE; ++PI) {
1338 writeOperand(*PI, false);
1345 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1347 // Output all of the instructions in the basic block...
1348 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1349 printInstruction(*I);
1351 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1355 /// printInfoComment - Print a little comment after the instruction indicating
1356 /// which slot it occupies.
1358 void AssemblyWriter::printInfoComment(const Value &V) {
1359 if (V.getType() != Type::VoidTy) {
1361 TypePrinter.print(V.getType(), Out);
1364 if (!V.hasName() && !isa<Instruction>(V)) {
1366 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1367 SlotNum = Machine.getGlobalSlot(GV);
1369 SlotNum = Machine.getLocalSlot(&V);
1373 Out << ':' << SlotNum; // Print out the def slot taken.
1375 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1379 // This member is called for each Instruction in a function..
1380 void AssemblyWriter::printInstruction(const Instruction &I) {
1381 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1385 // Print out name if it exists...
1387 PrintLLVMName(Out, &I);
1389 } else if (I.getType() != Type::VoidTy) {
1390 // Print out the def slot taken.
1391 int SlotNum = Machine.getLocalSlot(&I);
1393 Out << "<badref> = ";
1395 Out << '%' << SlotNum << " = ";
1398 // If this is a volatile load or store, print out the volatile marker.
1399 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1400 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1402 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1403 // If this is a call, check if it's a tail call.
1407 // Print out the opcode...
1408 Out << I.getOpcodeName();
1410 // Print out the compare instruction predicates
1411 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1412 Out << ' ' << getPredicateText(CI->getPredicate());
1414 // Print out the type of the operands...
1415 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1417 // Special case conditional branches to swizzle the condition out to the front
1418 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1419 BranchInst &BI(cast<BranchInst>(I));
1421 writeOperand(BI.getCondition(), true);
1423 writeOperand(BI.getSuccessor(0), true);
1425 writeOperand(BI.getSuccessor(1), true);
1427 } else if (isa<SwitchInst>(I)) {
1428 // Special case switch statement to get formatting nice and correct...
1430 writeOperand(Operand , true);
1432 writeOperand(I.getOperand(1), true);
1435 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1437 writeOperand(I.getOperand(op ), true);
1439 writeOperand(I.getOperand(op+1), true);
1442 } else if (isa<PHINode>(I)) {
1444 TypePrinter.print(I.getType(), Out);
1447 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1448 if (op) Out << ", ";
1450 writeOperand(I.getOperand(op ), false); Out << ", ";
1451 writeOperand(I.getOperand(op+1), false); Out << " ]";
1453 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1455 writeOperand(I.getOperand(0), true);
1456 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1458 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1460 writeOperand(I.getOperand(0), true); Out << ", ";
1461 writeOperand(I.getOperand(1), true);
1462 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1464 } else if (isa<ReturnInst>(I) && !Operand) {
1466 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1467 // Print the calling convention being used.
1468 switch (CI->getCallingConv()) {
1469 case CallingConv::C: break; // default
1470 case CallingConv::Fast: Out << " fastcc"; break;
1471 case CallingConv::Cold: Out << " coldcc"; break;
1472 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1473 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1474 default: Out << " cc" << CI->getCallingConv(); break;
1477 const PointerType *PTy = cast<PointerType>(Operand->getType());
1478 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1479 const Type *RetTy = FTy->getReturnType();
1480 const AttrListPtr &PAL = CI->getAttributes();
1482 if (PAL.getRetAttributes() != Attribute::None)
1483 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1485 // If possible, print out the short form of the call instruction. We can
1486 // only do this if the first argument is a pointer to a nonvararg function,
1487 // and if the return type is not a pointer to a function.
1490 if (!FTy->isVarArg() &&
1491 (!isa<PointerType>(RetTy) ||
1492 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1493 TypePrinter.print(RetTy, Out);
1495 writeOperand(Operand, false);
1497 writeOperand(Operand, true);
1500 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1503 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1506 if (PAL.getFnAttributes() != Attribute::None)
1507 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1508 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1509 const PointerType *PTy = cast<PointerType>(Operand->getType());
1510 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1511 const Type *RetTy = FTy->getReturnType();
1512 const AttrListPtr &PAL = II->getAttributes();
1514 // Print the calling convention being used.
1515 switch (II->getCallingConv()) {
1516 case CallingConv::C: break; // default
1517 case CallingConv::Fast: Out << " fastcc"; break;
1518 case CallingConv::Cold: Out << " coldcc"; break;
1519 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1520 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1521 default: Out << " cc" << II->getCallingConv(); break;
1524 if (PAL.getRetAttributes() != Attribute::None)
1525 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1527 // If possible, print out the short form of the invoke instruction. We can
1528 // only do this if the first argument is a pointer to a nonvararg function,
1529 // and if the return type is not a pointer to a function.
1532 if (!FTy->isVarArg() &&
1533 (!isa<PointerType>(RetTy) ||
1534 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1535 TypePrinter.print(RetTy, Out);
1537 writeOperand(Operand, false);
1539 writeOperand(Operand, true);
1542 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1545 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1549 if (PAL.getFnAttributes() != Attribute::None)
1550 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1552 Out << "\n\t\t\tto ";
1553 writeOperand(II->getNormalDest(), true);
1555 writeOperand(II->getUnwindDest(), true);
1557 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1559 TypePrinter.print(AI->getType()->getElementType(), Out);
1560 if (AI->isArrayAllocation()) {
1562 writeOperand(AI->getArraySize(), true);
1564 if (AI->getAlignment()) {
1565 Out << ", align " << AI->getAlignment();
1567 } else if (isa<CastInst>(I)) {
1570 writeOperand(Operand, true); // Work with broken code
1573 TypePrinter.print(I.getType(), Out);
1574 } else if (isa<VAArgInst>(I)) {
1577 writeOperand(Operand, true); // Work with broken code
1580 TypePrinter.print(I.getType(), Out);
1581 } else if (Operand) { // Print the normal way.
1583 // PrintAllTypes - Instructions who have operands of all the same type
1584 // omit the type from all but the first operand. If the instruction has
1585 // different type operands (for example br), then they are all printed.
1586 bool PrintAllTypes = false;
1587 const Type *TheType = Operand->getType();
1589 // Select, Store and ShuffleVector always print all types.
1590 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1591 || isa<ReturnInst>(I)) {
1592 PrintAllTypes = true;
1594 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1595 Operand = I.getOperand(i);
1596 // note that Operand shouldn't be null, but the test helps make dump()
1597 // more tolerant of malformed IR
1598 if (Operand && Operand->getType() != TheType) {
1599 PrintAllTypes = true; // We have differing types! Print them all!
1605 if (!PrintAllTypes) {
1607 TypePrinter.print(TheType, Out);
1611 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1613 writeOperand(I.getOperand(i), PrintAllTypes);
1617 // Print post operand alignment for load/store
1618 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1619 Out << ", align " << cast<LoadInst>(I).getAlignment();
1620 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1621 Out << ", align " << cast<StoreInst>(I).getAlignment();
1624 printInfoComment(I);
1629 //===----------------------------------------------------------------------===//
1630 // External Interface declarations
1631 //===----------------------------------------------------------------------===//
1633 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1634 raw_os_ostream OS(o);
1637 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1638 SlotTracker SlotTable(this);
1639 AssemblyWriter W(OS, SlotTable, this, AAW);
1643 void Type::print(std::ostream &o) const {
1644 raw_os_ostream OS(o);
1648 void Type::print(raw_ostream &OS) const {
1650 OS << "<null Type>";
1653 TypePrinting(0).print(this, OS);
1656 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1658 OS << "printing a <null> value\n";
1662 if (const Instruction *I = dyn_cast<Instruction>(this)) {
1663 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1664 SlotTracker SlotTable(F);
1665 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1667 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1668 SlotTracker SlotTable(BB->getParent());
1669 AssemblyWriter W(OS, SlotTable,
1670 BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1672 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1673 SlotTracker SlotTable(GV->getParent());
1674 AssemblyWriter W(OS, SlotTable, GV->getParent(), 0);
1676 } else if (const Constant *C = dyn_cast<Constant>(this)) {
1677 TypePrinting TypePrinter(0);
1678 TypePrinter.print(C->getType(), OS);
1680 WriteConstantInt(OS, C, TypePrinter, 0);
1681 } else if (const Argument *A = dyn_cast<Argument>(this)) {
1682 WriteAsOperand(OS, this, true,
1683 A->getParent() ? A->getParent()->getParent() : 0);
1684 } else if (isa<InlineAsm>(this)) {
1685 WriteAsOperand(OS, this, true, 0);
1687 assert(0 && "Unknown value to print out!");
1691 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
1692 raw_os_ostream OS(O);
1696 // Value::dump - allow easy printing of Values from the debugger.
1697 void Value::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1699 // Type::dump - allow easy printing of Types from the debugger.
1700 // This one uses type names from the given context module
1701 void Type::dump(const Module *Context) const {
1702 WriteTypeSymbolic(errs(), this, Context);
1707 // Type::dump - allow easy printing of Types from the debugger.
1708 void Type::dump() const { dump(0); }
1711 // Module::dump() - Allow printing of Modules from the debugger.
1712 void Module::dump() const { print(errs(), 0); errs().flush(); }