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) {
149 TypeNames = new std::map<const Type *, std::string>();
152 // If the module has a symbol table, take all global types and stuff their
153 // names into the TypeNames map.
154 const TypeSymbolTable &ST = M->getTypeSymbolTable();
155 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
157 const Type *Ty = cast<Type>(TI->second);
159 // As a heuristic, don't insert pointer to primitive types, because
160 // they are used too often to have a single useful name.
161 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
162 const Type *PETy = PTy->getElementType();
163 if ((PETy->isPrimitiveType() || PETy->isInteger()) &&
164 !isa<OpaqueType>(PETy))
168 // Likewise don't insert primitives either.
169 if (Ty->isInteger() || Ty->isPrimitiveType())
172 // Get the name as a string and insert it into TypeNames.
174 raw_string_ostream NameOS(NameStr);
175 PrintLLVMName(NameOS, TI->first.c_str(), TI->first.length(), LocalPrefix);
176 getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, NameOS.str()));
180 TypePrinting::~TypePrinting() {
181 delete &getTypeNamesMap(TypeNames);
184 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
185 /// use of type names or up references to shorten the type name where possible.
186 void TypePrinting::CalcTypeName(const Type *Ty,
187 SmallVectorImpl<const Type *> &TypeStack,
189 // Check to see if the type is named.
190 std::map<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
191 std::map<const Type *, std::string>::iterator I = TM.find(Ty);
193 // If the name wasn't temporarily removed use it.
194 !I->second.empty()) {
199 // Check to see if the Type is already on the stack...
200 unsigned Slot = 0, CurSize = TypeStack.size();
201 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
203 // This is another base case for the recursion. In this case, we know
204 // that we have looped back to a type that we have previously visited.
205 // Generate the appropriate upreference to handle this.
206 if (Slot < CurSize) {
207 OS << '\\' << unsigned(CurSize-Slot); // Here's the upreference
211 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
213 switch (Ty->getTypeID()) {
214 case Type::VoidTyID: OS << "void"; break;
215 case Type::FloatTyID: OS << "float"; break;
216 case Type::DoubleTyID: OS << "double"; break;
217 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
218 case Type::FP128TyID: OS << "fp128"; break;
219 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
220 case Type::LabelTyID: OS << "label"; break;
221 case Type::IntegerTyID:
222 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
225 case Type::FunctionTyID: {
226 const FunctionType *FTy = cast<FunctionType>(Ty);
227 CalcTypeName(FTy->getReturnType(), TypeStack, OS);
229 for (FunctionType::param_iterator I = FTy->param_begin(),
230 E = FTy->param_end(); I != E; ++I) {
231 if (I != FTy->param_begin())
233 CalcTypeName(*I, TypeStack, OS);
235 if (FTy->isVarArg()) {
236 if (FTy->getNumParams()) OS << ", ";
242 case Type::StructTyID: {
243 const StructType *STy = cast<StructType>(Ty);
247 for (StructType::element_iterator I = STy->element_begin(),
248 E = STy->element_end(); I != E; ++I) {
249 CalcTypeName(*I, TypeStack, OS);
250 if (next(I) != STy->element_end())
259 case Type::PointerTyID: {
260 const PointerType *PTy = cast<PointerType>(Ty);
261 CalcTypeName(PTy->getElementType(), TypeStack, OS);
262 if (unsigned AddressSpace = PTy->getAddressSpace())
263 OS << " addrspace(" << AddressSpace << ')';
267 case Type::ArrayTyID: {
268 const ArrayType *ATy = cast<ArrayType>(Ty);
269 OS << '[' << ATy->getNumElements() << " x ";
270 CalcTypeName(ATy->getElementType(), TypeStack, OS);
274 case Type::VectorTyID: {
275 const VectorType *PTy = cast<VectorType>(Ty);
276 OS << "<" << PTy->getNumElements() << " x ";
277 CalcTypeName(PTy->getElementType(), TypeStack, OS);
281 case Type::OpaqueTyID:
285 OS << "<unrecognized-type>";
289 TypeStack.pop_back(); // Remove self from stack.
292 /// printTypeInt - The internal guts of printing out a type that has a
293 /// potentially named portion.
295 void TypePrinting::print(const Type *Ty, raw_ostream &OS) {
296 // Check to see if the type is named.
297 std::map<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
298 std::map<const Type*, std::string>::iterator I = TM.find(Ty);
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;
310 raw_string_ostream TypeOS(TypeName);
311 CalcTypeName(Ty, TypeStack, TypeOS);
314 // Cache type name for later use.
315 TM.insert(std::make_pair(Ty, TypeOS.str()));
318 /// printAtLeastOneLevel - Print out one level of the possibly complex type
319 /// without considering any symbolic types that we may have equal to it.
320 void TypePrinting::printAtLeastOneLevel(const Type *Ty, raw_ostream &OS) {
321 // If the type does not have a name, then it is already guaranteed to print at
323 std::map<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
324 std::map<const Type*, std::string>::iterator I = TM.find(Ty);
326 return print(Ty, OS);
328 // Otherwise, temporarily remove the name and print it.
330 std::swap(OldName, I->second);
332 // Print the type without the name.
333 SmallVector<const Type *, 16> TypeStack;
334 CalcTypeName(Ty, TypeStack, OS);
337 std::swap(OldName, I->second);
341 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
342 /// type, iff there is an entry in the modules symbol table for the specified
343 /// type or one of it's component types.
345 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M){
346 TypePrinting(M).print(Ty, OS);
349 //===----------------------------------------------------------------------===//
350 // SlotTracker Class: Enumerate slot numbers for unnamed values
351 //===----------------------------------------------------------------------===//
355 /// This class provides computation of slot numbers for LLVM Assembly writing.
359 /// ValueMap - A mapping of Values to slot numbers
360 typedef DenseMap<const Value*, unsigned> ValueMap;
363 /// TheModule - The module for which we are holding slot numbers
364 const Module* TheModule;
366 /// TheFunction - The function for which we are holding slot numbers
367 const Function* TheFunction;
368 bool FunctionProcessed;
370 /// mMap - The TypePlanes map for the module level data
374 /// fMap - The TypePlanes map for the function level data
379 /// Construct from a module
380 explicit SlotTracker(const Module *M);
381 /// Construct from a function, starting out in incorp state.
382 explicit SlotTracker(const Function *F);
384 /// Return the slot number of the specified value in it's type
385 /// plane. If something is not in the SlotTracker, return -1.
386 int getLocalSlot(const Value *V);
387 int getGlobalSlot(const GlobalValue *V);
389 /// If you'd like to deal with a function instead of just a module, use
390 /// this method to get its data into the SlotTracker.
391 void incorporateFunction(const Function *F) {
393 FunctionProcessed = false;
396 /// After calling incorporateFunction, use this method to remove the
397 /// most recently incorporated function from the SlotTracker. This
398 /// will reset the state of the machine back to just the module contents.
399 void purgeFunction();
401 // Implementation Details
403 /// This function does the actual initialization.
404 inline void initialize();
406 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
407 void CreateModuleSlot(const GlobalValue *V);
409 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
410 void CreateFunctionSlot(const Value *V);
412 /// Add all of the module level global variables (and their initializers)
413 /// and function declarations, but not the contents of those functions.
414 void processModule();
416 /// Add all of the functions arguments, basic blocks, and instructions
417 void processFunction();
419 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
420 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
423 } // end anonymous namespace
426 static SlotTracker *createSlotTracker(const Value *V) {
427 if (const Argument *FA = dyn_cast<Argument>(V))
428 return new SlotTracker(FA->getParent());
430 if (const Instruction *I = dyn_cast<Instruction>(V))
431 return new SlotTracker(I->getParent()->getParent());
433 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
434 return new SlotTracker(BB->getParent());
436 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
437 return new SlotTracker(GV->getParent());
439 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
440 return new SlotTracker(GA->getParent());
442 if (const Function *Func = dyn_cast<Function>(V))
443 return new SlotTracker(Func);
449 #define ST_DEBUG(X) cerr << X
454 // Module level constructor. Causes the contents of the Module (sans functions)
455 // to be added to the slot table.
456 SlotTracker::SlotTracker(const Module *M)
457 : TheModule(M), TheFunction(0), FunctionProcessed(false), mNext(0), fNext(0) {
460 // Function level constructor. Causes the contents of the Module and the one
461 // function provided to be added to the slot table.
462 SlotTracker::SlotTracker(const Function *F)
463 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
467 inline void SlotTracker::initialize() {
470 TheModule = 0; ///< Prevent re-processing next time we're called.
473 if (TheFunction && !FunctionProcessed)
477 // Iterate through all the global variables, functions, and global
478 // variable initializers and create slots for them.
479 void SlotTracker::processModule() {
480 ST_DEBUG("begin processModule!\n");
482 // Add all of the unnamed global variables to the value table.
483 for (Module::const_global_iterator I = TheModule->global_begin(),
484 E = TheModule->global_end(); I != E; ++I)
488 // Add all the unnamed functions to the table.
489 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
494 ST_DEBUG("end processModule!\n");
498 // Process the arguments, basic blocks, and instructions of a function.
499 void SlotTracker::processFunction() {
500 ST_DEBUG("begin processFunction!\n");
503 // Add all the function arguments with no names.
504 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
505 AE = TheFunction->arg_end(); AI != AE; ++AI)
507 CreateFunctionSlot(AI);
509 ST_DEBUG("Inserting Instructions:\n");
511 // Add all of the basic blocks and instructions with no names.
512 for (Function::const_iterator BB = TheFunction->begin(),
513 E = TheFunction->end(); BB != E; ++BB) {
515 CreateFunctionSlot(BB);
516 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
517 if (I->getType() != Type::VoidTy && !I->hasName())
518 CreateFunctionSlot(I);
521 FunctionProcessed = true;
523 ST_DEBUG("end processFunction!\n");
526 /// Clean up after incorporating a function. This is the only way to get out of
527 /// the function incorporation state that affects get*Slot/Create*Slot. Function
528 /// incorporation state is indicated by TheFunction != 0.
529 void SlotTracker::purgeFunction() {
530 ST_DEBUG("begin purgeFunction!\n");
531 fMap.clear(); // Simply discard the function level map
533 FunctionProcessed = false;
534 ST_DEBUG("end purgeFunction!\n");
537 /// getGlobalSlot - Get the slot number of a global value.
538 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
539 // Check for uninitialized state and do lazy initialization.
542 // Find the type plane in the module map
543 ValueMap::iterator MI = mMap.find(V);
544 return MI == mMap.end() ? -1 : (int)MI->second;
548 /// getLocalSlot - Get the slot number for a value that is local to a function.
549 int SlotTracker::getLocalSlot(const Value *V) {
550 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
552 // Check for uninitialized state and do lazy initialization.
555 ValueMap::iterator FI = fMap.find(V);
556 return FI == fMap.end() ? -1 : (int)FI->second;
560 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
561 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
562 assert(V && "Can't insert a null Value into SlotTracker!");
563 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
564 assert(!V->hasName() && "Doesn't need a slot!");
566 unsigned DestSlot = mNext++;
569 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
571 // G = Global, F = Function, A = Alias, o = other
572 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
573 (isa<Function>(V) ? 'F' :
574 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
578 /// CreateSlot - Create a new slot for the specified value if it has no name.
579 void SlotTracker::CreateFunctionSlot(const Value *V) {
580 assert(V->getType() != Type::VoidTy && !V->hasName() &&
581 "Doesn't need a slot!");
583 unsigned DestSlot = fNext++;
586 // G = Global, F = Function, o = other
587 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
588 DestSlot << " [o]\n");
593 //===----------------------------------------------------------------------===//
594 // AsmWriter Implementation
595 //===----------------------------------------------------------------------===//
597 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
598 TypePrinting &TypePrinter,
599 SlotTracker *Machine);
603 static const char *getPredicateText(unsigned predicate) {
604 const char * pred = "unknown";
606 case FCmpInst::FCMP_FALSE: pred = "false"; break;
607 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
608 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
609 case FCmpInst::FCMP_OGE: pred = "oge"; break;
610 case FCmpInst::FCMP_OLT: pred = "olt"; break;
611 case FCmpInst::FCMP_OLE: pred = "ole"; break;
612 case FCmpInst::FCMP_ONE: pred = "one"; break;
613 case FCmpInst::FCMP_ORD: pred = "ord"; break;
614 case FCmpInst::FCMP_UNO: pred = "uno"; break;
615 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
616 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
617 case FCmpInst::FCMP_UGE: pred = "uge"; break;
618 case FCmpInst::FCMP_ULT: pred = "ult"; break;
619 case FCmpInst::FCMP_ULE: pred = "ule"; break;
620 case FCmpInst::FCMP_UNE: pred = "une"; break;
621 case FCmpInst::FCMP_TRUE: pred = "true"; break;
622 case ICmpInst::ICMP_EQ: pred = "eq"; break;
623 case ICmpInst::ICMP_NE: pred = "ne"; break;
624 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
625 case ICmpInst::ICMP_SGE: pred = "sge"; break;
626 case ICmpInst::ICMP_SLT: pred = "slt"; break;
627 case ICmpInst::ICMP_SLE: pred = "sle"; break;
628 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
629 case ICmpInst::ICMP_UGE: pred = "uge"; break;
630 case ICmpInst::ICMP_ULT: pred = "ult"; break;
631 case ICmpInst::ICMP_ULE: pred = "ule"; break;
636 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
637 TypePrinting &TypePrinter, SlotTracker *Machine) {
638 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
639 if (CI->getType() == Type::Int1Ty) {
640 Out << (CI->getZExtValue() ? "true" : "false");
643 Out << CI->getValue();
647 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
648 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
649 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
650 // We would like to output the FP constant value in exponential notation,
651 // but we cannot do this if doing so will lose precision. Check here to
652 // make sure that we only output it in exponential format if we can parse
653 // the value back and get the same value.
656 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
657 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
658 CFP->getValueAPF().convertToFloat();
659 std::string StrVal = ftostr(CFP->getValueAPF());
661 // Check to make sure that the stringized number is not some string like
662 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
663 // that the string matches the "[-+]?[0-9]" regex.
665 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
666 ((StrVal[0] == '-' || StrVal[0] == '+') &&
667 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
668 // Reparse stringized version!
669 if (atof(StrVal.c_str()) == Val) {
674 // Otherwise we could not reparse it to exactly the same value, so we must
675 // output the string in hexadecimal format! Note that loading and storing
676 // floating point types changes the bits of NaNs on some hosts, notably
677 // x86, so we must not use these types.
678 assert(sizeof(double) == sizeof(uint64_t) &&
679 "assuming that double is 64 bits!");
681 APFloat apf = CFP->getValueAPF();
682 // Floats are represented in ASCII IR as double, convert.
684 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
687 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
692 // Some form of long double. These appear as a magic letter identifying
693 // the type, then a fixed number of hex digits.
695 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended)
697 else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
699 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
702 assert(0 && "Unsupported floating point type");
703 // api needed to prevent premature destruction
704 APInt api = CFP->getValueAPF().bitcastToAPInt();
705 const uint64_t* p = api.getRawData();
708 int width = api.getBitWidth();
709 for (int j=0; j<width; j+=4, shiftcount-=4) {
710 unsigned int nibble = (word>>shiftcount) & 15;
712 Out << (unsigned char)(nibble + '0');
714 Out << (unsigned char)(nibble - 10 + 'A');
715 if (shiftcount == 0 && j+4 < width) {
719 shiftcount = width-j-4;
725 if (isa<ConstantAggregateZero>(CV)) {
726 Out << "zeroinitializer";
730 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
731 // As a special case, print the array as a string if it is an array of
732 // i8 with ConstantInt values.
734 const Type *ETy = CA->getType()->getElementType();
735 if (CA->isString()) {
737 PrintEscapedString(CA->getAsString(), Out);
739 } else { // Cannot output in string format...
741 if (CA->getNumOperands()) {
742 TypePrinter.print(ETy, Out);
744 WriteAsOperandInternal(Out, CA->getOperand(0),
745 TypePrinter, Machine);
746 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
748 TypePrinter.print(ETy, Out);
750 WriteAsOperandInternal(Out, CA->getOperand(i), TypePrinter, Machine);
758 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
759 if (CS->getType()->isPacked())
762 unsigned N = CS->getNumOperands();
765 TypePrinter.print(CS->getOperand(0)->getType(), Out);
768 WriteAsOperandInternal(Out, CS->getOperand(0), TypePrinter, Machine);
770 for (unsigned i = 1; i < N; i++) {
772 TypePrinter.print(CS->getOperand(i)->getType(), Out);
775 WriteAsOperandInternal(Out, CS->getOperand(i), TypePrinter, Machine);
781 if (CS->getType()->isPacked())
786 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
787 const Type *ETy = CP->getType()->getElementType();
788 assert(CP->getNumOperands() > 0 &&
789 "Number of operands for a PackedConst must be > 0");
791 TypePrinter.print(ETy, Out);
793 WriteAsOperandInternal(Out, CP->getOperand(0), TypePrinter, Machine);
794 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
796 TypePrinter.print(ETy, Out);
798 WriteAsOperandInternal(Out, CP->getOperand(i), TypePrinter, Machine);
804 if (isa<ConstantPointerNull>(CV)) {
809 if (isa<UndefValue>(CV)) {
814 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
815 Out << CE->getOpcodeName();
817 Out << ' ' << getPredicateText(CE->getPredicate());
820 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
821 TypePrinter.print((*OI)->getType(), Out);
823 WriteAsOperandInternal(Out, *OI, TypePrinter, Machine);
824 if (OI+1 != CE->op_end())
828 if (CE->hasIndices()) {
829 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
830 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
831 Out << ", " << Indices[i];
836 TypePrinter.print(CE->getType(), Out);
843 Out << "<placeholder or erroneous Constant>";
847 /// WriteAsOperand - Write the name of the specified value out to the specified
848 /// ostream. This can be useful when you just want to print int %reg126, not
849 /// the whole instruction that generated it.
851 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
852 TypePrinting &TypePrinter,
853 SlotTracker *Machine) {
855 PrintLLVMName(Out, V);
859 const Constant *CV = dyn_cast<Constant>(V);
860 if (CV && !isa<GlobalValue>(CV)) {
861 WriteConstantInt(Out, CV, TypePrinter, Machine);
865 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
867 if (IA->hasSideEffects())
868 Out << "sideeffect ";
870 PrintEscapedString(IA->getAsmString(), Out);
872 PrintEscapedString(IA->getConstraintString(), Out);
880 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
881 Slot = Machine->getGlobalSlot(GV);
884 Slot = Machine->getLocalSlot(V);
887 Machine = createSlotTracker(V);
889 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
890 Slot = Machine->getGlobalSlot(GV);
893 Slot = Machine->getLocalSlot(V);
902 Out << Prefix << Slot;
907 /// WriteAsOperand - Write the name of the specified value out to the specified
908 /// ostream. This can be useful when you just want to print int %reg126, not
909 /// the whole instruction that generated it.
911 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
912 const Module *Context) {
913 raw_os_ostream OS(Out);
914 WriteAsOperand(OS, V, PrintType, Context);
917 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
918 const Module *Context) {
919 if (Context == 0) Context = getModuleFromVal(V);
921 TypePrinting TypePrinter(Context);
923 TypePrinter.print(V->getType(), Out);
927 WriteAsOperandInternal(Out, V, TypePrinter, 0);
933 class AssemblyWriter {
935 SlotTracker &Machine;
936 const Module *TheModule;
937 TypePrinting TypePrinter;
938 AssemblyAnnotationWriter *AnnotationWriter;
940 inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
941 AssemblyAnnotationWriter *AAW)
942 : Out(o), Machine(Mac), TheModule(M), TypePrinter(M),
943 AnnotationWriter(AAW) {
946 void write(const Module *M) { printModule(M); }
948 void write(const GlobalValue *G) {
949 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
951 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
953 else if (const Function *F = dyn_cast<Function>(G))
956 assert(0 && "Unknown global");
959 void write(const BasicBlock *BB) { printBasicBlock(BB); }
960 void write(const Instruction *I) { printInstruction(*I); }
962 void writeOperand(const Value *Op, bool PrintType);
963 void writeParamOperand(const Value *Operand, Attributes Attrs);
965 const Module* getModule() { return TheModule; }
968 void printModule(const Module *M);
969 void printTypeSymbolTable(const TypeSymbolTable &ST);
970 void printGlobal(const GlobalVariable *GV);
971 void printAlias(const GlobalAlias *GV);
972 void printFunction(const Function *F);
973 void printArgument(const Argument *FA, Attributes Attrs);
974 void printBasicBlock(const BasicBlock *BB);
975 void printInstruction(const Instruction &I);
977 // printInfoComment - Print a little comment after the instruction indicating
978 // which slot it occupies.
979 void printInfoComment(const Value &V);
981 } // end of llvm namespace
984 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
986 Out << "<null operand!>";
989 TypePrinter.print(Operand->getType(), Out);
992 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
996 void AssemblyWriter::writeParamOperand(const Value *Operand,
999 Out << "<null operand!>";
1002 TypePrinter.print(Operand->getType(), Out);
1003 // Print parameter attributes list
1004 if (Attrs != Attribute::None)
1005 Out << ' ' << Attribute::getAsString(Attrs);
1007 // Print the operand
1008 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1012 void AssemblyWriter::printModule(const Module *M) {
1013 if (!M->getModuleIdentifier().empty() &&
1014 // Don't print the ID if it will start a new line (which would
1015 // require a comment char before it).
1016 M->getModuleIdentifier().find('\n') == std::string::npos)
1017 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1019 if (!M->getDataLayout().empty())
1020 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1021 if (!M->getTargetTriple().empty())
1022 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1024 if (!M->getModuleInlineAsm().empty()) {
1025 // Split the string into lines, to make it easier to read the .ll file.
1026 std::string Asm = M->getModuleInlineAsm();
1028 size_t NewLine = Asm.find_first_of('\n', CurPos);
1029 while (NewLine != std::string::npos) {
1030 // We found a newline, print the portion of the asm string from the
1031 // last newline up to this newline.
1032 Out << "module asm \"";
1033 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1037 NewLine = Asm.find_first_of('\n', CurPos);
1039 Out << "module asm \"";
1040 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1044 // Loop over the dependent libraries and emit them.
1045 Module::lib_iterator LI = M->lib_begin();
1046 Module::lib_iterator LE = M->lib_end();
1048 Out << "deplibs = [ ";
1050 Out << '"' << *LI << '"';
1058 // Loop over the symbol table, emitting all named constants.
1059 printTypeSymbolTable(M->getTypeSymbolTable());
1061 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1065 // Output all aliases.
1066 if (!M->alias_empty()) Out << "\n";
1067 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1071 // Output all of the functions.
1072 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1076 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1078 case GlobalValue::PrivateLinkage: Out << "private "; break;
1079 case GlobalValue::InternalLinkage: Out << "internal "; break;
1080 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
1081 case GlobalValue::WeakLinkage: Out << "weak "; break;
1082 case GlobalValue::CommonLinkage: Out << "common "; break;
1083 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1084 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1085 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1086 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1087 case GlobalValue::ExternalLinkage: break;
1088 case GlobalValue::GhostLinkage:
1089 Out << "GhostLinkage not allowed in AsmWriter!\n";
1095 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1098 default: assert(0 && "Invalid visibility style!");
1099 case GlobalValue::DefaultVisibility: break;
1100 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1101 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1105 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1106 if (GV->hasName()) {
1107 PrintLLVMName(Out, GV);
1111 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1114 PrintLinkage(GV->getLinkage(), Out);
1115 PrintVisibility(GV->getVisibility(), Out);
1117 if (GV->isThreadLocal()) Out << "thread_local ";
1118 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1119 Out << "addrspace(" << AddressSpace << ") ";
1120 Out << (GV->isConstant() ? "constant " : "global ");
1121 TypePrinter.print(GV->getType()->getElementType(), Out);
1123 if (GV->hasInitializer()) {
1125 writeOperand(GV->getInitializer(), false);
1128 if (GV->hasSection())
1129 Out << ", section \"" << GV->getSection() << '"';
1130 if (GV->getAlignment())
1131 Out << ", align " << GV->getAlignment();
1133 printInfoComment(*GV);
1137 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1138 // Don't crash when dumping partially built GA
1140 Out << "<<nameless>> = ";
1142 PrintLLVMName(Out, GA);
1145 PrintVisibility(GA->getVisibility(), Out);
1149 PrintLinkage(GA->getLinkage(), Out);
1151 const Constant *Aliasee = GA->getAliasee();
1153 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1154 TypePrinter.print(GV->getType(), Out);
1156 PrintLLVMName(Out, GV);
1157 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1158 TypePrinter.print(F->getFunctionType(), Out);
1161 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1162 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1163 TypePrinter.print(GA->getType(), Out);
1165 PrintLLVMName(Out, GA);
1167 const ConstantExpr *CE = 0;
1168 if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
1169 (CE->getOpcode() == Instruction::BitCast)) {
1170 writeOperand(CE, false);
1172 assert(0 && "Unsupported aliasee");
1175 printInfoComment(*GA);
1179 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1181 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1184 PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1187 // Make sure we print out at least one level of the type structure, so
1188 // that we do not get %FILE = type %FILE
1189 TypePrinter.printAtLeastOneLevel(TI->second, Out);
1194 /// printFunction - Print all aspects of a function.
1196 void AssemblyWriter::printFunction(const Function *F) {
1197 // Print out the return type and name.
1200 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1202 if (F->isDeclaration())
1207 PrintLinkage(F->getLinkage(), Out);
1208 PrintVisibility(F->getVisibility(), Out);
1210 // Print the calling convention.
1211 switch (F->getCallingConv()) {
1212 case CallingConv::C: break; // default
1213 case CallingConv::Fast: Out << "fastcc "; break;
1214 case CallingConv::Cold: Out << "coldcc "; break;
1215 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1216 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1217 default: Out << "cc" << F->getCallingConv() << " "; break;
1220 const FunctionType *FT = F->getFunctionType();
1221 const AttrListPtr &Attrs = F->getAttributes();
1222 Attributes RetAttrs = Attrs.getRetAttributes();
1223 if (RetAttrs != Attribute::None)
1224 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1225 TypePrinter.print(F->getReturnType(), Out);
1227 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1229 Machine.incorporateFunction(F);
1231 // Loop over the arguments, printing them...
1234 if (!F->isDeclaration()) {
1235 // If this isn't a declaration, print the argument names as well.
1236 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1238 // Insert commas as we go... the first arg doesn't get a comma
1239 if (I != F->arg_begin()) Out << ", ";
1240 printArgument(I, Attrs.getParamAttributes(Idx));
1244 // Otherwise, print the types from the function type.
1245 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1246 // Insert commas as we go... the first arg doesn't get a comma
1250 TypePrinter.print(FT->getParamType(i), Out);
1252 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1253 if (ArgAttrs != Attribute::None)
1254 Out << ' ' << Attribute::getAsString(ArgAttrs);
1258 // Finish printing arguments...
1259 if (FT->isVarArg()) {
1260 if (FT->getNumParams()) Out << ", ";
1261 Out << "..."; // Output varargs portion of signature!
1264 Attributes FnAttrs = Attrs.getFnAttributes();
1265 if (FnAttrs != Attribute::None)
1266 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1267 if (F->hasSection())
1268 Out << " section \"" << F->getSection() << '"';
1269 if (F->getAlignment())
1270 Out << " align " << F->getAlignment();
1272 Out << " gc \"" << F->getGC() << '"';
1273 if (F->isDeclaration()) {
1278 // Output all of its basic blocks... for the function
1279 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1285 Machine.purgeFunction();
1288 /// printArgument - This member is called for every argument that is passed into
1289 /// the function. Simply print it out
1291 void AssemblyWriter::printArgument(const Argument *Arg,
1294 TypePrinter.print(Arg->getType(), Out);
1296 // Output parameter attributes list
1297 if (Attrs != Attribute::None)
1298 Out << ' ' << Attribute::getAsString(Attrs);
1300 // Output name, if available...
1301 if (Arg->hasName()) {
1303 PrintLLVMName(Out, Arg);
1307 /// printBasicBlock - This member is called for each basic block in a method.
1309 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1310 if (BB->hasName()) { // Print out the label if it exists...
1312 PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1314 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1315 Out << "\n; <label>:";
1316 int Slot = Machine.getLocalSlot(BB);
1323 if (BB->getParent() == 0)
1324 Out << "\t\t; Error: Block without parent!";
1325 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1326 // Output predecessors for the block...
1328 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1331 Out << " No predecessors!";
1334 writeOperand(*PI, false);
1335 for (++PI; PI != PE; ++PI) {
1337 writeOperand(*PI, false);
1344 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1346 // Output all of the instructions in the basic block...
1347 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1348 printInstruction(*I);
1350 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1354 /// printInfoComment - Print a little comment after the instruction indicating
1355 /// which slot it occupies.
1357 void AssemblyWriter::printInfoComment(const Value &V) {
1358 if (V.getType() != Type::VoidTy) {
1360 TypePrinter.print(V.getType(), Out);
1363 if (!V.hasName() && !isa<Instruction>(V)) {
1365 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1366 SlotNum = Machine.getGlobalSlot(GV);
1368 SlotNum = Machine.getLocalSlot(&V);
1372 Out << ':' << SlotNum; // Print out the def slot taken.
1374 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1378 // This member is called for each Instruction in a function..
1379 void AssemblyWriter::printInstruction(const Instruction &I) {
1380 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1384 // Print out name if it exists...
1386 PrintLLVMName(Out, &I);
1388 } else if (I.getType() != Type::VoidTy) {
1389 // Print out the def slot taken.
1390 int SlotNum = Machine.getLocalSlot(&I);
1392 Out << "<badref> = ";
1394 Out << '%' << SlotNum << " = ";
1397 // If this is a volatile load or store, print out the volatile marker.
1398 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1399 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1401 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1402 // If this is a call, check if it's a tail call.
1406 // Print out the opcode...
1407 Out << I.getOpcodeName();
1409 // Print out the compare instruction predicates
1410 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1411 Out << ' ' << getPredicateText(CI->getPredicate());
1413 // Print out the type of the operands...
1414 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1416 // Special case conditional branches to swizzle the condition out to the front
1417 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1418 BranchInst &BI(cast<BranchInst>(I));
1420 writeOperand(BI.getCondition(), true);
1422 writeOperand(BI.getSuccessor(0), true);
1424 writeOperand(BI.getSuccessor(1), true);
1426 } else if (isa<SwitchInst>(I)) {
1427 // Special case switch statement to get formatting nice and correct...
1429 writeOperand(Operand , true);
1431 writeOperand(I.getOperand(1), true);
1434 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1436 writeOperand(I.getOperand(op ), true);
1438 writeOperand(I.getOperand(op+1), true);
1441 } else if (isa<PHINode>(I)) {
1443 TypePrinter.print(I.getType(), Out);
1446 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1447 if (op) Out << ", ";
1449 writeOperand(I.getOperand(op ), false); Out << ", ";
1450 writeOperand(I.getOperand(op+1), false); Out << " ]";
1452 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1454 writeOperand(I.getOperand(0), true);
1455 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1457 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1459 writeOperand(I.getOperand(0), true); Out << ", ";
1460 writeOperand(I.getOperand(1), true);
1461 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1463 } else if (isa<ReturnInst>(I) && !Operand) {
1465 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1466 // Print the calling convention being used.
1467 switch (CI->getCallingConv()) {
1468 case CallingConv::C: break; // default
1469 case CallingConv::Fast: Out << " fastcc"; break;
1470 case CallingConv::Cold: Out << " coldcc"; break;
1471 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1472 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1473 default: Out << " cc" << CI->getCallingConv(); break;
1476 const PointerType *PTy = cast<PointerType>(Operand->getType());
1477 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1478 const Type *RetTy = FTy->getReturnType();
1479 const AttrListPtr &PAL = CI->getAttributes();
1481 if (PAL.getRetAttributes() != Attribute::None)
1482 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1484 // If possible, print out the short form of the call instruction. We can
1485 // only do this if the first argument is a pointer to a nonvararg function,
1486 // and if the return type is not a pointer to a function.
1489 if (!FTy->isVarArg() &&
1490 (!isa<PointerType>(RetTy) ||
1491 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1492 TypePrinter.print(RetTy, Out);
1494 writeOperand(Operand, false);
1496 writeOperand(Operand, true);
1499 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1502 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1505 if (PAL.getFnAttributes() != Attribute::None)
1506 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1507 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1508 const PointerType *PTy = cast<PointerType>(Operand->getType());
1509 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1510 const Type *RetTy = FTy->getReturnType();
1511 const AttrListPtr &PAL = II->getAttributes();
1513 // Print the calling convention being used.
1514 switch (II->getCallingConv()) {
1515 case CallingConv::C: break; // default
1516 case CallingConv::Fast: Out << " fastcc"; break;
1517 case CallingConv::Cold: Out << " coldcc"; break;
1518 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1519 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1520 default: Out << " cc" << II->getCallingConv(); break;
1523 if (PAL.getRetAttributes() != Attribute::None)
1524 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1526 // If possible, print out the short form of the invoke instruction. We can
1527 // only do this if the first argument is a pointer to a nonvararg function,
1528 // and if the return type is not a pointer to a function.
1531 if (!FTy->isVarArg() &&
1532 (!isa<PointerType>(RetTy) ||
1533 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1534 TypePrinter.print(RetTy, Out);
1536 writeOperand(Operand, false);
1538 writeOperand(Operand, true);
1541 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1544 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1548 if (PAL.getFnAttributes() != Attribute::None)
1549 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1551 Out << "\n\t\t\tto ";
1552 writeOperand(II->getNormalDest(), true);
1554 writeOperand(II->getUnwindDest(), true);
1556 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1558 TypePrinter.print(AI->getType()->getElementType(), Out);
1559 if (AI->isArrayAllocation()) {
1561 writeOperand(AI->getArraySize(), true);
1563 if (AI->getAlignment()) {
1564 Out << ", align " << AI->getAlignment();
1566 } else if (isa<CastInst>(I)) {
1569 writeOperand(Operand, true); // Work with broken code
1572 TypePrinter.print(I.getType(), Out);
1573 } else if (isa<VAArgInst>(I)) {
1576 writeOperand(Operand, true); // Work with broken code
1579 TypePrinter.print(I.getType(), Out);
1580 } else if (Operand) { // Print the normal way.
1582 // PrintAllTypes - Instructions who have operands of all the same type
1583 // omit the type from all but the first operand. If the instruction has
1584 // different type operands (for example br), then they are all printed.
1585 bool PrintAllTypes = false;
1586 const Type *TheType = Operand->getType();
1588 // Select, Store and ShuffleVector always print all types.
1589 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1590 || isa<ReturnInst>(I)) {
1591 PrintAllTypes = true;
1593 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1594 Operand = I.getOperand(i);
1595 // note that Operand shouldn't be null, but the test helps make dump()
1596 // more tolerant of malformed IR
1597 if (Operand && Operand->getType() != TheType) {
1598 PrintAllTypes = true; // We have differing types! Print them all!
1604 if (!PrintAllTypes) {
1606 TypePrinter.print(TheType, Out);
1610 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1612 writeOperand(I.getOperand(i), PrintAllTypes);
1616 // Print post operand alignment for load/store
1617 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1618 Out << ", align " << cast<LoadInst>(I).getAlignment();
1619 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1620 Out << ", align " << cast<StoreInst>(I).getAlignment();
1623 printInfoComment(I);
1628 //===----------------------------------------------------------------------===//
1629 // External Interface declarations
1630 //===----------------------------------------------------------------------===//
1632 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1633 raw_os_ostream OS(o);
1636 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1637 SlotTracker SlotTable(this);
1638 AssemblyWriter W(OS, SlotTable, this, AAW);
1642 void Type::print(std::ostream &o) const {
1643 raw_os_ostream OS(o);
1647 void Type::print(raw_ostream &OS) const {
1649 OS << "<null Type>";
1652 TypePrinting(0).print(this, OS);
1655 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1657 OS << "printing a <null> value\n";
1661 if (const Instruction *I = dyn_cast<Instruction>(this)) {
1662 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1663 SlotTracker SlotTable(F);
1664 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1666 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1667 SlotTracker SlotTable(BB->getParent());
1668 AssemblyWriter W(OS, SlotTable,
1669 BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1671 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1672 SlotTracker SlotTable(GV->getParent());
1673 AssemblyWriter W(OS, SlotTable, GV->getParent(), 0);
1675 } else if (const Constant *C = dyn_cast<Constant>(this)) {
1676 TypePrinting TypePrinter(0);
1677 TypePrinter.print(C->getType(), OS);
1679 WriteConstantInt(OS, C, TypePrinter, 0);
1680 } else if (const Argument *A = dyn_cast<Argument>(this)) {
1681 WriteAsOperand(OS, this, true,
1682 A->getParent() ? A->getParent()->getParent() : 0);
1683 } else if (isa<InlineAsm>(this)) {
1684 WriteAsOperand(OS, this, true, 0);
1686 assert(0 && "Unknown value to print out!");
1690 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
1691 raw_os_ostream OS(O);
1695 // Value::dump - allow easy printing of Values from the debugger.
1696 void Value::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1698 // Type::dump - allow easy printing of Types from the debugger.
1699 // This one uses type names from the given context module
1700 void Type::dump(const Module *Context) const {
1701 WriteTypeSymbolic(errs(), this, Context);
1706 // Type::dump - allow easy printing of Types from the debugger.
1707 void Type::dump() const { dump(0); }
1710 // Module::dump() - Allow printing of Modules from the debugger.
1711 void Module::dump() const { print(errs(), 0); errs().flush(); }