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