The contents of the SymTabValue class have been incorporated into the
[oota-llvm.git] / lib / VMCore / AsmWriter.cpp
1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
2 //
3 // This library implements the functionality defined in llvm/Assembly/Writer.h
4 //
5 // Note that these routines must be extremely tolerant of various errors in the
6 // LLVM code, because of of the primary uses of it is for debugging
7 // transformations.
8 //
9 // TODO: print out the type name instead of the full type if a particular type
10 // is in the symbol table...
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Assembly/CachedWriter.h"
15 #include "llvm/Assembly/Writer.h"
16 #include "llvm/SlotCalculator.h"
17 #include "llvm/Module.h"
18 #include "llvm/Function.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/BasicBlock.h"
21 #include "llvm/ConstantVals.h"
22 #include "llvm/iMemory.h"
23 #include "llvm/iTerminators.h"
24 #include "llvm/iPHINode.h"
25 #include "llvm/iOther.h"
26 #include "llvm/SymbolTable.h"
27 #include "llvm/Argument.h"
28 #include "Support/StringExtras.h"
29 #include "Support/STLExtras.h"
30 #include <algorithm>
31 #include <map>
32 using std::string;
33 using std::map;
34 using std::vector;
35 using std::ostream;
36
37 static void WriteAsOperandInternal(ostream &Out, const Value *V, bool PrintName,
38                                    map<const Type *, string> &TypeTable,
39                                    SlotCalculator *Table);
40
41 static const Module *getModuleFromVal(const Value *V) {
42   if (const Argument *MA = dyn_cast<const Argument>(V))
43     return MA->getParent() ? MA->getParent()->getParent() : 0;
44   else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(V))
45     return BB->getParent() ? BB->getParent()->getParent() : 0;
46   else if (const Instruction *I = dyn_cast<const Instruction>(V)) {
47     const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
48     return M ? M->getParent() : 0;
49   } else if (const GlobalValue *GV = dyn_cast<const GlobalValue>(V))
50     return GV->getParent();
51   return 0;
52 }
53
54 static SlotCalculator *createSlotCalculator(const Value *V) {
55   assert(!isa<Type>(V) && "Can't create an SC for a type!");
56   if (const Argument *FA = dyn_cast<const Argument>(V)) {
57     return new SlotCalculator(FA->getParent(), true);
58   } else if (const Instruction *I = dyn_cast<const Instruction>(V)) {
59     return new SlotCalculator(I->getParent()->getParent(), true);
60   } else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(V)) {
61     return new SlotCalculator(BB->getParent(), true);
62   } else if (const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V)){
63     return new SlotCalculator(GV->getParent(), true);
64   } else if (const Function *Func = dyn_cast<const Function>(V)) {
65     return new SlotCalculator(Func, true);
66   }
67   return 0;
68 }
69
70
71 // If the module has a symbol table, take all global types and stuff their
72 // names into the TypeNames map.
73 //
74 static void fillTypeNameTable(const Module *M,
75                               map<const Type *, string> &TypeNames) {
76   if (M && M->hasSymbolTable()) {
77     const SymbolTable *ST = M->getSymbolTable();
78     SymbolTable::const_iterator PI = ST->find(Type::TypeTy);
79     if (PI != ST->end()) {
80       SymbolTable::type_const_iterator I = PI->second.begin();
81       for (; I != PI->second.end(); ++I) {
82         // As a heuristic, don't insert pointer to primitive types, because
83         // they are used too often to have a single useful name.
84         //
85         const Type *Ty = cast<const Type>(I->second);
86         if (!isa<PointerType>(Ty) ||
87             !cast<PointerType>(Ty)->getElementType()->isPrimitiveType())
88           TypeNames.insert(std::make_pair(Ty, "%"+I->first));
89       }
90     }
91   }
92 }
93
94
95
96 static string calcTypeName(const Type *Ty, vector<const Type *> &TypeStack,
97                            map<const Type *, string> &TypeNames) {
98   if (Ty->isPrimitiveType()) return Ty->getDescription();  // Base case
99
100   // Check to see if the type is named.
101   map<const Type *, string>::iterator I = TypeNames.find(Ty);
102   if (I != TypeNames.end()) return I->second;
103
104   // Check to see if the Type is already on the stack...
105   unsigned Slot = 0, CurSize = TypeStack.size();
106   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
107
108   // This is another base case for the recursion.  In this case, we know 
109   // that we have looped back to a type that we have previously visited.
110   // Generate the appropriate upreference to handle this.
111   // 
112   if (Slot < CurSize)
113     return "\\" + utostr(CurSize-Slot);       // Here's the upreference
114
115   TypeStack.push_back(Ty);    // Recursive case: Add us to the stack..
116   
117   string Result;
118   switch (Ty->getPrimitiveID()) {
119   case Type::FunctionTyID: {
120     const FunctionType *FTy = cast<const FunctionType>(Ty);
121     Result = calcTypeName(FTy->getReturnType(), TypeStack, TypeNames) + " (";
122     for (FunctionType::ParamTypes::const_iterator
123            I = FTy->getParamTypes().begin(),
124            E = FTy->getParamTypes().end(); I != E; ++I) {
125       if (I != FTy->getParamTypes().begin())
126         Result += ", ";
127       Result += calcTypeName(*I, TypeStack, TypeNames);
128     }
129     if (FTy->isVarArg()) {
130       if (!FTy->getParamTypes().empty()) Result += ", ";
131       Result += "...";
132     }
133     Result += ")";
134     break;
135   }
136   case Type::StructTyID: {
137     const StructType *STy = cast<const StructType>(Ty);
138     Result = "{ ";
139     for (StructType::ElementTypes::const_iterator
140            I = STy->getElementTypes().begin(),
141            E = STy->getElementTypes().end(); I != E; ++I) {
142       if (I != STy->getElementTypes().begin())
143         Result += ", ";
144       Result += calcTypeName(*I, TypeStack, TypeNames);
145     }
146     Result += " }";
147     break;
148   }
149   case Type::PointerTyID:
150     Result = calcTypeName(cast<const PointerType>(Ty)->getElementType(), 
151                           TypeStack, TypeNames) + "*";
152     break;
153   case Type::ArrayTyID: {
154     const ArrayType *ATy = cast<const ArrayType>(Ty);
155     Result = "[" + utostr(ATy->getNumElements()) + " x ";
156     Result += calcTypeName(ATy->getElementType(), TypeStack, TypeNames) + "]";
157     break;
158   }
159   default:
160     assert(0 && "Unhandled case in getTypeProps!");
161     Result = "<error>";
162   }
163
164   TypeStack.pop_back();       // Remove self from stack...
165   return Result;
166 }
167
168
169 // printTypeInt - The internal guts of printing out a type that has a
170 // potentially named portion.
171 //
172 static ostream &printTypeInt(ostream &Out, const Type *Ty,
173                              map<const Type *, string> &TypeNames) {
174   // Primitive types always print out their description, regardless of whether
175   // they have been named or not.
176   //
177   if (Ty->isPrimitiveType()) return Out << Ty->getDescription();
178
179   // Check to see if the type is named.
180   map<const Type *, string>::iterator I = TypeNames.find(Ty);
181   if (I != TypeNames.end()) return Out << I->second;
182
183   // Otherwise we have a type that has not been named but is a derived type.
184   // Carefully recurse the type hierarchy to print out any contained symbolic
185   // names.
186   //
187   vector<const Type *> TypeStack;
188   string TypeName = calcTypeName(Ty, TypeStack, TypeNames);
189   TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
190   return Out << TypeName;
191 }
192
193
194 // WriteTypeSymbolic - This attempts to write the specified type as a symbolic
195 // type, iff there is an entry in the modules symbol table for the specified
196 // type or one of it's component types.  This is slower than a simple x << Type;
197 //
198 ostream &WriteTypeSymbolic(ostream &Out, const Type *Ty, const Module *M) {
199   Out << " "; 
200
201   // If they want us to print out a type, attempt to make it symbolic if there
202   // is a symbol table in the module...
203   if (M && M->hasSymbolTable()) {
204     map<const Type *, string> TypeNames;
205     fillTypeNameTable(M, TypeNames);
206     
207     return printTypeInt(Out, Ty, TypeNames);
208   } else {
209     return Out << Ty->getDescription();
210   }
211 }
212
213 static void WriteConstantInt(ostream &Out, const Constant *CV, bool PrintName,
214                              map<const Type *, string> &TypeTable,
215                              SlotCalculator *Table) {
216   if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
217     Out << (CB == ConstantBool::True ? "true" : "false");
218   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
219     Out << CI->getValue();
220   } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
221     Out << CI->getValue();
222   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
223     // We would like to output the FP constant value in exponential notation,
224     // but we cannot do this if doing so will lose precision.  Check here to
225     // make sure that we only output it in exponential format if we can parse
226     // the value back and get the same value.
227     //
228     std::string StrVal = ftostr(CFP->getValue());
229
230     // Check to make sure that the stringized number is not some string like
231     // "Inf" or NaN, that atof will accept, but the lexer will not.  Check that
232     // the string matches the "[-+]?[0-9]" regex.
233     //
234     if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
235         ((StrVal[0] == '-' || StrVal[0] == '+') &&
236          (StrVal[0] >= '0' && StrVal[0] <= '9')))
237       // Reparse stringized version!
238       if (atof(StrVal.c_str()) == CFP->getValue()) {
239         Out << StrVal; return;
240       }
241     
242     // Otherwise we could not reparse it to exactly the same value, so we must
243     // output the string in hexadecimal format!
244     //
245     // Behave nicely in the face of C TBAA rules... see:
246     // http://www.nullstone.com/htmls/category/aliastyp.htm
247     //
248     double Val = CFP->getValue();
249     char *Ptr = (char*)&Val;
250     assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
251            "assuming that double is 64 bits!");
252     Out << "0x" << utohexstr(*(uint64_t*)Ptr);
253
254   } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
255     // As a special case, print the array as a string if it is an array of
256     // ubytes or an array of sbytes with positive values.
257     // 
258     const Type *ETy = CA->getType()->getElementType();
259     bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
260
261     if (ETy == Type::SByteTy)
262       for (unsigned i = 0; i < CA->getNumOperands(); ++i)
263         if (cast<ConstantSInt>(CA->getOperand(i))->getValue() < 0) {
264           isString = false;
265           break;
266         }
267
268     if (isString) {
269       Out << "c\"";
270       for (unsigned i = 0; i < CA->getNumOperands(); ++i) {
271         unsigned char C = (ETy == Type::SByteTy) ?
272           (unsigned char)cast<ConstantSInt>(CA->getOperand(i))->getValue() :
273           (unsigned char)cast<ConstantUInt>(CA->getOperand(i))->getValue();
274         
275         if (isprint(C)) {
276           Out << C;
277         } else {
278           Out << '\\'
279               << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
280               << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
281         }
282       }
283       Out << "\"";
284
285     } else {                // Cannot output in string format...
286       Out << "[";
287       if (CA->getNumOperands()) {
288         Out << " ";
289         printTypeInt(Out, ETy, TypeTable);
290         WriteAsOperandInternal(Out, CA->getOperand(0),
291                                PrintName, TypeTable, Table);
292         for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
293           Out << ", ";
294           printTypeInt(Out, ETy, TypeTable);
295           WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
296                                  TypeTable, Table);
297         }
298       }
299       Out << " ]";
300     }
301   } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
302     Out << "{";
303     if (CS->getNumOperands()) {
304       Out << " ";
305       printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
306
307       WriteAsOperandInternal(Out, CS->getOperand(0),
308                              PrintName, TypeTable, Table);
309
310       for (unsigned i = 1; i < CS->getNumOperands(); i++) {
311         Out << ", ";
312         printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
313
314         WriteAsOperandInternal(Out, CS->getOperand(i),
315                                PrintName, TypeTable, Table);
316       }
317     }
318
319     Out << " }";
320   } else if (isa<ConstantPointerNull>(CV)) {
321     Out << "null";
322
323   } else if (ConstantPointerRef *PR = dyn_cast<ConstantPointerRef>(CV)) {
324     const GlobalValue *V = PR->getValue();
325     if (V->hasName()) {
326       Out << "%" << V->getName();
327     } else if (Table) {
328       int Slot = Table->getValSlot(V);
329       if (Slot >= 0)
330         Out << "%" << Slot;
331       else
332         Out << "<pointer reference badref>";
333     } else {
334       Out << "<pointer reference without context info>";
335     }
336   } else {
337     assert(0 && "Unrecognized constant value!!!");
338   }
339 }
340
341
342 // WriteAsOperand - Write the name of the specified value out to the specified
343 // ostream.  This can be useful when you just want to print int %reg126, not the
344 // whole instruction that generated it.
345 //
346 static void WriteAsOperandInternal(ostream &Out, const Value *V, bool PrintName,
347                                    map<const Type *, string> &TypeTable,
348                                    SlotCalculator *Table) {
349   Out << " ";
350   if (PrintName && V->hasName()) {
351     Out << "%" << V->getName();
352   } else {
353     if (const Constant *CV = dyn_cast<const Constant>(V)) {
354       WriteConstantInt(Out, CV, PrintName, TypeTable, Table);
355     } else {
356       int Slot;
357       if (Table) {
358         Slot = Table->getValSlot(V);
359       } else {
360         if (const Type *Ty = dyn_cast<const Type>(V)) {
361           Out << Ty->getDescription();
362           return;
363         }
364
365         Table = createSlotCalculator(V);
366         if (Table == 0) { Out << "BAD VALUE TYPE!"; return; }
367
368         Slot = Table->getValSlot(V);
369         delete Table;
370       }
371       if (Slot >= 0)  Out << "%" << Slot;
372       else if (PrintName)
373         Out << "<badref>";     // Not embeded into a location?
374     }
375   }
376 }
377
378
379
380 // WriteAsOperand - Write the name of the specified value out to the specified
381 // ostream.  This can be useful when you just want to print int %reg126, not the
382 // whole instruction that generated it.
383 //
384 ostream &WriteAsOperand(ostream &Out, const Value *V, bool PrintType, 
385                         bool PrintName, SlotCalculator *Table) {
386   map<const Type *, string> TypeNames;
387   const Module *M = getModuleFromVal(V);
388
389   if (M && M->hasSymbolTable())
390     fillTypeNameTable(M, TypeNames);
391
392   if (PrintType)
393     printTypeInt(Out, V->getType(), TypeNames);
394   
395   WriteAsOperandInternal(Out, V, PrintName, TypeNames, Table);
396   return Out;
397 }
398
399
400
401 class AssemblyWriter {
402   ostream &Out;
403   SlotCalculator &Table;
404   const Module *TheModule;
405   map<const Type *, string> TypeNames;
406 public:
407   inline AssemblyWriter(ostream &o, SlotCalculator &Tab, const Module *M)
408     : Out(o), Table(Tab), TheModule(M) {
409
410     // If the module has a symbol table, take all global types and stuff their
411     // names into the TypeNames map.
412     //
413     fillTypeNameTable(M, TypeNames);
414   }
415
416   inline void write(const Module *M)         { printModule(M);      }
417   inline void write(const GlobalVariable *G) { printGlobal(G);      }
418   inline void write(const Function *F)       { printFunction(F);    }
419   inline void write(const BasicBlock *BB)    { printBasicBlock(BB); }
420   inline void write(const Instruction *I)    { printInstruction(I); }
421   inline void write(const Constant *CPV)     { printConstant(CPV);  }
422   inline void write(const Type *Ty)          { printType(Ty);       }
423
424   void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
425
426 private :
427   void printModule(const Module *M);
428   void printSymbolTable(const SymbolTable &ST);
429   void printConstant(const Constant *CPV);
430   void printGlobal(const GlobalVariable *GV);
431   void printFunction(const Function *F);
432   void printArgument(const Argument *FA);
433   void printBasicBlock(const BasicBlock *BB);
434   void printInstruction(const Instruction *I);
435
436   // printType - Go to extreme measures to attempt to print out a short,
437   // symbolic version of a type name.
438   //
439   ostream &printType(const Type *Ty) {
440     return printTypeInt(Out, Ty, TypeNames);
441   }
442
443   // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
444   // without considering any symbolic types that we may have equal to it.
445   //
446   ostream &printTypeAtLeastOneLevel(const Type *Ty);
447
448   // printInfoComment - Print a little comment after the instruction indicating
449   // which slot it occupies.
450   void printInfoComment(const Value *V);
451 };
452
453
454 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
455 // without considering any symbolic types that we may have equal to it.
456 //
457 ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
458   if (FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
459     printType(FTy->getReturnType()) << " (";
460     for (FunctionType::ParamTypes::const_iterator
461            I = FTy->getParamTypes().begin(),
462            E = FTy->getParamTypes().end(); I != E; ++I) {
463       if (I != FTy->getParamTypes().begin())
464         Out << ", ";
465       printType(*I);
466     }
467     if (FTy->isVarArg()) {
468       if (!FTy->getParamTypes().empty()) Out << ", ";
469       Out << "...";
470     }
471     Out << ")";
472   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
473     Out << "{ ";
474     for (StructType::ElementTypes::const_iterator
475            I = STy->getElementTypes().begin(),
476            E = STy->getElementTypes().end(); I != E; ++I) {
477       if (I != STy->getElementTypes().begin())
478         Out << ", ";
479       printType(*I);
480     }
481     Out << " }";
482   } else if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
483     printType(PTy->getElementType()) << "*";
484   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
485     Out << "[" << ATy->getNumElements() << " x ";
486     printType(ATy->getElementType()) << "]";
487   } else {
488     assert(Ty->isPrimitiveType() && "Unknown derived type!");
489     printType(Ty);
490   }
491   return Out;
492 }
493
494
495 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType, 
496                                   bool PrintName) {
497   if (PrintType) { Out << " "; printType(Operand->getType()); }
498   WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Table);
499 }
500
501
502 void AssemblyWriter::printModule(const Module *M) {
503   // Loop over the symbol table, emitting all named constants...
504   if (M->hasSymbolTable())
505     printSymbolTable(*M->getSymbolTable());
506   
507   for_each(M->gbegin(), M->gend(), 
508            bind_obj(this, &AssemblyWriter::printGlobal));
509
510   Out << "implementation\n";
511   
512   // Output all of the functions...
513   for_each(M->begin(), M->end(), bind_obj(this,&AssemblyWriter::printFunction));
514 }
515
516 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
517   if (GV->hasName()) Out << "%" << GV->getName() << " = ";
518
519   if (GV->hasInternalLinkage()) Out << "internal ";
520   if (!GV->hasInitializer()) Out << "uninitialized ";
521
522   Out << (GV->isConstant() ? "constant " : "global ");
523   printType(GV->getType()->getElementType());
524
525   if (GV->hasInitializer())
526     writeOperand(GV->getInitializer(), false, false);
527
528   printInfoComment(GV);
529   Out << "\n";
530 }
531
532
533 // printSymbolTable - Run through symbol table looking for named constants
534 // if a named constant is found, emit it's declaration...
535 //
536 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
537   for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
538     SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
539     SymbolTable::type_const_iterator End = ST.type_end(TI->first);
540     
541     for (; I != End; ++I) {
542       const Value *V = I->second;
543       if (const Constant *CPV = dyn_cast<const Constant>(V)) {
544         printConstant(CPV);
545       } else if (const Type *Ty = dyn_cast<const Type>(V)) {
546         Out << "\t%" << I->first << " = type ";
547
548         // Make sure we print out at least one level of the type structure, so
549         // that we do not get %FILE = type %FILE
550         //
551         printTypeAtLeastOneLevel(Ty) << "\n";
552       }
553     }
554   }
555 }
556
557
558 // printConstant - Print out a constant pool entry...
559 //
560 void AssemblyWriter::printConstant(const Constant *CPV) {
561   // Don't print out unnamed constants, they will be inlined
562   if (!CPV->hasName()) return;
563
564   // Print out name...
565   Out << "\t%" << CPV->getName() << " =";
566
567   // Write the value out now...
568   writeOperand(CPV, true, false);
569
570   printInfoComment(CPV);
571   Out << "\n";
572 }
573
574 // printFunction - Print all aspects of a function.
575 //
576 void AssemblyWriter::printFunction(const Function *M) {
577   // Print out the return type and name...
578   Out << "\n" << (M->isExternal() ? "declare " : "")
579       << (M->hasInternalLinkage() ? "internal " : "");
580   printType(M->getReturnType()) << " \"" << M->getName() << "\"(";
581   Table.incorporateFunction(M);
582
583   // Loop over the arguments, printing them...
584   const FunctionType *MT = M->getFunctionType();
585
586   if (!M->isExternal()) {
587     for_each(M->getArgumentList().begin(), M->getArgumentList().end(),
588              bind_obj(this, &AssemblyWriter::printArgument));
589   } else {
590     // Loop over the arguments, printing them...
591     const FunctionType *MT = M->getFunctionType();
592     for (FunctionType::ParamTypes::const_iterator I = MT->getParamTypes().begin(),
593            E = MT->getParamTypes().end(); I != E; ++I) {
594       if (I != MT->getParamTypes().begin()) Out << ", ";
595       printType(*I);
596     }
597   }
598
599   // Finish printing arguments...
600   if (MT->isVarArg()) {
601     if (MT->getParamTypes().size()) Out << ", ";
602     Out << "...";  // Output varargs portion of signature!
603   }
604   Out << ")\n";
605
606   if (!M->isExternal()) {
607     // Loop over the symbol table, emitting all named constants...
608     if (M->hasSymbolTable())
609       printSymbolTable(*M->getSymbolTable());
610
611     Out << "begin";
612   
613     // Output all of its basic blocks... for the function
614     for_each(M->begin(), M->end(),
615              bind_obj(this, &AssemblyWriter::printBasicBlock));
616
617     Out << "end\n";
618   }
619
620   Table.purgeFunction();
621 }
622
623 // printArgument - This member is called for every argument that 
624 // is passed into the function.  Simply print it out
625 //
626 void AssemblyWriter::printArgument(const Argument *Arg) {
627   // Insert commas as we go... the first arg doesn't get a comma
628   if (Arg != Arg->getParent()->getArgumentList().front()) Out << ", ";
629
630   // Output type...
631   printType(Arg->getType());
632   
633   // Output name, if available...
634   if (Arg->hasName())
635     Out << " %" << Arg->getName();
636   else if (Table.getValSlot(Arg) < 0)
637     Out << "<badref>";
638 }
639
640 // printBasicBlock - This member is called for each basic block in a methd.
641 //
642 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
643   if (BB->hasName()) {              // Print out the label if it exists...
644     Out << "\n" << BB->getName() << ":";
645   } else {
646     int Slot = Table.getValSlot(BB);
647     Out << "\n; <label>:";
648     if (Slot >= 0) 
649       Out << Slot;         // Extra newline seperates out label's
650     else 
651       Out << "<badref>"; 
652   }
653   Out << "\t\t\t\t\t;[#uses=" << BB->use_size() << "]\n";  // Output # uses
654
655   // Output all of the instructions in the basic block...
656   for_each(BB->begin(), BB->end(),
657            bind_obj(this, &AssemblyWriter::printInstruction));
658 }
659
660
661 // printInfoComment - Print a little comment after the instruction indicating
662 // which slot it occupies.
663 //
664 void AssemblyWriter::printInfoComment(const Value *V) {
665   if (V->getType() != Type::VoidTy) {
666     Out << "\t\t; <";
667     printType(V->getType()) << ">";
668
669     if (!V->hasName()) {
670       int Slot = Table.getValSlot(V); // Print out the def slot taken...
671       if (Slot >= 0) Out << ":" << Slot;
672       else Out << ":<badref>";
673     }
674     Out << " [#uses=" << V->use_size() << "]";  // Output # uses
675   }
676 }
677
678 // printInstruction - This member is called for each Instruction in a methd.
679 //
680 void AssemblyWriter::printInstruction(const Instruction *I) {
681   Out << "\t";
682
683   // Print out name if it exists...
684   if (I && I->hasName())
685     Out << "%" << I->getName() << " = ";
686
687   // Print out the opcode...
688   Out << I->getOpcodeName();
689
690   // Print out the type of the operands...
691   const Value *Operand = I->getNumOperands() ? I->getOperand(0) : 0;
692
693   // Special case conditional branches to swizzle the condition out to the front
694   if (isa<BranchInst>(I) && I->getNumOperands() > 1) {
695     writeOperand(I->getOperand(2), true);
696     Out << ",";
697     writeOperand(Operand, true);
698     Out << ",";
699     writeOperand(I->getOperand(1), true);
700
701   } else if (isa<SwitchInst>(I)) {
702     // Special case switch statement to get formatting nice and correct...
703     writeOperand(Operand         , true); Out << ",";
704     writeOperand(I->getOperand(1), true); Out << " [";
705
706     for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; op += 2) {
707       Out << "\n\t\t";
708       writeOperand(I->getOperand(op  ), true); Out << ",";
709       writeOperand(I->getOperand(op+1), true);
710     }
711     Out << "\n\t]";
712   } else if (isa<PHINode>(I)) {
713     Out << " ";
714     printType(I->getType());
715     Out << " ";
716
717     for (unsigned op = 0, Eop = I->getNumOperands(); op < Eop; op += 2) {
718       if (op) Out << ", ";
719       Out << "[";  
720       writeOperand(I->getOperand(op  ), false); Out << ",";
721       writeOperand(I->getOperand(op+1), false); Out << " ]";
722     }
723   } else if (isa<ReturnInst>(I) && !Operand) {
724     Out << " void";
725   } else if (isa<CallInst>(I)) {
726     const PointerType *PTy = dyn_cast<PointerType>(Operand->getType());
727     const FunctionType*MTy = PTy ? dyn_cast<FunctionType>(PTy->getElementType()):0;
728     const Type      *RetTy = MTy ? MTy->getReturnType() : 0;
729
730     // If possible, print out the short form of the call instruction, but we can
731     // only do this if the first argument is a pointer to a nonvararg function,
732     // and if the value returned is not a pointer to a function.
733     //
734     if (RetTy && MTy && !MTy->isVarArg() &&
735         (!isa<PointerType>(RetTy) || 
736          !isa<FunctionType>(cast<PointerType>(RetTy)))) {
737       Out << " "; printType(RetTy);
738       writeOperand(Operand, false);
739     } else {
740       writeOperand(Operand, true);
741     }
742     Out << "(";
743     if (I->getNumOperands() > 1) writeOperand(I->getOperand(1), true);
744     for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; ++op) {
745       Out << ",";
746       writeOperand(I->getOperand(op), true);
747     }
748
749     Out << " )";
750   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(I)) {
751     // TODO: Should try to print out short form of the Invoke instruction
752     writeOperand(Operand, true);
753     Out << "(";
754     if (I->getNumOperands() > 3) writeOperand(I->getOperand(3), true);
755     for (unsigned op = 4, Eop = I->getNumOperands(); op < Eop; ++op) {
756       Out << ",";
757       writeOperand(I->getOperand(op), true);
758     }
759
760     Out << " )\n\t\t\tto";
761     writeOperand(II->getNormalDest(), true);
762     Out << " except";
763     writeOperand(II->getExceptionalDest(), true);
764
765   } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(I)) {
766     Out << " ";
767     printType(AI->getType()->getElementType());
768     if (AI->isArrayAllocation()) {
769       Out << ",";
770       writeOperand(AI->getArraySize(), true);
771     }
772   } else if (isa<CastInst>(I)) {
773     writeOperand(Operand, true);
774     Out << " to ";
775     printType(I->getType());
776   } else if (Operand) {   // Print the normal way...
777
778     // PrintAllTypes - Instructions who have operands of all the same type 
779     // omit the type from all but the first operand.  If the instruction has
780     // different type operands (for example br), then they are all printed.
781     bool PrintAllTypes = false;
782     const Type *TheType = Operand->getType();
783
784     for (unsigned i = 1, E = I->getNumOperands(); i != E; ++i) {
785       Operand = I->getOperand(i);
786       if (Operand->getType() != TheType) {
787         PrintAllTypes = true;       // We have differing types!  Print them all!
788         break;
789       }
790     }
791
792     // Shift Left & Right print both types even for Ubyte LHS
793     if (isa<ShiftInst>(I)) PrintAllTypes = true;
794
795     if (!PrintAllTypes) {
796       Out << " ";
797       printType(I->getOperand(0)->getType());
798     }
799
800     for (unsigned i = 0, E = I->getNumOperands(); i != E; ++i) {
801       if (i) Out << ",";
802       writeOperand(I->getOperand(i), PrintAllTypes);
803     }
804   }
805
806   printInfoComment(I);
807   Out << "\n";
808 }
809
810
811 //===----------------------------------------------------------------------===//
812 //                       External Interface declarations
813 //===----------------------------------------------------------------------===//
814
815
816 void Module::print(std::ostream &o) const {
817   SlotCalculator SlotTable(this, true);
818   AssemblyWriter W(o, SlotTable, this);
819   W.write(this);
820 }
821
822 void GlobalVariable::print(std::ostream &o) const {
823   SlotCalculator SlotTable(getParent(), true);
824   AssemblyWriter W(o, SlotTable, getParent());
825   W.write(this);
826 }
827
828 void Function::print(std::ostream &o) const {
829   SlotCalculator SlotTable(getParent(), true);
830   AssemblyWriter W(o, SlotTable, getParent());
831
832   W.write(this);
833 }
834
835 void BasicBlock::print(std::ostream &o) const {
836   SlotCalculator SlotTable(getParent(), true);
837   AssemblyWriter W(o, SlotTable, 
838                    getParent() ? getParent()->getParent() : 0);
839   W.write(this);
840 }
841
842 void Instruction::print(std::ostream &o) const {
843   const Function *F = getParent() ? getParent()->getParent() : 0;
844   SlotCalculator SlotTable(F, true);
845   AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0);
846
847   W.write(this);
848 }
849
850 void Constant::print(std::ostream &o) const {
851   if (this == 0) { o << "<null> constant value\n"; return; }
852   o << " " << getType()->getDescription() << " ";
853
854   map<const Type *, string> TypeTable;
855   WriteConstantInt(o, this, false, TypeTable, 0);
856 }
857
858 void Type::print(std::ostream &o) const { 
859   if (this == 0)
860     o << "<null Type>";
861   else
862     o << getDescription();
863 }
864
865 void Argument::print(std::ostream &o) const {
866   o << getType() << " " << getName();
867 }
868
869 void Value::dump() const { print(std::cerr); }
870
871 //===----------------------------------------------------------------------===//
872 //  CachedWriter Class Implementation
873 //===----------------------------------------------------------------------===//
874
875 void CachedWriter::setModule(const Module *M) {
876   delete SC; delete AW;
877   if (M) {
878     SC = new SlotCalculator(M, true);
879     AW = new AssemblyWriter(Out, *SC, M);
880   } else {
881     SC = 0; AW = 0;
882   }
883 }
884
885 CachedWriter::~CachedWriter() {
886   delete AW;
887   delete SC;
888 }
889
890 CachedWriter &CachedWriter::operator<<(const Value *V) {
891   assert(AW && SC && "CachedWriter does not have a current module!");
892   switch (V->getValueType()) {
893   case Value::ConstantVal:
894   case Value::ArgumentVal:       AW->writeOperand(V, true, true); break;
895   case Value::TypeVal:           AW->write(cast<const Type>(V)); break;
896   case Value::InstructionVal:    AW->write(cast<Instruction>(V)); break;
897   case Value::BasicBlockVal:     AW->write(cast<BasicBlock>(V)); break;
898   case Value::FunctionVal:       AW->write(cast<Function>(V)); break;
899   case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
900   default: Out << "<unknown value type: " << V->getValueType() << ">"; break;
901   }
902   return *this;
903 }