class AssemblyWriter:
[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/SymbolTable.h"
30 #include "llvm/Analysis/SlotCalculator.h"
31 #include "llvm/Assembly/Writer.h"
32 #include "llvm/Support/CFG.h"
33 #include "Support/StringExtras.h"
34 #include "Support/STLExtras.h"
35 #include <algorithm>
36 using namespace llvm;
37
38 static RegisterPass<PrintModulePass>
39 X("printm", "Print module to stderr",PassInfo::Analysis|PassInfo::Optimization);
40 static RegisterPass<PrintFunctionPass>
41 Y("print","Print function to stderr",PassInfo::Analysis|PassInfo::Optimization);
42
43 static void WriteAsOperandInternal(std::ostream &Out, const Value *V, 
44                                    bool PrintName,
45                                  std::map<const Type *, std::string> &TypeTable,
46                                    SlotCalculator *Table);
47
48 static const Module *getModuleFromVal(const Value *V) {
49   if (const Argument *MA = dyn_cast<Argument>(V))
50     return MA->getParent() ? MA->getParent()->getParent() : 0;
51   else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
52     return BB->getParent() ? BB->getParent()->getParent() : 0;
53   else if (const Instruction *I = dyn_cast<Instruction>(V)) {
54     const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
55     return M ? M->getParent() : 0;
56   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
57     return GV->getParent();
58   return 0;
59 }
60
61 static SlotCalculator *createSlotCalculator(const Value *V) {
62   assert(!isa<Type>(V) && "Can't create an SC for a type!");
63   if (const Argument *FA = dyn_cast<Argument>(V)) {
64     return new SlotCalculator(FA->getParent(), false);
65   } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
66     return new SlotCalculator(I->getParent()->getParent(), false);
67   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
68     return new SlotCalculator(BB->getParent(), false);
69   } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
70     return new SlotCalculator(GV->getParent(), false);
71   } else if (const Function *Func = dyn_cast<Function>(V)) {
72     return new SlotCalculator(Func, false);
73   }
74   return 0;
75 }
76
77 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
78 // prefixed with % (if the string only contains simple characters) or is
79 // surrounded with ""'s (if it has special chars in it).
80 static std::string getLLVMName(const std::string &Name) {
81   assert(!Name.empty() && "Cannot get empty name!");
82
83   // First character cannot start with a number...
84   if (Name[0] >= '0' && Name[0] <= '9')
85     return "\"" + Name + "\"";
86
87   // Scan to see if we have any characters that are not on the "white list"
88   for (unsigned i = 0, e = Name.size(); i != e; ++i) {
89     char C = Name[i];
90     assert(C != '"' && "Illegal character in LLVM value name!");
91     if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
92         C != '-' && C != '.' && C != '_')
93       return "\"" + Name + "\"";
94   }
95   
96   // If we get here, then the identifier is legal to use as a "VarID".
97   return "%"+Name;
98 }
99
100
101 /// fillTypeNameTable - If the module has a symbol table, take all global types
102 /// and stuff their names into the TypeNames map.
103 ///
104 static void fillTypeNameTable(const Module *M,
105                               std::map<const Type *, std::string> &TypeNames) {
106   if (!M) return;
107   const SymbolTable &ST = M->getSymbolTable();
108   SymbolTable::const_iterator PI = ST.find(Type::TypeTy);
109   if (PI != ST.end()) {
110     SymbolTable::type_const_iterator I = PI->second.begin();
111     for (; I != PI->second.end(); ++I) {
112       // As a heuristic, don't insert pointer to primitive types, because
113       // they are used too often to have a single useful name.
114       //
115       const Type *Ty = cast<Type>(I->second);
116       if (!isa<PointerType>(Ty) ||
117           !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
118           isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
119         TypeNames.insert(std::make_pair(Ty, getLLVMName(I->first)));
120     }
121   }
122 }
123
124
125
126 static std::string calcTypeName(const Type *Ty, 
127                                 std::vector<const Type *> &TypeStack,
128                                 std::map<const Type *, std::string> &TypeNames){
129   if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
130     return Ty->getDescription();  // Base case
131
132   // Check to see if the type is named.
133   std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
134   if (I != TypeNames.end()) return I->second;
135
136   if (isa<OpaqueType>(Ty))
137     return "opaque";
138
139   // Check to see if the Type is already on the stack...
140   unsigned Slot = 0, CurSize = TypeStack.size();
141   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
142
143   // This is another base case for the recursion.  In this case, we know 
144   // that we have looped back to a type that we have previously visited.
145   // Generate the appropriate upreference to handle this.
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
387 /// the 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         if (V->hasName())
418           Out << "<badref: " << getLLVMName(V->getName()) << ">";
419         else
420           Out << "<badref>";     // Not embedded into a location?
421     }
422   }
423 }
424
425
426 /// WriteAsOperand - Write the name of the specified value out to the specified
427 /// ostream.  This can be useful when you just want to print int %reg126, not
428 /// the whole instruction that generated it.
429 ///
430 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
431                                    bool PrintType, bool PrintName, 
432                                    const Module *Context) {
433   std::map<const Type *, std::string> TypeNames;
434   if (Context == 0) Context = getModuleFromVal(V);
435
436   if (Context)
437     fillTypeNameTable(Context, TypeNames);
438
439   if (PrintType)
440     printTypeInt(Out, V->getType(), TypeNames);
441   
442   if (const Type *Ty = dyn_cast<Type> (V))
443     printTypeInt(Out, Ty, TypeNames);
444
445   WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
446   return Out;
447 }
448
449 namespace llvm {
450
451 class AssemblyWriter {
452   std::ostream *Out;
453   SlotCalculator &Table;
454   const Module *TheModule;
455   std::map<const Type *, std::string> TypeNames;
456   AssemblyAnnotationWriter *AnnotationWriter;
457 public:
458   inline AssemblyWriter(std::ostream &o, SlotCalculator &Tab, const Module *M,
459                         AssemblyAnnotationWriter *AAW)
460     : Out(&o), Table(Tab), TheModule(M), AnnotationWriter(AAW) {
461
462     // If the module has a symbol table, take all global types and stuff their
463     // names into the TypeNames map.
464     //
465     fillTypeNameTable(M, TypeNames);
466   }
467
468   inline void write(const Module *M)         { printModule(M);      }
469   inline void write(const GlobalVariable *G) { printGlobal(G);      }
470   inline void write(const Function *F)       { printFunction(F);    }
471   inline void write(const BasicBlock *BB)    { printBasicBlock(BB); }
472   inline void write(const Instruction *I)    { printInstruction(*I); }
473   inline void write(const Constant *CPV)     { printConstant(CPV);  }
474   inline void write(const Type *Ty)          { printType(Ty);       }
475
476   void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
477
478   const Module* getModule() { return TheModule; }
479   void setStream(std::ostream &os) { Out = &os; }
480
481 private :
482   void printModule(const Module *M);
483   void printSymbolTable(const SymbolTable &ST);
484   void printConstant(const Constant *CPV);
485   void printGlobal(const GlobalVariable *GV);
486   void printFunction(const Function *F);
487   void printArgument(const Argument *FA);
488   void printBasicBlock(const BasicBlock *BB);
489   void printInstruction(const Instruction &I);
490
491   // printType - Go to extreme measures to attempt to print out a short,
492   // symbolic version of a type name.
493   //
494   std::ostream &printType(const Type *Ty) {
495     return printTypeInt(*Out, Ty, TypeNames);
496   }
497
498   // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
499   // without considering any symbolic types that we may have equal to it.
500   //
501   std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
502
503   // printInfoComment - Print a little comment after the instruction indicating
504   // which slot it occupies.
505   void printInfoComment(const Value &V);
506 };
507 }  // end of anonymous namespace
508
509 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
510 /// without considering any symbolic types that we may have equal to it.
511 ///
512 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
513   if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
514     printType(FTy->getReturnType()) << " (";
515     for (FunctionType::param_iterator I = FTy->param_begin(),
516            E = FTy->param_end(); I != E; ++I) {
517       if (I != FTy->param_begin())
518         *Out << ", ";
519       printType(*I);
520     }
521     if (FTy->isVarArg()) {
522       if (FTy->getNumParams()) *Out << ", ";
523       *Out << "...";
524     }
525     *Out << ")";
526   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
527     *Out << "{ ";
528     for (StructType::element_iterator I = STy->element_begin(),
529            E = STy->element_end(); I != E; ++I) {
530       if (I != STy->element_begin())
531         *Out << ", ";
532       printType(*I);
533     }
534     *Out << " }";
535   } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
536     printType(PTy->getElementType()) << "*";
537   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
538     *Out << "[" << ATy->getNumElements() << " x ";
539     printType(ATy->getElementType()) << "]";
540   } else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
541     *Out << "opaque";
542   } else {
543     if (!Ty->isPrimitiveType())
544       *Out << "<unknown derived type>";
545     printType(Ty);
546   }
547   return *Out;
548 }
549
550
551 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType, 
552                                   bool PrintName) {
553   if (PrintType) { *Out << " "; printType(Operand->getType()); }
554   WriteAsOperandInternal(*Out, Operand, PrintName, TypeNames, &Table);
555 }
556
557
558 void AssemblyWriter::printModule(const Module *M) {
559   switch (M->getEndianness()) {
560   case Module::LittleEndian: *Out << "target endian = little\n"; break;
561   case Module::BigEndian:    *Out << "target endian = big\n";    break;
562   case Module::AnyEndianness: break;
563   }
564   switch (M->getPointerSize()) {
565   case Module::Pointer32:    *Out << "target pointersize = 32\n"; break;
566   case Module::Pointer64:    *Out << "target pointersize = 64\n"; break;
567   case Module::AnyPointerSize: break;
568   }
569   
570   // Loop over the symbol table, emitting all named constants...
571   printSymbolTable(M->getSymbolTable());
572   
573   for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
574     printGlobal(I);
575
576   *Out << "\nimplementation   ; Functions:\n";
577   
578   // Output all of the functions...
579   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
580     printFunction(I);
581 }
582
583 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
584   if (GV->hasName()) *Out << getLLVMName(GV->getName()) << " = ";
585
586   if (!GV->hasInitializer()) 
587     *Out << "external ";
588   else
589     switch (GV->getLinkage()) {
590     case GlobalValue::InternalLinkage:  *Out << "internal "; break;
591     case GlobalValue::LinkOnceLinkage:  *Out << "linkonce "; break;
592     case GlobalValue::WeakLinkage:      *Out << "weak "; break;
593     case GlobalValue::AppendingLinkage: *Out << "appending "; break;
594     case GlobalValue::ExternalLinkage: break;
595     }
596
597   *Out << (GV->isConstant() ? "constant " : "global ");
598   printType(GV->getType()->getElementType());
599
600   if (GV->hasInitializer())
601     writeOperand(GV->getInitializer(), false, false);
602
603   printInfoComment(*GV);
604   *Out << "\n";
605 }
606
607
608 /// printSymbolTable - Run through symbol table looking for named constants
609 /// if a named constant is found, emit it's declaration...
610 ///
611 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
612   for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
613     SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
614     SymbolTable::type_const_iterator End = ST.type_end(TI->first);
615     
616     for (; I != End; ++I) {
617       const Value *V = I->second;
618       if (const Constant *CPV = dyn_cast<Constant>(V)) {
619         printConstant(CPV);
620       } else if (const Type *Ty = dyn_cast<Type>(V)) {
621         assert(Ty->getType() == Type::TypeTy && TI->first == Type::TypeTy);
622         *Out << "\t" << getLLVMName(I->first) << " = type ";
623
624         // Make sure we print out at least one level of the type structure, so
625         // that we do not get %FILE = type %FILE
626         //
627         printTypeAtLeastOneLevel(Ty) << "\n";
628       }
629     }
630   }
631 }
632
633
634 /// printConstant - Print out a constant pool entry...
635 ///
636 void AssemblyWriter::printConstant(const Constant *CPV) {
637   // Don't print out unnamed constants, they will be inlined
638   if (!CPV->hasName()) return;
639
640   // Print out name...
641   *Out << "\t" << getLLVMName(CPV->getName()) << " =";
642
643   // Write the value out now...
644   writeOperand(CPV, true, false);
645
646   printInfoComment(*CPV);
647   *Out << "\n";
648 }
649
650 /// printFunction - Print all aspects of a function.
651 ///
652 void AssemblyWriter::printFunction(const Function *F) {
653   // Print out the return type and name...
654   *Out << "\n";
655
656   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, *Out);
657
658   if (F->isExternal())
659     *Out << "declare ";
660   else
661     switch (F->getLinkage()) {
662     case GlobalValue::InternalLinkage:  *Out << "internal "; break;
663     case GlobalValue::LinkOnceLinkage:  *Out << "linkonce "; break;
664     case GlobalValue::WeakLinkage:      *Out << "weak "; break;
665     case GlobalValue::AppendingLinkage: *Out << "appending "; break;
666     case GlobalValue::ExternalLinkage: break;
667     }
668
669   printType(F->getReturnType()) << " ";
670   if (!F->getName().empty())
671     *Out << getLLVMName(F->getName());
672   else
673     *Out << "\"\"";
674   *Out << "(";
675   Table.incorporateFunction(F);
676
677   // Loop over the arguments, printing them...
678   const FunctionType *FT = F->getFunctionType();
679
680   for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
681     printArgument(I);
682
683   // Finish printing arguments...
684   if (FT->isVarArg()) {
685     if (FT->getNumParams()) *Out << ", ";
686     *Out << "...";  // Output varargs portion of signature!
687   }
688   *Out << ")";
689
690   if (F->isExternal()) {
691     *Out << "\n";
692   } else {
693     *Out << " {";
694   
695     // Output all of its basic blocks... for the function
696     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
697       printBasicBlock(I);
698
699     *Out << "}\n";
700   }
701
702   Table.purgeFunction();
703 }
704
705 /// printArgument - This member is called for every argument that is passed into
706 /// the function.  Simply print it out
707 ///
708 void AssemblyWriter::printArgument(const Argument *Arg) {
709   // Insert commas as we go... the first arg doesn't get a comma
710   if (Arg != &Arg->getParent()->afront()) *Out << ", ";
711
712   // Output type...
713   printType(Arg->getType());
714   
715   // Output name, if available...
716   if (Arg->hasName())
717     *Out << " " << getLLVMName(Arg->getName());
718   else if (Table.getSlot(Arg) < 0)
719     *Out << "<badref>";
720 }
721
722 /// printBasicBlock - This member is called for each basic block in a method.
723 ///
724 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
725   if (BB->hasName()) {              // Print out the label if it exists...
726     *Out << "\n" << BB->getName() << ":";
727   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
728     int Slot = Table.getSlot(BB);
729     *Out << "\n; <label>:";
730     if (Slot >= 0) 
731       *Out << Slot;         // Extra newline separates out label's
732     else 
733       *Out << "<badref>"; 
734   }
735
736   if (BB->getParent() == 0)
737     *Out << "\t\t; Error: Block without parent!";
738   else {
739     if (BB != &BB->getParent()->front()) {  // Not the entry block?
740       // Output predecessors for the block...
741       *Out << "\t\t;";
742       pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
743       
744       if (PI == PE) {
745         *Out << " No predecessors!";
746       } else {
747         *Out << " preds =";
748         writeOperand(*PI, false, true);
749         for (++PI; PI != PE; ++PI) {
750           *Out << ",";
751           writeOperand(*PI, false, true);
752         }
753       }
754     }
755   }
756   
757   *Out << "\n";
758
759   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, *Out);
760
761   // Output all of the instructions in the basic block...
762   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
763     printInstruction(*I);
764
765   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, *Out);
766 }
767
768
769 /// printInfoComment - Print a little comment after the instruction indicating
770 /// which slot it occupies.
771 ///
772 void AssemblyWriter::printInfoComment(const Value &V) {
773   if (V.getType() != Type::VoidTy) {
774     *Out << "\t\t; <";
775     printType(V.getType()) << ">";
776
777     if (!V.hasName()) {
778       int Slot = Table.getSlot(&V); // Print out the def slot taken...
779       if (Slot >= 0) *Out << ":" << Slot;
780       else *Out << ":<badref>";
781     }
782     *Out << " [#uses=" << V.use_size() << "]";  // Output # uses
783   }
784 }
785
786 /// printInstruction - This member is called for each Instruction in a method.
787 ///
788 void AssemblyWriter::printInstruction(const Instruction &I) {
789   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, *Out);
790
791   *Out << "\t";
792
793   // Print out name if it exists...
794   if (I.hasName())
795     *Out << getLLVMName(I.getName()) << " = ";
796
797   // If this is a volatile load or store, print out the volatile marker
798   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
799       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()))
800       *Out << "volatile ";
801
802   // Print out the opcode...
803   *Out << I.getOpcodeName();
804
805   // Print out the type of the operands...
806   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
807
808   // Special case conditional branches to swizzle the condition out to the front
809   if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
810     writeOperand(I.getOperand(2), true);
811     *Out << ",";
812     writeOperand(Operand, true);
813     *Out << ",";
814     writeOperand(I.getOperand(1), true);
815
816   } else if (isa<SwitchInst>(I)) {
817     // Special case switch statement to get formatting nice and correct...
818     writeOperand(Operand        , true); *Out << ",";
819     writeOperand(I.getOperand(1), true); *Out << " [";
820
821     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
822       *Out << "\n\t\t";
823       writeOperand(I.getOperand(op  ), true); *Out << ",";
824       writeOperand(I.getOperand(op+1), true);
825     }
826     *Out << "\n\t]";
827   } else if (isa<PHINode>(I)) {
828     *Out << " ";
829     printType(I.getType());
830     *Out << " ";
831
832     for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
833       if (op) *Out << ", ";
834       *Out << "[";  
835       writeOperand(I.getOperand(op  ), false); *Out << ",";
836       writeOperand(I.getOperand(op+1), false); *Out << " ]";
837     }
838   } else if (isa<ReturnInst>(I) && !Operand) {
839     *Out << " void";
840   } else if (isa<CallInst>(I)) {
841     const PointerType  *PTy = cast<PointerType>(Operand->getType());
842     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
843     const Type       *RetTy = FTy->getReturnType();
844
845     // If possible, print out the short form of the call instruction.  We can
846     // only do this if the first argument is a pointer to a nonvararg function,
847     // and if the return type is not a pointer to a function.
848     //
849     if (!FTy->isVarArg() &&
850         (!isa<PointerType>(RetTy) || 
851          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
852       *Out << " "; printType(RetTy);
853       writeOperand(Operand, false);
854     } else {
855       writeOperand(Operand, true);
856     }
857     *Out << "(";
858     if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
859     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
860       *Out << ",";
861       writeOperand(I.getOperand(op), true);
862     }
863
864     *Out << " )";
865   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
866     const PointerType  *PTy = cast<PointerType>(Operand->getType());
867     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
868     const Type       *RetTy = FTy->getReturnType();
869
870     // If possible, print out the short form of the invoke instruction. We can
871     // only do this if the first argument is a pointer to a nonvararg function,
872     // and if the return type is not a pointer to a function.
873     //
874     if (!FTy->isVarArg() &&
875         (!isa<PointerType>(RetTy) || 
876          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
877       *Out << " "; printType(RetTy);
878       writeOperand(Operand, false);
879     } else {
880       writeOperand(Operand, true);
881     }
882
883     *Out << "(";
884     if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
885     for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
886       *Out << ",";
887       writeOperand(I.getOperand(op), true);
888     }
889
890     *Out << " )\n\t\t\tto";
891     writeOperand(II->getNormalDest(), true);
892     *Out << " unwind";
893     writeOperand(II->getUnwindDest(), true);
894
895   } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
896     *Out << " ";
897     printType(AI->getType()->getElementType());
898     if (AI->isArrayAllocation()) {
899       *Out << ",";
900       writeOperand(AI->getArraySize(), true);
901     }
902   } else if (isa<CastInst>(I)) {
903     if (Operand) writeOperand(Operand, true);   // Work with broken code
904     *Out << " to ";
905     printType(I.getType());
906   } else if (isa<VAArgInst>(I)) {
907     if (Operand) writeOperand(Operand, true);   // Work with broken code
908     *Out << ", ";
909     printType(I.getType());
910   } else if (const VANextInst *VAN = dyn_cast<VANextInst>(&I)) {
911     if (Operand) writeOperand(Operand, true);   // Work with broken code
912     *Out << ", ";
913     printType(VAN->getArgType());
914   } else if (Operand) {   // Print the normal way...
915
916     // PrintAllTypes - Instructions who have operands of all the same type 
917     // omit the type from all but the first operand.  If the instruction has
918     // different type operands (for example br), then they are all printed.
919     bool PrintAllTypes = false;
920     const Type *TheType = Operand->getType();
921
922     // Shift Left & Right print both types even for Ubyte LHS, and select prints
923     // types even if all operands are bools.
924     if (isa<ShiftInst>(I) || isa<SelectInst>(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 }
1051
1052 CachedWriter& CachedWriter::operator<<(const Type *X) {
1053   if (SymbolicTypes) {
1054     const Module *M = AW->getModule();
1055     if (M) WriteTypeSymbolic(*Out, X, M);
1056     return *this;
1057   } else
1058     return *this << (const Value*)X;
1059 }
1060
1061 void CachedWriter::setStream(std::ostream &os) {
1062   Out = &os;
1063   if (AW) AW->setStream(os);
1064 }