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