1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // This library implements the functionality defined in llvm/Assembly/Writer.h
5 // TODO: print out the type name instead of the full type if a particular type
6 // is in the symbol table...
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Assembly/CachedWriter.h"
11 #include "llvm/Analysis/SlotCalculator.h"
12 #include "llvm/Module.h"
13 #include "llvm/Function.h"
14 #include "llvm/GlobalVariable.h"
15 #include "llvm/BasicBlock.h"
16 #include "llvm/ConstantVals.h"
17 #include "llvm/iMemory.h"
18 #include "llvm/iTerminators.h"
19 #include "llvm/iPHINode.h"
20 #include "llvm/iOther.h"
21 #include "llvm/SymbolTable.h"
22 #include "Support/StringExtras.h"
23 #include "Support/STLExtras.h"
31 void Value::dump() const {
35 static const Module *getModuleFromVal(const Value *V) {
36 if (const FunctionArgument *MA = dyn_cast<const FunctionArgument>(V))
37 return MA->getParent() ? MA->getParent()->getParent() : 0;
38 else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(V))
39 return BB->getParent() ? BB->getParent()->getParent() : 0;
40 else if (const Instruction *I = dyn_cast<const Instruction>(V)) {
41 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
42 return M ? M->getParent() : 0;
43 } else if (const GlobalValue *GV = dyn_cast<const GlobalValue>(V))
44 return GV->getParent();
45 else if (const Module *Mod = dyn_cast<const Module>(V))
50 static SlotCalculator *createSlotCalculator(const Value *V) {
51 assert(!isa<Type>(V) && "Can't create an SC for a type!");
52 if (const FunctionArgument *FA = dyn_cast<const FunctionArgument>(V)) {
53 return new SlotCalculator(FA->getParent(), true);
54 } else if (const Instruction *I = dyn_cast<const Instruction>(V)) {
55 return new SlotCalculator(I->getParent()->getParent(), true);
56 } else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(V)) {
57 return new SlotCalculator(BB->getParent(), true);
58 } else if (const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V)){
59 return new SlotCalculator(GV->getParent(), true);
60 } else if (const Function *Func = dyn_cast<const Function>(V)) {
61 return new SlotCalculator(Func, true);
62 } else if (const Module *Mod = dyn_cast<const Module>(V)) {
63 return new SlotCalculator(Mod, true);
68 // WriteAsOperand - Write the name of the specified value out to the specified
69 // ostream. This can be useful when you just want to print int %reg126, not the
70 // whole instruction that generated it.
72 static void WriteAsOperandInternal(ostream &Out, const Value *V, bool PrintName,
73 SlotCalculator *Table) {
74 if (PrintName && V->hasName()) {
75 Out << " %" << V->getName();
77 if (const Constant *CPV = dyn_cast<const Constant>(V)) {
78 Out << " " << CPV->getStrValue();
82 Slot = Table->getValSlot(V);
84 if (const Type *Ty = dyn_cast<const Type>(V)) {
85 Out << " " << Ty->getDescription();
89 Table = createSlotCalculator(V);
90 if (Table == 0) { Out << "BAD VALUE TYPE!"; return; }
92 Slot = Table->getValSlot(V);
95 if (Slot >= 0) Out << " %" << Slot;
97 Out << "<badref>"; // Not embeded into a location?
103 // If the module has a symbol table, take all global types and stuff their
104 // names into the TypeNames map.
106 static void fillTypeNameTable(const Module *M,
107 map<const Type *, string> &TypeNames) {
108 if (M && M->hasSymbolTable()) {
109 const SymbolTable *ST = M->getSymbolTable();
110 SymbolTable::const_iterator PI = ST->find(Type::TypeTy);
111 if (PI != ST->end()) {
112 SymbolTable::type_const_iterator I = PI->second.begin();
113 for (; I != PI->second.end(); ++I) {
114 // As a heuristic, don't insert pointer to primitive types, because
115 // they are used too often to have a single useful name.
117 const Type *Ty = cast<const Type>(I->second);
118 if (!isa<PointerType>(Ty) ||
119 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType())
120 TypeNames.insert(std::make_pair(Ty, "%"+I->first));
128 static string calcTypeName(const Type *Ty, vector<const Type *> &TypeStack,
129 map<const Type *, string> &TypeNames) {
130 if (Ty->isPrimitiveType()) return Ty->getDescription(); // Base case
132 // Check to see if the type is named.
133 map<const Type *, string>::iterator I = TypeNames.find(Ty);
134 if (I != TypeNames.end()) return I->second;
136 // Check to see if the Type is already on the stack...
137 unsigned Slot = 0, CurSize = TypeStack.size();
138 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
140 // This is another base case for the recursion. In this case, we know
141 // that we have looped back to a type that we have previously visited.
142 // Generate the appropriate upreference to handle this.
145 return "\\" + utostr(CurSize-Slot); // Here's the upreference
147 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
150 switch (Ty->getPrimitiveID()) {
151 case Type::FunctionTyID: {
152 const FunctionType *MTy = cast<const FunctionType>(Ty);
153 Result = calcTypeName(MTy->getReturnType(), TypeStack, TypeNames) + " (";
154 for (FunctionType::ParamTypes::const_iterator
155 I = MTy->getParamTypes().begin(),
156 E = MTy->getParamTypes().end(); I != E; ++I) {
157 if (I != MTy->getParamTypes().begin())
159 Result += calcTypeName(*I, TypeStack, TypeNames);
161 if (MTy->isVarArg()) {
162 if (!MTy->getParamTypes().empty()) Result += ", ";
168 case Type::StructTyID: {
169 const StructType *STy = cast<const StructType>(Ty);
171 for (StructType::ElementTypes::const_iterator
172 I = STy->getElementTypes().begin(),
173 E = STy->getElementTypes().end(); I != E; ++I) {
174 if (I != STy->getElementTypes().begin())
176 Result += calcTypeName(*I, TypeStack, TypeNames);
181 case Type::PointerTyID:
182 Result = calcTypeName(cast<const PointerType>(Ty)->getElementType(),
183 TypeStack, TypeNames) + " *";
185 case Type::ArrayTyID: {
186 const ArrayType *ATy = cast<const ArrayType>(Ty);
187 int NumElements = ATy->getNumElements();
189 if (NumElements != -1) Result += itostr(NumElements) + " x ";
190 Result += calcTypeName(ATy->getElementType(), TypeStack, TypeNames) + "]";
194 assert(0 && "Unhandled case in getTypeProps!");
198 TypeStack.pop_back(); // Remove self from stack...
203 // printTypeInt - The internal guts of printing out a type that has a
204 // potentially named portion.
206 static ostream &printTypeInt(ostream &Out, const Type *Ty,
207 map<const Type *, string> &TypeNames) {
208 // Primitive types always print out their description, regardless of whether
209 // they have been named or not.
211 if (Ty->isPrimitiveType()) return Out << Ty->getDescription();
213 // Check to see if the type is named.
214 map<const Type *, string>::iterator I = TypeNames.find(Ty);
215 if (I != TypeNames.end()) return Out << I->second;
217 // Otherwise we have a type that has not been named but is a derived type.
218 // Carefully recurse the type hierarchy to print out any contained symbolic
221 vector<const Type *> TypeStack;
222 string TypeName = calcTypeName(Ty, TypeStack, TypeNames);
223 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
224 return Out << TypeName;
228 // WriteTypeSymbolic - This attempts to write the specified type as a symbolic
229 // type, iff there is an entry in the modules symbol table for the specified
230 // type or one of it's component types. This is slower than a simple x << Type;
232 ostream &WriteTypeSymbolic(ostream &Out, const Type *Ty, const Module *M) {
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...
237 if (M && M->hasSymbolTable()) {
238 map<const Type *, string> TypeNames;
239 fillTypeNameTable(M, TypeNames);
241 return printTypeInt(Out, Ty, TypeNames);
243 return Out << Ty->getDescription();
248 // WriteAsOperand - Write the name of the specified value out to the specified
249 // ostream. This can be useful when you just want to print int %reg126, not the
250 // whole instruction that generated it.
252 ostream &WriteAsOperand(ostream &Out, const Value *V, bool PrintType,
253 bool PrintName, SlotCalculator *Table) {
255 WriteTypeSymbolic(Out, V->getType(), getModuleFromVal(V));
257 WriteAsOperandInternal(Out, V, PrintName, Table);
263 class AssemblyWriter {
265 SlotCalculator &Table;
266 const Module *TheModule;
267 map<const Type *, string> TypeNames;
269 inline AssemblyWriter(ostream &o, SlotCalculator &Tab, const Module *M)
270 : Out(o), Table(Tab), TheModule(M) {
272 // If the module has a symbol table, take all global types and stuff their
273 // names into the TypeNames map.
275 fillTypeNameTable(M, TypeNames);
278 inline void write(const Module *M) { printModule(M); }
279 inline void write(const GlobalVariable *G) { printGlobal(G); }
280 inline void write(const Function *F) { printFunction(F); }
281 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
282 inline void write(const Instruction *I) { printInstruction(I); }
283 inline void write(const Constant *CPV) { printConstant(CPV); }
284 inline void write(const Type *Ty) { printType(Ty); }
287 void printModule(const Module *M);
288 void printSymbolTable(const SymbolTable &ST);
289 void printConstant(const Constant *CPV);
290 void printGlobal(const GlobalVariable *GV);
291 void printFunction(const Function *F);
292 void printFunctionArgument(const FunctionArgument *FA);
293 void printBasicBlock(const BasicBlock *BB);
294 void printInstruction(const Instruction *I);
295 ostream &printType(const Type *Ty);
297 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
299 // printInfoComment - Print a little comment after the instruction indicating
300 // which slot it occupies.
301 void printInfoComment(const Value *V);
305 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
307 if (PrintType) { Out << " "; printType(Operand->getType()); }
308 WriteAsOperandInternal(Out, Operand, PrintName, &Table);
312 void AssemblyWriter::printModule(const Module *M) {
313 // Loop over the symbol table, emitting all named constants...
314 if (M->hasSymbolTable())
315 printSymbolTable(*M->getSymbolTable());
317 for_each(M->gbegin(), M->gend(),
318 bind_obj(this, &AssemblyWriter::printGlobal));
320 Out << "implementation\n";
322 // Output all of the methods...
323 for_each(M->begin(), M->end(), bind_obj(this,&AssemblyWriter::printFunction));
326 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
327 if (GV->hasName()) Out << "%" << GV->getName() << " = ";
329 if (GV->hasInternalLinkage()) Out << "internal ";
330 if (!GV->hasInitializer()) Out << "uninitialized ";
332 Out << (GV->isConstant() ? "constant " : "global ");
333 printType(GV->getType()->getElementType());
335 if (GV->hasInitializer())
336 writeOperand(GV->getInitializer(), false, false);
338 printInfoComment(GV);
343 // printSymbolTable - Run through symbol table looking for named constants
344 // if a named constant is found, emit it's declaration...
346 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
347 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
348 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
349 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
351 for (; I != End; ++I) {
352 const Value *V = I->second;
353 if (const Constant *CPV = dyn_cast<const Constant>(V)) {
355 } else if (const Type *Ty = dyn_cast<const Type>(V)) {
356 Out << "\t%" << I->first << " = type " << Ty->getDescription() << "\n";
363 // printConstant - Print out a constant pool entry...
365 void AssemblyWriter::printConstant(const Constant *CPV) {
366 // Don't print out unnamed constants, they will be inlined
367 if (!CPV->hasName()) return;
370 Out << "\t%" << CPV->getName() << " = ";
372 // Print out the constant type...
373 printType(CPV->getType());
375 // Write the value out now...
376 writeOperand(CPV, false, false);
378 if (!CPV->hasName() && CPV->getType() != Type::VoidTy) {
379 int Slot = Table.getValSlot(CPV); // Print out the def slot taken...
381 printType(CPV->getType()) << ">:";
382 if (Slot >= 0) Out << Slot;
383 else Out << "<badref>";
389 // printFunction - Print all aspects of a method.
391 void AssemblyWriter::printFunction(const Function *M) {
392 // Print out the return type and name...
393 Out << "\n" << (M->isExternal() ? "declare " : "")
394 << (M->hasInternalLinkage() ? "internal " : "");
395 printType(M->getReturnType()) << " \"" << M->getName() << "\"(";
396 Table.incorporateMethod(M);
398 // Loop over the arguments, printing them...
399 const FunctionType *MT = M->getFunctionType();
401 if (!M->isExternal()) {
402 for_each(M->getArgumentList().begin(), M->getArgumentList().end(),
403 bind_obj(this, &AssemblyWriter::printFunctionArgument));
405 // Loop over the arguments, printing them...
406 const FunctionType *MT = M->getFunctionType();
407 for (FunctionType::ParamTypes::const_iterator I = MT->getParamTypes().begin(),
408 E = MT->getParamTypes().end(); I != E; ++I) {
409 if (I != MT->getParamTypes().begin()) Out << ", ";
414 // Finish printing arguments...
415 if (MT->isVarArg()) {
416 if (MT->getParamTypes().size()) Out << ", ";
417 Out << "..."; // Output varargs portion of signature!
421 if (!M->isExternal()) {
422 // Loop over the symbol table, emitting all named constants...
423 if (M->hasSymbolTable())
424 printSymbolTable(*M->getSymbolTable());
428 // Output all of its basic blocks... for the method
429 for_each(M->begin(), M->end(),
430 bind_obj(this, &AssemblyWriter::printBasicBlock));
438 // printFunctionArgument - This member is called for every argument that
439 // is passed into the method. Simply print it out
441 void AssemblyWriter::printFunctionArgument(const FunctionArgument *Arg) {
442 // Insert commas as we go... the first arg doesn't get a comma
443 if (Arg != Arg->getParent()->getArgumentList().front()) Out << ", ";
446 printType(Arg->getType());
448 // Output name, if available...
450 Out << " %" << Arg->getName();
451 else if (Table.getValSlot(Arg) < 0)
455 // printBasicBlock - This member is called for each basic block in a methd.
457 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
458 if (BB->hasName()) { // Print out the label if it exists...
459 Out << "\n" << BB->getName() << ":";
461 int Slot = Table.getValSlot(BB);
462 Out << "\n; <label>:";
464 Out << Slot; // Extra newline seperates out label's
468 Out << "\t\t\t\t\t;[#uses=" << BB->use_size() << "]\n"; // Output # uses
470 // Output all of the instructions in the basic block...
471 for_each(BB->begin(), BB->end(),
472 bind_obj(this, &AssemblyWriter::printInstruction));
476 // printInfoComment - Print a little comment after the instruction indicating
477 // which slot it occupies.
479 void AssemblyWriter::printInfoComment(const Value *V) {
480 if (V->getType() != Type::VoidTy) {
482 printType(V->getType()) << ">";
485 int Slot = Table.getValSlot(V); // Print out the def slot taken...
486 if (Slot >= 0) Out << ":" << Slot;
487 else Out << ":<badref>";
489 Out << " [#uses=" << V->use_size() << "]"; // Output # uses
493 // printInstruction - This member is called for each Instruction in a methd.
495 void AssemblyWriter::printInstruction(const Instruction *I) {
498 // Print out name if it exists...
499 if (I && I->hasName())
500 Out << "%" << I->getName() << " = ";
502 // Print out the opcode...
503 Out << I->getOpcodeName();
505 // Print out the type of the operands...
506 const Value *Operand = I->getNumOperands() ? I->getOperand(0) : 0;
508 // Special case conditional branches to swizzle the condition out to the front
509 if (I->getOpcode() == Instruction::Br && I->getNumOperands() > 1) {
510 writeOperand(I->getOperand(2), true);
512 writeOperand(Operand, true);
514 writeOperand(I->getOperand(1), true);
516 } else if (I->getOpcode() == Instruction::Switch) {
517 // Special case switch statement to get formatting nice and correct...
518 writeOperand(Operand , true); Out << ",";
519 writeOperand(I->getOperand(1), true); Out << " [";
521 for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; op += 2) {
523 writeOperand(I->getOperand(op ), true); Out << ",";
524 writeOperand(I->getOperand(op+1), true);
527 } else if (isa<PHINode>(I)) {
529 printType(I->getType());
532 for (unsigned op = 0, Eop = I->getNumOperands(); op < Eop; op += 2) {
535 writeOperand(I->getOperand(op ), false); Out << ",";
536 writeOperand(I->getOperand(op+1), false); Out << " ]";
538 } else if (isa<ReturnInst>(I) && !Operand) {
540 } else if (isa<CallInst>(I)) {
541 const PointerType *PTy = dyn_cast<PointerType>(Operand->getType());
542 const FunctionType*MTy = PTy ? dyn_cast<FunctionType>(PTy->getElementType()):0;
543 const Type *RetTy = MTy ? MTy->getReturnType() : 0;
545 // If possible, print out the short form of the call instruction, but we can
546 // only do this if the first argument is a pointer to a nonvararg method,
547 // and if the value returned is not a pointer to a method.
549 if (RetTy && !MTy->isVarArg() &&
550 (!isa<PointerType>(RetTy)||!isa<FunctionType>(cast<PointerType>(RetTy)))){
551 Out << " "; printType(RetTy);
552 writeOperand(Operand, false);
554 writeOperand(Operand, true);
557 if (I->getNumOperands() > 1) writeOperand(I->getOperand(1), true);
558 for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; ++op) {
560 writeOperand(I->getOperand(op), true);
564 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(I)) {
565 // TODO: Should try to print out short form of the Invoke instruction
566 writeOperand(Operand, true);
568 if (I->getNumOperands() > 3) writeOperand(I->getOperand(3), true);
569 for (unsigned op = 4, Eop = I->getNumOperands(); op < Eop; ++op) {
571 writeOperand(I->getOperand(op), true);
574 Out << " )\n\t\t\tto";
575 writeOperand(II->getNormalDest(), true);
577 writeOperand(II->getExceptionalDest(), true);
579 } else if (I->getOpcode() == Instruction::Malloc ||
580 I->getOpcode() == Instruction::Alloca) {
582 printType(cast<const PointerType>(I->getType())->getElementType());
583 if (I->getNumOperands()) {
585 writeOperand(I->getOperand(0), true);
587 } else if (isa<CastInst>(I)) {
588 writeOperand(Operand, true);
590 printType(I->getType());
591 } else if (Operand) { // Print the normal way...
593 // PrintAllTypes - Instructions who have operands of all the same type
594 // omit the type from all but the first operand. If the instruction has
595 // different type operands (for example br), then they are all printed.
596 bool PrintAllTypes = false;
597 const Type *TheType = Operand->getType();
599 for (unsigned i = 1, E = I->getNumOperands(); i != E; ++i) {
600 Operand = I->getOperand(i);
601 if (Operand->getType() != TheType) {
602 PrintAllTypes = true; // We have differing types! Print them all!
607 // Shift Left & Right print both types even for Ubyte LHS
608 if (isa<ShiftInst>(I)) PrintAllTypes = true;
610 if (!PrintAllTypes) {
612 printType(I->getOperand(0)->getType());
615 for (unsigned i = 0, E = I->getNumOperands(); i != E; ++i) {
617 writeOperand(I->getOperand(i), PrintAllTypes);
626 // printType - Go to extreme measures to attempt to print out a short, symbolic
627 // version of a type name.
629 ostream &AssemblyWriter::printType(const Type *Ty) {
630 return printTypeInt(Out, Ty, TypeNames);
634 //===----------------------------------------------------------------------===//
635 // External Interface declarations
636 //===----------------------------------------------------------------------===//
640 void WriteToAssembly(const Module *M, ostream &o) {
641 if (M == 0) { o << "<null> module\n"; return; }
642 SlotCalculator SlotTable(M, true);
643 AssemblyWriter W(o, SlotTable, M);
648 void WriteToAssembly(const GlobalVariable *G, ostream &o) {
649 if (G == 0) { o << "<null> global variable\n"; return; }
650 SlotCalculator SlotTable(G->getParent(), true);
651 AssemblyWriter W(o, SlotTable, G->getParent());
655 void WriteToAssembly(const Function *F, ostream &o) {
656 if (F == 0) { o << "<null> function\n"; return; }
657 SlotCalculator SlotTable(F->getParent(), true);
658 AssemblyWriter W(o, SlotTable, F->getParent());
664 void WriteToAssembly(const BasicBlock *BB, ostream &o) {
665 if (BB == 0) { o << "<null> basic block\n"; return; }
667 SlotCalculator SlotTable(BB->getParent(), true);
668 AssemblyWriter W(o, SlotTable,
669 BB->getParent() ? BB->getParent()->getParent() : 0);
674 void WriteToAssembly(const Constant *CPV, ostream &o) {
675 if (CPV == 0) { o << "<null> constant pool value\n"; return; }
676 o << " " << CPV->getType()->getDescription() << " " << CPV->getStrValue();
679 void WriteToAssembly(const Instruction *I, ostream &o) {
680 if (I == 0) { o << "<null> instruction\n"; return; }
682 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
683 SlotCalculator SlotTable(F, true);
684 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0);
689 void CachedWriter::setModule(const Module *M) {
690 delete SC; delete AW;
692 SC = new SlotCalculator(M, true);
693 AW = new AssemblyWriter(Out, *SC, M);
699 CachedWriter::~CachedWriter() {
704 CachedWriter &CachedWriter::operator<<(const Value *V) {
705 assert(AW && SC && "CachedWriter does not have a current module!");
706 switch (V->getValueType()) {
707 case Value::ConstantVal:
708 Out << " "; AW->write(V->getType());
709 Out << " " << cast<Constant>(V)->getStrValue(); break;
710 case Value::FunctionArgumentVal:
711 AW->write(V->getType()); Out << " " << V->getName(); break;
712 case Value::TypeVal: AW->write(cast<const Type>(V)); break;
713 case Value::InstructionVal: AW->write(cast<Instruction>(V)); break;
714 case Value::BasicBlockVal: AW->write(cast<BasicBlock>(V)); break;
715 case Value::FunctionVal: AW->write(cast<Function>(V)); break;
716 case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
717 case Value::ModuleVal: AW->write(cast<Module>(V)); break;
718 default: Out << "<unknown value type: " << V->getValueType() << ">"; break;