1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/CachedWriter.h"
18 #include "llvm/Assembly/Writer.h"
19 #include "llvm/Assembly/PrintModulePass.h"
20 #include "llvm/SlotCalculator.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Instruction.h"
23 #include "llvm/Module.h"
24 #include "llvm/Constants.h"
25 #include "llvm/iMemory.h"
26 #include "llvm/iTerminators.h"
27 #include "llvm/iPHINode.h"
28 #include "llvm/iOther.h"
29 #include "llvm/SymbolTable.h"
30 #include "llvm/Support/CFG.h"
31 #include "Support/StringExtras.h"
32 #include "Support/STLExtras.h"
35 static RegisterPass<PrintModulePass>
36 X("printm", "Print module to stderr",PassInfo::Analysis|PassInfo::Optimization);
37 static RegisterPass<PrintFunctionPass>
38 Y("print","Print function to stderr",PassInfo::Analysis|PassInfo::Optimization);
40 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
42 std::map<const Type *, std::string> &TypeTable,
43 SlotCalculator *Table);
45 static const Module *getModuleFromVal(const Value *V) {
46 if (const Argument *MA = dyn_cast<Argument>(V))
47 return MA->getParent() ? MA->getParent()->getParent() : 0;
48 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
49 return BB->getParent() ? BB->getParent()->getParent() : 0;
50 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
51 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
52 return M ? M->getParent() : 0;
53 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
54 return GV->getParent();
58 static SlotCalculator *createSlotCalculator(const Value *V) {
59 assert(!isa<Type>(V) && "Can't create an SC for a type!");
60 if (const Argument *FA = dyn_cast<Argument>(V)) {
61 return new SlotCalculator(FA->getParent(), true);
62 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
63 return new SlotCalculator(I->getParent()->getParent(), true);
64 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
65 return new SlotCalculator(BB->getParent(), true);
66 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
67 return new SlotCalculator(GV->getParent(), true);
68 } else if (const Function *Func = dyn_cast<Function>(V)) {
69 return new SlotCalculator(Func, true);
74 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
75 // prefixed with % (if the string only contains simple characters) or is
76 // surrounded with ""'s (if it has special chars in it).
77 static std::string getLLVMName(const std::string &Name) {
78 assert(!Name.empty() && "Cannot get empty name!");
80 // First character cannot start with a number...
81 if (Name[0] >= '0' && Name[0] <= '9')
82 return "\"" + Name + "\"";
84 // Scan to see if we have any characters that are not on the "white list"
85 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
87 assert(C != '"' && "Illegal character in LLVM value name!");
88 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
89 C != '-' && C != '.' && C != '_')
90 return "\"" + Name + "\"";
93 // If we get here, then the identifier is legal to use as a "VarID".
98 // If the module has a symbol table, take all global types and stuff their
99 // names into the TypeNames map.
101 static void fillTypeNameTable(const Module *M,
102 std::map<const Type *, std::string> &TypeNames) {
104 const SymbolTable &ST = M->getSymbolTable();
105 SymbolTable::const_iterator PI = ST.find(Type::TypeTy);
106 if (PI != ST.end()) {
107 SymbolTable::type_const_iterator I = PI->second.begin();
108 for (; I != PI->second.end(); ++I) {
109 // As a heuristic, don't insert pointer to primitive types, because
110 // they are used too often to have a single useful name.
112 const Type *Ty = cast<Type>(I->second);
113 if (!isa<PointerType>(Ty) ||
114 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType())
115 TypeNames.insert(std::make_pair(Ty, getLLVMName(I->first)));
122 static std::string calcTypeName(const Type *Ty,
123 std::vector<const Type *> &TypeStack,
124 std::map<const Type *, std::string> &TypeNames){
125 if (Ty->isPrimitiveType()) return Ty->getDescription(); // Base case
127 // Check to see if the type is named.
128 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
129 if (I != TypeNames.end()) return I->second;
131 // Check to see if the Type is already on the stack...
132 unsigned Slot = 0, CurSize = TypeStack.size();
133 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
135 // This is another base case for the recursion. In this case, we know
136 // that we have looped back to a type that we have previously visited.
137 // Generate the appropriate upreference to handle this.
140 return "\\" + utostr(CurSize-Slot); // Here's the upreference
142 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
145 switch (Ty->getPrimitiveID()) {
146 case Type::FunctionTyID: {
147 const FunctionType *FTy = cast<FunctionType>(Ty);
148 Result = calcTypeName(FTy->getReturnType(), TypeStack, TypeNames) + " (";
149 for (FunctionType::ParamTypes::const_iterator
150 I = FTy->getParamTypes().begin(),
151 E = FTy->getParamTypes().end(); I != E; ++I) {
152 if (I != FTy->getParamTypes().begin())
154 Result += calcTypeName(*I, TypeStack, TypeNames);
156 if (FTy->isVarArg()) {
157 if (!FTy->getParamTypes().empty()) Result += ", ";
163 case Type::StructTyID: {
164 const StructType *STy = cast<StructType>(Ty);
166 for (StructType::ElementTypes::const_iterator
167 I = STy->getElementTypes().begin(),
168 E = STy->getElementTypes().end(); I != E; ++I) {
169 if (I != STy->getElementTypes().begin())
171 Result += calcTypeName(*I, TypeStack, TypeNames);
176 case Type::PointerTyID:
177 Result = calcTypeName(cast<PointerType>(Ty)->getElementType(),
178 TypeStack, TypeNames) + "*";
180 case Type::ArrayTyID: {
181 const ArrayType *ATy = cast<ArrayType>(Ty);
182 Result = "[" + utostr(ATy->getNumElements()) + " x ";
183 Result += calcTypeName(ATy->getElementType(), TypeStack, TypeNames) + "]";
186 case Type::OpaqueTyID:
190 Result = "<unrecognized-type>";
193 TypeStack.pop_back(); // Remove self from stack...
198 // printTypeInt - The internal guts of printing out a type that has a
199 // potentially named portion.
201 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
202 std::map<const Type *, std::string> &TypeNames) {
203 // Primitive types always print out their description, regardless of whether
204 // they have been named or not.
206 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
207 return Out << Ty->getDescription();
209 // Check to see if the type is named.
210 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
211 if (I != TypeNames.end()) return Out << I->second;
213 if (isa<OpaqueType>(Ty))
214 return Out << "opaque";
216 // Otherwise we have a type that has not been named but is a derived type.
217 // Carefully recurse the type hierarchy to print out any contained symbolic
220 std::vector<const Type *> TypeStack;
221 std::string TypeName = calcTypeName(Ty, TypeStack, TypeNames);
222 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
223 return Out << TypeName;
227 // WriteTypeSymbolic - This attempts to write the specified type as a symbolic
228 // type, iff there is an entry in the modules symbol table for the specified
229 // type or one of it's component types. This is slower than a simple x << Type;
231 std::ostream &WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
235 // If they want us to print out a type, attempt to make it symbolic if there
236 // is a symbol table in the module...
238 std::map<const Type *, std::string> TypeNames;
239 fillTypeNameTable(M, TypeNames);
241 return printTypeInt(Out, Ty, TypeNames);
243 return Out << Ty->getDescription();
247 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
249 std::map<const Type *, std::string> &TypeTable,
250 SlotCalculator *Table) {
251 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
252 Out << (CB == ConstantBool::True ? "true" : "false");
253 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
254 Out << CI->getValue();
255 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
256 Out << CI->getValue();
257 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
258 // We would like to output the FP constant value in exponential notation,
259 // but we cannot do this if doing so will lose precision. Check here to
260 // make sure that we only output it in exponential format if we can parse
261 // the value back and get the same value.
263 std::string StrVal = ftostr(CFP->getValue());
265 // Check to make sure that the stringized number is not some string like
266 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
267 // the string matches the "[-+]?[0-9]" regex.
269 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
270 ((StrVal[0] == '-' || StrVal[0] == '+') &&
271 (StrVal[1] >= '0' && StrVal[1] <= '9')))
272 // Reparse stringized version!
273 if (atof(StrVal.c_str()) == CFP->getValue()) {
274 Out << StrVal; return;
277 // Otherwise we could not reparse it to exactly the same value, so we must
278 // output the string in hexadecimal format!
280 // Behave nicely in the face of C TBAA rules... see:
281 // http://www.nullstone.com/htmls/category/aliastyp.htm
283 double Val = CFP->getValue();
284 char *Ptr = (char*)&Val;
285 assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
286 "assuming that double is 64 bits!");
287 Out << "0x" << utohexstr(*(uint64_t*)Ptr);
289 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
290 if (CA->getNumOperands() > 5 && CA->isNullValue()) {
291 Out << "zeroinitializer";
295 // As a special case, print the array as a string if it is an array of
296 // ubytes or an array of sbytes with positive values.
298 const Type *ETy = CA->getType()->getElementType();
299 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
301 if (ETy == Type::SByteTy)
302 for (unsigned i = 0; i < CA->getNumOperands(); ++i)
303 if (cast<ConstantSInt>(CA->getOperand(i))->getValue() < 0) {
310 for (unsigned i = 0; i < CA->getNumOperands(); ++i) {
311 unsigned char C = cast<ConstantInt>(CA->getOperand(i))->getRawValue();
313 if (isprint(C) && C != '"' && C != '\\') {
317 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
318 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
323 } else { // Cannot output in string format...
325 if (CA->getNumOperands()) {
327 printTypeInt(Out, ETy, TypeTable);
328 WriteAsOperandInternal(Out, CA->getOperand(0),
329 PrintName, TypeTable, Table);
330 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
332 printTypeInt(Out, ETy, TypeTable);
333 WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
339 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
340 if (CS->getNumOperands() > 5 && CS->isNullValue()) {
341 Out << "zeroinitializer";
346 if (CS->getNumOperands()) {
348 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
350 WriteAsOperandInternal(Out, CS->getOperand(0),
351 PrintName, TypeTable, Table);
353 for (unsigned i = 1; i < CS->getNumOperands(); i++) {
355 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
357 WriteAsOperandInternal(Out, CS->getOperand(i),
358 PrintName, TypeTable, Table);
363 } else if (isa<ConstantPointerNull>(CV)) {
366 } else if (const ConstantPointerRef *PR = dyn_cast<ConstantPointerRef>(CV)) {
367 const GlobalValue *V = PR->getValue();
369 Out << getLLVMName(V->getName());
371 int Slot = Table->getSlot(V);
375 Out << "<pointer reference badref>";
377 Out << "<pointer reference without context info>";
380 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
381 Out << CE->getOpcodeName() << " (";
383 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
384 printTypeInt(Out, (*OI)->getType(), TypeTable);
385 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Table);
386 if (OI+1 != CE->op_end())
390 if (CE->getOpcode() == Instruction::Cast) {
392 printTypeInt(Out, CE->getType(), TypeTable);
397 Out << "<placeholder or erroneous Constant>";
402 // WriteAsOperand - Write the name of the specified value out to the specified
403 // ostream. This can be useful when you just want to print int %reg126, not the
404 // whole instruction that generated it.
406 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
408 std::map<const Type*, std::string> &TypeTable,
409 SlotCalculator *Table) {
411 if (PrintName && V->hasName()) {
412 Out << getLLVMName(V->getName());
414 if (const Constant *CV = dyn_cast<Constant>(V)) {
415 WriteConstantInt(Out, CV, PrintName, TypeTable, Table);
419 Slot = Table->getSlot(V);
421 if (const Type *Ty = dyn_cast<Type>(V)) {
422 Out << Ty->getDescription();
426 Table = createSlotCalculator(V);
427 if (Table == 0) { Out << "BAD VALUE TYPE!"; return; }
429 Slot = Table->getSlot(V);
432 if (Slot >= 0) Out << "%" << Slot;
434 Out << "<badref>"; // Not embedded into a location?
441 // WriteAsOperand - Write the name of the specified value out to the specified
442 // ostream. This can be useful when you just want to print int %reg126, not the
443 // whole instruction that generated it.
445 std::ostream &WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
446 bool PrintName, const Module *Context) {
447 std::map<const Type *, std::string> TypeNames;
448 if (Context == 0) Context = getModuleFromVal(V);
451 fillTypeNameTable(Context, TypeNames);
454 printTypeInt(Out, V->getType(), TypeNames);
456 WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
462 class AssemblyWriter {
464 SlotCalculator &Table;
465 const Module *TheModule;
466 std::map<const Type *, std::string> TypeNames;
468 inline AssemblyWriter(std::ostream &o, SlotCalculator &Tab, const Module *M)
469 : Out(o), Table(Tab), TheModule(M) {
471 // If the module has a symbol table, take all global types and stuff their
472 // names into the TypeNames map.
474 fillTypeNameTable(M, TypeNames);
477 inline void write(const Module *M) { printModule(M); }
478 inline void write(const GlobalVariable *G) { printGlobal(G); }
479 inline void write(const Function *F) { printFunction(F); }
480 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
481 inline void write(const Instruction *I) { printInstruction(*I); }
482 inline void write(const Constant *CPV) { printConstant(CPV); }
483 inline void write(const Type *Ty) { printType(Ty); }
485 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
488 void printModule(const Module *M);
489 void printSymbolTable(const SymbolTable &ST);
490 void printConstant(const Constant *CPV);
491 void printGlobal(const GlobalVariable *GV);
492 void printFunction(const Function *F);
493 void printArgument(const Argument *FA);
494 void printBasicBlock(const BasicBlock *BB);
495 void printInstruction(const Instruction &I);
497 // printType - Go to extreme measures to attempt to print out a short,
498 // symbolic version of a type name.
500 std::ostream &printType(const Type *Ty) {
501 return printTypeInt(Out, Ty, TypeNames);
504 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
505 // without considering any symbolic types that we may have equal to it.
507 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
509 // printInfoComment - Print a little comment after the instruction indicating
510 // which slot it occupies.
511 void printInfoComment(const Value &V);
515 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
516 // without considering any symbolic types that we may have equal to it.
518 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
519 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
520 printType(FTy->getReturnType()) << " (";
521 for (FunctionType::ParamTypes::const_iterator
522 I = FTy->getParamTypes().begin(),
523 E = FTy->getParamTypes().end(); I != E; ++I) {
524 if (I != FTy->getParamTypes().begin())
528 if (FTy->isVarArg()) {
529 if (!FTy->getParamTypes().empty()) Out << ", ";
533 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
535 for (StructType::ElementTypes::const_iterator
536 I = STy->getElementTypes().begin(),
537 E = STy->getElementTypes().end(); I != E; ++I) {
538 if (I != STy->getElementTypes().begin())
543 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
544 printType(PTy->getElementType()) << "*";
545 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
546 Out << "[" << ATy->getNumElements() << " x ";
547 printType(ATy->getElementType()) << "]";
548 } else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
551 if (!Ty->isPrimitiveType())
552 Out << "<unknown derived type>";
559 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
561 if (PrintType) { Out << " "; printType(Operand->getType()); }
562 WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Table);
566 void AssemblyWriter::printModule(const Module *M) {
567 switch (M->getEndianness()) {
568 case Module::LittleEndian: Out << "target endian = little\n"; break;
569 case Module::BigEndian: Out << "target endian = big\n"; break;
570 case Module::AnyEndianness: break;
572 switch (M->getPointerSize()) {
573 case Module::Pointer32: Out << "target pointersize = 32\n"; break;
574 case Module::Pointer64: Out << "target pointersize = 64\n"; break;
575 case Module::AnyPointerSize: break;
578 // Loop over the symbol table, emitting all named constants...
579 printSymbolTable(M->getSymbolTable());
581 for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
584 Out << "\nimplementation ; Functions:\n";
586 // Output all of the functions...
587 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
591 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
592 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
594 if (!GV->hasInitializer())
597 switch (GV->getLinkage()) {
598 case GlobalValue::InternalLinkage: Out << "internal "; break;
599 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
600 case GlobalValue::WeakLinkage: Out << "weak "; break;
601 case GlobalValue::AppendingLinkage: Out << "appending "; break;
602 case GlobalValue::ExternalLinkage: break;
605 Out << (GV->isConstant() ? "constant " : "global ");
606 printType(GV->getType()->getElementType());
608 if (GV->hasInitializer())
609 writeOperand(GV->getInitializer(), false, false);
611 printInfoComment(*GV);
616 // printSymbolTable - Run through symbol table looking for named constants
617 // if a named constant is found, emit it's declaration...
619 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
620 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
621 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
622 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
624 for (; I != End; ++I) {
625 const Value *V = I->second;
626 if (const Constant *CPV = dyn_cast<Constant>(V)) {
628 } else if (const Type *Ty = dyn_cast<Type>(V)) {
629 Out << "\t" << getLLVMName(I->first) << " = type ";
631 // Make sure we print out at least one level of the type structure, so
632 // that we do not get %FILE = type %FILE
634 printTypeAtLeastOneLevel(Ty) << "\n";
641 // printConstant - Print out a constant pool entry...
643 void AssemblyWriter::printConstant(const Constant *CPV) {
644 // Don't print out unnamed constants, they will be inlined
645 if (!CPV->hasName()) return;
648 Out << "\t" << getLLVMName(CPV->getName()) << " =";
650 // Write the value out now...
651 writeOperand(CPV, true, false);
653 printInfoComment(*CPV);
657 // printFunction - Print all aspects of a function.
659 void AssemblyWriter::printFunction(const Function *F) {
660 // Print out the return type and name...
666 switch (F->getLinkage()) {
667 case GlobalValue::InternalLinkage: Out << "internal "; break;
668 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
669 case GlobalValue::WeakLinkage: Out << "weak "; break;
670 case GlobalValue::AppendingLinkage: Out << "appending "; break;
671 case GlobalValue::ExternalLinkage: break;
674 printType(F->getReturnType()) << " ";
675 if (!F->getName().empty())
676 Out << getLLVMName(F->getName());
680 Table.incorporateFunction(F);
682 // Loop over the arguments, printing them...
683 const FunctionType *FT = F->getFunctionType();
685 for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
688 // Finish printing arguments...
689 if (FT->isVarArg()) {
690 if (FT->getParamTypes().size()) Out << ", ";
691 Out << "..."; // Output varargs portion of signature!
695 if (F->isExternal()) {
700 // Output all of its basic blocks... for the function
701 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
707 Table.purgeFunction();
710 // printArgument - This member is called for every argument that
711 // is passed into the function. Simply print it out
713 void AssemblyWriter::printArgument(const Argument *Arg) {
714 // Insert commas as we go... the first arg doesn't get a comma
715 if (Arg != &Arg->getParent()->afront()) Out << ", ";
718 printType(Arg->getType());
720 // Output name, if available...
722 Out << " " << getLLVMName(Arg->getName());
723 else if (Table.getSlot(Arg) < 0)
727 // printBasicBlock - This member is called for each basic block in a method.
729 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
730 if (BB->hasName()) { // Print out the label if it exists...
731 Out << "\n" << BB->getName() << ":";
732 } else if (!BB->use_empty()) { // Don't print block # of no uses...
733 int Slot = Table.getSlot(BB);
734 Out << "\n; <label>:";
736 Out << Slot; // Extra newline separates out label's
741 // Output predecessors for the block...
743 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
746 Out << " No predecessors!";
749 writeOperand(*PI, false, true);
750 for (++PI; PI != PE; ++PI) {
752 writeOperand(*PI, false, true);
758 // Output all of the instructions in the basic block...
759 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
760 printInstruction(*I);
764 // printInfoComment - Print a little comment after the instruction indicating
765 // which slot it occupies.
767 void AssemblyWriter::printInfoComment(const Value &V) {
768 if (V.getType() != Type::VoidTy) {
770 printType(V.getType()) << ">";
773 int Slot = Table.getSlot(&V); // Print out the def slot taken...
774 if (Slot >= 0) Out << ":" << Slot;
775 else Out << ":<badref>";
777 Out << " [#uses=" << V.use_size() << "]"; // Output # uses
781 // printInstruction - This member is called for each Instruction in a method.
783 void AssemblyWriter::printInstruction(const Instruction &I) {
786 // Print out name if it exists...
788 Out << getLLVMName(I.getName()) << " = ";
790 // If this is a volatile load or store, print out the volatile marker
791 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
792 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()))
795 // Print out the opcode...
796 Out << I.getOpcodeName();
798 // Print out the type of the operands...
799 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
801 // Special case conditional branches to swizzle the condition out to the front
802 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
803 writeOperand(I.getOperand(2), true);
805 writeOperand(Operand, true);
807 writeOperand(I.getOperand(1), true);
809 } else if (isa<SwitchInst>(I)) {
810 // Special case switch statement to get formatting nice and correct...
811 writeOperand(Operand , true); Out << ",";
812 writeOperand(I.getOperand(1), true); Out << " [";
814 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
816 writeOperand(I.getOperand(op ), true); Out << ",";
817 writeOperand(I.getOperand(op+1), true);
820 } else if (isa<PHINode>(I)) {
822 printType(I.getType());
825 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
828 writeOperand(I.getOperand(op ), false); Out << ",";
829 writeOperand(I.getOperand(op+1), false); Out << " ]";
831 } else if (isa<ReturnInst>(I) && !Operand) {
833 } else if (isa<CallInst>(I)) {
834 const PointerType *PTy = cast<PointerType>(Operand->getType());
835 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
836 const Type *RetTy = FTy->getReturnType();
838 // If possible, print out the short form of the call instruction. We can
839 // only do this if the first argument is a pointer to a nonvararg function,
840 // and if the return type is not a pointer to a function.
842 if (!FTy->isVarArg() &&
843 (!isa<PointerType>(RetTy) ||
844 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
845 Out << " "; printType(RetTy);
846 writeOperand(Operand, false);
848 writeOperand(Operand, true);
851 if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
852 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
854 writeOperand(I.getOperand(op), true);
858 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
859 const PointerType *PTy = cast<PointerType>(Operand->getType());
860 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
861 const Type *RetTy = FTy->getReturnType();
863 // If possible, print out the short form of the invoke instruction. We can
864 // only do this if the first argument is a pointer to a nonvararg function,
865 // and if the return type is not a pointer to a function.
867 if (!FTy->isVarArg() &&
868 (!isa<PointerType>(RetTy) ||
869 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
870 Out << " "; printType(RetTy);
871 writeOperand(Operand, false);
873 writeOperand(Operand, true);
877 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
878 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
880 writeOperand(I.getOperand(op), true);
883 Out << " )\n\t\t\tto";
884 writeOperand(II->getNormalDest(), true);
886 writeOperand(II->getExceptionalDest(), true);
888 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
890 printType(AI->getType()->getElementType());
891 if (AI->isArrayAllocation()) {
893 writeOperand(AI->getArraySize(), true);
895 } else if (isa<CastInst>(I)) {
896 writeOperand(Operand, true);
898 printType(I.getType());
899 } else if (isa<VAArgInst>(I)) {
900 writeOperand(Operand, true);
902 printType(I.getType());
903 } else if (const VANextInst *VAN = dyn_cast<VANextInst>(&I)) {
904 writeOperand(Operand, true);
906 printType(VAN->getArgType());
907 } else if (Operand) { // Print the normal way...
909 // PrintAllTypes - Instructions who have operands of all the same type
910 // omit the type from all but the first operand. If the instruction has
911 // different type operands (for example br), then they are all printed.
912 bool PrintAllTypes = false;
913 const Type *TheType = Operand->getType();
915 // Shift Left & Right print both types even for Ubyte LHS
916 if (isa<ShiftInst>(I)) {
917 PrintAllTypes = true;
919 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
920 Operand = I.getOperand(i);
921 if (Operand->getType() != TheType) {
922 PrintAllTypes = true; // We have differing types! Print them all!
928 if (!PrintAllTypes) {
933 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
935 writeOperand(I.getOperand(i), PrintAllTypes);
944 //===----------------------------------------------------------------------===//
945 // External Interface declarations
946 //===----------------------------------------------------------------------===//
949 void Module::print(std::ostream &o) const {
950 SlotCalculator SlotTable(this, true);
951 AssemblyWriter W(o, SlotTable, this);
955 void GlobalVariable::print(std::ostream &o) const {
956 SlotCalculator SlotTable(getParent(), true);
957 AssemblyWriter W(o, SlotTable, getParent());
961 void Function::print(std::ostream &o) const {
962 SlotCalculator SlotTable(getParent(), true);
963 AssemblyWriter W(o, SlotTable, getParent());
968 void BasicBlock::print(std::ostream &o) const {
969 SlotCalculator SlotTable(getParent(), true);
970 AssemblyWriter W(o, SlotTable,
971 getParent() ? getParent()->getParent() : 0);
975 void Instruction::print(std::ostream &o) const {
976 const Function *F = getParent() ? getParent()->getParent() : 0;
977 SlotCalculator SlotTable(F, true);
978 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0);
983 void Constant::print(std::ostream &o) const {
984 if (this == 0) { o << "<null> constant value\n"; return; }
986 // Handle CPR's special, because they have context information...
987 if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
988 CPR->getValue()->print(o); // Print as a global value, with context info.
992 o << " " << getType()->getDescription() << " ";
994 std::map<const Type *, std::string> TypeTable;
995 WriteConstantInt(o, this, false, TypeTable, 0);
998 void Type::print(std::ostream &o) const {
1002 o << getDescription();
1005 void Argument::print(std::ostream &o) const {
1006 o << getType() << " " << getName();
1009 void Value::dump() const { print(std::cerr); }
1011 //===----------------------------------------------------------------------===//
1012 // CachedWriter Class Implementation
1013 //===----------------------------------------------------------------------===//
1015 void CachedWriter::setModule(const Module *M) {
1016 delete SC; delete AW;
1018 SC = new SlotCalculator(M, true);
1019 AW = new AssemblyWriter(Out, *SC, M);
1025 CachedWriter::~CachedWriter() {
1030 CachedWriter &CachedWriter::operator<<(const Value *V) {
1031 assert(AW && SC && "CachedWriter does not have a current module!");
1032 switch (V->getValueType()) {
1033 case Value::ConstantVal:
1034 case Value::ArgumentVal: AW->writeOperand(V, true, true); break;
1035 case Value::TypeVal: AW->write(cast<Type>(V)); break;
1036 case Value::InstructionVal: AW->write(cast<Instruction>(V)); break;
1037 case Value::BasicBlockVal: AW->write(cast<BasicBlock>(V)); break;
1038 case Value::FunctionVal: AW->write(cast<Function>(V)); break;
1039 case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
1040 default: Out << "<unknown value type: " << V->getValueType() << ">"; break;