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