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()) return Out << Ty->getDescription();
208 // Check to see if the type is named.
209 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
210 if (I != TypeNames.end()) return Out << I->second;
212 // Otherwise we have a type that has not been named but is a derived type.
213 // Carefully recurse the type hierarchy to print out any contained symbolic
216 std::vector<const Type *> TypeStack;
217 std::string TypeName = calcTypeName(Ty, TypeStack, TypeNames);
218 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
219 return Out << TypeName;
223 // WriteTypeSymbolic - This attempts to write the specified type as a symbolic
224 // type, iff there is an entry in the modules symbol table for the specified
225 // type or one of it's component types. This is slower than a simple x << Type;
227 std::ostream &WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
231 // If they want us to print out a type, attempt to make it symbolic if there
232 // is a symbol table in the module...
234 std::map<const Type *, std::string> TypeNames;
235 fillTypeNameTable(M, TypeNames);
237 return printTypeInt(Out, Ty, TypeNames);
239 return Out << Ty->getDescription();
243 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
245 std::map<const Type *, std::string> &TypeTable,
246 SlotCalculator *Table) {
247 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
248 Out << (CB == ConstantBool::True ? "true" : "false");
249 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
250 Out << CI->getValue();
251 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
252 Out << CI->getValue();
253 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
254 // We would like to output the FP constant value in exponential notation,
255 // but we cannot do this if doing so will lose precision. Check here to
256 // make sure that we only output it in exponential format if we can parse
257 // the value back and get the same value.
259 std::string StrVal = ftostr(CFP->getValue());
261 // Check to make sure that the stringized number is not some string like
262 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
263 // the string matches the "[-+]?[0-9]" regex.
265 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
266 ((StrVal[0] == '-' || StrVal[0] == '+') &&
267 (StrVal[1] >= '0' && StrVal[1] <= '9')))
268 // Reparse stringized version!
269 if (atof(StrVal.c_str()) == CFP->getValue()) {
270 Out << StrVal; return;
273 // Otherwise we could not reparse it to exactly the same value, so we must
274 // output the string in hexadecimal format!
276 // Behave nicely in the face of C TBAA rules... see:
277 // http://www.nullstone.com/htmls/category/aliastyp.htm
279 double Val = CFP->getValue();
280 char *Ptr = (char*)&Val;
281 assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
282 "assuming that double is 64 bits!");
283 Out << "0x" << utohexstr(*(uint64_t*)Ptr);
285 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
286 if (CA->getNumOperands() > 5 && CA->isNullValue()) {
287 Out << "zeroinitializer";
291 // As a special case, print the array as a string if it is an array of
292 // ubytes or an array of sbytes with positive values.
294 const Type *ETy = CA->getType()->getElementType();
295 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
297 if (ETy == Type::SByteTy)
298 for (unsigned i = 0; i < CA->getNumOperands(); ++i)
299 if (cast<ConstantSInt>(CA->getOperand(i))->getValue() < 0) {
306 for (unsigned i = 0; i < CA->getNumOperands(); ++i) {
307 unsigned char C = cast<ConstantInt>(CA->getOperand(i))->getRawValue();
309 if (isprint(C) && C != '"' && C != '\\') {
313 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
314 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
319 } else { // Cannot output in string format...
321 if (CA->getNumOperands()) {
323 printTypeInt(Out, ETy, TypeTable);
324 WriteAsOperandInternal(Out, CA->getOperand(0),
325 PrintName, TypeTable, Table);
326 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
328 printTypeInt(Out, ETy, TypeTable);
329 WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
335 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
336 if (CS->getNumOperands() > 5 && CS->isNullValue()) {
337 Out << "zeroinitializer";
342 if (CS->getNumOperands()) {
344 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
346 WriteAsOperandInternal(Out, CS->getOperand(0),
347 PrintName, TypeTable, Table);
349 for (unsigned i = 1; i < CS->getNumOperands(); i++) {
351 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
353 WriteAsOperandInternal(Out, CS->getOperand(i),
354 PrintName, TypeTable, Table);
359 } else if (isa<ConstantPointerNull>(CV)) {
362 } else if (const ConstantPointerRef *PR = dyn_cast<ConstantPointerRef>(CV)) {
363 const GlobalValue *V = PR->getValue();
365 Out << getLLVMName(V->getName());
367 int Slot = Table->getSlot(V);
371 Out << "<pointer reference badref>";
373 Out << "<pointer reference without context info>";
376 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
377 Out << CE->getOpcodeName() << " (";
379 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
380 printTypeInt(Out, (*OI)->getType(), TypeTable);
381 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Table);
382 if (OI+1 != CE->op_end())
386 if (CE->getOpcode() == Instruction::Cast) {
388 printTypeInt(Out, CE->getType(), TypeTable);
393 Out << "<placeholder or erroneous Constant>";
398 // WriteAsOperand - Write the name of the specified value out to the specified
399 // ostream. This can be useful when you just want to print int %reg126, not the
400 // whole instruction that generated it.
402 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
404 std::map<const Type*, std::string> &TypeTable,
405 SlotCalculator *Table) {
407 if (PrintName && V->hasName()) {
408 Out << getLLVMName(V->getName());
410 if (const Constant *CV = dyn_cast<Constant>(V)) {
411 WriteConstantInt(Out, CV, PrintName, TypeTable, Table);
415 Slot = Table->getSlot(V);
417 if (const Type *Ty = dyn_cast<Type>(V)) {
418 Out << Ty->getDescription();
422 Table = createSlotCalculator(V);
423 if (Table == 0) { Out << "BAD VALUE TYPE!"; return; }
425 Slot = Table->getSlot(V);
428 if (Slot >= 0) Out << "%" << Slot;
430 Out << "<badref>"; // Not embedded into a location?
437 // WriteAsOperand - Write the name of the specified value out to the specified
438 // ostream. This can be useful when you just want to print int %reg126, not the
439 // whole instruction that generated it.
441 std::ostream &WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
442 bool PrintName, const Module *Context) {
443 std::map<const Type *, std::string> TypeNames;
444 if (Context == 0) Context = getModuleFromVal(V);
447 fillTypeNameTable(Context, TypeNames);
450 printTypeInt(Out, V->getType(), TypeNames);
452 WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
458 class AssemblyWriter {
460 SlotCalculator &Table;
461 const Module *TheModule;
462 std::map<const Type *, std::string> TypeNames;
464 inline AssemblyWriter(std::ostream &o, SlotCalculator &Tab, const Module *M)
465 : Out(o), Table(Tab), TheModule(M) {
467 // If the module has a symbol table, take all global types and stuff their
468 // names into the TypeNames map.
470 fillTypeNameTable(M, TypeNames);
473 inline void write(const Module *M) { printModule(M); }
474 inline void write(const GlobalVariable *G) { printGlobal(G); }
475 inline void write(const Function *F) { printFunction(F); }
476 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
477 inline void write(const Instruction *I) { printInstruction(*I); }
478 inline void write(const Constant *CPV) { printConstant(CPV); }
479 inline void write(const Type *Ty) { printType(Ty); }
481 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
484 void printModule(const Module *M);
485 void printSymbolTable(const SymbolTable &ST);
486 void printConstant(const Constant *CPV);
487 void printGlobal(const GlobalVariable *GV);
488 void printFunction(const Function *F);
489 void printArgument(const Argument *FA);
490 void printBasicBlock(const BasicBlock *BB);
491 void printInstruction(const Instruction &I);
493 // printType - Go to extreme measures to attempt to print out a short,
494 // symbolic version of a type name.
496 std::ostream &printType(const Type *Ty) {
497 return printTypeInt(Out, Ty, TypeNames);
500 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
501 // without considering any symbolic types that we may have equal to it.
503 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
505 // printInfoComment - Print a little comment after the instruction indicating
506 // which slot it occupies.
507 void printInfoComment(const Value &V);
511 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
512 // without considering any symbolic types that we may have equal to it.
514 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
515 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
516 printType(FTy->getReturnType()) << " (";
517 for (FunctionType::ParamTypes::const_iterator
518 I = FTy->getParamTypes().begin(),
519 E = FTy->getParamTypes().end(); I != E; ++I) {
520 if (I != FTy->getParamTypes().begin())
524 if (FTy->isVarArg()) {
525 if (!FTy->getParamTypes().empty()) Out << ", ";
529 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
531 for (StructType::ElementTypes::const_iterator
532 I = STy->getElementTypes().begin(),
533 E = STy->getElementTypes().end(); I != E; ++I) {
534 if (I != STy->getElementTypes().begin())
539 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
540 printType(PTy->getElementType()) << "*";
541 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
542 Out << "[" << ATy->getNumElements() << " x ";
543 printType(ATy->getElementType()) << "]";
544 } else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
547 if (!Ty->isPrimitiveType())
548 Out << "<unknown derived type>";
555 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
557 if (PrintType) { Out << " "; printType(Operand->getType()); }
558 WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Table);
562 void AssemblyWriter::printModule(const Module *M) {
563 switch (M->getEndianness()) {
564 case Module::LittleEndian: Out << "target endian = little\n"; break;
565 case Module::BigEndian: Out << "target endian = big\n"; break;
566 case Module::AnyEndianness: break;
568 switch (M->getPointerSize()) {
569 case Module::Pointer32: Out << "target pointersize = 32\n"; break;
570 case Module::Pointer64: Out << "target pointersize = 64\n"; break;
571 case Module::AnyPointerSize: break;
574 // Loop over the symbol table, emitting all named constants...
575 printSymbolTable(M->getSymbolTable());
577 for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
580 Out << "\nimplementation ; Functions:\n";
582 // Output all of the functions...
583 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
587 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
588 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
590 if (!GV->hasInitializer())
593 switch (GV->getLinkage()) {
594 case GlobalValue::InternalLinkage: Out << "internal "; break;
595 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
596 case GlobalValue::WeakLinkage: Out << "weak "; break;
597 case GlobalValue::AppendingLinkage: Out << "appending "; break;
598 case GlobalValue::ExternalLinkage: break;
601 Out << (GV->isConstant() ? "constant " : "global ");
602 printType(GV->getType()->getElementType());
604 if (GV->hasInitializer())
605 writeOperand(GV->getInitializer(), false, false);
607 printInfoComment(*GV);
612 // printSymbolTable - Run through symbol table looking for named constants
613 // if a named constant is found, emit it's declaration...
615 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
616 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
617 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
618 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
620 for (; I != End; ++I) {
621 const Value *V = I->second;
622 if (const Constant *CPV = dyn_cast<Constant>(V)) {
624 } else if (const Type *Ty = dyn_cast<Type>(V)) {
625 Out << "\t" << getLLVMName(I->first) << " = type ";
627 // Make sure we print out at least one level of the type structure, so
628 // that we do not get %FILE = type %FILE
630 printTypeAtLeastOneLevel(Ty) << "\n";
637 // printConstant - Print out a constant pool entry...
639 void AssemblyWriter::printConstant(const Constant *CPV) {
640 // Don't print out unnamed constants, they will be inlined
641 if (!CPV->hasName()) return;
644 Out << "\t" << getLLVMName(CPV->getName()) << " =";
646 // Write the value out now...
647 writeOperand(CPV, true, false);
649 printInfoComment(*CPV);
653 // printFunction - Print all aspects of a function.
655 void AssemblyWriter::printFunction(const Function *F) {
656 // Print out the return type and name...
662 switch (F->getLinkage()) {
663 case GlobalValue::InternalLinkage: Out << "internal "; break;
664 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
665 case GlobalValue::WeakLinkage: Out << "weak "; break;
666 case GlobalValue::AppendingLinkage: Out << "appending "; break;
667 case GlobalValue::ExternalLinkage: break;
670 printType(F->getReturnType()) << " ";
671 if (!F->getName().empty())
672 Out << getLLVMName(F->getName());
676 Table.incorporateFunction(F);
678 // Loop over the arguments, printing them...
679 const FunctionType *FT = F->getFunctionType();
681 for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
684 // Finish printing arguments...
685 if (FT->isVarArg()) {
686 if (FT->getParamTypes().size()) Out << ", ";
687 Out << "..."; // Output varargs portion of signature!
691 if (F->isExternal()) {
696 // Output all of its basic blocks... for the function
697 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
703 Table.purgeFunction();
706 // printArgument - This member is called for every argument that
707 // is passed into the function. Simply print it out
709 void AssemblyWriter::printArgument(const Argument *Arg) {
710 // Insert commas as we go... the first arg doesn't get a comma
711 if (Arg != &Arg->getParent()->afront()) Out << ", ";
714 printType(Arg->getType());
716 // Output name, if available...
718 Out << " " << getLLVMName(Arg->getName());
719 else if (Table.getSlot(Arg) < 0)
723 // printBasicBlock - This member is called for each basic block in a method.
725 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
726 if (BB->hasName()) { // Print out the label if it exists...
727 Out << "\n" << BB->getName() << ":";
728 } else if (!BB->use_empty()) { // Don't print block # of no uses...
729 int Slot = Table.getSlot(BB);
730 Out << "\n; <label>:";
732 Out << Slot; // Extra newline separates out label's
737 // Output predecessors for the block...
739 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
742 Out << " No predecessors!";
745 writeOperand(*PI, false, true);
746 for (++PI; PI != PE; ++PI) {
748 writeOperand(*PI, false, true);
754 // Output all of the instructions in the basic block...
755 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
756 printInstruction(*I);
760 // printInfoComment - Print a little comment after the instruction indicating
761 // which slot it occupies.
763 void AssemblyWriter::printInfoComment(const Value &V) {
764 if (V.getType() != Type::VoidTy) {
766 printType(V.getType()) << ">";
769 int Slot = Table.getSlot(&V); // Print out the def slot taken...
770 if (Slot >= 0) Out << ":" << Slot;
771 else Out << ":<badref>";
773 Out << " [#uses=" << V.use_size() << "]"; // Output # uses
777 // printInstruction - This member is called for each Instruction in a method.
779 void AssemblyWriter::printInstruction(const Instruction &I) {
782 // Print out name if it exists...
784 Out << getLLVMName(I.getName()) << " = ";
786 // If this is a volatile load or store, print out the volatile marker
787 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
788 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()))
791 // Print out the opcode...
792 Out << I.getOpcodeName();
794 // Print out the type of the operands...
795 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
797 // Special case conditional branches to swizzle the condition out to the front
798 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
799 writeOperand(I.getOperand(2), true);
801 writeOperand(Operand, true);
803 writeOperand(I.getOperand(1), true);
805 } else if (isa<SwitchInst>(I)) {
806 // Special case switch statement to get formatting nice and correct...
807 writeOperand(Operand , true); Out << ",";
808 writeOperand(I.getOperand(1), true); Out << " [";
810 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
812 writeOperand(I.getOperand(op ), true); Out << ",";
813 writeOperand(I.getOperand(op+1), true);
816 } else if (isa<PHINode>(I)) {
818 printType(I.getType());
821 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
824 writeOperand(I.getOperand(op ), false); Out << ",";
825 writeOperand(I.getOperand(op+1), false); Out << " ]";
827 } else if (isa<ReturnInst>(I) && !Operand) {
829 } else if (isa<CallInst>(I)) {
830 const PointerType *PTy = cast<PointerType>(Operand->getType());
831 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
832 const Type *RetTy = FTy->getReturnType();
834 // If possible, print out the short form of the call instruction. We can
835 // only do this if the first argument is a pointer to a nonvararg function,
836 // and if the return type is not a pointer to a function.
838 if (!FTy->isVarArg() &&
839 (!isa<PointerType>(RetTy) ||
840 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
841 Out << " "; printType(RetTy);
842 writeOperand(Operand, false);
844 writeOperand(Operand, true);
847 if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
848 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
850 writeOperand(I.getOperand(op), true);
854 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
855 const PointerType *PTy = cast<PointerType>(Operand->getType());
856 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
857 const Type *RetTy = FTy->getReturnType();
859 // If possible, print out the short form of the invoke instruction. We can
860 // only do this if the first argument is a pointer to a nonvararg function,
861 // and if the return type is not a pointer to a function.
863 if (!FTy->isVarArg() &&
864 (!isa<PointerType>(RetTy) ||
865 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
866 Out << " "; printType(RetTy);
867 writeOperand(Operand, false);
869 writeOperand(Operand, true);
873 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
874 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
876 writeOperand(I.getOperand(op), true);
879 Out << " )\n\t\t\tto";
880 writeOperand(II->getNormalDest(), true);
882 writeOperand(II->getExceptionalDest(), true);
884 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
886 printType(AI->getType()->getElementType());
887 if (AI->isArrayAllocation()) {
889 writeOperand(AI->getArraySize(), true);
891 } else if (isa<CastInst>(I)) {
892 writeOperand(Operand, true);
894 printType(I.getType());
895 } else if (isa<VAArgInst>(I)) {
896 writeOperand(Operand, true);
898 printType(I.getType());
899 } else if (const VANextInst *VAN = dyn_cast<VANextInst>(&I)) {
900 writeOperand(Operand, true);
902 printType(VAN->getArgType());
903 } else if (Operand) { // Print the normal way...
905 // PrintAllTypes - Instructions who have operands of all the same type
906 // omit the type from all but the first operand. If the instruction has
907 // different type operands (for example br), then they are all printed.
908 bool PrintAllTypes = false;
909 const Type *TheType = Operand->getType();
911 // Shift Left & Right print both types even for Ubyte LHS
912 if (isa<ShiftInst>(I)) {
913 PrintAllTypes = true;
915 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
916 Operand = I.getOperand(i);
917 if (Operand->getType() != TheType) {
918 PrintAllTypes = true; // We have differing types! Print them all!
924 if (!PrintAllTypes) {
929 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
931 writeOperand(I.getOperand(i), PrintAllTypes);
940 //===----------------------------------------------------------------------===//
941 // External Interface declarations
942 //===----------------------------------------------------------------------===//
945 void Module::print(std::ostream &o) const {
946 SlotCalculator SlotTable(this, true);
947 AssemblyWriter W(o, SlotTable, this);
951 void GlobalVariable::print(std::ostream &o) const {
952 SlotCalculator SlotTable(getParent(), true);
953 AssemblyWriter W(o, SlotTable, getParent());
957 void Function::print(std::ostream &o) const {
958 SlotCalculator SlotTable(getParent(), true);
959 AssemblyWriter W(o, SlotTable, getParent());
964 void BasicBlock::print(std::ostream &o) const {
965 SlotCalculator SlotTable(getParent(), true);
966 AssemblyWriter W(o, SlotTable,
967 getParent() ? getParent()->getParent() : 0);
971 void Instruction::print(std::ostream &o) const {
972 const Function *F = getParent() ? getParent()->getParent() : 0;
973 SlotCalculator SlotTable(F, true);
974 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0);
979 void Constant::print(std::ostream &o) const {
980 if (this == 0) { o << "<null> constant value\n"; return; }
982 // Handle CPR's special, because they have context information...
983 if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
984 CPR->getValue()->print(o); // Print as a global value, with context info.
988 o << " " << getType()->getDescription() << " ";
990 std::map<const Type *, std::string> TypeTable;
991 WriteConstantInt(o, this, false, TypeTable, 0);
994 void Type::print(std::ostream &o) const {
998 o << getDescription();
1001 void Argument::print(std::ostream &o) const {
1002 o << getType() << " " << getName();
1005 void Value::dump() const { print(std::cerr); }
1007 //===----------------------------------------------------------------------===//
1008 // CachedWriter Class Implementation
1009 //===----------------------------------------------------------------------===//
1011 void CachedWriter::setModule(const Module *M) {
1012 delete SC; delete AW;
1014 SC = new SlotCalculator(M, true);
1015 AW = new AssemblyWriter(Out, *SC, M);
1021 CachedWriter::~CachedWriter() {
1026 CachedWriter &CachedWriter::operator<<(const Value *V) {
1027 assert(AW && SC && "CachedWriter does not have a current module!");
1028 switch (V->getValueType()) {
1029 case Value::ConstantVal:
1030 case Value::ArgumentVal: AW->writeOperand(V, true, true); break;
1031 case Value::TypeVal: AW->write(cast<Type>(V)); break;
1032 case Value::InstructionVal: AW->write(cast<Instruction>(V)); break;
1033 case Value::BasicBlockVal: AW->write(cast<BasicBlock>(V)); break;
1034 case Value::FunctionVal: AW->write(cast<Function>(V)); break;
1035 case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
1036 default: Out << "<unknown value type: " << V->getValueType() << ">"; break;