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