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 either
114 /// prefixed with % (if the string only contains simple characters) or is
115 /// surrounded with ""'s (if it has special chars in it).
116 static std::string getLLVMName(const std::string &Name) {
117 assert(!Name.empty() && "Cannot get empty name!");
118 return '%' + QuoteNameIfNeeded(Name);
127 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
128 /// prefixed with % (if the string only contains simple characters) or is
129 /// surrounded with ""'s (if it has special chars in it). Print it out.
130 static void PrintLLVMName(std::ostream &OS, const ValueName *Name,
132 assert(Name && "Cannot get empty name!");
134 default: assert(0 && "Bad prefix!");
135 case GlobalPrefix: OS << '@'; break;
136 case LabelPrefix: break;
137 case LocalPrefix: OS << '%'; break;
140 // Scan the name to see if it needs quotes first.
141 const char *NameStr = Name->getKeyData();
142 unsigned NameLen = Name->getKeyLength();
144 bool NeedsQuotes = NameStr[0] >= '0' && NameStr[0] <= '9';
146 for (unsigned i = 0; i != NameLen; ++i) {
148 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
155 // If we didn't need any quotes, just write out the name in one blast.
157 OS.write(NameStr, NameLen);
161 // Okay, we need quotes. Output the quotes and escape any scary characters as
164 for (unsigned i = 0; i != NameLen; ++i) {
166 assert(C != '"' && "Illegal character in LLVM value name!");
169 } else if (isprint(C)) {
173 char hex1 = (C >> 4) & 0x0F;
175 OS << (char)(hex1 + '0');
177 OS << (char)(hex1 - 10 + 'A');
178 char hex2 = C & 0x0F;
180 OS << (char)(hex2 + '0');
182 OS << (char)(hex2 - 10 + 'A');
188 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
189 /// prefixed with % (if the string only contains simple characters) or is
190 /// surrounded with ""'s (if it has special chars in it). Print it out.
191 static void PrintLLVMName(std::ostream &OS, const Value *V) {
192 PrintLLVMName(OS, V->getValueName(),
193 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
198 //===----------------------------------------------------------------------===//
199 // SlotTracker Class: Enumerate slot numbers for unnamed values
200 //===----------------------------------------------------------------------===//
204 /// This class provides computation of slot numbers for LLVM Assembly writing.
208 /// ValueMap - A mapping of Values to slot numbers
209 typedef DenseMap<const Value*, unsigned> ValueMap;
212 /// TheModule - The module for which we are holding slot numbers
213 const Module* TheModule;
215 /// TheFunction - The function for which we are holding slot numbers
216 const Function* TheFunction;
217 bool FunctionProcessed;
219 /// mMap - The TypePlanes map for the module level data
223 /// fMap - The TypePlanes map for the function level data
228 /// Construct from a module
229 explicit SlotTracker(const Module *M);
230 /// Construct from a function, starting out in incorp state.
231 explicit SlotTracker(const Function *F);
233 /// Return the slot number of the specified value in it's type
234 /// plane. If something is not in the SlotTracker, return -1.
235 int getLocalSlot(const Value *V);
236 int getGlobalSlot(const GlobalValue *V);
238 /// If you'd like to deal with a function instead of just a module, use
239 /// this method to get its data into the SlotTracker.
240 void incorporateFunction(const Function *F) {
242 FunctionProcessed = false;
245 /// After calling incorporateFunction, use this method to remove the
246 /// most recently incorporated function from the SlotTracker. This
247 /// will reset the state of the machine back to just the module contents.
248 void purgeFunction();
250 // Implementation Details
252 /// This function does the actual initialization.
253 inline void initialize();
255 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
256 void CreateModuleSlot(const GlobalValue *V);
258 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
259 void CreateFunctionSlot(const Value *V);
261 /// Add all of the module level global variables (and their initializers)
262 /// and function declarations, but not the contents of those functions.
263 void processModule();
265 /// Add all of the functions arguments, basic blocks, and instructions
266 void processFunction();
268 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
269 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
272 } // end anonymous namespace
275 static SlotTracker *createSlotTracker(const Value *V) {
276 if (const Argument *FA = dyn_cast<Argument>(V))
277 return new SlotTracker(FA->getParent());
279 if (const Instruction *I = dyn_cast<Instruction>(V))
280 return new SlotTracker(I->getParent()->getParent());
282 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
283 return new SlotTracker(BB->getParent());
285 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
286 return new SlotTracker(GV->getParent());
288 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
289 return new SlotTracker(GA->getParent());
291 if (const Function *Func = dyn_cast<Function>(V))
292 return new SlotTracker(Func);
298 #define ST_DEBUG(X) cerr << X
303 // Module level constructor. Causes the contents of the Module (sans functions)
304 // to be added to the slot table.
305 SlotTracker::SlotTracker(const Module *M)
306 : TheModule(M), TheFunction(0), FunctionProcessed(false), mNext(0), fNext(0) {
309 // Function level constructor. Causes the contents of the Module and the one
310 // function provided to be added to the slot table.
311 SlotTracker::SlotTracker(const Function *F)
312 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
316 inline void SlotTracker::initialize() {
319 TheModule = 0; ///< Prevent re-processing next time we're called.
322 if (TheFunction && !FunctionProcessed)
326 // Iterate through all the global variables, functions, and global
327 // variable initializers and create slots for them.
328 void SlotTracker::processModule() {
329 ST_DEBUG("begin processModule!\n");
331 // Add all of the unnamed global variables to the value table.
332 for (Module::const_global_iterator I = TheModule->global_begin(),
333 E = TheModule->global_end(); I != E; ++I)
337 // Add all the unnamed functions to the table.
338 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
343 ST_DEBUG("end processModule!\n");
347 // Process the arguments, basic blocks, and instructions of a function.
348 void SlotTracker::processFunction() {
349 ST_DEBUG("begin processFunction!\n");
352 // Add all the function arguments with no names.
353 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
354 AE = TheFunction->arg_end(); AI != AE; ++AI)
356 CreateFunctionSlot(AI);
358 ST_DEBUG("Inserting Instructions:\n");
360 // Add all of the basic blocks and instructions with no names.
361 for (Function::const_iterator BB = TheFunction->begin(),
362 E = TheFunction->end(); BB != E; ++BB) {
364 CreateFunctionSlot(BB);
365 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
366 if (I->getType() != Type::VoidTy && !I->hasName())
367 CreateFunctionSlot(I);
370 FunctionProcessed = true;
372 ST_DEBUG("end processFunction!\n");
375 /// Clean up after incorporating a function. This is the only way to get out of
376 /// the function incorporation state that affects get*Slot/Create*Slot. Function
377 /// incorporation state is indicated by TheFunction != 0.
378 void SlotTracker::purgeFunction() {
379 ST_DEBUG("begin purgeFunction!\n");
380 fMap.clear(); // Simply discard the function level map
382 FunctionProcessed = false;
383 ST_DEBUG("end purgeFunction!\n");
386 /// getGlobalSlot - Get the slot number of a global value.
387 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
388 // Check for uninitialized state and do lazy initialization.
391 // Find the type plane in the module map
392 ValueMap::iterator MI = mMap.find(V);
393 return MI == mMap.end() ? -1 : MI->second;
397 /// getLocalSlot - Get the slot number for a value that is local to a function.
398 int SlotTracker::getLocalSlot(const Value *V) {
399 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
401 // Check for uninitialized state and do lazy initialization.
404 ValueMap::iterator FI = fMap.find(V);
405 return FI == fMap.end() ? -1 : FI->second;
409 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
410 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
411 assert(V && "Can't insert a null Value into SlotTracker!");
412 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
413 assert(!V->hasName() && "Doesn't need a slot!");
415 unsigned DestSlot = mNext++;
418 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
420 // G = Global, F = Function, A = Alias, o = other
421 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
422 (isa<Function>(V) ? 'F' :
423 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
427 /// CreateSlot - Create a new slot for the specified value if it has no name.
428 void SlotTracker::CreateFunctionSlot(const Value *V) {
429 assert(V->getType() != Type::VoidTy && !V->hasName() &&
430 "Doesn't need a slot!");
432 unsigned DestSlot = fNext++;
435 // G = Global, F = Function, o = other
436 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
437 DestSlot << " [o]\n");
442 //===----------------------------------------------------------------------===//
443 // AsmWriter Implementation
444 //===----------------------------------------------------------------------===//
446 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
447 std::map<const Type *, std::string> &TypeTable,
448 SlotTracker *Machine);
452 /// fillTypeNameTable - If the module has a symbol table, take all global types
453 /// and stuff their names into the TypeNames map.
455 static void fillTypeNameTable(const Module *M,
456 std::map<const Type *, std::string> &TypeNames) {
458 const TypeSymbolTable &ST = M->getTypeSymbolTable();
459 TypeSymbolTable::const_iterator TI = ST.begin();
460 for (; TI != ST.end(); ++TI) {
461 // As a heuristic, don't insert pointer to primitive types, because
462 // they are used too often to have a single useful name.
464 const Type *Ty = cast<Type>(TI->second);
465 if (!isa<PointerType>(Ty) ||
466 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
467 !cast<PointerType>(Ty)->getElementType()->isInteger() ||
468 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
469 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
475 static void calcTypeName(const Type *Ty,
476 std::vector<const Type *> &TypeStack,
477 std::map<const Type *, std::string> &TypeNames,
478 std::string & Result){
479 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
480 Result += Ty->getDescription(); // Base case
484 // Check to see if the type is named.
485 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
486 if (I != TypeNames.end()) {
491 if (isa<OpaqueType>(Ty)) {
496 // Check to see if the Type is already on the stack...
497 unsigned Slot = 0, CurSize = TypeStack.size();
498 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
500 // This is another base case for the recursion. In this case, we know
501 // that we have looped back to a type that we have previously visited.
502 // Generate the appropriate upreference to handle this.
503 if (Slot < CurSize) {
504 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
508 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
510 switch (Ty->getTypeID()) {
511 case Type::IntegerTyID: {
512 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
513 Result += "i" + utostr(BitWidth);
516 case Type::FunctionTyID: {
517 const FunctionType *FTy = cast<FunctionType>(Ty);
518 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
520 for (FunctionType::param_iterator I = FTy->param_begin(),
521 E = FTy->param_end(); I != E; ++I) {
522 if (I != FTy->param_begin())
524 calcTypeName(*I, TypeStack, TypeNames, Result);
526 if (FTy->isVarArg()) {
527 if (FTy->getNumParams()) Result += ", ";
533 case Type::StructTyID: {
534 const StructType *STy = cast<StructType>(Ty);
538 for (StructType::element_iterator I = STy->element_begin(),
539 E = STy->element_end(); I != E; ++I) {
540 if (I != STy->element_begin())
542 calcTypeName(*I, TypeStack, TypeNames, Result);
549 case Type::PointerTyID: {
550 const PointerType *PTy = cast<PointerType>(Ty);
551 calcTypeName(PTy->getElementType(),
552 TypeStack, TypeNames, Result);
553 if (unsigned AddressSpace = PTy->getAddressSpace())
554 Result += " addrspace(" + utostr(AddressSpace) + ")";
558 case Type::ArrayTyID: {
559 const ArrayType *ATy = cast<ArrayType>(Ty);
560 Result += "[" + utostr(ATy->getNumElements()) + " x ";
561 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
565 case Type::VectorTyID: {
566 const VectorType *PTy = cast<VectorType>(Ty);
567 Result += "<" + utostr(PTy->getNumElements()) + " x ";
568 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
572 case Type::OpaqueTyID:
576 Result += "<unrecognized-type>";
580 TypeStack.pop_back(); // Remove self from stack...
584 /// printTypeInt - The internal guts of printing out a type that has a
585 /// potentially named portion.
587 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
588 std::map<const Type *, std::string> &TypeNames) {
589 // Primitive types always print out their description, regardless of whether
590 // they have been named or not.
592 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)))
593 return Out << Ty->getDescription();
595 // Check to see if the type is named.
596 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
597 if (I != TypeNames.end()) return Out << I->second;
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
607 return (Out << TypeName);
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 std::ostream &printType(const Type *Ty) {
998 return 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()) << ']';
1068 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
1069 Out << '<' << PTy->getNumElements() << " x ";
1070 printType(PTy->getElementType()) << '>';
1074 if (isa<OpaqueType>(Ty)) {
1079 if (!Ty->isPrimitiveType())
1080 Out << "<unknown derived type>";
1085 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1087 Out << "<null operand!>";
1091 printType(Operand->getType());
1093 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
1097 void AssemblyWriter::writeParamOperand(const Value *Operand,
1098 ParameterAttributes Attrs) {
1100 Out << "<null operand!>";
1104 printType(Operand->getType());
1105 // Print parameter attributes list
1106 if (Attrs != ParamAttr::None)
1107 Out << ' ' << ParamAttr::getAsString(Attrs);
1108 // Print the operand
1109 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
1113 void AssemblyWriter::printModule(const Module *M) {
1114 if (!M->getModuleIdentifier().empty() &&
1115 // Don't print the ID if it will start a new line (which would
1116 // require a comment char before it).
1117 M->getModuleIdentifier().find('\n') == std::string::npos)
1118 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1120 if (!M->getDataLayout().empty())
1121 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1122 if (!M->getTargetTriple().empty())
1123 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1125 if (!M->getModuleInlineAsm().empty()) {
1126 // Split the string into lines, to make it easier to read the .ll file.
1127 std::string Asm = M->getModuleInlineAsm();
1129 size_t NewLine = Asm.find_first_of('\n', CurPos);
1130 while (NewLine != std::string::npos) {
1131 // We found a newline, print the portion of the asm string from the
1132 // last newline up to this newline.
1133 Out << "module asm \"";
1134 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1138 NewLine = Asm.find_first_of('\n', CurPos);
1140 Out << "module asm \"";
1141 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1145 // Loop over the dependent libraries and emit them.
1146 Module::lib_iterator LI = M->lib_begin();
1147 Module::lib_iterator LE = M->lib_end();
1149 Out << "deplibs = [ ";
1151 Out << '"' << *LI << '"';
1159 // Loop over the symbol table, emitting all named constants.
1160 printTypeSymbolTable(M->getTypeSymbolTable());
1162 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1166 // Output all aliases.
1167 if (!M->alias_empty()) Out << "\n";
1168 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1172 // Output all of the functions.
1173 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1177 static void PrintLinkage(GlobalValue::LinkageTypes LT, std::ostream &Out) {
1179 case GlobalValue::InternalLinkage: Out << "internal "; break;
1180 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
1181 case GlobalValue::WeakLinkage: Out << "weak "; break;
1182 case GlobalValue::CommonLinkage: Out << "common "; break;
1183 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1184 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1185 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1186 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1187 case GlobalValue::ExternalLinkage: break;
1188 case GlobalValue::GhostLinkage:
1189 Out << "GhostLinkage not allowed in AsmWriter!\n";
1195 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1196 std::ostream &Out) {
1198 default: assert(0 && "Invalid visibility style!");
1199 case GlobalValue::DefaultVisibility: break;
1200 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1201 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1205 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1206 if (GV->hasName()) {
1207 PrintLLVMName(Out, GV);
1211 if (!GV->hasInitializer()) {
1212 switch (GV->getLinkage()) {
1213 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1214 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1215 default: Out << "external "; break;
1218 PrintLinkage(GV->getLinkage(), Out);
1219 PrintVisibility(GV->getVisibility(), Out);
1222 if (GV->isThreadLocal()) Out << "thread_local ";
1223 Out << (GV->isConstant() ? "constant " : "global ");
1224 printType(GV->getType()->getElementType());
1226 if (GV->hasInitializer())
1227 writeOperand(GV->getInitializer(), false);
1229 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1230 Out << " addrspace(" << AddressSpace << ") ";
1232 if (GV->hasSection())
1233 Out << ", section \"" << GV->getSection() << '"';
1234 if (GV->getAlignment())
1235 Out << ", align " << GV->getAlignment();
1237 printInfoComment(*GV);
1241 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1242 // Don't crash when dumping partially built GA
1244 Out << "<<nameless>> = ";
1246 PrintLLVMName(Out, GA);
1249 PrintVisibility(GA->getVisibility(), Out);
1253 PrintLinkage(GA->getLinkage(), Out);
1255 const Constant *Aliasee = GA->getAliasee();
1257 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1258 printType(GV->getType());
1260 PrintLLVMName(Out, GV);
1261 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1262 printType(F->getFunctionType());
1266 PrintLLVMName(Out, F);
1269 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1270 printType(GA->getType());
1272 PrintLLVMName(Out, GA);
1274 const ConstantExpr *CE = 0;
1275 if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
1276 (CE->getOpcode() == Instruction::BitCast)) {
1277 writeOperand(CE, false);
1279 assert(0 && "Unsupported aliasee");
1282 printInfoComment(*GA);
1286 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1288 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1290 Out << '\t' << getLLVMName(TI->first) << " = type ";
1292 // Make sure we print out at least one level of the type structure, so
1293 // that we do not get %FILE = type %FILE
1295 printTypeAtLeastOneLevel(TI->second);
1300 /// printFunction - Print all aspects of a function.
1302 void AssemblyWriter::printFunction(const Function *F) {
1303 // Print out the return type and name.
1306 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1308 if (F->isDeclaration())
1313 PrintLinkage(F->getLinkage(), Out);
1314 PrintVisibility(F->getVisibility(), Out);
1316 // Print the calling convention.
1317 switch (F->getCallingConv()) {
1318 case CallingConv::C: break; // default
1319 case CallingConv::Fast: Out << "fastcc "; break;
1320 case CallingConv::Cold: Out << "coldcc "; break;
1321 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1322 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1323 case CallingConv::X86_SSECall: Out << "x86_ssecallcc "; break;
1324 default: Out << "cc" << F->getCallingConv() << " "; break;
1327 const FunctionType *FT = F->getFunctionType();
1328 const PAListPtr &Attrs = F->getParamAttrs();
1329 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->getValueName(), 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()) << '>';
1471 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1472 SlotNum = Machine.getGlobalSlot(GV);
1474 SlotNum = Machine.getLocalSlot(&V);
1478 Out << ':' << SlotNum; // Print out the def slot taken.
1480 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1484 // This member is called for each Instruction in a function..
1485 void AssemblyWriter::printInstruction(const Instruction &I) {
1486 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1490 // Print out name if it exists...
1492 PrintLLVMName(Out, &I);
1496 // If this is a volatile load or store, print out the volatile marker.
1497 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1498 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1500 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1501 // If this is a call, check if it's a tail call.
1505 // Print out the opcode...
1506 Out << I.getOpcodeName();
1508 // Print out the compare instruction predicates
1509 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1510 Out << " " << getPredicateText(CI->getPredicate());
1512 // Print out the type of the operands...
1513 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1515 // Special case conditional branches to swizzle the condition out to the front
1516 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1517 writeOperand(I.getOperand(2), true);
1519 writeOperand(Operand, true);
1521 writeOperand(I.getOperand(1), true);
1523 } else if (isa<SwitchInst>(I)) {
1524 // Special case switch statement to get formatting nice and correct...
1525 writeOperand(Operand , true); Out << ',';
1526 writeOperand(I.getOperand(1), true); Out << " [";
1528 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1530 writeOperand(I.getOperand(op ), true); Out << ',';
1531 writeOperand(I.getOperand(op+1), true);
1534 } else if (isa<PHINode>(I)) {
1536 printType(I.getType());
1539 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1540 if (op) Out << ", ";
1542 writeOperand(I.getOperand(op ), false); Out << ',';
1543 writeOperand(I.getOperand(op+1), false); Out << " ]";
1545 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1546 writeOperand(I.getOperand(0), true);
1547 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1549 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1550 writeOperand(I.getOperand(0), true); Out << ',';
1551 writeOperand(I.getOperand(1), true);
1552 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1554 } else if (isa<ReturnInst>(I) && !Operand) {
1556 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1557 // Print the calling convention being used.
1558 switch (CI->getCallingConv()) {
1559 case CallingConv::C: break; // default
1560 case CallingConv::Fast: Out << " fastcc"; break;
1561 case CallingConv::Cold: Out << " coldcc"; break;
1562 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1563 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1564 case CallingConv::X86_SSECall: Out << " x86_ssecallcc"; break;
1565 default: Out << " cc" << CI->getCallingConv(); break;
1568 const PointerType *PTy = cast<PointerType>(Operand->getType());
1569 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1570 const Type *RetTy = FTy->getReturnType();
1571 const PAListPtr &PAL = CI->getParamAttrs();
1573 // If possible, print out the short form of the call instruction. We can
1574 // only do this if the first argument is a pointer to a nonvararg function,
1575 // and if the return type is not a pointer to a function.
1577 if (!FTy->isVarArg() &&
1578 (!isa<PointerType>(RetTy) ||
1579 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1580 Out << ' '; printType(RetTy);
1581 writeOperand(Operand, false);
1583 writeOperand(Operand, true);
1586 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1589 writeParamOperand(I.getOperand(op), PAL.getParamAttrs(op));
1592 if (PAL.getParamAttrs(0) != ParamAttr::None)
1593 Out << ' ' << ParamAttr::getAsString(PAL.getParamAttrs(0));
1594 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1595 const PointerType *PTy = cast<PointerType>(Operand->getType());
1596 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1597 const Type *RetTy = FTy->getReturnType();
1598 const PAListPtr &PAL = II->getParamAttrs();
1600 // Print the calling convention being used.
1601 switch (II->getCallingConv()) {
1602 case CallingConv::C: break; // default
1603 case CallingConv::Fast: Out << " fastcc"; break;
1604 case CallingConv::Cold: Out << " coldcc"; break;
1605 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1606 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1607 case CallingConv::X86_SSECall: Out << "x86_ssecallcc "; break;
1608 default: Out << " cc" << II->getCallingConv(); break;
1611 // If possible, print out the short form of the invoke instruction. We can
1612 // only do this if the first argument is a pointer to a nonvararg function,
1613 // and if the return type is not a pointer to a function.
1615 if (!FTy->isVarArg() &&
1616 (!isa<PointerType>(RetTy) ||
1617 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1618 Out << ' '; printType(RetTy);
1619 writeOperand(Operand, false);
1621 writeOperand(Operand, true);
1625 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1628 writeParamOperand(I.getOperand(op), PAL.getParamAttrs(op-2));
1632 if (PAL.getParamAttrs(0) != ParamAttr::None)
1633 Out << ' ' << ParamAttr::getAsString(PAL.getParamAttrs(0));
1634 Out << "\n\t\t\tto";
1635 writeOperand(II->getNormalDest(), true);
1637 writeOperand(II->getUnwindDest(), true);
1639 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1641 printType(AI->getType()->getElementType());
1642 if (AI->isArrayAllocation()) {
1644 writeOperand(AI->getArraySize(), true);
1646 if (AI->getAlignment()) {
1647 Out << ", align " << AI->getAlignment();
1649 } else if (isa<CastInst>(I)) {
1650 if (Operand) writeOperand(Operand, true); // Work with broken code
1652 printType(I.getType());
1653 } else if (isa<VAArgInst>(I)) {
1654 if (Operand) writeOperand(Operand, true); // Work with broken code
1656 printType(I.getType());
1657 } else if (Operand) { // Print the normal way...
1659 // PrintAllTypes - Instructions who have operands of all the same type
1660 // omit the type from all but the first operand. If the instruction has
1661 // different type operands (for example br), then they are all printed.
1662 bool PrintAllTypes = false;
1663 const Type *TheType = Operand->getType();
1665 // Select, Store and ShuffleVector always print all types.
1666 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1667 || isa<ReturnInst>(I)) {
1668 PrintAllTypes = true;
1670 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1671 Operand = I.getOperand(i);
1672 if (Operand->getType() != TheType) {
1673 PrintAllTypes = true; // We have differing types! Print them all!
1679 if (!PrintAllTypes) {
1684 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1686 writeOperand(I.getOperand(i), PrintAllTypes);
1690 // Print post operand alignment for load/store
1691 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1692 Out << ", align " << cast<LoadInst>(I).getAlignment();
1693 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1694 Out << ", align " << cast<StoreInst>(I).getAlignment();
1697 printInfoComment(I);
1702 //===----------------------------------------------------------------------===//
1703 // External Interface declarations
1704 //===----------------------------------------------------------------------===//
1706 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1707 SlotTracker SlotTable(this);
1708 AssemblyWriter W(o, SlotTable, this, AAW);
1712 void GlobalVariable::print(std::ostream &o) const {
1713 SlotTracker SlotTable(getParent());
1714 AssemblyWriter W(o, SlotTable, getParent(), 0);
1718 void GlobalAlias::print(std::ostream &o) const {
1719 SlotTracker SlotTable(getParent());
1720 AssemblyWriter W(o, SlotTable, getParent(), 0);
1724 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1725 SlotTracker SlotTable(getParent());
1726 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1731 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1732 WriteAsOperand(o, this, true, 0);
1735 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1736 SlotTracker SlotTable(getParent());
1737 AssemblyWriter W(o, SlotTable,
1738 getParent() ? getParent()->getParent() : 0, AAW);
1742 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1743 const Function *F = getParent() ? getParent()->getParent() : 0;
1744 SlotTracker SlotTable(F);
1745 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1750 void Constant::print(std::ostream &o) const {
1751 if (this == 0) { o << "<null> constant value\n"; return; }
1753 o << ' ' << getType()->getDescription() << ' ';
1755 std::map<const Type *, std::string> TypeTable;
1756 WriteConstantInt(o, this, TypeTable, 0);
1759 void Type::print(std::ostream &o) const {
1763 o << getDescription();
1766 void Argument::print(std::ostream &o) const {
1767 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1770 // Value::dump - allow easy printing of Values from the debugger.
1771 // Located here because so much of the needed functionality is here.
1772 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1774 // Type::dump - allow easy printing of Values from the debugger.
1775 // Located here because so much of the needed functionality is here.
1776 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }