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/Streams.h"
35 #include "llvm/Support/raw_ostream.h"
40 // Make virtual table appear in this compilation unit.
41 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
43 char PrintModulePass::ID = 0;
44 static RegisterPass<PrintModulePass>
45 X("printm", "Print module to stderr");
46 char PrintFunctionPass::ID = 0;
47 static RegisterPass<PrintFunctionPass>
48 Y("print","Print function to stderr");
51 //===----------------------------------------------------------------------===//
53 //===----------------------------------------------------------------------===//
55 static const Module *getModuleFromVal(const Value *V) {
56 if (const Argument *MA = dyn_cast<Argument>(V))
57 return MA->getParent() ? MA->getParent()->getParent() : 0;
59 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
60 return BB->getParent() ? BB->getParent()->getParent() : 0;
62 if (const Instruction *I = dyn_cast<Instruction>(V)) {
63 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
64 return M ? M->getParent() : 0;
67 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
68 return GV->getParent();
73 /// NameNeedsQuotes - Return true if the specified llvm name should be wrapped
75 static std::string QuoteNameIfNeeded(const std::string &Name) {
77 bool needsQuotes = Name[0] >= '0' && Name[0] <= '9';
78 // Scan the name to see if it needs quotes and to replace funky chars with
79 // their octal equivalent.
80 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
82 assert(C != '"' && "Illegal character in LLVM value name!");
83 if (isalnum(C) || C == '-' || C == '.' || C == '_')
88 } else if (isprint(C)) {
94 char hex1 = (C >> 4) & 0x0F;
98 result += hex1 - 10 + 'A';
101 result += hex2 + '0';
103 result += hex2 - 10 + 'A';
107 result.insert(0,"\"");
113 /// getLLVMName - Turn the specified string into an 'LLVM name', which is
114 /// surrounded with ""'s and escaped if it has special chars in it.
115 static std::string getLLVMName(const std::string &Name) {
116 assert(!Name.empty() && "Cannot get empty name!");
117 return QuoteNameIfNeeded(Name);
126 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
127 /// prefixed with % (if the string only contains simple characters) or is
128 /// surrounded with ""'s (if it has special chars in it). Print it out.
129 static void PrintLLVMName(std::ostream &OS, const char *NameStr,
130 unsigned NameLen, PrefixType Prefix) {
131 assert(NameStr && "Cannot get empty name!");
133 default: assert(0 && "Bad prefix!");
134 case GlobalPrefix: OS << '@'; break;
135 case LabelPrefix: break;
136 case LocalPrefix: OS << '%'; break;
139 // Scan the name to see if it needs quotes first.
140 bool NeedsQuotes = NameStr[0] >= '0' && NameStr[0] <= '9';
142 for (unsigned i = 0; i != NameLen; ++i) {
144 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
151 // If we didn't need any quotes, just write out the name in one blast.
153 OS.write(NameStr, NameLen);
157 // Okay, we need quotes. Output the quotes and escape any scary characters as
160 for (unsigned i = 0; i != NameLen; ++i) {
162 assert(C != '"' && "Illegal character in LLVM value name!");
165 } else if (isprint(C)) {
169 char hex1 = (C >> 4) & 0x0F;
171 OS << (char)(hex1 + '0');
173 OS << (char)(hex1 - 10 + 'A');
174 char hex2 = C & 0x0F;
176 OS << (char)(hex2 + '0');
178 OS << (char)(hex2 - 10 + 'A');
184 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
185 /// prefixed with % (if the string only contains simple characters) or is
186 /// surrounded with ""'s (if it has special chars in it). Print it out.
187 static void PrintLLVMName(std::ostream &OS, const Value *V) {
188 PrintLLVMName(OS, V->getNameStart(), V->getNameLen(),
189 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
194 //===----------------------------------------------------------------------===//
195 // SlotTracker Class: Enumerate slot numbers for unnamed values
196 //===----------------------------------------------------------------------===//
200 /// This class provides computation of slot numbers for LLVM Assembly writing.
204 /// ValueMap - A mapping of Values to slot numbers
205 typedef DenseMap<const Value*, unsigned> ValueMap;
208 /// TheModule - The module for which we are holding slot numbers
209 const Module* TheModule;
211 /// TheFunction - The function for which we are holding slot numbers
212 const Function* TheFunction;
213 bool FunctionProcessed;
215 /// mMap - The TypePlanes map for the module level data
219 /// fMap - The TypePlanes map for the function level data
224 /// Construct from a module
225 explicit SlotTracker(const Module *M);
226 /// Construct from a function, starting out in incorp state.
227 explicit SlotTracker(const Function *F);
229 /// Return the slot number of the specified value in it's type
230 /// plane. If something is not in the SlotTracker, return -1.
231 int getLocalSlot(const Value *V);
232 int getGlobalSlot(const GlobalValue *V);
234 /// If you'd like to deal with a function instead of just a module, use
235 /// this method to get its data into the SlotTracker.
236 void incorporateFunction(const Function *F) {
238 FunctionProcessed = false;
241 /// After calling incorporateFunction, use this method to remove the
242 /// most recently incorporated function from the SlotTracker. This
243 /// will reset the state of the machine back to just the module contents.
244 void purgeFunction();
246 // Implementation Details
248 /// This function does the actual initialization.
249 inline void initialize();
251 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
252 void CreateModuleSlot(const GlobalValue *V);
254 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
255 void CreateFunctionSlot(const Value *V);
257 /// Add all of the module level global variables (and their initializers)
258 /// and function declarations, but not the contents of those functions.
259 void processModule();
261 /// Add all of the functions arguments, basic blocks, and instructions
262 void processFunction();
264 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
265 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
268 } // end anonymous namespace
271 static SlotTracker *createSlotTracker(const Value *V) {
272 if (const Argument *FA = dyn_cast<Argument>(V))
273 return new SlotTracker(FA->getParent());
275 if (const Instruction *I = dyn_cast<Instruction>(V))
276 return new SlotTracker(I->getParent()->getParent());
278 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
279 return new SlotTracker(BB->getParent());
281 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
282 return new SlotTracker(GV->getParent());
284 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
285 return new SlotTracker(GA->getParent());
287 if (const Function *Func = dyn_cast<Function>(V))
288 return new SlotTracker(Func);
294 #define ST_DEBUG(X) cerr << X
299 // Module level constructor. Causes the contents of the Module (sans functions)
300 // to be added to the slot table.
301 SlotTracker::SlotTracker(const Module *M)
302 : TheModule(M), TheFunction(0), FunctionProcessed(false), mNext(0), fNext(0) {
305 // Function level constructor. Causes the contents of the Module and the one
306 // function provided to be added to the slot table.
307 SlotTracker::SlotTracker(const Function *F)
308 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
312 inline void SlotTracker::initialize() {
315 TheModule = 0; ///< Prevent re-processing next time we're called.
318 if (TheFunction && !FunctionProcessed)
322 // Iterate through all the global variables, functions, and global
323 // variable initializers and create slots for them.
324 void SlotTracker::processModule() {
325 ST_DEBUG("begin processModule!\n");
327 // Add all of the unnamed global variables to the value table.
328 for (Module::const_global_iterator I = TheModule->global_begin(),
329 E = TheModule->global_end(); I != E; ++I)
333 // Add all the unnamed functions to the table.
334 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
339 ST_DEBUG("end processModule!\n");
343 // Process the arguments, basic blocks, and instructions of a function.
344 void SlotTracker::processFunction() {
345 ST_DEBUG("begin processFunction!\n");
348 // Add all the function arguments with no names.
349 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
350 AE = TheFunction->arg_end(); AI != AE; ++AI)
352 CreateFunctionSlot(AI);
354 ST_DEBUG("Inserting Instructions:\n");
356 // Add all of the basic blocks and instructions with no names.
357 for (Function::const_iterator BB = TheFunction->begin(),
358 E = TheFunction->end(); BB != E; ++BB) {
360 CreateFunctionSlot(BB);
361 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
362 if (I->getType() != Type::VoidTy && !I->hasName())
363 CreateFunctionSlot(I);
366 FunctionProcessed = true;
368 ST_DEBUG("end processFunction!\n");
371 /// Clean up after incorporating a function. This is the only way to get out of
372 /// the function incorporation state that affects get*Slot/Create*Slot. Function
373 /// incorporation state is indicated by TheFunction != 0.
374 void SlotTracker::purgeFunction() {
375 ST_DEBUG("begin purgeFunction!\n");
376 fMap.clear(); // Simply discard the function level map
378 FunctionProcessed = false;
379 ST_DEBUG("end purgeFunction!\n");
382 /// getGlobalSlot - Get the slot number of a global value.
383 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
384 // Check for uninitialized state and do lazy initialization.
387 // Find the type plane in the module map
388 ValueMap::iterator MI = mMap.find(V);
389 return MI == mMap.end() ? -1 : MI->second;
393 /// getLocalSlot - Get the slot number for a value that is local to a function.
394 int SlotTracker::getLocalSlot(const Value *V) {
395 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
397 // Check for uninitialized state and do lazy initialization.
400 ValueMap::iterator FI = fMap.find(V);
401 return FI == fMap.end() ? -1 : FI->second;
405 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
406 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
407 assert(V && "Can't insert a null Value into SlotTracker!");
408 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
409 assert(!V->hasName() && "Doesn't need a slot!");
411 unsigned DestSlot = mNext++;
414 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
416 // G = Global, F = Function, A = Alias, o = other
417 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
418 (isa<Function>(V) ? 'F' :
419 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
423 /// CreateSlot - Create a new slot for the specified value if it has no name.
424 void SlotTracker::CreateFunctionSlot(const Value *V) {
425 assert(V->getType() != Type::VoidTy && !V->hasName() &&
426 "Doesn't need a slot!");
428 unsigned DestSlot = fNext++;
431 // G = Global, F = Function, o = other
432 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
433 DestSlot << " [o]\n");
438 //===----------------------------------------------------------------------===//
439 // AsmWriter Implementation
440 //===----------------------------------------------------------------------===//
442 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
443 std::map<const Type *, std::string> &TypeTable,
444 SlotTracker *Machine);
448 /// fillTypeNameTable - If the module has a symbol table, take all global types
449 /// and stuff their names into the TypeNames map.
451 static void fillTypeNameTable(const Module *M,
452 std::map<const Type *, std::string> &TypeNames) {
454 const TypeSymbolTable &ST = M->getTypeSymbolTable();
455 TypeSymbolTable::const_iterator TI = ST.begin();
456 for (; TI != ST.end(); ++TI) {
457 // As a heuristic, don't insert pointer to primitive types, because
458 // they are used too often to have a single useful name.
460 const Type *Ty = cast<Type>(TI->second);
461 if (!isa<PointerType>(Ty) ||
462 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
463 !cast<PointerType>(Ty)->getElementType()->isInteger() ||
464 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
465 TypeNames.insert(std::make_pair(Ty, '%' + getLLVMName(TI->first)));
471 static void calcTypeName(const Type *Ty,
472 std::vector<const Type *> &TypeStack,
473 std::map<const Type *, std::string> &TypeNames,
474 std::string &Result) {
475 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
476 Result += Ty->getDescription(); // Base case
480 // Check to see if the type is named.
481 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
482 if (I != TypeNames.end()) {
487 if (isa<OpaqueType>(Ty)) {
492 // Check to see if the Type is already on the stack...
493 unsigned Slot = 0, CurSize = TypeStack.size();
494 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
496 // This is another base case for the recursion. In this case, we know
497 // that we have looped back to a type that we have previously visited.
498 // Generate the appropriate upreference to handle this.
499 if (Slot < CurSize) {
500 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
504 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
506 switch (Ty->getTypeID()) {
507 case Type::IntegerTyID: {
508 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
509 Result += "i" + utostr(BitWidth);
512 case Type::FunctionTyID: {
513 const FunctionType *FTy = cast<FunctionType>(Ty);
514 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
516 for (FunctionType::param_iterator I = FTy->param_begin(),
517 E = FTy->param_end(); I != E; ++I) {
518 if (I != FTy->param_begin())
520 calcTypeName(*I, TypeStack, TypeNames, Result);
522 if (FTy->isVarArg()) {
523 if (FTy->getNumParams()) Result += ", ";
529 case Type::StructTyID: {
530 const StructType *STy = cast<StructType>(Ty);
534 for (StructType::element_iterator I = STy->element_begin(),
535 E = STy->element_end(); I != E; ++I) {
536 if (I != STy->element_begin())
538 calcTypeName(*I, TypeStack, TypeNames, Result);
545 case Type::PointerTyID: {
546 const PointerType *PTy = cast<PointerType>(Ty);
547 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
548 if (unsigned AddressSpace = PTy->getAddressSpace())
549 Result += " addrspace(" + utostr(AddressSpace) + ")";
553 case Type::ArrayTyID: {
554 const ArrayType *ATy = cast<ArrayType>(Ty);
555 Result += "[" + utostr(ATy->getNumElements()) + " x ";
556 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
560 case Type::VectorTyID: {
561 const VectorType *PTy = cast<VectorType>(Ty);
562 Result += "<" + utostr(PTy->getNumElements()) + " x ";
563 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
567 case Type::OpaqueTyID:
571 Result += "<unrecognized-type>";
575 TypeStack.pop_back(); // Remove self from stack...
579 /// printTypeInt - The internal guts of printing out a type that has a
580 /// potentially named portion.
582 static void printTypeInt(std::ostream &Out, const Type *Ty,
583 std::map<const Type *, std::string> &TypeNames) {
584 // Primitive types always print out their description, regardless of whether
585 // they have been named or not.
587 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
588 Out << Ty->getDescription();
592 // Check to see if the type is named.
593 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
594 if (I != TypeNames.end()) {
599 // Otherwise we have a type that has not been named but is a derived type.
600 // Carefully recurse the type hierarchy to print out any contained symbolic
603 std::vector<const Type *> TypeStack;
604 std::string TypeName;
605 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
606 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
611 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
612 /// type, iff there is an entry in the modules symbol table for the specified
613 /// type or one of it's component types. This is slower than a simple x << Type
615 void llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
619 // If they want us to print out a type, but there is no context, we can't
620 // print it symbolically.
622 Out << Ty->getDescription();
624 std::map<const Type *, std::string> TypeNames;
625 fillTypeNameTable(M, TypeNames);
626 printTypeInt(Out, Ty, TypeNames);
630 // PrintEscapedString - Print each character of the specified string, escaping
631 // it if it is not printable or if it is an escape char.
632 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
633 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
634 unsigned char C = Str[i];
635 if (isprint(C) && C != '"' && C != '\\') {
639 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
640 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
645 static const char *getPredicateText(unsigned predicate) {
646 const char * pred = "unknown";
648 case FCmpInst::FCMP_FALSE: pred = "false"; break;
649 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
650 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
651 case FCmpInst::FCMP_OGE: pred = "oge"; break;
652 case FCmpInst::FCMP_OLT: pred = "olt"; break;
653 case FCmpInst::FCMP_OLE: pred = "ole"; break;
654 case FCmpInst::FCMP_ONE: pred = "one"; break;
655 case FCmpInst::FCMP_ORD: pred = "ord"; break;
656 case FCmpInst::FCMP_UNO: pred = "uno"; break;
657 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
658 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
659 case FCmpInst::FCMP_UGE: pred = "uge"; break;
660 case FCmpInst::FCMP_ULT: pred = "ult"; break;
661 case FCmpInst::FCMP_ULE: pred = "ule"; break;
662 case FCmpInst::FCMP_UNE: pred = "une"; break;
663 case FCmpInst::FCMP_TRUE: pred = "true"; break;
664 case ICmpInst::ICMP_EQ: pred = "eq"; break;
665 case ICmpInst::ICMP_NE: pred = "ne"; break;
666 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
667 case ICmpInst::ICMP_SGE: pred = "sge"; break;
668 case ICmpInst::ICMP_SLT: pred = "slt"; break;
669 case ICmpInst::ICMP_SLE: pred = "sle"; break;
670 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
671 case ICmpInst::ICMP_UGE: pred = "uge"; break;
672 case ICmpInst::ICMP_ULT: pred = "ult"; break;
673 case ICmpInst::ICMP_ULE: pred = "ule"; break;
678 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
679 std::map<const Type *, std::string> &TypeTable,
680 SlotTracker *Machine) {
681 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
682 if (CI->getType() == Type::Int1Ty) {
683 Out << (CI->getZExtValue() ? "true" : "false");
686 Out << CI->getValue();
690 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
691 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
692 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
693 // We would like to output the FP constant value in exponential notation,
694 // but we cannot do this if doing so will lose precision. Check here to
695 // make sure that we only output it in exponential format if we can parse
696 // the value back and get the same value.
698 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
699 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
700 CFP->getValueAPF().convertToFloat();
701 std::string StrVal = ftostr(CFP->getValueAPF());
703 // Check to make sure that the stringized number is not some string like
704 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
705 // that the string matches the "[-+]?[0-9]" regex.
707 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
708 ((StrVal[0] == '-' || StrVal[0] == '+') &&
709 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
710 // Reparse stringized version!
711 if (atof(StrVal.c_str()) == Val) {
716 // Otherwise we could not reparse it to exactly the same value, so we must
717 // output the string in hexadecimal format!
718 assert(sizeof(double) == sizeof(uint64_t) &&
719 "assuming that double is 64 bits!");
720 Out << "0x" << utohexstr(DoubleToBits(Val));
724 // Some form of long double. These appear as a magic letter identifying
725 // the type, then a fixed number of hex digits.
727 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended)
729 else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
731 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
734 assert(0 && "Unsupported floating point type");
735 // api needed to prevent premature destruction
736 APInt api = CFP->getValueAPF().convertToAPInt();
737 const uint64_t* p = api.getRawData();
740 int width = api.getBitWidth();
741 for (int j=0; j<width; j+=4, shiftcount-=4) {
742 unsigned int nibble = (word>>shiftcount) & 15;
744 Out << (unsigned char)(nibble + '0');
746 Out << (unsigned char)(nibble - 10 + 'A');
747 if (shiftcount == 0 && j+4 < width) {
751 shiftcount = width-j-4;
757 if (isa<ConstantAggregateZero>(CV)) {
758 Out << "zeroinitializer";
762 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
763 // As a special case, print the array as a string if it is an array of
764 // i8 with ConstantInt values.
766 const Type *ETy = CA->getType()->getElementType();
767 if (CA->isString()) {
769 PrintEscapedString(CA->getAsString(), Out);
771 } else { // Cannot output in string format...
773 if (CA->getNumOperands()) {
775 printTypeInt(Out, ETy, TypeTable);
776 WriteAsOperandInternal(Out, CA->getOperand(0),
778 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
780 printTypeInt(Out, ETy, TypeTable);
781 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
789 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
790 if (CS->getType()->isPacked())
793 unsigned N = CS->getNumOperands();
796 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
798 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
800 for (unsigned i = 1; i < N; i++) {
802 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
804 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
809 if (CS->getType()->isPacked())
814 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
815 const Type *ETy = CP->getType()->getElementType();
816 assert(CP->getNumOperands() > 0 &&
817 "Number of operands for a PackedConst must be > 0");
819 printTypeInt(Out, ETy, TypeTable);
820 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
821 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
823 printTypeInt(Out, ETy, TypeTable);
824 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
830 if (isa<ConstantPointerNull>(CV)) {
835 if (isa<UndefValue>(CV)) {
840 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
841 Out << CE->getOpcodeName();
843 Out << ' ' << getPredicateText(CE->getPredicate());
846 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
847 printTypeInt(Out, (*OI)->getType(), TypeTable);
848 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
849 if (OI+1 != CE->op_end())
853 if (CE->hasIndices()) {
854 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
855 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
856 Out << ", " << Indices[i];
861 printTypeInt(Out, CE->getType(), TypeTable);
868 Out << "<placeholder or erroneous Constant>";
872 /// WriteAsOperand - Write the name of the specified value out to the specified
873 /// ostream. This can be useful when you just want to print int %reg126, not
874 /// the whole instruction that generated it.
876 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
877 std::map<const Type*, std::string> &TypeTable,
878 SlotTracker *Machine) {
881 PrintLLVMName(Out, V);
885 const Constant *CV = dyn_cast<Constant>(V);
886 if (CV && !isa<GlobalValue>(CV)) {
887 WriteConstantInt(Out, CV, TypeTable, Machine);
891 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
893 if (IA->hasSideEffects())
894 Out << "sideeffect ";
896 PrintEscapedString(IA->getAsmString(), Out);
898 PrintEscapedString(IA->getConstraintString(), Out);
906 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
907 Slot = Machine->getGlobalSlot(GV);
910 Slot = Machine->getLocalSlot(V);
913 Machine = createSlotTracker(V);
915 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
916 Slot = Machine->getGlobalSlot(GV);
919 Slot = Machine->getLocalSlot(V);
928 Out << Prefix << Slot;
933 /// WriteAsOperand - Write the name of the specified value out to the specified
934 /// ostream. This can be useful when you just want to print int %reg126, not
935 /// the whole instruction that generated it.
937 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
938 const Module *Context) {
939 std::map<const Type *, std::string> TypeNames;
940 if (Context == 0) Context = getModuleFromVal(V);
943 fillTypeNameTable(Context, TypeNames);
946 printTypeInt(Out, V->getType(), TypeNames);
948 WriteAsOperandInternal(Out, V, TypeNames, 0);
954 class AssemblyWriter {
956 SlotTracker &Machine;
957 const Module *TheModule;
958 std::map<const Type *, std::string> TypeNames;
959 AssemblyAnnotationWriter *AnnotationWriter;
961 inline AssemblyWriter(std::ostream &o, SlotTracker &Mac, const Module *M,
962 AssemblyAnnotationWriter *AAW)
963 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
965 // If the module has a symbol table, take all global types and stuff their
966 // names into the TypeNames map.
968 fillTypeNameTable(M, TypeNames);
971 void write(const Module *M) { printModule(M); }
972 void write(const GlobalVariable *G) { printGlobal(G); }
973 void write(const GlobalAlias *G) { printAlias(G); }
974 void write(const Function *F) { printFunction(F); }
975 void write(const BasicBlock *BB) { printBasicBlock(BB); }
976 void write(const Instruction *I) { printInstruction(*I); }
977 void write(const Type *Ty) { printType(Ty); }
979 void writeOperand(const Value *Op, bool PrintType);
980 void writeParamOperand(const Value *Operand, ParameterAttributes Attrs);
982 const Module* getModule() { return TheModule; }
985 void printModule(const Module *M);
986 void printTypeSymbolTable(const TypeSymbolTable &ST);
987 void printGlobal(const GlobalVariable *GV);
988 void printAlias(const GlobalAlias *GV);
989 void printFunction(const Function *F);
990 void printArgument(const Argument *FA, ParameterAttributes Attrs);
991 void printBasicBlock(const BasicBlock *BB);
992 void printInstruction(const Instruction &I);
994 // printType - Go to extreme measures to attempt to print out a short,
995 // symbolic version of a type name.
997 void printType(const Type *Ty) {
998 printTypeInt(Out, Ty, TypeNames);
1001 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
1002 // without considering any symbolic types that we may have equal to it.
1004 void printTypeAtLeastOneLevel(const Type *Ty);
1006 // printInfoComment - Print a little comment after the instruction indicating
1007 // which slot it occupies.
1008 void printInfoComment(const Value &V);
1010 } // end of llvm namespace
1012 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
1013 /// without considering any symbolic types that we may have equal to it.
1015 void AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
1016 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
1017 Out << "i" << utostr(ITy->getBitWidth());
1021 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
1022 printType(FTy->getReturnType());
1024 for (FunctionType::param_iterator I = FTy->param_begin(),
1025 E = FTy->param_end(); I != E; ++I) {
1026 if (I != FTy->param_begin())
1030 if (FTy->isVarArg()) {
1031 if (FTy->getNumParams()) Out << ", ";
1038 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1039 if (STy->isPacked())
1042 for (StructType::element_iterator I = STy->element_begin(),
1043 E = STy->element_end(); I != E; ++I) {
1044 if (I != STy->element_begin())
1049 if (STy->isPacked())
1054 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1055 printType(PTy->getElementType());
1056 if (unsigned AddressSpace = PTy->getAddressSpace())
1057 Out << " addrspace(" << AddressSpace << ")";
1062 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1063 Out << '[' << ATy->getNumElements() << " x ";
1064 printType(ATy->getElementType());
1069 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
1070 Out << '<' << PTy->getNumElements() << " x ";
1071 printType(PTy->getElementType());
1076 if (isa<OpaqueType>(Ty)) {
1081 if (!Ty->isPrimitiveType())
1082 Out << "<unknown derived type>";
1087 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1089 Out << "<null operand!>";
1093 printType(Operand->getType());
1095 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
1099 void AssemblyWriter::writeParamOperand(const Value *Operand,
1100 ParameterAttributes Attrs) {
1102 Out << "<null operand!>";
1106 printType(Operand->getType());
1107 // Print parameter attributes list
1108 if (Attrs != ParamAttr::None)
1109 Out << ' ' << ParamAttr::getAsString(Attrs);
1110 // Print the operand
1111 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
1115 void AssemblyWriter::printModule(const Module *M) {
1116 if (!M->getModuleIdentifier().empty() &&
1117 // Don't print the ID if it will start a new line (which would
1118 // require a comment char before it).
1119 M->getModuleIdentifier().find('\n') == std::string::npos)
1120 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1122 if (!M->getDataLayout().empty())
1123 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1124 if (!M->getTargetTriple().empty())
1125 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1127 if (!M->getModuleInlineAsm().empty()) {
1128 // Split the string into lines, to make it easier to read the .ll file.
1129 std::string Asm = M->getModuleInlineAsm();
1131 size_t NewLine = Asm.find_first_of('\n', CurPos);
1132 while (NewLine != std::string::npos) {
1133 // We found a newline, print the portion of the asm string from the
1134 // last newline up to this newline.
1135 Out << "module asm \"";
1136 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1140 NewLine = Asm.find_first_of('\n', CurPos);
1142 Out << "module asm \"";
1143 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1147 // Loop over the dependent libraries and emit them.
1148 Module::lib_iterator LI = M->lib_begin();
1149 Module::lib_iterator LE = M->lib_end();
1151 Out << "deplibs = [ ";
1153 Out << '"' << *LI << '"';
1161 // Loop over the symbol table, emitting all named constants.
1162 printTypeSymbolTable(M->getTypeSymbolTable());
1164 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1168 // Output all aliases.
1169 if (!M->alias_empty()) Out << "\n";
1170 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1174 // Output all of the functions.
1175 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1179 static void PrintLinkage(GlobalValue::LinkageTypes LT, std::ostream &Out) {
1181 case GlobalValue::InternalLinkage: Out << "internal "; break;
1182 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
1183 case GlobalValue::WeakLinkage: Out << "weak "; break;
1184 case GlobalValue::CommonLinkage: Out << "common "; break;
1185 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1186 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1187 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1188 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1189 case GlobalValue::ExternalLinkage: break;
1190 case GlobalValue::GhostLinkage:
1191 Out << "GhostLinkage not allowed in AsmWriter!\n";
1197 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1198 std::ostream &Out) {
1200 default: assert(0 && "Invalid visibility style!");
1201 case GlobalValue::DefaultVisibility: break;
1202 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1203 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1207 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1208 if (GV->hasName()) {
1209 PrintLLVMName(Out, GV);
1213 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1216 PrintLinkage(GV->getLinkage(), Out);
1217 PrintVisibility(GV->getVisibility(), Out);
1219 if (GV->isThreadLocal()) Out << "thread_local ";
1220 Out << (GV->isConstant() ? "constant " : "global ");
1221 printType(GV->getType()->getElementType());
1223 if (GV->hasInitializer())
1224 writeOperand(GV->getInitializer(), false);
1226 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1227 Out << " addrspace(" << AddressSpace << ") ";
1229 if (GV->hasSection())
1230 Out << ", section \"" << GV->getSection() << '"';
1231 if (GV->getAlignment())
1232 Out << ", align " << GV->getAlignment();
1234 printInfoComment(*GV);
1238 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1239 // Don't crash when dumping partially built GA
1241 Out << "<<nameless>> = ";
1243 PrintLLVMName(Out, GA);
1246 PrintVisibility(GA->getVisibility(), Out);
1250 PrintLinkage(GA->getLinkage(), Out);
1252 const Constant *Aliasee = GA->getAliasee();
1254 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1255 printType(GV->getType());
1257 PrintLLVMName(Out, GV);
1258 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1259 printType(F->getFunctionType());
1263 PrintLLVMName(Out, F);
1266 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1267 printType(GA->getType());
1269 PrintLLVMName(Out, GA);
1271 const ConstantExpr *CE = 0;
1272 if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
1273 (CE->getOpcode() == Instruction::BitCast)) {
1274 writeOperand(CE, false);
1276 assert(0 && "Unsupported aliasee");
1279 printInfoComment(*GA);
1283 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1285 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1288 PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1291 // Make sure we print out at least one level of the type structure, so
1292 // that we do not get %FILE = type %FILE
1294 printTypeAtLeastOneLevel(TI->second);
1299 /// printFunction - Print all aspects of a function.
1301 void AssemblyWriter::printFunction(const Function *F) {
1302 // Print out the return type and name.
1305 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1307 if (F->isDeclaration())
1312 PrintLinkage(F->getLinkage(), Out);
1313 PrintVisibility(F->getVisibility(), Out);
1315 // Print the calling convention.
1316 switch (F->getCallingConv()) {
1317 case CallingConv::C: break; // default
1318 case CallingConv::Fast: Out << "fastcc "; break;
1319 case CallingConv::Cold: Out << "coldcc "; break;
1320 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1321 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1322 case CallingConv::X86_SSECall: Out << "x86_ssecallcc "; break;
1323 default: Out << "cc" << F->getCallingConv() << " "; break;
1326 const FunctionType *FT = F->getFunctionType();
1327 const PAListPtr &Attrs = F->getParamAttrs();
1328 printType(F->getReturnType());
1331 PrintLLVMName(Out, F);
1335 Machine.incorporateFunction(F);
1337 // Loop over the arguments, printing them...
1340 if (!F->isDeclaration()) {
1341 // If this isn't a declaration, print the argument names as well.
1342 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1344 // Insert commas as we go... the first arg doesn't get a comma
1345 if (I != F->arg_begin()) Out << ", ";
1346 printArgument(I, Attrs.getParamAttrs(Idx));
1350 // Otherwise, print the types from the function type.
1351 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1352 // Insert commas as we go... the first arg doesn't get a comma
1356 printType(FT->getParamType(i));
1358 ParameterAttributes ArgAttrs = Attrs.getParamAttrs(i+1);
1359 if (ArgAttrs != ParamAttr::None)
1360 Out << ' ' << ParamAttr::getAsString(ArgAttrs);
1364 // Finish printing arguments...
1365 if (FT->isVarArg()) {
1366 if (FT->getNumParams()) Out << ", ";
1367 Out << "..."; // Output varargs portion of signature!
1370 ParameterAttributes RetAttrs = Attrs.getParamAttrs(0);
1371 if (RetAttrs != ParamAttr::None)
1372 Out << ' ' << ParamAttr::getAsString(Attrs.getParamAttrs(0));
1373 if (F->hasSection())
1374 Out << " section \"" << F->getSection() << '"';
1375 if (F->getAlignment())
1376 Out << " align " << F->getAlignment();
1378 Out << " gc \"" << F->getGC() << '"';
1380 if (F->isDeclaration()) {
1385 // Output all of its basic blocks... for the function
1386 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1392 Machine.purgeFunction();
1395 /// printArgument - This member is called for every argument that is passed into
1396 /// the function. Simply print it out
1398 void AssemblyWriter::printArgument(const Argument *Arg,
1399 ParameterAttributes Attrs) {
1401 printType(Arg->getType());
1403 // Output parameter attributes list
1404 if (Attrs != ParamAttr::None)
1405 Out << ' ' << ParamAttr::getAsString(Attrs);
1407 // Output name, if available...
1408 if (Arg->hasName()) {
1410 PrintLLVMName(Out, Arg);
1414 /// printBasicBlock - This member is called for each basic block in a method.
1416 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1417 if (BB->hasName()) { // Print out the label if it exists...
1419 PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1421 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1422 Out << "\n; <label>:";
1423 int Slot = Machine.getLocalSlot(BB);
1430 if (BB->getParent() == 0)
1431 Out << "\t\t; Error: Block without parent!";
1432 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1433 // Output predecessors for the block...
1435 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1438 Out << " No predecessors!";
1441 writeOperand(*PI, false);
1442 for (++PI; PI != PE; ++PI) {
1444 writeOperand(*PI, false);
1451 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1453 // Output all of the instructions in the basic block...
1454 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1455 printInstruction(*I);
1457 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1461 /// printInfoComment - Print a little comment after the instruction indicating
1462 /// which slot it occupies.
1464 void AssemblyWriter::printInfoComment(const Value &V) {
1465 if (V.getType() != Type::VoidTy) {
1467 printType(V.getType());
1472 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1473 SlotNum = Machine.getGlobalSlot(GV);
1475 SlotNum = Machine.getLocalSlot(&V);
1479 Out << ':' << SlotNum; // Print out the def slot taken.
1481 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1485 // This member is called for each Instruction in a function..
1486 void AssemblyWriter::printInstruction(const Instruction &I) {
1487 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1491 // Print out name if it exists...
1493 PrintLLVMName(Out, &I);
1497 // If this is a volatile load or store, print out the volatile marker.
1498 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1499 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1501 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1502 // If this is a call, check if it's a tail call.
1506 // Print out the opcode...
1507 Out << I.getOpcodeName();
1509 // Print out the compare instruction predicates
1510 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1511 Out << " " << getPredicateText(CI->getPredicate());
1513 // Print out the type of the operands...
1514 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1516 // Special case conditional branches to swizzle the condition out to the front
1517 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1518 writeOperand(I.getOperand(2), true);
1520 writeOperand(Operand, true);
1522 writeOperand(I.getOperand(1), true);
1524 } else if (isa<SwitchInst>(I)) {
1525 // Special case switch statement to get formatting nice and correct...
1526 writeOperand(Operand , true); Out << ',';
1527 writeOperand(I.getOperand(1), true); Out << " [";
1529 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1531 writeOperand(I.getOperand(op ), true); Out << ',';
1532 writeOperand(I.getOperand(op+1), true);
1535 } else if (isa<PHINode>(I)) {
1537 printType(I.getType());
1540 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1541 if (op) Out << ", ";
1543 writeOperand(I.getOperand(op ), false); Out << ',';
1544 writeOperand(I.getOperand(op+1), false); Out << " ]";
1546 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1547 writeOperand(I.getOperand(0), true);
1548 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1550 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1551 writeOperand(I.getOperand(0), true); Out << ',';
1552 writeOperand(I.getOperand(1), true);
1553 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1555 } else if (isa<ReturnInst>(I) && !Operand) {
1557 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1558 // Print the calling convention being used.
1559 switch (CI->getCallingConv()) {
1560 case CallingConv::C: break; // default
1561 case CallingConv::Fast: Out << " fastcc"; break;
1562 case CallingConv::Cold: Out << " coldcc"; break;
1563 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1564 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1565 case CallingConv::X86_SSECall: Out << " x86_ssecallcc"; break;
1566 default: Out << " cc" << CI->getCallingConv(); break;
1569 const PointerType *PTy = cast<PointerType>(Operand->getType());
1570 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1571 const Type *RetTy = FTy->getReturnType();
1572 const PAListPtr &PAL = CI->getParamAttrs();
1574 // If possible, print out the short form of the call instruction. We can
1575 // only do this if the first argument is a pointer to a nonvararg function,
1576 // and if the return type is not a pointer to a function.
1578 if (!FTy->isVarArg() &&
1579 (!isa<PointerType>(RetTy) ||
1580 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1581 Out << ' '; printType(RetTy);
1582 writeOperand(Operand, false);
1584 writeOperand(Operand, true);
1587 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1590 writeParamOperand(I.getOperand(op), PAL.getParamAttrs(op));
1593 if (PAL.getParamAttrs(0) != ParamAttr::None)
1594 Out << ' ' << ParamAttr::getAsString(PAL.getParamAttrs(0));
1595 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1596 const PointerType *PTy = cast<PointerType>(Operand->getType());
1597 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1598 const Type *RetTy = FTy->getReturnType();
1599 const PAListPtr &PAL = II->getParamAttrs();
1601 // Print the calling convention being used.
1602 switch (II->getCallingConv()) {
1603 case CallingConv::C: break; // default
1604 case CallingConv::Fast: Out << " fastcc"; break;
1605 case CallingConv::Cold: Out << " coldcc"; break;
1606 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1607 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1608 case CallingConv::X86_SSECall: Out << "x86_ssecallcc "; break;
1609 default: Out << " cc" << II->getCallingConv(); break;
1612 // If possible, print out the short form of the invoke instruction. We can
1613 // only do this if the first argument is a pointer to a nonvararg function,
1614 // and if the return type is not a pointer to a function.
1616 if (!FTy->isVarArg() &&
1617 (!isa<PointerType>(RetTy) ||
1618 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1619 Out << ' '; printType(RetTy);
1620 writeOperand(Operand, false);
1622 writeOperand(Operand, true);
1626 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1629 writeParamOperand(I.getOperand(op), PAL.getParamAttrs(op-2));
1633 if (PAL.getParamAttrs(0) != ParamAttr::None)
1634 Out << ' ' << ParamAttr::getAsString(PAL.getParamAttrs(0));
1635 Out << "\n\t\t\tto";
1636 writeOperand(II->getNormalDest(), true);
1638 writeOperand(II->getUnwindDest(), true);
1640 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1642 printType(AI->getType()->getElementType());
1643 if (AI->isArrayAllocation()) {
1645 writeOperand(AI->getArraySize(), true);
1647 if (AI->getAlignment()) {
1648 Out << ", align " << AI->getAlignment();
1650 } else if (isa<CastInst>(I)) {
1651 if (Operand) writeOperand(Operand, true); // Work with broken code
1653 printType(I.getType());
1654 } else if (isa<VAArgInst>(I)) {
1655 if (Operand) writeOperand(Operand, true); // Work with broken code
1657 printType(I.getType());
1658 } else if (Operand) { // Print the normal way...
1660 // PrintAllTypes - Instructions who have operands of all the same type
1661 // omit the type from all but the first operand. If the instruction has
1662 // different type operands (for example br), then they are all printed.
1663 bool PrintAllTypes = false;
1664 const Type *TheType = Operand->getType();
1666 // Select, Store and ShuffleVector always print all types.
1667 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1668 || isa<ReturnInst>(I)) {
1669 PrintAllTypes = true;
1671 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1672 Operand = I.getOperand(i);
1673 if (Operand->getType() != TheType) {
1674 PrintAllTypes = true; // We have differing types! Print them all!
1680 if (!PrintAllTypes) {
1685 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1687 writeOperand(I.getOperand(i), PrintAllTypes);
1691 // Print post operand alignment for load/store
1692 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1693 Out << ", align " << cast<LoadInst>(I).getAlignment();
1694 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1695 Out << ", align " << cast<StoreInst>(I).getAlignment();
1698 printInfoComment(I);
1703 //===----------------------------------------------------------------------===//
1704 // External Interface declarations
1705 //===----------------------------------------------------------------------===//
1707 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1708 SlotTracker SlotTable(this);
1709 AssemblyWriter W(o, SlotTable, this, AAW);
1713 void GlobalVariable::print(std::ostream &o) const {
1714 SlotTracker SlotTable(getParent());
1715 AssemblyWriter W(o, SlotTable, getParent(), 0);
1719 void GlobalAlias::print(std::ostream &o) const {
1720 SlotTracker SlotTable(getParent());
1721 AssemblyWriter W(o, SlotTable, getParent(), 0);
1725 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1726 SlotTracker SlotTable(getParent());
1727 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1732 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1733 WriteAsOperand(o, this, true, 0);
1736 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1737 SlotTracker SlotTable(getParent());
1738 AssemblyWriter W(o, SlotTable,
1739 getParent() ? getParent()->getParent() : 0, AAW);
1743 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1744 const Function *F = getParent() ? getParent()->getParent() : 0;
1745 SlotTracker SlotTable(F);
1746 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1751 void Constant::print(std::ostream &o) const {
1752 if (this == 0) { o << "<null> constant value\n"; return; }
1754 o << ' ' << getType()->getDescription() << ' ';
1756 std::map<const Type *, std::string> TypeTable;
1757 WriteConstantInt(o, this, TypeTable, 0);
1760 void Type::print(std::ostream &o) const {
1764 o << getDescription();
1767 void Argument::print(std::ostream &o) const {
1768 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1771 // Value::dump - allow easy printing of Values from the debugger.
1772 // Located here because so much of the needed functionality is here.
1773 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1775 // Type::dump - allow easy printing of Values from the debugger.
1776 // Located here because so much of the needed functionality is here.
1777 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }