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