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/Assembly/Writer.h"
12 #include "llvm/SlotCalculator.h"
13 #include "llvm/Module.h"
14 #include "llvm/Function.h"
15 #include "llvm/GlobalVariable.h"
16 #include "llvm/BasicBlock.h"
17 #include "llvm/ConstantVals.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 "Support/StringExtras.h"
24 #include "Support/STLExtras.h"
32 static const Module *getModuleFromVal(const Value *V) {
33 if (const FunctionArgument *MA = dyn_cast<const FunctionArgument>(V))
34 return MA->getParent() ? MA->getParent()->getParent() : 0;
35 else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(V))
36 return BB->getParent() ? BB->getParent()->getParent() : 0;
37 else if (const Instruction *I = dyn_cast<const Instruction>(V)) {
38 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
39 return M ? M->getParent() : 0;
40 } else if (const GlobalValue *GV = dyn_cast<const GlobalValue>(V))
41 return GV->getParent();
42 else if (const Module *Mod = dyn_cast<const Module>(V))
47 static SlotCalculator *createSlotCalculator(const Value *V) {
48 assert(!isa<Type>(V) && "Can't create an SC for a type!");
49 if (const FunctionArgument *FA = dyn_cast<const FunctionArgument>(V)) {
50 return new SlotCalculator(FA->getParent(), true);
51 } else if (const Instruction *I = dyn_cast<const Instruction>(V)) {
52 return new SlotCalculator(I->getParent()->getParent(), true);
53 } else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(V)) {
54 return new SlotCalculator(BB->getParent(), true);
55 } else if (const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V)){
56 return new SlotCalculator(GV->getParent(), true);
57 } else if (const Function *Func = dyn_cast<const Function>(V)) {
58 return new SlotCalculator(Func, true);
59 } else if (const Module *Mod = dyn_cast<const Module>(V)) {
60 return new SlotCalculator(Mod, true);
65 // WriteAsOperand - Write the name of the specified value out to the specified
66 // ostream. This can be useful when you just want to print int %reg126, not the
67 // whole instruction that generated it.
69 static void WriteAsOperandInternal(ostream &Out, const Value *V, bool PrintName,
70 SlotCalculator *Table) {
71 if (PrintName && V->hasName()) {
72 Out << " %" << V->getName();
74 if (const Constant *CPV = dyn_cast<const Constant>(V)) {
75 Out << " " << CPV->getStrValue();
79 Slot = Table->getValSlot(V);
81 if (const Type *Ty = dyn_cast<const Type>(V)) {
82 Out << " " << Ty->getDescription();
86 Table = createSlotCalculator(V);
87 if (Table == 0) { Out << "BAD VALUE TYPE!"; return; }
89 Slot = Table->getValSlot(V);
92 if (Slot >= 0) Out << " %" << Slot;
94 Out << "<badref>"; // Not embeded into a location?
100 // If the module has a symbol table, take all global types and stuff their
101 // names into the TypeNames map.
103 static void fillTypeNameTable(const Module *M,
104 map<const Type *, string> &TypeNames) {
105 if (M && M->hasSymbolTable()) {
106 const SymbolTable *ST = M->getSymbolTable();
107 SymbolTable::const_iterator PI = ST->find(Type::TypeTy);
108 if (PI != ST->end()) {
109 SymbolTable::type_const_iterator I = PI->second.begin();
110 for (; I != PI->second.end(); ++I) {
111 // As a heuristic, don't insert pointer to primitive types, because
112 // they are used too often to have a single useful name.
114 const Type *Ty = cast<const Type>(I->second);
115 if (!isa<PointerType>(Ty) ||
116 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType())
117 TypeNames.insert(std::make_pair(Ty, "%"+I->first));
125 static string calcTypeName(const Type *Ty, vector<const Type *> &TypeStack,
126 map<const Type *, string> &TypeNames) {
127 if (Ty->isPrimitiveType()) return Ty->getDescription(); // Base case
129 // Check to see if the type is named.
130 map<const Type *, string>::iterator I = TypeNames.find(Ty);
131 if (I != TypeNames.end()) return I->second;
133 // Check to see if the Type is already on the stack...
134 unsigned Slot = 0, CurSize = TypeStack.size();
135 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
137 // This is another base case for the recursion. In this case, we know
138 // that we have looped back to a type that we have previously visited.
139 // Generate the appropriate upreference to handle this.
142 return "\\" + utostr(CurSize-Slot); // Here's the upreference
144 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
147 switch (Ty->getPrimitiveID()) {
148 case Type::FunctionTyID: {
149 const FunctionType *MTy = cast<const FunctionType>(Ty);
150 Result = calcTypeName(MTy->getReturnType(), TypeStack, TypeNames) + " (";
151 for (FunctionType::ParamTypes::const_iterator
152 I = MTy->getParamTypes().begin(),
153 E = MTy->getParamTypes().end(); I != E; ++I) {
154 if (I != MTy->getParamTypes().begin())
156 Result += calcTypeName(*I, TypeStack, TypeNames);
158 if (MTy->isVarArg()) {
159 if (!MTy->getParamTypes().empty()) Result += ", ";
165 case Type::StructTyID: {
166 const StructType *STy = cast<const StructType>(Ty);
168 for (StructType::ElementTypes::const_iterator
169 I = STy->getElementTypes().begin(),
170 E = STy->getElementTypes().end(); I != E; ++I) {
171 if (I != STy->getElementTypes().begin())
173 Result += calcTypeName(*I, TypeStack, TypeNames);
178 case Type::PointerTyID:
179 Result = calcTypeName(cast<const PointerType>(Ty)->getElementType(),
180 TypeStack, TypeNames) + " *";
182 case Type::ArrayTyID: {
183 const ArrayType *ATy = cast<const ArrayType>(Ty);
184 int NumElements = ATy->getNumElements();
186 if (NumElements != -1) Result += itostr(NumElements) + " x ";
187 Result += calcTypeName(ATy->getElementType(), TypeStack, TypeNames) + "]";
191 assert(0 && "Unhandled case in getTypeProps!");
195 TypeStack.pop_back(); // Remove self from stack...
200 // printTypeInt - The internal guts of printing out a type that has a
201 // potentially named portion.
203 static ostream &printTypeInt(ostream &Out, const Type *Ty,
204 map<const Type *, string> &TypeNames) {
205 // Primitive types always print out their description, regardless of whether
206 // they have been named or not.
208 if (Ty->isPrimitiveType()) return Out << Ty->getDescription();
210 // Check to see if the type is named.
211 map<const Type *, string>::iterator I = TypeNames.find(Ty);
212 if (I != TypeNames.end()) return Out << I->second;
214 // Otherwise we have a type that has not been named but is a derived type.
215 // Carefully recurse the type hierarchy to print out any contained symbolic
218 vector<const Type *> TypeStack;
219 string TypeName = calcTypeName(Ty, TypeStack, TypeNames);
220 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
221 return Out << TypeName;
225 // WriteTypeSymbolic - This attempts to write the specified type as a symbolic
226 // type, iff there is an entry in the modules symbol table for the specified
227 // type or one of it's component types. This is slower than a simple x << Type;
229 ostream &WriteTypeSymbolic(ostream &Out, const Type *Ty, const Module *M) {
232 // If they want us to print out a type, attempt to make it symbolic if there
233 // is a symbol table in the module...
234 if (M && M->hasSymbolTable()) {
235 map<const Type *, string> TypeNames;
236 fillTypeNameTable(M, TypeNames);
238 return printTypeInt(Out, Ty, TypeNames);
240 return Out << Ty->getDescription();
245 // WriteAsOperand - Write the name of the specified value out to the specified
246 // ostream. This can be useful when you just want to print int %reg126, not the
247 // whole instruction that generated it.
249 ostream &WriteAsOperand(ostream &Out, const Value *V, bool PrintType,
250 bool PrintName, SlotCalculator *Table) {
252 WriteTypeSymbolic(Out, V->getType(), getModuleFromVal(V));
254 WriteAsOperandInternal(Out, V, PrintName, Table);
260 class AssemblyWriter {
262 SlotCalculator &Table;
263 const Module *TheModule;
264 map<const Type *, string> TypeNames;
266 inline AssemblyWriter(ostream &o, SlotCalculator &Tab, const Module *M)
267 : Out(o), Table(Tab), TheModule(M) {
269 // If the module has a symbol table, take all global types and stuff their
270 // names into the TypeNames map.
272 fillTypeNameTable(M, TypeNames);
275 inline void write(const Module *M) { printModule(M); }
276 inline void write(const GlobalVariable *G) { printGlobal(G); }
277 inline void write(const Function *F) { printFunction(F); }
278 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
279 inline void write(const Instruction *I) { printInstruction(I); }
280 inline void write(const Constant *CPV) { printConstant(CPV); }
281 inline void write(const Type *Ty) { printType(Ty); }
284 void printModule(const Module *M);
285 void printSymbolTable(const SymbolTable &ST);
286 void printConstant(const Constant *CPV);
287 void printGlobal(const GlobalVariable *GV);
288 void printFunction(const Function *F);
289 void printFunctionArgument(const FunctionArgument *FA);
290 void printBasicBlock(const BasicBlock *BB);
291 void printInstruction(const Instruction *I);
292 ostream &printType(const Type *Ty);
294 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
296 // printInfoComment - Print a little comment after the instruction indicating
297 // which slot it occupies.
298 void printInfoComment(const Value *V);
302 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
304 if (PrintType) { Out << " "; printType(Operand->getType()); }
305 WriteAsOperandInternal(Out, Operand, PrintName, &Table);
309 void AssemblyWriter::printModule(const Module *M) {
310 // Loop over the symbol table, emitting all named constants...
311 if (M->hasSymbolTable())
312 printSymbolTable(*M->getSymbolTable());
314 for_each(M->gbegin(), M->gend(),
315 bind_obj(this, &AssemblyWriter::printGlobal));
317 Out << "implementation\n";
319 // Output all of the functions...
320 for_each(M->begin(), M->end(), bind_obj(this,&AssemblyWriter::printFunction));
323 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
324 if (GV->hasName()) Out << "%" << GV->getName() << " = ";
326 if (GV->hasInternalLinkage()) Out << "internal ";
327 if (!GV->hasInitializer()) Out << "uninitialized ";
329 Out << (GV->isConstant() ? "constant " : "global ");
330 printType(GV->getType()->getElementType());
332 if (GV->hasInitializer())
333 writeOperand(GV->getInitializer(), false, false);
335 printInfoComment(GV);
340 // printSymbolTable - Run through symbol table looking for named constants
341 // if a named constant is found, emit it's declaration...
343 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
344 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
345 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
346 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
348 for (; I != End; ++I) {
349 const Value *V = I->second;
350 if (const Constant *CPV = dyn_cast<const Constant>(V)) {
352 } else if (const Type *Ty = dyn_cast<const Type>(V)) {
353 Out << "\t%" << I->first << " = type " << Ty->getDescription() << "\n";
360 // printConstant - Print out a constant pool entry...
362 void AssemblyWriter::printConstant(const Constant *CPV) {
363 // Don't print out unnamed constants, they will be inlined
364 if (!CPV->hasName()) return;
367 Out << "\t%" << CPV->getName() << " = ";
369 // Print out the constant type...
370 printType(CPV->getType());
372 // Write the value out now...
373 writeOperand(CPV, false, false);
375 if (!CPV->hasName() && CPV->getType() != Type::VoidTy) {
376 int Slot = Table.getValSlot(CPV); // Print out the def slot taken...
378 printType(CPV->getType()) << ">:";
379 if (Slot >= 0) Out << Slot;
380 else Out << "<badref>";
386 // printFunction - Print all aspects of a function.
388 void AssemblyWriter::printFunction(const Function *M) {
389 // Print out the return type and name...
390 Out << "\n" << (M->isExternal() ? "declare " : "")
391 << (M->hasInternalLinkage() ? "internal " : "");
392 printType(M->getReturnType()) << " \"" << M->getName() << "\"(";
393 Table.incorporateFunction(M);
395 // Loop over the arguments, printing them...
396 const FunctionType *MT = M->getFunctionType();
398 if (!M->isExternal()) {
399 for_each(M->getArgumentList().begin(), M->getArgumentList().end(),
400 bind_obj(this, &AssemblyWriter::printFunctionArgument));
402 // Loop over the arguments, printing them...
403 const FunctionType *MT = M->getFunctionType();
404 for (FunctionType::ParamTypes::const_iterator I = MT->getParamTypes().begin(),
405 E = MT->getParamTypes().end(); I != E; ++I) {
406 if (I != MT->getParamTypes().begin()) Out << ", ";
411 // Finish printing arguments...
412 if (MT->isVarArg()) {
413 if (MT->getParamTypes().size()) Out << ", ";
414 Out << "..."; // Output varargs portion of signature!
418 if (!M->isExternal()) {
419 // Loop over the symbol table, emitting all named constants...
420 if (M->hasSymbolTable())
421 printSymbolTable(*M->getSymbolTable());
425 // Output all of its basic blocks... for the function
426 for_each(M->begin(), M->end(),
427 bind_obj(this, &AssemblyWriter::printBasicBlock));
432 Table.purgeFunction();
435 // printFunctionArgument - This member is called for every argument that
436 // is passed into the function. Simply print it out
438 void AssemblyWriter::printFunctionArgument(const FunctionArgument *Arg) {
439 // Insert commas as we go... the first arg doesn't get a comma
440 if (Arg != Arg->getParent()->getArgumentList().front()) Out << ", ";
443 printType(Arg->getType());
445 // Output name, if available...
447 Out << " %" << Arg->getName();
448 else if (Table.getValSlot(Arg) < 0)
452 // printBasicBlock - This member is called for each basic block in a methd.
454 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
455 if (BB->hasName()) { // Print out the label if it exists...
456 Out << "\n" << BB->getName() << ":";
458 int Slot = Table.getValSlot(BB);
459 Out << "\n; <label>:";
461 Out << Slot; // Extra newline seperates out label's
465 Out << "\t\t\t\t\t;[#uses=" << BB->use_size() << "]\n"; // Output # uses
467 // Output all of the instructions in the basic block...
468 for_each(BB->begin(), BB->end(),
469 bind_obj(this, &AssemblyWriter::printInstruction));
473 // printInfoComment - Print a little comment after the instruction indicating
474 // which slot it occupies.
476 void AssemblyWriter::printInfoComment(const Value *V) {
477 if (V->getType() != Type::VoidTy) {
479 printType(V->getType()) << ">";
482 int Slot = Table.getValSlot(V); // Print out the def slot taken...
483 if (Slot >= 0) Out << ":" << Slot;
484 else Out << ":<badref>";
486 Out << " [#uses=" << V->use_size() << "]"; // Output # uses
490 // printInstruction - This member is called for each Instruction in a methd.
492 void AssemblyWriter::printInstruction(const Instruction *I) {
495 // Print out name if it exists...
496 if (I && I->hasName())
497 Out << "%" << I->getName() << " = ";
499 // Print out the opcode...
500 Out << I->getOpcodeName();
502 // Print out the type of the operands...
503 const Value *Operand = I->getNumOperands() ? I->getOperand(0) : 0;
505 // Special case conditional branches to swizzle the condition out to the front
506 if (I->getOpcode() == Instruction::Br && I->getNumOperands() > 1) {
507 writeOperand(I->getOperand(2), true);
509 writeOperand(Operand, true);
511 writeOperand(I->getOperand(1), true);
513 } else if (I->getOpcode() == Instruction::Switch) {
514 // Special case switch statement to get formatting nice and correct...
515 writeOperand(Operand , true); Out << ",";
516 writeOperand(I->getOperand(1), true); Out << " [";
518 for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; op += 2) {
520 writeOperand(I->getOperand(op ), true); Out << ",";
521 writeOperand(I->getOperand(op+1), true);
524 } else if (isa<PHINode>(I)) {
526 printType(I->getType());
529 for (unsigned op = 0, Eop = I->getNumOperands(); op < Eop; op += 2) {
532 writeOperand(I->getOperand(op ), false); Out << ",";
533 writeOperand(I->getOperand(op+1), false); Out << " ]";
535 } else if (isa<ReturnInst>(I) && !Operand) {
537 } else if (isa<CallInst>(I)) {
538 const PointerType *PTy = dyn_cast<PointerType>(Operand->getType());
539 const FunctionType*MTy = PTy ? dyn_cast<FunctionType>(PTy->getElementType()):0;
540 const Type *RetTy = MTy ? MTy->getReturnType() : 0;
542 // If possible, print out the short form of the call instruction, but we can
543 // only do this if the first argument is a pointer to a nonvararg function,
544 // and if the value returned is not a pointer to a function.
546 if (RetTy && !MTy->isVarArg() &&
547 (!isa<PointerType>(RetTy)||!isa<FunctionType>(cast<PointerType>(RetTy)))){
548 Out << " "; printType(RetTy);
549 writeOperand(Operand, false);
551 writeOperand(Operand, true);
554 if (I->getNumOperands() > 1) writeOperand(I->getOperand(1), true);
555 for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; ++op) {
557 writeOperand(I->getOperand(op), true);
561 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(I)) {
562 // TODO: Should try to print out short form of the Invoke instruction
563 writeOperand(Operand, true);
565 if (I->getNumOperands() > 3) writeOperand(I->getOperand(3), true);
566 for (unsigned op = 4, Eop = I->getNumOperands(); op < Eop; ++op) {
568 writeOperand(I->getOperand(op), true);
571 Out << " )\n\t\t\tto";
572 writeOperand(II->getNormalDest(), true);
574 writeOperand(II->getExceptionalDest(), true);
576 } else if (I->getOpcode() == Instruction::Malloc ||
577 I->getOpcode() == Instruction::Alloca) {
579 printType(cast<const PointerType>(I->getType())->getElementType());
580 if (I->getNumOperands()) {
582 writeOperand(I->getOperand(0), true);
584 } else if (isa<CastInst>(I)) {
585 writeOperand(Operand, true);
587 printType(I->getType());
588 } else if (Operand) { // Print the normal way...
590 // PrintAllTypes - Instructions who have operands of all the same type
591 // omit the type from all but the first operand. If the instruction has
592 // different type operands (for example br), then they are all printed.
593 bool PrintAllTypes = false;
594 const Type *TheType = Operand->getType();
596 for (unsigned i = 1, E = I->getNumOperands(); i != E; ++i) {
597 Operand = I->getOperand(i);
598 if (Operand->getType() != TheType) {
599 PrintAllTypes = true; // We have differing types! Print them all!
604 // Shift Left & Right print both types even for Ubyte LHS
605 if (isa<ShiftInst>(I)) PrintAllTypes = true;
607 if (!PrintAllTypes) {
609 printType(I->getOperand(0)->getType());
612 for (unsigned i = 0, E = I->getNumOperands(); i != E; ++i) {
614 writeOperand(I->getOperand(i), PrintAllTypes);
623 // printType - Go to extreme measures to attempt to print out a short, symbolic
624 // version of a type name.
626 ostream &AssemblyWriter::printType(const Type *Ty) {
627 return printTypeInt(Out, Ty, TypeNames);
631 //===----------------------------------------------------------------------===//
632 // External Interface declarations
633 //===----------------------------------------------------------------------===//
636 void Module::print(std::ostream &o) const {
637 SlotCalculator SlotTable(this, true);
638 AssemblyWriter W(o, SlotTable, this);
642 void GlobalVariable::print(std::ostream &o) const {
643 SlotCalculator SlotTable(getParent(), true);
644 AssemblyWriter W(o, SlotTable, getParent());
648 void Function::print(std::ostream &o) const {
649 SlotCalculator SlotTable(getParent(), true);
650 AssemblyWriter W(o, SlotTable, getParent());
655 void BasicBlock::print(std::ostream &o) const {
656 SlotCalculator SlotTable(getParent(), true);
657 AssemblyWriter W(o, SlotTable,
658 getParent() ? getParent()->getParent() : 0);
662 void Instruction::print(std::ostream &o) const {
663 const Function *F = getParent() ? getParent()->getParent() : 0;
664 SlotCalculator SlotTable(F, true);
665 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0);
670 void Constant::print(std::ostream &o) const {
671 if (this == 0) { o << "<null> constant value\n"; return; }
672 o << " " << getType()->getDescription() << " " << getStrValue();
675 void Type::print(std::ostream &o) const {
679 o << getDescription();
682 void FunctionArgument::print(std::ostream &o) const {
683 o << getType() << " " << getName();
686 void Value::dump() const { print(std::cerr); }
688 //===----------------------------------------------------------------------===//
689 // CachedWriter Class Implementation
690 //===----------------------------------------------------------------------===//
692 void CachedWriter::setModule(const Module *M) {
693 delete SC; delete AW;
695 SC = new SlotCalculator(M, true);
696 AW = new AssemblyWriter(Out, *SC, M);
702 CachedWriter::~CachedWriter() {
707 CachedWriter &CachedWriter::operator<<(const Value *V) {
708 assert(AW && SC && "CachedWriter does not have a current module!");
709 switch (V->getValueType()) {
710 case Value::ConstantVal:
711 Out << " "; AW->write(V->getType());
712 Out << " " << cast<Constant>(V)->getStrValue(); break;
713 case Value::FunctionArgumentVal:
714 AW->write(V->getType()); Out << " " << V->getName(); break;
715 case Value::TypeVal: AW->write(cast<const Type>(V)); break;
716 case Value::InstructionVal: AW->write(cast<Instruction>(V)); break;
717 case Value::BasicBlockVal: AW->write(cast<BasicBlock>(V)); break;
718 case Value::FunctionVal: AW->write(cast<Function>(V)); break;
719 case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
720 case Value::ModuleVal: AW->write(cast<Module>(V)); break;
721 default: Out << "<unknown value type: " << V->getValueType() << ">"; break;