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