1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Assembly/Writer.h
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/Assembly/AsmAnnotationWriter.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instruction.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Module.h"
27 #include "llvm/ValueSymbolTable.h"
28 #include "llvm/TypeSymbolTable.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
39 // Make virtual table appear in this compilation unit.
40 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
42 char PrintModulePass::ID = 0;
43 static RegisterPass<PrintModulePass>
44 X("printm", "Print module to stderr");
45 char PrintFunctionPass::ID = 0;
46 static RegisterPass<PrintFunctionPass>
47 Y("print","Print function to stderr");
50 //===----------------------------------------------------------------------===//
52 //===----------------------------------------------------------------------===//
54 static const Module *getModuleFromVal(const Value *V) {
55 if (const Argument *MA = dyn_cast<Argument>(V))
56 return MA->getParent() ? MA->getParent()->getParent() : 0;
58 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
59 return BB->getParent() ? BB->getParent()->getParent() : 0;
61 if (const Instruction *I = dyn_cast<Instruction>(V)) {
62 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
63 return M ? M->getParent() : 0;
66 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
67 return GV->getParent();
72 /// NameNeedsQuotes - Return true if the specified llvm name should be wrapped
74 static std::string QuoteNameIfNeeded(const std::string &Name) {
76 bool needsQuotes = Name[0] >= '0' && Name[0] <= '9';
77 // Scan the name to see if it needs quotes and to replace funky chars with
78 // their octal equivalent.
79 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
81 assert(C != '"' && "Illegal character in LLVM value name!");
82 if (isalnum(C) || C == '-' || C == '.' || C == '_')
87 } else if (isprint(C)) {
93 char hex1 = (C >> 4) & 0x0F;
97 result += hex1 - 10 + 'A';
100 result += hex2 + '0';
102 result += hex2 - 10 + 'A';
106 result.insert(0,"\"");
112 /// getLLVMName - Turn the specified string into an 'LLVM name', which is
113 /// surrounded with ""'s and escaped if it has special chars in it.
114 static std::string getLLVMName(const std::string &Name) {
115 assert(!Name.empty() && "Cannot get empty name!");
116 return QuoteNameIfNeeded(Name);
125 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
126 /// prefixed with % (if the string only contains simple characters) or is
127 /// surrounded with ""'s (if it has special chars in it). Print it out.
128 static void PrintLLVMName(raw_ostream &OS, const char *NameStr,
129 unsigned NameLen, PrefixType Prefix) {
130 assert(NameStr && "Cannot get empty name!");
132 default: assert(0 && "Bad prefix!");
133 case GlobalPrefix: OS << '@'; break;
134 case LabelPrefix: break;
135 case LocalPrefix: OS << '%'; break;
138 // Scan the name to see if it needs quotes first.
139 bool NeedsQuotes = NameStr[0] >= '0' && NameStr[0] <= '9';
141 for (unsigned i = 0; i != NameLen; ++i) {
143 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
150 // If we didn't need any quotes, just write out the name in one blast.
152 OS.write(NameStr, NameLen);
156 // Okay, we need quotes. Output the quotes and escape any scary characters as
159 for (unsigned i = 0; i != NameLen; ++i) {
161 assert(C != '"' && "Illegal character in LLVM value name!");
164 } else if (isprint(C)) {
168 char hex1 = (C >> 4) & 0x0F;
170 OS << (char)(hex1 + '0');
172 OS << (char)(hex1 - 10 + 'A');
173 char hex2 = C & 0x0F;
175 OS << (char)(hex2 + '0');
177 OS << (char)(hex2 - 10 + 'A');
183 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
184 /// prefixed with % (if the string only contains simple characters) or is
185 /// surrounded with ""'s (if it has special chars in it). Print it out.
186 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
187 PrintLLVMName(OS, V->getNameStart(), V->getNameLen(),
188 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
193 //===----------------------------------------------------------------------===//
194 // SlotTracker Class: Enumerate slot numbers for unnamed values
195 //===----------------------------------------------------------------------===//
199 /// This class provides computation of slot numbers for LLVM Assembly writing.
203 /// ValueMap - A mapping of Values to slot numbers
204 typedef DenseMap<const Value*, unsigned> ValueMap;
207 /// TheModule - The module for which we are holding slot numbers
208 const Module* TheModule;
210 /// TheFunction - The function for which we are holding slot numbers
211 const Function* TheFunction;
212 bool FunctionProcessed;
214 /// mMap - The TypePlanes map for the module level data
218 /// fMap - The TypePlanes map for the function level data
223 /// Construct from a module
224 explicit SlotTracker(const Module *M);
225 /// Construct from a function, starting out in incorp state.
226 explicit SlotTracker(const Function *F);
228 /// Return the slot number of the specified value in it's type
229 /// plane. If something is not in the SlotTracker, return -1.
230 int getLocalSlot(const Value *V);
231 int getGlobalSlot(const GlobalValue *V);
233 /// If you'd like to deal with a function instead of just a module, use
234 /// this method to get its data into the SlotTracker.
235 void incorporateFunction(const Function *F) {
237 FunctionProcessed = false;
240 /// After calling incorporateFunction, use this method to remove the
241 /// most recently incorporated function from the SlotTracker. This
242 /// will reset the state of the machine back to just the module contents.
243 void purgeFunction();
245 // Implementation Details
247 /// This function does the actual initialization.
248 inline void initialize();
250 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
251 void CreateModuleSlot(const GlobalValue *V);
253 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
254 void CreateFunctionSlot(const Value *V);
256 /// Add all of the module level global variables (and their initializers)
257 /// and function declarations, but not the contents of those functions.
258 void processModule();
260 /// Add all of the functions arguments, basic blocks, and instructions
261 void processFunction();
263 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
264 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
267 } // end anonymous namespace
270 static SlotTracker *createSlotTracker(const Value *V) {
271 if (const Argument *FA = dyn_cast<Argument>(V))
272 return new SlotTracker(FA->getParent());
274 if (const Instruction *I = dyn_cast<Instruction>(V))
275 return new SlotTracker(I->getParent()->getParent());
277 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
278 return new SlotTracker(BB->getParent());
280 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
281 return new SlotTracker(GV->getParent());
283 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
284 return new SlotTracker(GA->getParent());
286 if (const Function *Func = dyn_cast<Function>(V))
287 return new SlotTracker(Func);
293 #define ST_DEBUG(X) cerr << X
298 // Module level constructor. Causes the contents of the Module (sans functions)
299 // to be added to the slot table.
300 SlotTracker::SlotTracker(const Module *M)
301 : TheModule(M), TheFunction(0), FunctionProcessed(false), mNext(0), fNext(0) {
304 // Function level constructor. Causes the contents of the Module and the one
305 // function provided to be added to the slot table.
306 SlotTracker::SlotTracker(const Function *F)
307 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
311 inline void SlotTracker::initialize() {
314 TheModule = 0; ///< Prevent re-processing next time we're called.
317 if (TheFunction && !FunctionProcessed)
321 // Iterate through all the global variables, functions, and global
322 // variable initializers and create slots for them.
323 void SlotTracker::processModule() {
324 ST_DEBUG("begin processModule!\n");
326 // Add all of the unnamed global variables to the value table.
327 for (Module::const_global_iterator I = TheModule->global_begin(),
328 E = TheModule->global_end(); I != E; ++I)
332 // Add all the unnamed functions to the table.
333 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
338 ST_DEBUG("end processModule!\n");
342 // Process the arguments, basic blocks, and instructions of a function.
343 void SlotTracker::processFunction() {
344 ST_DEBUG("begin processFunction!\n");
347 // Add all the function arguments with no names.
348 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
349 AE = TheFunction->arg_end(); AI != AE; ++AI)
351 CreateFunctionSlot(AI);
353 ST_DEBUG("Inserting Instructions:\n");
355 // Add all of the basic blocks and instructions with no names.
356 for (Function::const_iterator BB = TheFunction->begin(),
357 E = TheFunction->end(); BB != E; ++BB) {
359 CreateFunctionSlot(BB);
360 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
361 if (I->getType() != Type::VoidTy && !I->hasName())
362 CreateFunctionSlot(I);
365 FunctionProcessed = true;
367 ST_DEBUG("end processFunction!\n");
370 /// Clean up after incorporating a function. This is the only way to get out of
371 /// the function incorporation state that affects get*Slot/Create*Slot. Function
372 /// incorporation state is indicated by TheFunction != 0.
373 void SlotTracker::purgeFunction() {
374 ST_DEBUG("begin purgeFunction!\n");
375 fMap.clear(); // Simply discard the function level map
377 FunctionProcessed = false;
378 ST_DEBUG("end purgeFunction!\n");
381 /// getGlobalSlot - Get the slot number of a global value.
382 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
383 // Check for uninitialized state and do lazy initialization.
386 // Find the type plane in the module map
387 ValueMap::iterator MI = mMap.find(V);
388 return MI == mMap.end() ? -1 : MI->second;
392 /// getLocalSlot - Get the slot number for a value that is local to a function.
393 int SlotTracker::getLocalSlot(const Value *V) {
394 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
396 // Check for uninitialized state and do lazy initialization.
399 ValueMap::iterator FI = fMap.find(V);
400 return FI == fMap.end() ? -1 : FI->second;
404 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
405 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
406 assert(V && "Can't insert a null Value into SlotTracker!");
407 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
408 assert(!V->hasName() && "Doesn't need a slot!");
410 unsigned DestSlot = mNext++;
413 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
415 // G = Global, F = Function, A = Alias, o = other
416 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
417 (isa<Function>(V) ? 'F' :
418 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
422 /// CreateSlot - Create a new slot for the specified value if it has no name.
423 void SlotTracker::CreateFunctionSlot(const Value *V) {
424 assert(V->getType() != Type::VoidTy && !V->hasName() &&
425 "Doesn't need a slot!");
427 unsigned DestSlot = fNext++;
430 // G = Global, F = Function, o = other
431 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
432 DestSlot << " [o]\n");
437 //===----------------------------------------------------------------------===//
438 // AsmWriter Implementation
439 //===----------------------------------------------------------------------===//
441 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
442 std::map<const Type *, std::string> &TypeTable,
443 SlotTracker *Machine);
447 /// fillTypeNameTable - If the module has a symbol table, take all global types
448 /// and stuff their names into the TypeNames map.
450 static void fillTypeNameTable(const Module *M,
451 std::map<const Type *, std::string> &TypeNames) {
453 const TypeSymbolTable &ST = M->getTypeSymbolTable();
454 TypeSymbolTable::const_iterator TI = ST.begin();
455 for (; TI != ST.end(); ++TI) {
456 // As a heuristic, don't insert pointer to primitive types, because
457 // they are used too often to have a single useful name.
459 const Type *Ty = cast<Type>(TI->second);
460 if (!isa<PointerType>(Ty) ||
461 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
462 !cast<PointerType>(Ty)->getElementType()->isInteger() ||
463 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
464 TypeNames.insert(std::make_pair(Ty, '%' + getLLVMName(TI->first)));
470 static void calcTypeName(const Type *Ty,
471 std::vector<const Type *> &TypeStack,
472 std::map<const Type *, std::string> &TypeNames,
473 std::string &Result) {
474 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
475 Result += Ty->getDescription(); // Base case
479 // Check to see if the type is named.
480 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
481 if (I != TypeNames.end()) {
486 if (isa<OpaqueType>(Ty)) {
491 // Check to see if the Type is already on the stack...
492 unsigned Slot = 0, CurSize = TypeStack.size();
493 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
495 // This is another base case for the recursion. In this case, we know
496 // that we have looped back to a type that we have previously visited.
497 // Generate the appropriate upreference to handle this.
498 if (Slot < CurSize) {
499 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
503 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
505 switch (Ty->getTypeID()) {
506 case Type::IntegerTyID: {
507 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
508 Result += "i" + utostr(BitWidth);
511 case Type::FunctionTyID: {
512 const FunctionType *FTy = cast<FunctionType>(Ty);
513 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
515 for (FunctionType::param_iterator I = FTy->param_begin(),
516 E = FTy->param_end(); I != E; ++I) {
517 if (I != FTy->param_begin())
519 calcTypeName(*I, TypeStack, TypeNames, Result);
521 if (FTy->isVarArg()) {
522 if (FTy->getNumParams()) Result += ", ";
528 case Type::StructTyID: {
529 const StructType *STy = cast<StructType>(Ty);
533 for (StructType::element_iterator I = STy->element_begin(),
534 E = STy->element_end(); I != E; ++I) {
535 if (I != STy->element_begin())
537 calcTypeName(*I, TypeStack, TypeNames, Result);
544 case Type::PointerTyID: {
545 const PointerType *PTy = cast<PointerType>(Ty);
546 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
547 if (unsigned AddressSpace = PTy->getAddressSpace())
548 Result += " addrspace(" + utostr(AddressSpace) + ")";
552 case Type::ArrayTyID: {
553 const ArrayType *ATy = cast<ArrayType>(Ty);
554 Result += "[" + utostr(ATy->getNumElements()) + " x ";
555 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
559 case Type::VectorTyID: {
560 const VectorType *PTy = cast<VectorType>(Ty);
561 Result += "<" + utostr(PTy->getNumElements()) + " x ";
562 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
566 case Type::OpaqueTyID:
570 Result += "<unrecognized-type>";
574 TypeStack.pop_back(); // Remove self from stack...
578 /// printTypeInt - The internal guts of printing out a type that has a
579 /// potentially named portion.
581 static void printTypeInt(raw_ostream &Out, const Type *Ty,
582 std::map<const Type *, std::string> &TypeNames) {
583 // Primitive types always print out their description, regardless of whether
584 // they have been named or not.
586 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
587 Out << Ty->getDescription();
591 // Check to see if the type is named.
592 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
593 if (I != TypeNames.end()) {
598 // Otherwise we have a type that has not been named but is a derived type.
599 // Carefully recurse the type hierarchy to print out any contained symbolic
602 std::vector<const Type *> TypeStack;
603 std::string TypeName;
604 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
605 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
610 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
611 /// type, iff there is an entry in the modules symbol table for the specified
612 /// type or one of it's component types. This is slower than a simple x << Type
614 void llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
616 raw_os_ostream RO(Out);
617 WriteTypeSymbolic(RO, Ty, M);
620 void llvm::WriteTypeSymbolic(raw_ostream &Out, const Type *Ty, const Module *M){
623 // If they want us to print out a type, but there is no context, we can't
624 // print it symbolically.
626 Out << Ty->getDescription();
628 std::map<const Type *, std::string> TypeNames;
629 fillTypeNameTable(M, TypeNames);
630 printTypeInt(Out, Ty, TypeNames);
634 // PrintEscapedString - Print each character of the specified string, escaping
635 // it if it is not printable or if it is an escape char.
636 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
637 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
638 unsigned char C = Str[i];
639 if (isprint(C) && C != '"' && C != '\\') {
643 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
644 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
649 static const char *getPredicateText(unsigned predicate) {
650 const char * pred = "unknown";
652 case FCmpInst::FCMP_FALSE: pred = "false"; break;
653 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
654 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
655 case FCmpInst::FCMP_OGE: pred = "oge"; break;
656 case FCmpInst::FCMP_OLT: pred = "olt"; break;
657 case FCmpInst::FCMP_OLE: pred = "ole"; break;
658 case FCmpInst::FCMP_ONE: pred = "one"; break;
659 case FCmpInst::FCMP_ORD: pred = "ord"; break;
660 case FCmpInst::FCMP_UNO: pred = "uno"; break;
661 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
662 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
663 case FCmpInst::FCMP_UGE: pred = "uge"; break;
664 case FCmpInst::FCMP_ULT: pred = "ult"; break;
665 case FCmpInst::FCMP_ULE: pred = "ule"; break;
666 case FCmpInst::FCMP_UNE: pred = "une"; break;
667 case FCmpInst::FCMP_TRUE: pred = "true"; break;
668 case ICmpInst::ICMP_EQ: pred = "eq"; break;
669 case ICmpInst::ICMP_NE: pred = "ne"; break;
670 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
671 case ICmpInst::ICMP_SGE: pred = "sge"; break;
672 case ICmpInst::ICMP_SLT: pred = "slt"; break;
673 case ICmpInst::ICMP_SLE: pred = "sle"; break;
674 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
675 case ICmpInst::ICMP_UGE: pred = "uge"; break;
676 case ICmpInst::ICMP_ULT: pred = "ult"; break;
677 case ICmpInst::ICMP_ULE: pred = "ule"; break;
682 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
683 std::map<const Type *, std::string> &TypeTable,
684 SlotTracker *Machine) {
685 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
686 if (CI->getType() == Type::Int1Ty) {
687 Out << (CI->getZExtValue() ? "true" : "false");
690 Out << CI->getValue();
694 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
695 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
696 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
697 // We would like to output the FP constant value in exponential notation,
698 // but we cannot do this if doing so will lose precision. Check here to
699 // make sure that we only output it in exponential format if we can parse
700 // the value back and get the same value.
702 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
703 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
704 CFP->getValueAPF().convertToFloat();
705 std::string StrVal = ftostr(CFP->getValueAPF());
707 // Check to make sure that the stringized number is not some string like
708 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
709 // that the string matches the "[-+]?[0-9]" regex.
711 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
712 ((StrVal[0] == '-' || StrVal[0] == '+') &&
713 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
714 // Reparse stringized version!
715 if (atof(StrVal.c_str()) == Val) {
720 // Otherwise we could not reparse it to exactly the same value, so we must
721 // output the string in hexadecimal format!
722 assert(sizeof(double) == sizeof(uint64_t) &&
723 "assuming that double is 64 bits!");
724 Out << "0x" << utohexstr(DoubleToBits(Val));
728 // Some form of long double. These appear as a magic letter identifying
729 // the type, then a fixed number of hex digits.
731 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended)
733 else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
735 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
738 assert(0 && "Unsupported floating point type");
739 // api needed to prevent premature destruction
740 APInt api = CFP->getValueAPF().convertToAPInt();
741 const uint64_t* p = api.getRawData();
744 int width = api.getBitWidth();
745 for (int j=0; j<width; j+=4, shiftcount-=4) {
746 unsigned int nibble = (word>>shiftcount) & 15;
748 Out << (unsigned char)(nibble + '0');
750 Out << (unsigned char)(nibble - 10 + 'A');
751 if (shiftcount == 0 && j+4 < width) {
755 shiftcount = width-j-4;
761 if (isa<ConstantAggregateZero>(CV)) {
762 Out << "zeroinitializer";
766 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
767 // As a special case, print the array as a string if it is an array of
768 // i8 with ConstantInt values.
770 const Type *ETy = CA->getType()->getElementType();
771 if (CA->isString()) {
773 PrintEscapedString(CA->getAsString(), Out);
775 } else { // Cannot output in string format...
777 if (CA->getNumOperands()) {
779 printTypeInt(Out, ETy, TypeTable);
780 WriteAsOperandInternal(Out, CA->getOperand(0),
782 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
784 printTypeInt(Out, ETy, TypeTable);
785 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
793 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
794 if (CS->getType()->isPacked())
797 unsigned N = CS->getNumOperands();
800 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
802 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
804 for (unsigned i = 1; i < N; i++) {
806 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
808 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
813 if (CS->getType()->isPacked())
818 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
819 const Type *ETy = CP->getType()->getElementType();
820 assert(CP->getNumOperands() > 0 &&
821 "Number of operands for a PackedConst must be > 0");
823 printTypeInt(Out, ETy, TypeTable);
824 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
825 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
827 printTypeInt(Out, ETy, TypeTable);
828 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
834 if (isa<ConstantPointerNull>(CV)) {
839 if (isa<UndefValue>(CV)) {
844 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
845 Out << CE->getOpcodeName();
847 Out << ' ' << getPredicateText(CE->getPredicate());
850 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
851 printTypeInt(Out, (*OI)->getType(), TypeTable);
852 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
853 if (OI+1 != CE->op_end())
857 if (CE->hasIndices()) {
858 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
859 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
860 Out << ", " << Indices[i];
865 printTypeInt(Out, CE->getType(), TypeTable);
872 Out << "<placeholder or erroneous Constant>";
876 /// WriteAsOperand - Write the name of the specified value out to the specified
877 /// ostream. This can be useful when you just want to print int %reg126, not
878 /// the whole instruction that generated it.
880 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
881 std::map<const Type*, std::string> &TypeTable,
882 SlotTracker *Machine) {
885 PrintLLVMName(Out, V);
889 const Constant *CV = dyn_cast<Constant>(V);
890 if (CV && !isa<GlobalValue>(CV)) {
891 WriteConstantInt(Out, CV, TypeTable, Machine);
895 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
897 if (IA->hasSideEffects())
898 Out << "sideeffect ";
900 PrintEscapedString(IA->getAsmString(), Out);
902 PrintEscapedString(IA->getConstraintString(), Out);
910 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
911 Slot = Machine->getGlobalSlot(GV);
914 Slot = Machine->getLocalSlot(V);
917 Machine = createSlotTracker(V);
919 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
920 Slot = Machine->getGlobalSlot(GV);
923 Slot = Machine->getLocalSlot(V);
932 Out << Prefix << Slot;
937 /// WriteAsOperand - Write the name of the specified value out to the specified
938 /// ostream. This can be useful when you just want to print int %reg126, not
939 /// the whole instruction that generated it.
941 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
942 const Module *Context) {
943 raw_os_ostream OS(Out);
944 WriteAsOperand(OS, V, PrintType, Context);
947 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
948 const Module *Context) {
949 std::map<const Type *, std::string> TypeNames;
950 if (Context == 0) Context = getModuleFromVal(V);
953 fillTypeNameTable(Context, TypeNames);
956 printTypeInt(Out, V->getType(), TypeNames);
958 WriteAsOperandInternal(Out, V, TypeNames, 0);
964 class AssemblyWriter {
966 SlotTracker &Machine;
967 const Module *TheModule;
968 std::map<const Type *, std::string> TypeNames;
969 AssemblyAnnotationWriter *AnnotationWriter;
971 inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
972 AssemblyAnnotationWriter *AAW)
973 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
975 // If the module has a symbol table, take all global types and stuff their
976 // names into the TypeNames map.
978 fillTypeNameTable(M, TypeNames);
981 void write(const Module *M) { printModule(M); }
983 void write(const GlobalValue *G) {
984 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
986 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
988 else if (const Function *F = dyn_cast<Function>(G))
991 assert(0 && "Unknown global");
994 void write(const BasicBlock *BB) { printBasicBlock(BB); }
995 void write(const Instruction *I) { printInstruction(*I); }
996 void write(const Type *Ty) { printType(Ty); }
998 void writeOperand(const Value *Op, bool PrintType);
999 void writeParamOperand(const Value *Operand, ParameterAttributes Attrs);
1001 const Module* getModule() { return TheModule; }
1004 void printModule(const Module *M);
1005 void printTypeSymbolTable(const TypeSymbolTable &ST);
1006 void printGlobal(const GlobalVariable *GV);
1007 void printAlias(const GlobalAlias *GV);
1008 void printFunction(const Function *F);
1009 void printArgument(const Argument *FA, ParameterAttributes Attrs);
1010 void printBasicBlock(const BasicBlock *BB);
1011 void printInstruction(const Instruction &I);
1013 // printType - Go to extreme measures to attempt to print out a short,
1014 // symbolic version of a type name.
1016 void printType(const Type *Ty) {
1017 printTypeInt(Out, Ty, TypeNames);
1020 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
1021 // without considering any symbolic types that we may have equal to it.
1023 void printTypeAtLeastOneLevel(const Type *Ty);
1025 // printInfoComment - Print a little comment after the instruction indicating
1026 // which slot it occupies.
1027 void printInfoComment(const Value &V);
1029 } // end of llvm namespace
1031 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
1032 /// without considering any symbolic types that we may have equal to it.
1034 void AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
1035 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
1036 Out << "i" << utostr(ITy->getBitWidth());
1040 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
1041 printType(FTy->getReturnType());
1043 for (FunctionType::param_iterator I = FTy->param_begin(),
1044 E = FTy->param_end(); I != E; ++I) {
1045 if (I != FTy->param_begin())
1049 if (FTy->isVarArg()) {
1050 if (FTy->getNumParams()) Out << ", ";
1057 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1058 if (STy->isPacked())
1061 for (StructType::element_iterator I = STy->element_begin(),
1062 E = STy->element_end(); I != E; ++I) {
1063 if (I != STy->element_begin())
1068 if (STy->isPacked())
1073 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1074 printType(PTy->getElementType());
1075 if (unsigned AddressSpace = PTy->getAddressSpace())
1076 Out << " addrspace(" << AddressSpace << ")";
1081 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1082 Out << '[' << ATy->getNumElements() << " x ";
1083 printType(ATy->getElementType());
1088 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
1089 Out << '<' << PTy->getNumElements() << " x ";
1090 printType(PTy->getElementType());
1095 if (isa<OpaqueType>(Ty)) {
1100 if (!Ty->isPrimitiveType())
1101 Out << "<unknown derived type>";
1106 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1108 Out << "<null operand!>";
1112 printType(Operand->getType());
1114 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
1118 void AssemblyWriter::writeParamOperand(const Value *Operand,
1119 ParameterAttributes Attrs) {
1121 Out << "<null operand!>";
1125 printType(Operand->getType());
1126 // Print parameter attributes list
1127 if (Attrs != ParamAttr::None)
1128 Out << ' ' << ParamAttr::getAsString(Attrs);
1129 // Print the operand
1130 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
1134 void AssemblyWriter::printModule(const Module *M) {
1135 if (!M->getModuleIdentifier().empty() &&
1136 // Don't print the ID if it will start a new line (which would
1137 // require a comment char before it).
1138 M->getModuleIdentifier().find('\n') == std::string::npos)
1139 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1141 if (!M->getDataLayout().empty())
1142 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1143 if (!M->getTargetTriple().empty())
1144 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1146 if (!M->getModuleInlineAsm().empty()) {
1147 // Split the string into lines, to make it easier to read the .ll file.
1148 std::string Asm = M->getModuleInlineAsm();
1150 size_t NewLine = Asm.find_first_of('\n', CurPos);
1151 while (NewLine != std::string::npos) {
1152 // We found a newline, print the portion of the asm string from the
1153 // last newline up to this newline.
1154 Out << "module asm \"";
1155 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1159 NewLine = Asm.find_first_of('\n', CurPos);
1161 Out << "module asm \"";
1162 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1166 // Loop over the dependent libraries and emit them.
1167 Module::lib_iterator LI = M->lib_begin();
1168 Module::lib_iterator LE = M->lib_end();
1170 Out << "deplibs = [ ";
1172 Out << '"' << *LI << '"';
1180 // Loop over the symbol table, emitting all named constants.
1181 printTypeSymbolTable(M->getTypeSymbolTable());
1183 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1187 // Output all aliases.
1188 if (!M->alias_empty()) Out << "\n";
1189 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1193 // Output all of the functions.
1194 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1198 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1200 case GlobalValue::InternalLinkage: Out << "internal "; break;
1201 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
1202 case GlobalValue::WeakLinkage: Out << "weak "; break;
1203 case GlobalValue::CommonLinkage: Out << "common "; break;
1204 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1205 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1206 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1207 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1208 case GlobalValue::ExternalLinkage: break;
1209 case GlobalValue::GhostLinkage:
1210 Out << "GhostLinkage not allowed in AsmWriter!\n";
1216 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1219 default: assert(0 && "Invalid visibility style!");
1220 case GlobalValue::DefaultVisibility: break;
1221 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1222 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1226 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1227 if (GV->hasName()) {
1228 PrintLLVMName(Out, GV);
1232 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1235 PrintLinkage(GV->getLinkage(), Out);
1236 PrintVisibility(GV->getVisibility(), Out);
1238 if (GV->isThreadLocal()) Out << "thread_local ";
1239 Out << (GV->isConstant() ? "constant " : "global ");
1240 printType(GV->getType()->getElementType());
1242 if (GV->hasInitializer())
1243 writeOperand(GV->getInitializer(), false);
1245 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1246 Out << " addrspace(" << AddressSpace << ") ";
1248 if (GV->hasSection())
1249 Out << ", section \"" << GV->getSection() << '"';
1250 if (GV->getAlignment())
1251 Out << ", align " << GV->getAlignment();
1253 printInfoComment(*GV);
1257 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1258 // Don't crash when dumping partially built GA
1260 Out << "<<nameless>> = ";
1262 PrintLLVMName(Out, GA);
1265 PrintVisibility(GA->getVisibility(), Out);
1269 PrintLinkage(GA->getLinkage(), Out);
1271 const Constant *Aliasee = GA->getAliasee();
1273 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1274 printType(GV->getType());
1276 PrintLLVMName(Out, GV);
1277 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1278 printType(F->getFunctionType());
1282 PrintLLVMName(Out, F);
1285 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1286 printType(GA->getType());
1288 PrintLLVMName(Out, GA);
1290 const ConstantExpr *CE = 0;
1291 if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
1292 (CE->getOpcode() == Instruction::BitCast)) {
1293 writeOperand(CE, false);
1295 assert(0 && "Unsupported aliasee");
1298 printInfoComment(*GA);
1302 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1304 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1307 PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1310 // Make sure we print out at least one level of the type structure, so
1311 // that we do not get %FILE = type %FILE
1313 printTypeAtLeastOneLevel(TI->second);
1318 /// printFunction - Print all aspects of a function.
1320 void AssemblyWriter::printFunction(const Function *F) {
1321 // Print out the return type and name.
1324 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1326 if (F->isDeclaration())
1331 PrintLinkage(F->getLinkage(), Out);
1332 PrintVisibility(F->getVisibility(), Out);
1334 // Print the calling convention.
1335 switch (F->getCallingConv()) {
1336 case CallingConv::C: break; // default
1337 case CallingConv::Fast: Out << "fastcc "; break;
1338 case CallingConv::Cold: Out << "coldcc "; break;
1339 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1340 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1341 case CallingConv::X86_SSECall: Out << "x86_ssecallcc "; break;
1342 default: Out << "cc" << F->getCallingConv() << " "; break;
1345 const FunctionType *FT = F->getFunctionType();
1346 const PAListPtr &Attrs = F->getParamAttrs();
1347 printType(F->getReturnType());
1350 PrintLLVMName(Out, F);
1354 Machine.incorporateFunction(F);
1356 // Loop over the arguments, printing them...
1359 if (!F->isDeclaration()) {
1360 // If this isn't a declaration, print the argument names as well.
1361 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1363 // Insert commas as we go... the first arg doesn't get a comma
1364 if (I != F->arg_begin()) Out << ", ";
1365 printArgument(I, Attrs.getParamAttrs(Idx));
1369 // Otherwise, print the types from the function type.
1370 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1371 // Insert commas as we go... the first arg doesn't get a comma
1375 printType(FT->getParamType(i));
1377 ParameterAttributes ArgAttrs = Attrs.getParamAttrs(i+1);
1378 if (ArgAttrs != ParamAttr::None)
1379 Out << ' ' << ParamAttr::getAsString(ArgAttrs);
1383 // Finish printing arguments...
1384 if (FT->isVarArg()) {
1385 if (FT->getNumParams()) Out << ", ";
1386 Out << "..."; // Output varargs portion of signature!
1389 ParameterAttributes RetAttrs = Attrs.getParamAttrs(0);
1390 if (RetAttrs != ParamAttr::None)
1391 Out << ' ' << ParamAttr::getAsString(Attrs.getParamAttrs(0));
1392 if (F->hasSection())
1393 Out << " section \"" << F->getSection() << '"';
1394 if (F->getAlignment())
1395 Out << " align " << F->getAlignment();
1397 Out << " gc \"" << F->getGC() << '"';
1399 if (F->isDeclaration()) {
1404 // Output all of its basic blocks... for the function
1405 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1411 Machine.purgeFunction();
1414 /// printArgument - This member is called for every argument that is passed into
1415 /// the function. Simply print it out
1417 void AssemblyWriter::printArgument(const Argument *Arg,
1418 ParameterAttributes Attrs) {
1420 printType(Arg->getType());
1422 // Output parameter attributes list
1423 if (Attrs != ParamAttr::None)
1424 Out << ' ' << ParamAttr::getAsString(Attrs);
1426 // Output name, if available...
1427 if (Arg->hasName()) {
1429 PrintLLVMName(Out, Arg);
1433 /// printBasicBlock - This member is called for each basic block in a method.
1435 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1436 if (BB->hasName()) { // Print out the label if it exists...
1438 PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1440 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1441 Out << "\n; <label>:";
1442 int Slot = Machine.getLocalSlot(BB);
1449 if (BB->getParent() == 0)
1450 Out << "\t\t; Error: Block without parent!";
1451 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1452 // Output predecessors for the block...
1454 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1457 Out << " No predecessors!";
1460 writeOperand(*PI, false);
1461 for (++PI; PI != PE; ++PI) {
1463 writeOperand(*PI, false);
1470 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1472 // Output all of the instructions in the basic block...
1473 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1474 printInstruction(*I);
1476 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1480 /// printInfoComment - Print a little comment after the instruction indicating
1481 /// which slot it occupies.
1483 void AssemblyWriter::printInfoComment(const Value &V) {
1484 if (V.getType() != Type::VoidTy) {
1486 printType(V.getType());
1491 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1492 SlotNum = Machine.getGlobalSlot(GV);
1494 SlotNum = Machine.getLocalSlot(&V);
1498 Out << ':' << SlotNum; // Print out the def slot taken.
1500 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1504 // This member is called for each Instruction in a function..
1505 void AssemblyWriter::printInstruction(const Instruction &I) {
1506 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1510 // Print out name if it exists...
1512 PrintLLVMName(Out, &I);
1516 // If this is a volatile load or store, print out the volatile marker.
1517 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1518 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1520 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1521 // If this is a call, check if it's a tail call.
1525 // Print out the opcode...
1526 Out << I.getOpcodeName();
1528 // Print out the compare instruction predicates
1529 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1530 Out << " " << getPredicateText(CI->getPredicate());
1532 // Print out the type of the operands...
1533 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1535 // Special case conditional branches to swizzle the condition out to the front
1536 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1537 writeOperand(I.getOperand(2), true);
1539 writeOperand(Operand, true);
1541 writeOperand(I.getOperand(1), true);
1543 } else if (isa<SwitchInst>(I)) {
1544 // Special case switch statement to get formatting nice and correct...
1545 writeOperand(Operand , true); Out << ',';
1546 writeOperand(I.getOperand(1), true); Out << " [";
1548 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1550 writeOperand(I.getOperand(op ), true); Out << ',';
1551 writeOperand(I.getOperand(op+1), true);
1554 } else if (isa<PHINode>(I)) {
1556 printType(I.getType());
1559 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1560 if (op) Out << ", ";
1562 writeOperand(I.getOperand(op ), false); Out << ',';
1563 writeOperand(I.getOperand(op+1), false); Out << " ]";
1565 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1566 writeOperand(I.getOperand(0), true);
1567 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1569 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1570 writeOperand(I.getOperand(0), true); Out << ',';
1571 writeOperand(I.getOperand(1), true);
1572 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1574 } else if (isa<ReturnInst>(I) && !Operand) {
1576 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1577 // Print the calling convention being used.
1578 switch (CI->getCallingConv()) {
1579 case CallingConv::C: break; // default
1580 case CallingConv::Fast: Out << " fastcc"; break;
1581 case CallingConv::Cold: Out << " coldcc"; break;
1582 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1583 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1584 case CallingConv::X86_SSECall: Out << " x86_ssecallcc"; break;
1585 default: Out << " cc" << CI->getCallingConv(); break;
1588 const PointerType *PTy = cast<PointerType>(Operand->getType());
1589 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1590 const Type *RetTy = FTy->getReturnType();
1591 const PAListPtr &PAL = CI->getParamAttrs();
1593 // If possible, print out the short form of the call instruction. We can
1594 // only do this if the first argument is a pointer to a nonvararg function,
1595 // and if the return type is not a pointer to a function.
1597 if (!FTy->isVarArg() &&
1598 (!isa<PointerType>(RetTy) ||
1599 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1600 Out << ' '; printType(RetTy);
1601 writeOperand(Operand, false);
1603 writeOperand(Operand, true);
1606 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1609 writeParamOperand(I.getOperand(op), PAL.getParamAttrs(op));
1612 if (PAL.getParamAttrs(0) != ParamAttr::None)
1613 Out << ' ' << ParamAttr::getAsString(PAL.getParamAttrs(0));
1614 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1615 const PointerType *PTy = cast<PointerType>(Operand->getType());
1616 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1617 const Type *RetTy = FTy->getReturnType();
1618 const PAListPtr &PAL = II->getParamAttrs();
1620 // Print the calling convention being used.
1621 switch (II->getCallingConv()) {
1622 case CallingConv::C: break; // default
1623 case CallingConv::Fast: Out << " fastcc"; break;
1624 case CallingConv::Cold: Out << " coldcc"; break;
1625 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1626 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1627 case CallingConv::X86_SSECall: Out << "x86_ssecallcc "; break;
1628 default: Out << " cc" << II->getCallingConv(); break;
1631 // If possible, print out the short form of the invoke instruction. We can
1632 // only do this if the first argument is a pointer to a nonvararg function,
1633 // and if the return type is not a pointer to a function.
1635 if (!FTy->isVarArg() &&
1636 (!isa<PointerType>(RetTy) ||
1637 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1638 Out << ' '; printType(RetTy);
1639 writeOperand(Operand, false);
1641 writeOperand(Operand, true);
1645 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1648 writeParamOperand(I.getOperand(op), PAL.getParamAttrs(op-2));
1652 if (PAL.getParamAttrs(0) != ParamAttr::None)
1653 Out << ' ' << ParamAttr::getAsString(PAL.getParamAttrs(0));
1654 Out << "\n\t\t\tto";
1655 writeOperand(II->getNormalDest(), true);
1657 writeOperand(II->getUnwindDest(), true);
1659 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1661 printType(AI->getType()->getElementType());
1662 if (AI->isArrayAllocation()) {
1664 writeOperand(AI->getArraySize(), true);
1666 if (AI->getAlignment()) {
1667 Out << ", align " << AI->getAlignment();
1669 } else if (isa<CastInst>(I)) {
1670 if (Operand) writeOperand(Operand, true); // Work with broken code
1672 printType(I.getType());
1673 } else if (isa<VAArgInst>(I)) {
1674 if (Operand) writeOperand(Operand, true); // Work with broken code
1676 printType(I.getType());
1677 } else if (Operand) { // Print the normal way...
1679 // PrintAllTypes - Instructions who have operands of all the same type
1680 // omit the type from all but the first operand. If the instruction has
1681 // different type operands (for example br), then they are all printed.
1682 bool PrintAllTypes = false;
1683 const Type *TheType = Operand->getType();
1685 // Select, Store and ShuffleVector always print all types.
1686 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1687 || isa<ReturnInst>(I)) {
1688 PrintAllTypes = true;
1690 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1691 Operand = I.getOperand(i);
1692 if (Operand->getType() != TheType) {
1693 PrintAllTypes = true; // We have differing types! Print them all!
1699 if (!PrintAllTypes) {
1704 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1706 writeOperand(I.getOperand(i), PrintAllTypes);
1710 // Print post operand alignment for load/store
1711 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1712 Out << ", align " << cast<LoadInst>(I).getAlignment();
1713 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1714 Out << ", align " << cast<StoreInst>(I).getAlignment();
1717 printInfoComment(I);
1722 //===----------------------------------------------------------------------===//
1723 // External Interface declarations
1724 //===----------------------------------------------------------------------===//
1726 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1727 raw_os_ostream OS(o);
1730 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1731 SlotTracker SlotTable(this);
1732 AssemblyWriter W(OS, SlotTable, this, AAW);
1736 void Type::print(std::ostream &o) const {
1737 raw_os_ostream OS(o);
1741 void Type::print(raw_ostream &o) const {
1745 o << getDescription();
1748 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1750 OS << "printing a <null> value\n";
1754 if (const Instruction *I = dyn_cast<Instruction>(this)) {
1755 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1756 SlotTracker SlotTable(F);
1757 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1759 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1760 SlotTracker SlotTable(BB->getParent());
1761 AssemblyWriter W(OS, SlotTable,
1762 BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1764 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1765 SlotTracker SlotTable(GV->getParent());
1766 AssemblyWriter W(OS, SlotTable, GV->getParent(), 0);
1768 } else if (const Constant *C = dyn_cast<Constant>(this)) {
1769 OS << ' ' << C->getType()->getDescription() << ' ';
1770 std::map<const Type *, std::string> TypeTable;
1771 WriteConstantInt(OS, C, TypeTable, 0);
1772 } else if (const Argument *A = dyn_cast<Argument>(this)) {
1773 WriteAsOperand(OS, this, true,
1774 A->getParent() ? A->getParent()->getParent() : 0);
1775 } else if (isa<InlineAsm>(this)) {
1776 WriteAsOperand(OS, this, true, 0);
1778 assert(0 && "Unknown value to print out!");
1782 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
1783 raw_os_ostream OS(O);
1787 // Value::dump - allow easy printing of Values from the debugger.
1788 // Located here because so much of the needed functionality is here.
1789 void Value::dump() const { print(errs()); errs() << '\n'; }
1791 // Type::dump - allow easy printing of Values from the debugger.
1792 // Located here because so much of the needed functionality is here.
1793 void Type::dump() const { print(errs()); errs() << '\n'; }
1795 // Module::dump() - Allow printing from debugger
1796 void Module::dump() const { print(errs(), 0); }