1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // This library implements the functionality defined in llvm/Assembly/Writer.h
5 // Note that these routines must be extremely tolerant of various errors in the
6 // LLVM code, because it can be used for debugging transformations.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Assembly/CachedWriter.h"
11 #include "llvm/Assembly/Writer.h"
12 #include "llvm/Assembly/PrintModulePass.h"
13 #include "llvm/SlotCalculator.h"
14 #include "llvm/DerivedTypes.h"
15 #include "llvm/Instruction.h"
16 #include "llvm/Module.h"
17 #include "llvm/Constants.h"
18 #include "llvm/iMemory.h"
19 #include "llvm/iTerminators.h"
20 #include "llvm/iPHINode.h"
21 #include "llvm/iOther.h"
22 #include "llvm/SymbolTable.h"
23 #include "llvm/Support/CFG.h"
24 #include "Support/StringExtras.h"
25 #include "Support/STLExtras.h"
28 static RegisterPass<PrintModulePass>
29 X("printm", "Print module to stderr",PassInfo::Analysis|PassInfo::Optimization);
30 static RegisterPass<PrintFunctionPass>
31 Y("print","Print function to stderr",PassInfo::Analysis|PassInfo::Optimization);
33 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
35 std::map<const Type *, std::string> &TypeTable,
36 SlotCalculator *Table);
38 static const Module *getModuleFromVal(const Value *V) {
39 if (const Argument *MA = dyn_cast<Argument>(V))
40 return MA->getParent() ? MA->getParent()->getParent() : 0;
41 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
42 return BB->getParent() ? BB->getParent()->getParent() : 0;
43 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
44 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
45 return M ? M->getParent() : 0;
46 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
47 return GV->getParent();
51 static SlotCalculator *createSlotCalculator(const Value *V) {
52 assert(!isa<Type>(V) && "Can't create an SC for a type!");
53 if (const Argument *FA = dyn_cast<Argument>(V)) {
54 return new SlotCalculator(FA->getParent(), true);
55 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
56 return new SlotCalculator(I->getParent()->getParent(), true);
57 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
58 return new SlotCalculator(BB->getParent(), true);
59 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
60 return new SlotCalculator(GV->getParent(), true);
61 } else if (const Function *Func = dyn_cast<Function>(V)) {
62 return new SlotCalculator(Func, true);
68 // If the module has a symbol table, take all global types and stuff their
69 // names into the TypeNames map.
71 static void fillTypeNameTable(const Module *M,
72 std::map<const Type *, std::string> &TypeNames) {
74 const SymbolTable &ST = M->getSymbolTable();
75 SymbolTable::const_iterator PI = ST.find(Type::TypeTy);
77 SymbolTable::type_const_iterator I = PI->second.begin();
78 for (; I != PI->second.end(); ++I) {
79 // As a heuristic, don't insert pointer to primitive types, because
80 // they are used too often to have a single useful name.
82 const Type *Ty = cast<Type>(I->second);
83 if (!isa<PointerType>(Ty) ||
84 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType())
85 TypeNames.insert(std::make_pair(Ty, "%"+I->first));
92 static std::string calcTypeName(const Type *Ty,
93 std::vector<const Type *> &TypeStack,
94 std::map<const Type *, std::string> &TypeNames){
95 if (Ty->isPrimitiveType()) return Ty->getDescription(); // Base case
97 // Check to see if the type is named.
98 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
99 if (I != TypeNames.end()) return I->second;
101 // Check to see if the Type is already on the stack...
102 unsigned Slot = 0, CurSize = TypeStack.size();
103 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
105 // This is another base case for the recursion. In this case, we know
106 // that we have looped back to a type that we have previously visited.
107 // Generate the appropriate upreference to handle this.
110 return "\\" + utostr(CurSize-Slot); // Here's the upreference
112 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
115 switch (Ty->getPrimitiveID()) {
116 case Type::FunctionTyID: {
117 const FunctionType *FTy = cast<FunctionType>(Ty);
118 Result = calcTypeName(FTy->getReturnType(), TypeStack, TypeNames) + " (";
119 for (FunctionType::ParamTypes::const_iterator
120 I = FTy->getParamTypes().begin(),
121 E = FTy->getParamTypes().end(); I != E; ++I) {
122 if (I != FTy->getParamTypes().begin())
124 Result += calcTypeName(*I, TypeStack, TypeNames);
126 if (FTy->isVarArg()) {
127 if (!FTy->getParamTypes().empty()) Result += ", ";
133 case Type::StructTyID: {
134 const StructType *STy = cast<StructType>(Ty);
136 for (StructType::ElementTypes::const_iterator
137 I = STy->getElementTypes().begin(),
138 E = STy->getElementTypes().end(); I != E; ++I) {
139 if (I != STy->getElementTypes().begin())
141 Result += calcTypeName(*I, TypeStack, TypeNames);
146 case Type::PointerTyID:
147 Result = calcTypeName(cast<PointerType>(Ty)->getElementType(),
148 TypeStack, TypeNames) + "*";
150 case Type::ArrayTyID: {
151 const ArrayType *ATy = cast<ArrayType>(Ty);
152 Result = "[" + utostr(ATy->getNumElements()) + " x ";
153 Result += calcTypeName(ATy->getElementType(), TypeStack, TypeNames) + "]";
156 case Type::OpaqueTyID:
160 Result = "<unrecognized-type>";
163 TypeStack.pop_back(); // Remove self from stack...
168 // printTypeInt - The internal guts of printing out a type that has a
169 // potentially named portion.
171 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
172 std::map<const Type *, std::string> &TypeNames) {
173 // Primitive types always print out their description, regardless of whether
174 // they have been named or not.
176 if (Ty->isPrimitiveType()) return Out << Ty->getDescription();
178 // Check to see if the type is named.
179 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
180 if (I != TypeNames.end()) return Out << I->second;
182 // Otherwise we have a type that has not been named but is a derived type.
183 // Carefully recurse the type hierarchy to print out any contained symbolic
186 std::vector<const Type *> TypeStack;
187 std::string TypeName = calcTypeName(Ty, TypeStack, TypeNames);
188 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
189 return Out << TypeName;
193 // WriteTypeSymbolic - This attempts to write the specified type as a symbolic
194 // type, iff there is an entry in the modules symbol table for the specified
195 // type or one of it's component types. This is slower than a simple x << Type;
197 std::ostream &WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
201 // If they want us to print out a type, attempt to make it symbolic if there
202 // is a symbol table in the module...
204 std::map<const Type *, std::string> TypeNames;
205 fillTypeNameTable(M, TypeNames);
207 return printTypeInt(Out, Ty, TypeNames);
209 return Out << Ty->getDescription();
213 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
215 std::map<const Type *, std::string> &TypeTable,
216 SlotCalculator *Table) {
217 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
218 Out << (CB == ConstantBool::True ? "true" : "false");
219 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
220 Out << CI->getValue();
221 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
222 Out << CI->getValue();
223 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
224 // We would like to output the FP constant value in exponential notation,
225 // but we cannot do this if doing so will lose precision. Check here to
226 // make sure that we only output it in exponential format if we can parse
227 // the value back and get the same value.
229 std::string StrVal = ftostr(CFP->getValue());
231 // Check to make sure that the stringized number is not some string like
232 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
233 // the string matches the "[-+]?[0-9]" regex.
235 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
236 ((StrVal[0] == '-' || StrVal[0] == '+') &&
237 (StrVal[1] >= '0' && StrVal[1] <= '9')))
238 // Reparse stringized version!
239 if (atof(StrVal.c_str()) == CFP->getValue()) {
240 Out << StrVal; return;
243 // Otherwise we could not reparse it to exactly the same value, so we must
244 // output the string in hexadecimal format!
246 // Behave nicely in the face of C TBAA rules... see:
247 // http://www.nullstone.com/htmls/category/aliastyp.htm
249 double Val = CFP->getValue();
250 char *Ptr = (char*)&Val;
251 assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
252 "assuming that double is 64 bits!");
253 Out << "0x" << utohexstr(*(uint64_t*)Ptr);
255 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
256 if (CA->getNumOperands() > 5 && CA->isNullValue()) {
257 Out << "zeroinitializer";
261 // As a special case, print the array as a string if it is an array of
262 // ubytes or an array of sbytes with positive values.
264 const Type *ETy = CA->getType()->getElementType();
265 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
267 if (ETy == Type::SByteTy)
268 for (unsigned i = 0; i < CA->getNumOperands(); ++i)
269 if (cast<ConstantSInt>(CA->getOperand(i))->getValue() < 0) {
276 for (unsigned i = 0; i < CA->getNumOperands(); ++i) {
277 unsigned char C = cast<ConstantInt>(CA->getOperand(i))->getRawValue();
279 if (isprint(C) && C != '"' && C != '\\') {
283 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
284 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
289 } else { // Cannot output in string format...
291 if (CA->getNumOperands()) {
293 printTypeInt(Out, ETy, TypeTable);
294 WriteAsOperandInternal(Out, CA->getOperand(0),
295 PrintName, TypeTable, Table);
296 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
298 printTypeInt(Out, ETy, TypeTable);
299 WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
305 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
306 if (CS->getNumOperands() > 5 && CS->isNullValue()) {
307 Out << "zeroinitializer";
312 if (CS->getNumOperands()) {
314 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
316 WriteAsOperandInternal(Out, CS->getOperand(0),
317 PrintName, TypeTable, Table);
319 for (unsigned i = 1; i < CS->getNumOperands(); i++) {
321 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
323 WriteAsOperandInternal(Out, CS->getOperand(i),
324 PrintName, TypeTable, Table);
329 } else if (isa<ConstantPointerNull>(CV)) {
332 } else if (const ConstantPointerRef *PR = dyn_cast<ConstantPointerRef>(CV)) {
333 const GlobalValue *V = PR->getValue();
335 Out << "%" << V->getName();
337 int Slot = Table->getValSlot(V);
341 Out << "<pointer reference badref>";
343 Out << "<pointer reference without context info>";
346 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
347 Out << CE->getOpcodeName() << " (";
349 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
350 printTypeInt(Out, (*OI)->getType(), TypeTable);
351 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Table);
352 if (OI+1 != CE->op_end())
356 if (CE->getOpcode() == Instruction::Cast) {
358 printTypeInt(Out, CE->getType(), TypeTable);
363 Out << "<placeholder or erroneous Constant>";
368 // WriteAsOperand - Write the name of the specified value out to the specified
369 // ostream. This can be useful when you just want to print int %reg126, not the
370 // whole instruction that generated it.
372 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
374 std::map<const Type*, std::string> &TypeTable,
375 SlotCalculator *Table) {
377 if (PrintName && V->hasName()) {
378 Out << "%" << V->getName();
380 if (const Constant *CV = dyn_cast<Constant>(V)) {
381 WriteConstantInt(Out, CV, PrintName, TypeTable, Table);
385 Slot = Table->getValSlot(V);
387 if (const Type *Ty = dyn_cast<Type>(V)) {
388 Out << Ty->getDescription();
392 Table = createSlotCalculator(V);
393 if (Table == 0) { Out << "BAD VALUE TYPE!"; return; }
395 Slot = Table->getValSlot(V);
398 if (Slot >= 0) Out << "%" << Slot;
400 Out << "<badref>"; // Not embeded into a location?
407 // WriteAsOperand - Write the name of the specified value out to the specified
408 // ostream. This can be useful when you just want to print int %reg126, not the
409 // whole instruction that generated it.
411 std::ostream &WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
412 bool PrintName, const Module *Context) {
413 std::map<const Type *, std::string> TypeNames;
414 if (Context == 0) Context = getModuleFromVal(V);
417 fillTypeNameTable(Context, TypeNames);
420 printTypeInt(Out, V->getType(), TypeNames);
422 WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
428 class AssemblyWriter {
430 SlotCalculator &Table;
431 const Module *TheModule;
432 std::map<const Type *, std::string> TypeNames;
434 inline AssemblyWriter(std::ostream &o, SlotCalculator &Tab, const Module *M)
435 : Out(o), Table(Tab), TheModule(M) {
437 // If the module has a symbol table, take all global types and stuff their
438 // names into the TypeNames map.
440 fillTypeNameTable(M, TypeNames);
443 inline void write(const Module *M) { printModule(M); }
444 inline void write(const GlobalVariable *G) { printGlobal(G); }
445 inline void write(const Function *F) { printFunction(F); }
446 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
447 inline void write(const Instruction *I) { printInstruction(*I); }
448 inline void write(const Constant *CPV) { printConstant(CPV); }
449 inline void write(const Type *Ty) { printType(Ty); }
451 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
454 void printModule(const Module *M);
455 void printSymbolTable(const SymbolTable &ST);
456 void printConstant(const Constant *CPV);
457 void printGlobal(const GlobalVariable *GV);
458 void printFunction(const Function *F);
459 void printArgument(const Argument *FA);
460 void printBasicBlock(const BasicBlock *BB);
461 void printInstruction(const Instruction &I);
463 // printType - Go to extreme measures to attempt to print out a short,
464 // symbolic version of a type name.
466 std::ostream &printType(const Type *Ty) {
467 return printTypeInt(Out, Ty, TypeNames);
470 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
471 // without considering any symbolic types that we may have equal to it.
473 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
475 // printInfoComment - Print a little comment after the instruction indicating
476 // which slot it occupies.
477 void printInfoComment(const Value &V);
481 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
482 // without considering any symbolic types that we may have equal to it.
484 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
485 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
486 printType(FTy->getReturnType()) << " (";
487 for (FunctionType::ParamTypes::const_iterator
488 I = FTy->getParamTypes().begin(),
489 E = FTy->getParamTypes().end(); I != E; ++I) {
490 if (I != FTy->getParamTypes().begin())
494 if (FTy->isVarArg()) {
495 if (!FTy->getParamTypes().empty()) Out << ", ";
499 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
501 for (StructType::ElementTypes::const_iterator
502 I = STy->getElementTypes().begin(),
503 E = STy->getElementTypes().end(); I != E; ++I) {
504 if (I != STy->getElementTypes().begin())
509 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
510 printType(PTy->getElementType()) << "*";
511 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
512 Out << "[" << ATy->getNumElements() << " x ";
513 printType(ATy->getElementType()) << "]";
514 } else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
517 if (!Ty->isPrimitiveType())
518 Out << "<unknown derived type>";
525 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
527 if (PrintType) { Out << " "; printType(Operand->getType()); }
528 WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Table);
532 void AssemblyWriter::printModule(const Module *M) {
533 Out << "target endian = " << (M->isLittleEndian() ? "little" : "big") << "\n";
534 Out << "target pointersize = " << (M->has32BitPointers() ? 32 : 64) << "\n";
536 // Loop over the symbol table, emitting all named constants...
537 printSymbolTable(M->getSymbolTable());
539 for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
542 Out << "\nimplementation ; Functions:\n";
544 // Output all of the functions...
545 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
549 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
550 if (GV->hasName()) Out << "%" << GV->getName() << " = ";
552 if (!GV->hasInitializer())
555 switch (GV->getLinkage()) {
556 case GlobalValue::InternalLinkage: Out << "internal "; break;
557 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
558 case GlobalValue::AppendingLinkage: Out << "appending "; break;
559 case GlobalValue::ExternalLinkage: break;
562 Out << (GV->isConstant() ? "constant " : "global ");
563 printType(GV->getType()->getElementType());
565 if (GV->hasInitializer())
566 writeOperand(GV->getInitializer(), false, false);
568 printInfoComment(*GV);
573 // printSymbolTable - Run through symbol table looking for named constants
574 // if a named constant is found, emit it's declaration...
576 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
577 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
578 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
579 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
581 for (; I != End; ++I) {
582 const Value *V = I->second;
583 if (const Constant *CPV = dyn_cast<Constant>(V)) {
585 } else if (const Type *Ty = dyn_cast<Type>(V)) {
586 Out << "\t%" << I->first << " = type ";
588 // Make sure we print out at least one level of the type structure, so
589 // that we do not get %FILE = type %FILE
591 printTypeAtLeastOneLevel(Ty) << "\n";
598 // printConstant - Print out a constant pool entry...
600 void AssemblyWriter::printConstant(const Constant *CPV) {
601 // Don't print out unnamed constants, they will be inlined
602 if (!CPV->hasName()) return;
605 Out << "\t%" << CPV->getName() << " =";
607 // Write the value out now...
608 writeOperand(CPV, true, false);
610 printInfoComment(*CPV);
614 // printFunction - Print all aspects of a function.
616 void AssemblyWriter::printFunction(const Function *F) {
617 // Print out the return type and name...
623 switch (F->getLinkage()) {
624 case GlobalValue::InternalLinkage: Out << "internal "; break;
625 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
626 case GlobalValue::AppendingLinkage: Out << "appending "; break;
627 case GlobalValue::ExternalLinkage: break;
630 printType(F->getReturnType()) << " %" << F->getName() << "(";
631 Table.incorporateFunction(F);
633 // Loop over the arguments, printing them...
634 const FunctionType *FT = F->getFunctionType();
636 for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
639 // Finish printing arguments...
640 if (FT->isVarArg()) {
641 if (FT->getParamTypes().size()) Out << ", ";
642 Out << "..."; // Output varargs portion of signature!
646 if (F->isExternal()) {
651 // Output all of its basic blocks... for the function
652 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
658 Table.purgeFunction();
661 // printArgument - This member is called for every argument that
662 // is passed into the function. Simply print it out
664 void AssemblyWriter::printArgument(const Argument *Arg) {
665 // Insert commas as we go... the first arg doesn't get a comma
666 if (Arg != &Arg->getParent()->afront()) Out << ", ";
669 printType(Arg->getType());
671 // Output name, if available...
673 Out << " %" << Arg->getName();
674 else if (Table.getValSlot(Arg) < 0)
678 // printBasicBlock - This member is called for each basic block in a methd.
680 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
681 if (BB->hasName()) { // Print out the label if it exists...
682 Out << "\n" << BB->getName() << ":";
683 } else if (!BB->use_empty()) { // Don't print block # of no uses...
684 int Slot = Table.getValSlot(BB);
685 Out << "\n; <label>:";
687 Out << Slot; // Extra newline separates out label's
692 // Output predecessors for the block...
694 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
697 Out << " No predecessors!";
700 writeOperand(*PI, false, true);
701 for (++PI; PI != PE; ++PI) {
703 writeOperand(*PI, false, true);
709 // Output all of the instructions in the basic block...
710 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
711 printInstruction(*I);
715 // printInfoComment - Print a little comment after the instruction indicating
716 // which slot it occupies.
718 void AssemblyWriter::printInfoComment(const Value &V) {
719 if (V.getType() != Type::VoidTy) {
721 printType(V.getType()) << ">";
724 int Slot = Table.getValSlot(&V); // Print out the def slot taken...
725 if (Slot >= 0) Out << ":" << Slot;
726 else Out << ":<badref>";
728 Out << " [#uses=" << V.use_size() << "]"; // Output # uses
732 // printInstruction - This member is called for each Instruction in a methd.
734 void AssemblyWriter::printInstruction(const Instruction &I) {
737 // Print out name if it exists...
739 Out << "%" << I.getName() << " = ";
741 // Print out the opcode...
742 Out << I.getOpcodeName();
744 // Print out the type of the operands...
745 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
747 // Special case conditional branches to swizzle the condition out to the front
748 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
749 writeOperand(I.getOperand(2), true);
751 writeOperand(Operand, true);
753 writeOperand(I.getOperand(1), true);
755 } else if (isa<SwitchInst>(I)) {
756 // Special case switch statement to get formatting nice and correct...
757 writeOperand(Operand , true); Out << ",";
758 writeOperand(I.getOperand(1), true); Out << " [";
760 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
762 writeOperand(I.getOperand(op ), true); Out << ",";
763 writeOperand(I.getOperand(op+1), true);
766 } else if (isa<PHINode>(I)) {
768 printType(I.getType());
771 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
774 writeOperand(I.getOperand(op ), false); Out << ",";
775 writeOperand(I.getOperand(op+1), false); Out << " ]";
777 } else if (isa<ReturnInst>(I) && !Operand) {
779 } else if (isa<CallInst>(I)) {
780 const PointerType *PTy = cast<PointerType>(Operand->getType());
781 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
782 const Type *RetTy = FTy->getReturnType();
784 // If possible, print out the short form of the call instruction. We can
785 // only do this if the first argument is a pointer to a nonvararg function,
786 // and if the return type is not a pointer to a function.
788 if (!FTy->isVarArg() &&
789 (!isa<PointerType>(RetTy) ||
790 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
791 Out << " "; printType(RetTy);
792 writeOperand(Operand, false);
794 writeOperand(Operand, true);
797 if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
798 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
800 writeOperand(I.getOperand(op), true);
804 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
805 const PointerType *PTy = cast<PointerType>(Operand->getType());
806 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
807 const Type *RetTy = FTy->getReturnType();
809 // If possible, print out the short form of the invoke instruction. We can
810 // only do this if the first argument is a pointer to a nonvararg function,
811 // and if the return type is not a pointer to a function.
813 if (!FTy->isVarArg() &&
814 (!isa<PointerType>(RetTy) ||
815 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
816 Out << " "; printType(RetTy);
817 writeOperand(Operand, false);
819 writeOperand(Operand, true);
823 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
824 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
826 writeOperand(I.getOperand(op), true);
829 Out << " )\n\t\t\tto";
830 writeOperand(II->getNormalDest(), true);
832 writeOperand(II->getExceptionalDest(), true);
834 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
836 printType(AI->getType()->getElementType());
837 if (AI->isArrayAllocation()) {
839 writeOperand(AI->getArraySize(), true);
841 } else if (isa<CastInst>(I)) {
842 writeOperand(Operand, true);
844 printType(I.getType());
845 } else if (isa<VarArgInst>(I)) {
846 writeOperand(Operand, true);
848 printType(I.getType());
849 } else if (Operand) { // Print the normal way...
851 // PrintAllTypes - Instructions who have operands of all the same type
852 // omit the type from all but the first operand. If the instruction has
853 // different type operands (for example br), then they are all printed.
854 bool PrintAllTypes = false;
855 const Type *TheType = Operand->getType();
857 // Shift Left & Right print both types even for Ubyte LHS
858 if (isa<ShiftInst>(I)) {
859 PrintAllTypes = true;
861 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
862 Operand = I.getOperand(i);
863 if (Operand->getType() != TheType) {
864 PrintAllTypes = true; // We have differing types! Print them all!
870 if (!PrintAllTypes) {
875 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
877 writeOperand(I.getOperand(i), PrintAllTypes);
886 //===----------------------------------------------------------------------===//
887 // External Interface declarations
888 //===----------------------------------------------------------------------===//
891 void Module::print(std::ostream &o) const {
892 SlotCalculator SlotTable(this, true);
893 AssemblyWriter W(o, SlotTable, this);
897 void GlobalVariable::print(std::ostream &o) const {
898 SlotCalculator SlotTable(getParent(), true);
899 AssemblyWriter W(o, SlotTable, getParent());
903 void Function::print(std::ostream &o) const {
904 SlotCalculator SlotTable(getParent(), true);
905 AssemblyWriter W(o, SlotTable, getParent());
910 void BasicBlock::print(std::ostream &o) const {
911 SlotCalculator SlotTable(getParent(), true);
912 AssemblyWriter W(o, SlotTable,
913 getParent() ? getParent()->getParent() : 0);
917 void Instruction::print(std::ostream &o) const {
918 const Function *F = getParent() ? getParent()->getParent() : 0;
919 SlotCalculator SlotTable(F, true);
920 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0);
925 void Constant::print(std::ostream &o) const {
926 if (this == 0) { o << "<null> constant value\n"; return; }
928 // Handle CPR's special, because they have context information...
929 if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
930 CPR->getValue()->print(o); // Print as a global value, with context info.
934 o << " " << getType()->getDescription() << " ";
936 std::map<const Type *, std::string> TypeTable;
937 WriteConstantInt(o, this, false, TypeTable, 0);
940 void Type::print(std::ostream &o) const {
944 o << getDescription();
947 void Argument::print(std::ostream &o) const {
948 o << getType() << " " << getName();
951 void Value::dump() const { print(std::cerr); }
953 //===----------------------------------------------------------------------===//
954 // CachedWriter Class Implementation
955 //===----------------------------------------------------------------------===//
957 void CachedWriter::setModule(const Module *M) {
958 delete SC; delete AW;
960 SC = new SlotCalculator(M, true);
961 AW = new AssemblyWriter(Out, *SC, M);
967 CachedWriter::~CachedWriter() {
972 CachedWriter &CachedWriter::operator<<(const Value *V) {
973 assert(AW && SC && "CachedWriter does not have a current module!");
974 switch (V->getValueType()) {
975 case Value::ConstantVal:
976 case Value::ArgumentVal: AW->writeOperand(V, true, true); break;
977 case Value::TypeVal: AW->write(cast<Type>(V)); break;
978 case Value::InstructionVal: AW->write(cast<Instruction>(V)); break;
979 case Value::BasicBlockVal: AW->write(cast<BasicBlock>(V)); break;
980 case Value::FunctionVal: AW->write(cast<Function>(V)); break;
981 case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
982 default: Out << "<unknown value type: " << V->getValueType() << ">"; break;