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