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