f16ae08ef1f10f9bb10c94a5327ed39c21f63b16
[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 is distributed under the University of Illinois Open Source
6 // 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/Writer.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/Assembly/AsmAnnotationWriter.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instruction.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Module.h"
27 #include "llvm/ValueSymbolTable.h"
28 #include "llvm/TypeSymbolTable.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/Streams.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <algorithm>
37 #include <cctype>
38 using namespace llvm;
39
40 namespace llvm {
41
42 // Make virtual table appear in this compilation unit.
43 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
44
45 /// This class provides computation of slot numbers for LLVM Assembly writing.
46 ///
47 class SlotMachine {
48 public:
49   /// ValueMap - A mapping of Values to slot numbers
50   typedef DenseMap<const Value*, unsigned> ValueMap;
51   
52 private:  
53   /// TheModule - The module for which we are holding slot numbers
54   const Module* TheModule;
55   
56   /// TheFunction - The function for which we are holding slot numbers
57   const Function* TheFunction;
58   bool FunctionProcessed;
59   
60   /// mMap - The TypePlanes map for the module level data
61   ValueMap mMap;
62   unsigned mNext;
63   
64   /// fMap - The TypePlanes map for the function level data
65   ValueMap fMap;
66   unsigned fNext;
67   
68 public:
69   /// Construct from a module
70   explicit SlotMachine(const Module *M);
71   /// Construct from a function, starting out in incorp state.
72   explicit SlotMachine(const Function *F);
73
74   /// Return the slot number of the specified value in it's type
75   /// plane.  If something is not in the SlotMachine, return -1.
76   int getLocalSlot(const Value *V);
77   int getGlobalSlot(const GlobalValue *V);
78
79   /// If you'd like to deal with a function instead of just a module, use
80   /// this method to get its data into the SlotMachine.
81   void incorporateFunction(const Function *F) {
82     TheFunction = F;
83     FunctionProcessed = false;
84   }
85
86   /// After calling incorporateFunction, use this method to remove the
87   /// most recently incorporated function from the SlotMachine. This
88   /// will reset the state of the machine back to just the module contents.
89   void purgeFunction();
90
91   // Implementation Details
92 private:
93   /// This function does the actual initialization.
94   inline void initialize();
95
96   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
97   void CreateModuleSlot(const GlobalValue *V);
98   
99   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
100   void CreateFunctionSlot(const Value *V);
101
102   /// Add all of the module level global variables (and their initializers)
103   /// and function declarations, but not the contents of those functions.
104   void processModule();
105
106   /// Add all of the functions arguments, basic blocks, and instructions
107   void processFunction();
108
109   SlotMachine(const SlotMachine &);  // DO NOT IMPLEMENT
110   void operator=(const SlotMachine &);  // DO NOT IMPLEMENT
111 };
112
113 }  // end namespace llvm
114
115 char PrintModulePass::ID = 0;
116 static RegisterPass<PrintModulePass>
117 X("printm", "Print module to stderr");
118 char PrintFunctionPass::ID = 0;
119 static RegisterPass<PrintFunctionPass>
120 Y("print","Print function to stderr");
121
122 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
123                                std::map<const Type *, std::string> &TypeTable,
124                                    SlotMachine *Machine);
125
126 static const Module *getModuleFromVal(const Value *V) {
127   if (const Argument *MA = dyn_cast<Argument>(V))
128     return MA->getParent() ? MA->getParent()->getParent() : 0;
129   else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
130     return BB->getParent() ? BB->getParent()->getParent() : 0;
131   else if (const Instruction *I = dyn_cast<Instruction>(V)) {
132     const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
133     return M ? M->getParent() : 0;
134   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
135     return GV->getParent();
136   return 0;
137 }
138
139 static SlotMachine *createSlotMachine(const Value *V) {
140   if (const Argument *FA = dyn_cast<Argument>(V)) {
141     return new SlotMachine(FA->getParent());
142   } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
143     return new SlotMachine(I->getParent()->getParent());
144   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
145     return new SlotMachine(BB->getParent());
146   } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
147     return new SlotMachine(GV->getParent());
148   } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)){
149     return new SlotMachine(GA->getParent());    
150   } else if (const Function *Func = dyn_cast<Function>(V)) {
151     return new SlotMachine(Func);
152   }
153   return 0;
154 }
155
156 /// NameNeedsQuotes - Return true if the specified llvm name should be wrapped
157 /// with ""'s.
158 static std::string QuoteNameIfNeeded(const std::string &Name) {
159   std::string result;
160   bool needsQuotes = Name[0] >= '0' && Name[0] <= '9';
161   // Scan the name to see if it needs quotes and to replace funky chars with
162   // their octal equivalent.
163   for (unsigned i = 0, e = Name.size(); i != e; ++i) {
164     char C = Name[i];
165     assert(C != '"' && "Illegal character in LLVM value name!");
166     if (isalnum(C) || C == '-' || C == '.' || C == '_')
167       result += C;
168     else if (C == '\\')  {
169       needsQuotes = true;
170       result += "\\\\";
171     } else if (isprint(C)) {
172       needsQuotes = true;
173       result += C;
174     } else {
175       needsQuotes = true;
176       result += "\\";
177       char hex1 = (C >> 4) & 0x0F;
178       if (hex1 < 10)
179         result += hex1 + '0';
180       else 
181         result += hex1 - 10 + 'A';
182       char hex2 = C & 0x0F;
183       if (hex2 < 10)
184         result += hex2 + '0';
185       else 
186         result += hex2 - 10 + 'A';
187     }
188   }
189   if (needsQuotes) {
190     result.insert(0,"\"");
191     result += '"';
192   }
193   return result;
194 }
195
196 /// getLLVMName - Turn the specified string into an 'LLVM name', which is either
197 /// prefixed with % (if the string only contains simple characters) or is
198 /// surrounded with ""'s (if it has special chars in it).
199 static std::string getLLVMName(const std::string &Name) {
200   assert(!Name.empty() && "Cannot get empty name!");
201   return '%' + QuoteNameIfNeeded(Name);
202 }
203
204 enum PrefixType {
205   GlobalPrefix,
206   LabelPrefix,
207   LocalPrefix
208 };
209
210 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
211 /// prefixed with % (if the string only contains simple characters) or is
212 /// surrounded with ""'s (if it has special chars in it).  Print it out.
213 static void PrintLLVMName(std::ostream &OS, const ValueName *Name,
214                           PrefixType Prefix) {
215   assert(Name && "Cannot get empty name!");
216   switch (Prefix) {
217   default: assert(0 && "Bad prefix!");
218   case GlobalPrefix: OS << '@'; break;
219   case LabelPrefix:  break;
220   case LocalPrefix:  OS << '%'; break;
221   }      
222   
223   // Scan the name to see if it needs quotes first.
224   const char *NameStr = Name->getKeyData();
225   unsigned NameLen = Name->getKeyLength();
226   
227   bool NeedsQuotes = NameStr[0] >= '0' && NameStr[0] <= '9';
228   if (!NeedsQuotes) {
229     for (unsigned i = 0; i != NameLen; ++i) {
230       char C = NameStr[i];
231       if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
232         NeedsQuotes = true;
233         break;
234       }
235     }
236   }
237
238   // If we didn't need any quotes, just write out the name in one blast.
239   if (!NeedsQuotes) {
240     OS.write(NameStr, NameLen);
241     return;
242   }
243   
244   // Okay, we need quotes.  Output the quotes and escape any scary characters as
245   // needed.
246   OS << '"';
247   for (unsigned i = 0; i != NameLen; ++i) {
248     char C = NameStr[i];
249     assert(C != '"' && "Illegal character in LLVM value name!");
250     if (C == '\\') {
251       OS << "\\\\";
252     } else if (isprint(C)) {
253       OS << C;
254     } else {
255       OS << "\\";
256       char hex1 = (C >> 4) & 0x0F;
257       if (hex1 < 10)
258         OS << (hex1 + '0');
259       else 
260         OS << (hex1 - 10 + 'A');
261       char hex2 = C & 0x0F;
262       if (hex2 < 10)
263         OS << (hex2 + '0');
264       else 
265         OS << (hex2 - 10 + 'A');
266     }
267   }
268   OS << '"';
269 }
270
271 static void PrintLLVMName(std::ostream &OS, const Value *V) {
272   PrintLLVMName(OS, V->getValueName(),
273                 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
274 }
275
276
277 /// fillTypeNameTable - If the module has a symbol table, take all global types
278 /// and stuff their names into the TypeNames map.
279 ///
280 static void fillTypeNameTable(const Module *M,
281                               std::map<const Type *, std::string> &TypeNames) {
282   if (!M) return;
283   const TypeSymbolTable &ST = M->getTypeSymbolTable();
284   TypeSymbolTable::const_iterator TI = ST.begin();
285   for (; TI != ST.end(); ++TI) {
286     // As a heuristic, don't insert pointer to primitive types, because
287     // they are used too often to have a single useful name.
288     //
289     const Type *Ty = cast<Type>(TI->second);
290     if (!isa<PointerType>(Ty) ||
291         !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
292         !cast<PointerType>(Ty)->getElementType()->isInteger() ||
293         isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
294       TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
295   }
296 }
297
298
299
300 static void calcTypeName(const Type *Ty,
301                          std::vector<const Type *> &TypeStack,
302                          std::map<const Type *, std::string> &TypeNames,
303                          std::string & Result){
304   if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
305     Result += Ty->getDescription();  // Base case
306     return;
307   }
308
309   // Check to see if the type is named.
310   std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
311   if (I != TypeNames.end()) {
312     Result += I->second;
313     return;
314   }
315
316   if (isa<OpaqueType>(Ty)) {
317     Result += "opaque";
318     return;
319   }
320
321   // Check to see if the Type is already on the stack...
322   unsigned Slot = 0, CurSize = TypeStack.size();
323   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
324
325   // This is another base case for the recursion.  In this case, we know
326   // that we have looped back to a type that we have previously visited.
327   // Generate the appropriate upreference to handle this.
328   if (Slot < CurSize) {
329     Result += "\\" + utostr(CurSize-Slot);     // Here's the upreference
330     return;
331   }
332
333   TypeStack.push_back(Ty);    // Recursive case: Add us to the stack..
334
335   switch (Ty->getTypeID()) {
336   case Type::IntegerTyID: {
337     unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
338     Result += "i" + utostr(BitWidth);
339     break;
340   }
341   case Type::FunctionTyID: {
342     const FunctionType *FTy = cast<FunctionType>(Ty);
343     calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
344     Result += " (";
345     for (FunctionType::param_iterator I = FTy->param_begin(),
346          E = FTy->param_end(); I != E; ++I) {
347       if (I != FTy->param_begin())
348         Result += ", ";
349       calcTypeName(*I, TypeStack, TypeNames, Result);
350     }
351     if (FTy->isVarArg()) {
352       if (FTy->getNumParams()) Result += ", ";
353       Result += "...";
354     }
355     Result += ")";
356     break;
357   }
358   case Type::StructTyID: {
359     const StructType *STy = cast<StructType>(Ty);
360     if (STy->isPacked())
361       Result += '<';
362     Result += "{ ";
363     for (StructType::element_iterator I = STy->element_begin(),
364            E = STy->element_end(); I != E; ++I) {
365       if (I != STy->element_begin())
366         Result += ", ";
367       calcTypeName(*I, TypeStack, TypeNames, Result);
368     }
369     Result += " }";
370     if (STy->isPacked())
371       Result += '>';
372     break;
373   }
374   case Type::PointerTyID: {
375     const PointerType *PTy = cast<PointerType>(Ty);
376     calcTypeName(PTy->getElementType(),
377                           TypeStack, TypeNames, Result);
378     if (unsigned AddressSpace = PTy->getAddressSpace())
379       Result += " addrspace(" + utostr(AddressSpace) + ")";
380     Result += "*";
381     break;
382   }
383   case Type::ArrayTyID: {
384     const ArrayType *ATy = cast<ArrayType>(Ty);
385     Result += "[" + utostr(ATy->getNumElements()) + " x ";
386     calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
387     Result += "]";
388     break;
389   }
390   case Type::VectorTyID: {
391     const VectorType *PTy = cast<VectorType>(Ty);
392     Result += "<" + utostr(PTy->getNumElements()) + " x ";
393     calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
394     Result += ">";
395     break;
396   }
397   case Type::OpaqueTyID:
398     Result += "opaque";
399     break;
400   default:
401     Result += "<unrecognized-type>";
402     break;
403   }
404
405   TypeStack.pop_back();       // Remove self from stack...
406 }
407
408
409 /// printTypeInt - The internal guts of printing out a type that has a
410 /// potentially named portion.
411 ///
412 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
413                               std::map<const Type *, std::string> &TypeNames) {
414   // Primitive types always print out their description, regardless of whether
415   // they have been named or not.
416   //
417   if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)))
418     return Out << Ty->getDescription();
419
420   // Check to see if the type is named.
421   std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
422   if (I != TypeNames.end()) return Out << I->second;
423
424   // Otherwise we have a type that has not been named but is a derived type.
425   // Carefully recurse the type hierarchy to print out any contained symbolic
426   // names.
427   //
428   std::vector<const Type *> TypeStack;
429   std::string TypeName;
430   calcTypeName(Ty, TypeStack, TypeNames, TypeName);
431   TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
432   return (Out << TypeName);
433 }
434
435
436 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
437 /// type, iff there is an entry in the modules symbol table for the specified
438 /// type or one of it's component types. This is slower than a simple x << Type
439 ///
440 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
441                                       const Module *M) {
442   Out << ' ';
443
444   // If they want us to print out a type, but there is no context, we can't
445   // print it symbolically.
446   if (!M)
447     return Out << Ty->getDescription();
448     
449   std::map<const Type *, std::string> TypeNames;
450   fillTypeNameTable(M, TypeNames);
451   return printTypeInt(Out, Ty, TypeNames);
452 }
453
454 // PrintEscapedString - Print each character of the specified string, escaping
455 // it if it is not printable or if it is an escape char.
456 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
457   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
458     unsigned char C = Str[i];
459     if (isprint(C) && C != '"' && C != '\\') {
460       Out << C;
461     } else {
462       Out << '\\'
463           << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
464           << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
465     }
466   }
467 }
468
469 static const char *getPredicateText(unsigned predicate) {
470   const char * pred = "unknown";
471   switch (predicate) {
472     case FCmpInst::FCMP_FALSE: pred = "false"; break;
473     case FCmpInst::FCMP_OEQ:   pred = "oeq"; break;
474     case FCmpInst::FCMP_OGT:   pred = "ogt"; break;
475     case FCmpInst::FCMP_OGE:   pred = "oge"; break;
476     case FCmpInst::FCMP_OLT:   pred = "olt"; break;
477     case FCmpInst::FCMP_OLE:   pred = "ole"; break;
478     case FCmpInst::FCMP_ONE:   pred = "one"; break;
479     case FCmpInst::FCMP_ORD:   pred = "ord"; break;
480     case FCmpInst::FCMP_UNO:   pred = "uno"; break;
481     case FCmpInst::FCMP_UEQ:   pred = "ueq"; break;
482     case FCmpInst::FCMP_UGT:   pred = "ugt"; break;
483     case FCmpInst::FCMP_UGE:   pred = "uge"; break;
484     case FCmpInst::FCMP_ULT:   pred = "ult"; break;
485     case FCmpInst::FCMP_ULE:   pred = "ule"; break;
486     case FCmpInst::FCMP_UNE:   pred = "une"; break;
487     case FCmpInst::FCMP_TRUE:  pred = "true"; break;
488     case ICmpInst::ICMP_EQ:    pred = "eq"; break;
489     case ICmpInst::ICMP_NE:    pred = "ne"; break;
490     case ICmpInst::ICMP_SGT:   pred = "sgt"; break;
491     case ICmpInst::ICMP_SGE:   pred = "sge"; break;
492     case ICmpInst::ICMP_SLT:   pred = "slt"; break;
493     case ICmpInst::ICMP_SLE:   pred = "sle"; break;
494     case ICmpInst::ICMP_UGT:   pred = "ugt"; break;
495     case ICmpInst::ICMP_UGE:   pred = "uge"; break;
496     case ICmpInst::ICMP_ULT:   pred = "ult"; break;
497     case ICmpInst::ICMP_ULE:   pred = "ule"; break;
498   }
499   return pred;
500 }
501
502 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
503                              std::map<const Type *, std::string> &TypeTable,
504                              SlotMachine *Machine) {
505   const int IndentSize = 4;
506   // FIXME: WHY IS INDENT STATIC??
507   static std::string Indent = "\n";
508   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
509     if (CI->getType() == Type::Int1Ty) {
510       Out << (CI->getZExtValue() ? "true" : "false");
511       return;
512     }
513     Out << CI->getValue();
514     return;
515   }
516   
517   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
518     if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
519         &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
520       // We would like to output the FP constant value in exponential notation,
521       // but we cannot do this if doing so will lose precision.  Check here to
522       // make sure that we only output it in exponential format if we can parse
523       // the value back and get the same value.
524       //
525       bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
526       double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
527                               CFP->getValueAPF().convertToFloat();
528       std::string StrVal = ftostr(CFP->getValueAPF());
529
530       // Check to make sure that the stringized number is not some string like
531       // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
532       // that the string matches the "[-+]?[0-9]" regex.
533       //
534       if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
535           ((StrVal[0] == '-' || StrVal[0] == '+') &&
536            (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
537         // Reparse stringized version!
538         if (atof(StrVal.c_str()) == Val) {
539           Out << StrVal;
540           return;
541         }
542       }
543       // Otherwise we could not reparse it to exactly the same value, so we must
544       // output the string in hexadecimal format!
545       assert(sizeof(double) == sizeof(uint64_t) &&
546              "assuming that double is 64 bits!");
547       Out << "0x" << utohexstr(DoubleToBits(Val));
548     } else {
549       // Some form of long double.  These appear as a magic letter identifying
550       // the type, then a fixed number of hex digits.
551       Out << "0x";
552       if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended)
553         Out << 'K';
554       else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
555         Out << 'L';
556       else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
557         Out << 'M';
558       else
559         assert(0 && "Unsupported floating point type");
560       // api needed to prevent premature destruction
561       APInt api = CFP->getValueAPF().convertToAPInt();
562       const uint64_t* p = api.getRawData();
563       uint64_t word = *p;
564       int shiftcount=60;
565       int width = api.getBitWidth();
566       for (int j=0; j<width; j+=4, shiftcount-=4) {
567         unsigned int nibble = (word>>shiftcount) & 15;
568         if (nibble < 10)
569           Out << (unsigned char)(nibble + '0');
570         else
571           Out << (unsigned char)(nibble - 10 + 'A');
572         if (shiftcount == 0 && j+4 < width) {
573           word = *(++p);
574           shiftcount = 64;
575           if (width-j-4 < 64)
576             shiftcount = width-j-4;
577         }
578       }
579     }
580   } else if (isa<ConstantAggregateZero>(CV)) {
581     Out << "zeroinitializer";
582   } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
583     // As a special case, print the array as a string if it is an array of
584     // i8 with ConstantInt values.
585     //
586     const Type *ETy = CA->getType()->getElementType();
587     if (CA->isString()) {
588       Out << "c\"";
589       PrintEscapedString(CA->getAsString(), Out);
590       Out << "\"";
591
592     } else {                // Cannot output in string format...
593       Out << '[';
594       if (CA->getNumOperands()) {
595         Out << ' ';
596         printTypeInt(Out, ETy, TypeTable);
597         WriteAsOperandInternal(Out, CA->getOperand(0),
598                                TypeTable, Machine);
599         for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
600           Out << ", ";
601           printTypeInt(Out, ETy, TypeTable);
602           WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
603         }
604       }
605       Out << " ]";
606     }
607   } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
608     if (CS->getType()->isPacked())
609       Out << '<';
610     Out << '{';
611     unsigned N = CS->getNumOperands();
612     if (N) {
613       if (N > 2) {
614         Indent += std::string(IndentSize, ' ');
615         Out << Indent;
616       } else {
617         Out << ' ';
618       }
619       printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
620
621       WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
622
623       for (unsigned i = 1; i < N; i++) {
624         Out << ", ";
625         if (N > 2) Out << Indent;
626         printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
627
628         WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
629       }
630       if (N > 2) Indent.resize(Indent.size() - IndentSize);
631     }
632  
633     Out << " }";
634     if (CS->getType()->isPacked())
635       Out << '>';
636   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
637       const Type *ETy = CP->getType()->getElementType();
638       assert(CP->getNumOperands() > 0 &&
639              "Number of operands for a PackedConst must be > 0");
640       Out << '<';
641       Out << ' ';
642       printTypeInt(Out, ETy, TypeTable);
643       WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
644       for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
645           Out << ", ";
646           printTypeInt(Out, ETy, TypeTable);
647           WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
648       }
649       Out << " >";
650   } else if (isa<ConstantPointerNull>(CV)) {
651     Out << "null";
652
653   } else if (isa<UndefValue>(CV)) {
654     Out << "undef";
655
656   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
657     Out << CE->getOpcodeName();
658     if (CE->isCompare())
659       Out << " " << getPredicateText(CE->getPredicate());
660     Out << " (";
661
662     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
663       printTypeInt(Out, (*OI)->getType(), TypeTable);
664       WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
665       if (OI+1 != CE->op_end())
666         Out << ", ";
667     }
668
669     if (CE->hasIndices()) {
670       const SmallVector<unsigned, 4> &Indices = CE->getIndices();
671       for (unsigned i = 0, e = Indices.size(); i != e; ++i)
672         Out << ", " << Indices[i];
673     }
674
675     if (CE->isCast()) {
676       Out << " to ";
677       printTypeInt(Out, CE->getType(), TypeTable);
678     }
679
680     Out << ')';
681
682   } else {
683     Out << "<placeholder or erroneous Constant>";
684   }
685 }
686
687
688 /// WriteAsOperand - Write the name of the specified value out to the specified
689 /// ostream.  This can be useful when you just want to print int %reg126, not
690 /// the whole instruction that generated it.
691 ///
692 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
693                                   std::map<const Type*, std::string> &TypeTable,
694                                    SlotMachine *Machine) {
695   Out << ' ';
696   if (V->hasName()) {
697     PrintLLVMName(Out, V);
698     return;
699   }
700   
701   const Constant *CV = dyn_cast<Constant>(V);
702   if (CV && !isa<GlobalValue>(CV)) {
703     WriteConstantInt(Out, CV, TypeTable, Machine);
704   } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
705     Out << "asm ";
706     if (IA->hasSideEffects())
707       Out << "sideeffect ";
708     Out << '"';
709     PrintEscapedString(IA->getAsmString(), Out);
710     Out << "\", \"";
711     PrintEscapedString(IA->getConstraintString(), Out);
712     Out << '"';
713   } else {
714     char Prefix = '%';
715     int Slot;
716     if (Machine) {
717       if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
718         Slot = Machine->getGlobalSlot(GV);
719         Prefix = '@';
720       } else {
721         Slot = Machine->getLocalSlot(V);
722       }
723     } else {
724       Machine = createSlotMachine(V);
725       if (Machine) {
726         if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
727           Slot = Machine->getGlobalSlot(GV);
728           Prefix = '@';
729         } else {
730           Slot = Machine->getLocalSlot(V);
731         }
732       } else {
733         Slot = -1;
734       }
735       delete Machine;
736     }
737     if (Slot != -1)
738       Out << Prefix << Slot;
739     else
740       Out << "<badref>";
741   }
742 }
743
744 /// WriteAsOperand - Write the name of the specified value out to the specified
745 /// ostream.  This can be useful when you just want to print int %reg126, not
746 /// the whole instruction that generated it.
747 ///
748 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
749                                    bool PrintType, const Module *Context) {
750   std::map<const Type *, std::string> TypeNames;
751   if (Context == 0) Context = getModuleFromVal(V);
752
753   if (Context)
754     fillTypeNameTable(Context, TypeNames);
755
756   if (PrintType)
757     printTypeInt(Out, V->getType(), TypeNames);
758
759   WriteAsOperandInternal(Out, V, TypeNames, 0);
760   return Out;
761 }
762
763
764 namespace llvm {
765
766 class AssemblyWriter {
767   std::ostream &Out;
768   SlotMachine &Machine;
769   const Module *TheModule;
770   std::map<const Type *, std::string> TypeNames;
771   AssemblyAnnotationWriter *AnnotationWriter;
772 public:
773   inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
774                         AssemblyAnnotationWriter *AAW)
775     : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
776
777     // If the module has a symbol table, take all global types and stuff their
778     // names into the TypeNames map.
779     //
780     fillTypeNameTable(M, TypeNames);
781   }
782
783   inline void write(const Module *M)         { printModule(M);       }
784   inline void write(const GlobalVariable *G) { printGlobal(G);       }
785   inline void write(const GlobalAlias *G)    { printAlias(G);        }
786   inline void write(const Function *F)       { printFunction(F);     }
787   inline void write(const BasicBlock *BB)    { printBasicBlock(BB);  }
788   inline void write(const Instruction *I)    { printInstruction(*I); }
789   inline void write(const Type *Ty)          { printType(Ty);        }
790
791   void writeOperand(const Value *Op, bool PrintType);
792   void writeParamOperand(const Value *Operand, ParameterAttributes Attrs);
793
794   const Module* getModule() { return TheModule; }
795
796 private:
797   void printModule(const Module *M);
798   void printTypeSymbolTable(const TypeSymbolTable &ST);
799   void printGlobal(const GlobalVariable *GV);
800   void printAlias(const GlobalAlias *GV);
801   void printFunction(const Function *F);
802   void printArgument(const Argument *FA, ParameterAttributes Attrs);
803   void printBasicBlock(const BasicBlock *BB);
804   void printInstruction(const Instruction &I);
805
806   // printType - Go to extreme measures to attempt to print out a short,
807   // symbolic version of a type name.
808   //
809   std::ostream &printType(const Type *Ty) {
810     return printTypeInt(Out, Ty, TypeNames);
811   }
812
813   // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
814   // without considering any symbolic types that we may have equal to it.
815   //
816   std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
817
818   // printInfoComment - Print a little comment after the instruction indicating
819   // which slot it occupies.
820   void printInfoComment(const Value &V);
821 };
822 }  // end of llvm namespace
823
824 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
825 /// without considering any symbolic types that we may have equal to it.
826 ///
827 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
828   if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
829     Out << "i" << utostr(ITy->getBitWidth());
830   else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
831     printType(FTy->getReturnType());
832     Out << " (";
833     for (FunctionType::param_iterator I = FTy->param_begin(),
834            E = FTy->param_end(); I != E; ++I) {
835       if (I != FTy->param_begin())
836         Out << ", ";
837       printType(*I);
838     }
839     if (FTy->isVarArg()) {
840       if (FTy->getNumParams()) Out << ", ";
841       Out << "...";
842     }
843     Out << ')';
844   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
845     if (STy->isPacked())
846       Out << '<';
847     Out << "{ ";
848     for (StructType::element_iterator I = STy->element_begin(),
849            E = STy->element_end(); I != E; ++I) {
850       if (I != STy->element_begin())
851         Out << ", ";
852       printType(*I);
853     }
854     Out << " }";
855     if (STy->isPacked())
856       Out << '>';
857   } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
858     printType(PTy->getElementType());
859     if (unsigned AddressSpace = PTy->getAddressSpace())
860       Out << " addrspace(" << AddressSpace << ")";
861     Out << '*';
862   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
863     Out << '[' << ATy->getNumElements() << " x ";
864     printType(ATy->getElementType()) << ']';
865   } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
866     Out << '<' << PTy->getNumElements() << " x ";
867     printType(PTy->getElementType()) << '>';
868   }
869   else if (isa<OpaqueType>(Ty)) {
870     Out << "opaque";
871   } else {
872     if (!Ty->isPrimitiveType())
873       Out << "<unknown derived type>";
874     printType(Ty);
875   }
876   return Out;
877 }
878
879
880 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
881   if (Operand == 0) {
882     Out << "<null operand!>";
883   } else {
884     if (PrintType) { Out << ' '; printType(Operand->getType()); }
885     WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
886   }
887 }
888
889 void AssemblyWriter::writeParamOperand(const Value *Operand, 
890                                        ParameterAttributes Attrs) {
891   if (Operand == 0) {
892     Out << "<null operand!>";
893   } else {
894     Out << ' ';
895     // Print the type
896     printType(Operand->getType());
897     // Print parameter attributes list
898     if (Attrs != ParamAttr::None)
899       Out << ' ' << ParamAttr::getAsString(Attrs);
900     // Print the operand
901     WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
902   }
903 }
904
905 void AssemblyWriter::printModule(const Module *M) {
906   if (!M->getModuleIdentifier().empty() &&
907       // Don't print the ID if it will start a new line (which would
908       // require a comment char before it).
909       M->getModuleIdentifier().find('\n') == std::string::npos)
910     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
911
912   if (!M->getDataLayout().empty())
913     Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
914   if (!M->getTargetTriple().empty())
915     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
916
917   if (!M->getModuleInlineAsm().empty()) {
918     // Split the string into lines, to make it easier to read the .ll file.
919     std::string Asm = M->getModuleInlineAsm();
920     size_t CurPos = 0;
921     size_t NewLine = Asm.find_first_of('\n', CurPos);
922     while (NewLine != std::string::npos) {
923       // We found a newline, print the portion of the asm string from the
924       // last newline up to this newline.
925       Out << "module asm \"";
926       PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
927                          Out);
928       Out << "\"\n";
929       CurPos = NewLine+1;
930       NewLine = Asm.find_first_of('\n', CurPos);
931     }
932     Out << "module asm \"";
933     PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
934     Out << "\"\n";
935   }
936   
937   // Loop over the dependent libraries and emit them.
938   Module::lib_iterator LI = M->lib_begin();
939   Module::lib_iterator LE = M->lib_end();
940   if (LI != LE) {
941     Out << "deplibs = [ ";
942     while (LI != LE) {
943       Out << '"' << *LI << '"';
944       ++LI;
945       if (LI != LE)
946         Out << ", ";
947     }
948     Out << " ]\n";
949   }
950
951   // Loop over the symbol table, emitting all named constants.
952   printTypeSymbolTable(M->getTypeSymbolTable());
953
954   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
955        I != E; ++I)
956     printGlobal(I);
957   
958   // Output all aliases.
959   if (!M->alias_empty()) Out << "\n";
960   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
961        I != E; ++I)
962     printAlias(I);
963
964   // Output all of the functions.
965   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
966     printFunction(I);
967 }
968
969 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
970   if (GV->hasName()) {
971     PrintLLVMName(Out, GV);
972     Out << " = ";
973   }
974
975   if (!GV->hasInitializer()) {
976     switch (GV->getLinkage()) {
977      case GlobalValue::DLLImportLinkage:   Out << "dllimport "; break;
978      case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
979      default: Out << "external "; break;
980     }
981   } else {
982     switch (GV->getLinkage()) {
983     case GlobalValue::InternalLinkage:     Out << "internal "; break;
984     case GlobalValue::CommonLinkage:       Out << "common "; break;
985     case GlobalValue::LinkOnceLinkage:     Out << "linkonce "; break;
986     case GlobalValue::WeakLinkage:         Out << "weak "; break;
987     case GlobalValue::AppendingLinkage:    Out << "appending "; break;
988     case GlobalValue::DLLImportLinkage:    Out << "dllimport "; break;
989     case GlobalValue::DLLExportLinkage:    Out << "dllexport "; break;     
990     case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
991     case GlobalValue::ExternalLinkage:     break;
992     case GlobalValue::GhostLinkage:
993       cerr << "GhostLinkage not allowed in AsmWriter!\n";
994       abort();
995     }
996     switch (GV->getVisibility()) {
997     default: assert(0 && "Invalid visibility style!");
998     case GlobalValue::DefaultVisibility: break;
999     case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1000     case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1001     }
1002   }
1003
1004   if (GV->isThreadLocal()) Out << "thread_local ";
1005   Out << (GV->isConstant() ? "constant " : "global ");
1006   printType(GV->getType()->getElementType());
1007
1008   if (GV->hasInitializer())
1009     writeOperand(GV->getInitializer(), false);
1010
1011   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1012     Out << " addrspace(" << AddressSpace << ") ";
1013     
1014   if (GV->hasSection())
1015     Out << ", section \"" << GV->getSection() << '"';
1016   if (GV->getAlignment())
1017     Out << ", align " << GV->getAlignment();
1018
1019   printInfoComment(*GV);
1020   Out << "\n";
1021 }
1022
1023 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1024   // Don't crash when dumping partially built GA
1025   if (!GA->hasName())
1026     Out << "<<nameless>> = ";
1027   else {
1028     PrintLLVMName(Out, GA);
1029     Out << " = ";
1030   }
1031   switch (GA->getVisibility()) {
1032   default: assert(0 && "Invalid visibility style!");
1033   case GlobalValue::DefaultVisibility: break;
1034   case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1035   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1036   }
1037
1038   Out << "alias ";
1039
1040   switch (GA->getLinkage()) {
1041   case GlobalValue::WeakLinkage: Out << "weak "; break;
1042   case GlobalValue::InternalLinkage: Out << "internal "; break;
1043   case GlobalValue::ExternalLinkage: break;
1044   default:
1045    assert(0 && "Invalid alias linkage");
1046   }
1047   
1048   const Constant *Aliasee = GA->getAliasee();
1049     
1050   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1051     printType(GV->getType());
1052     Out << ' ';
1053     PrintLLVMName(Out, GV);
1054   } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1055     printType(F->getFunctionType());
1056     Out << "* ";
1057
1058     if (F->hasName())
1059       PrintLLVMName(Out, F);
1060     else
1061       Out << "@\"\"";
1062   } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1063     printType(GA->getType());
1064     Out << " ";
1065     PrintLLVMName(Out, GA);
1066   } else {
1067     const ConstantExpr *CE = 0;
1068     if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
1069         (CE->getOpcode() == Instruction::BitCast)) {
1070       writeOperand(CE, false);    
1071     } else
1072       assert(0 && "Unsupported aliasee");
1073   }
1074   
1075   printInfoComment(*GA);
1076   Out << "\n";
1077 }
1078
1079 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1080   // Print the types.
1081   for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1082        TI != TE; ++TI) {
1083     Out << "\t" << getLLVMName(TI->first) << " = type ";
1084
1085     // Make sure we print out at least one level of the type structure, so
1086     // that we do not get %FILE = type %FILE
1087     //
1088     printTypeAtLeastOneLevel(TI->second) << "\n";
1089   }
1090 }
1091
1092 /// printFunction - Print all aspects of a function.
1093 ///
1094 void AssemblyWriter::printFunction(const Function *F) {
1095   // Print out the return type and name...
1096   Out << "\n";
1097
1098   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1099
1100   if (F->isDeclaration())
1101     Out << "declare ";
1102   else
1103     Out << "define ";
1104     
1105   switch (F->getLinkage()) {
1106   case GlobalValue::InternalLinkage:     Out << "internal "; break;
1107   case GlobalValue::LinkOnceLinkage:     Out << "linkonce "; break;
1108   case GlobalValue::WeakLinkage:         Out << "weak "; break;
1109   case GlobalValue::CommonLinkage:       Out << "common "; break;
1110   case GlobalValue::AppendingLinkage:    Out << "appending "; break;
1111   case GlobalValue::DLLImportLinkage:    Out << "dllimport "; break;
1112   case GlobalValue::DLLExportLinkage:    Out << "dllexport "; break;
1113   case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;      
1114   case GlobalValue::ExternalLinkage: break;
1115   case GlobalValue::GhostLinkage:
1116     cerr << "GhostLinkage not allowed in AsmWriter!\n";
1117     abort();
1118   }
1119   switch (F->getVisibility()) {
1120   default: assert(0 && "Invalid visibility style!");
1121   case GlobalValue::DefaultVisibility: break;
1122   case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1123   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1124   }
1125
1126   // Print the calling convention.
1127   switch (F->getCallingConv()) {
1128   case CallingConv::C: break;   // default
1129   case CallingConv::Fast:         Out << "fastcc "; break;
1130   case CallingConv::Cold:         Out << "coldcc "; break;
1131   case CallingConv::X86_StdCall:  Out << "x86_stdcallcc "; break;
1132   case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break; 
1133   case CallingConv::X86_SSECall:  Out << "x86_ssecallcc "; break;
1134   default: Out << "cc" << F->getCallingConv() << " "; break;
1135   }
1136
1137   const FunctionType *FT = F->getFunctionType();
1138   const PAListPtr &Attrs = F->getParamAttrs();
1139   printType(F->getReturnType()) << ' ';
1140   if (F->hasName())
1141     PrintLLVMName(Out, F);
1142   else
1143     Out << "@\"\"";
1144   Out << '(';
1145   Machine.incorporateFunction(F);
1146
1147   // Loop over the arguments, printing them...
1148
1149   unsigned Idx = 1;
1150   if (!F->isDeclaration()) {
1151     // If this isn't a declaration, print the argument names as well.
1152     for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1153          I != E; ++I) {
1154       // Insert commas as we go... the first arg doesn't get a comma
1155       if (I != F->arg_begin()) Out << ", ";
1156       printArgument(I, Attrs.getParamAttrs(Idx));
1157       Idx++;
1158     }
1159   } else {
1160     // Otherwise, print the types from the function type.
1161     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1162       // Insert commas as we go... the first arg doesn't get a comma
1163       if (i) Out << ", ";
1164       
1165       // Output type...
1166       printType(FT->getParamType(i));
1167       
1168       ParameterAttributes ArgAttrs = Attrs.getParamAttrs(i+1);
1169       if (ArgAttrs != ParamAttr::None)
1170         Out << ' ' << ParamAttr::getAsString(ArgAttrs);
1171     }
1172   }
1173
1174   // Finish printing arguments...
1175   if (FT->isVarArg()) {
1176     if (FT->getNumParams()) Out << ", ";
1177     Out << "...";  // Output varargs portion of signature!
1178   }
1179   Out << ')';
1180   ParameterAttributes RetAttrs = Attrs.getParamAttrs(0);
1181   if (RetAttrs != ParamAttr::None)
1182     Out << ' ' << ParamAttr::getAsString(Attrs.getParamAttrs(0));
1183   if (F->hasSection())
1184     Out << " section \"" << F->getSection() << '"';
1185   if (F->getAlignment())
1186     Out << " align " << F->getAlignment();
1187   if (F->hasGC())
1188     Out << " gc \"" << F->getGC() << '"';
1189
1190   if (F->isDeclaration()) {
1191     Out << "\n";
1192   } else {
1193     Out << " {";
1194
1195     // Output all of its basic blocks... for the function
1196     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1197       printBasicBlock(I);
1198
1199     Out << "}\n";
1200   }
1201
1202   Machine.purgeFunction();
1203 }
1204
1205 /// printArgument - This member is called for every argument that is passed into
1206 /// the function.  Simply print it out
1207 ///
1208 void AssemblyWriter::printArgument(const Argument *Arg, 
1209                                    ParameterAttributes Attrs) {
1210   // Output type...
1211   printType(Arg->getType());
1212
1213   // Output parameter attributes list
1214   if (Attrs != ParamAttr::None)
1215     Out << ' ' << ParamAttr::getAsString(Attrs);
1216
1217   // Output name, if available...
1218   if (Arg->hasName()) {
1219     Out << ' ';
1220     PrintLLVMName(Out, Arg);
1221   }
1222 }
1223
1224 /// printBasicBlock - This member is called for each basic block in a method.
1225 ///
1226 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1227   if (BB->hasName()) {              // Print out the label if it exists...
1228     Out << "\n";
1229     PrintLLVMName(Out, BB->getValueName(), LabelPrefix);
1230     Out << ':';
1231   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
1232     Out << "\n; <label>:";
1233     int Slot = Machine.getLocalSlot(BB);
1234     if (Slot != -1)
1235       Out << Slot;
1236     else
1237       Out << "<badref>";
1238   }
1239
1240   if (BB->getParent() == 0)
1241     Out << "\t\t; Error: Block without parent!";
1242   else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
1243     // Output predecessors for the block...
1244     Out << "\t\t;";
1245     pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1246     
1247     if (PI == PE) {
1248       Out << " No predecessors!";
1249     } else {
1250       Out << " preds =";
1251       writeOperand(*PI, false);
1252       for (++PI; PI != PE; ++PI) {
1253         Out << ',';
1254         writeOperand(*PI, false);
1255       }
1256     }
1257   }
1258
1259   Out << "\n";
1260
1261   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1262
1263   // Output all of the instructions in the basic block...
1264   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1265     printInstruction(*I);
1266
1267   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1268 }
1269
1270
1271 /// printInfoComment - Print a little comment after the instruction indicating
1272 /// which slot it occupies.
1273 ///
1274 void AssemblyWriter::printInfoComment(const Value &V) {
1275   if (V.getType() != Type::VoidTy) {
1276     Out << "\t\t; <";
1277     printType(V.getType()) << '>';
1278
1279     if (!V.hasName()) {
1280       int SlotNum;
1281       if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1282         SlotNum = Machine.getGlobalSlot(GV);
1283       else
1284         SlotNum = Machine.getLocalSlot(&V);
1285       if (SlotNum == -1)
1286         Out << ":<badref>";
1287       else
1288         Out << ':' << SlotNum; // Print out the def slot taken.
1289     }
1290     Out << " [#uses=" << V.getNumUses() << ']';  // Output # uses
1291   }
1292 }
1293
1294 // This member is called for each Instruction in a function..
1295 void AssemblyWriter::printInstruction(const Instruction &I) {
1296   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1297
1298   Out << "\t";
1299
1300   // Print out name if it exists...
1301   if (I.hasName()) {
1302     PrintLLVMName(Out, &I);
1303     Out << " = ";
1304   }
1305
1306   // If this is a volatile load or store, print out the volatile marker.
1307   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
1308       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1309       Out << "volatile ";
1310   } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1311     // If this is a call, check if it's a tail call.
1312     Out << "tail ";
1313   }
1314
1315   // Print out the opcode...
1316   Out << I.getOpcodeName();
1317
1318   // Print out the compare instruction predicates
1319   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1320     Out << " " << getPredicateText(CI->getPredicate());
1321
1322   // Print out the type of the operands...
1323   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1324
1325   // Special case conditional branches to swizzle the condition out to the front
1326   if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1327     writeOperand(I.getOperand(2), true);
1328     Out << ',';
1329     writeOperand(Operand, true);
1330     Out << ',';
1331     writeOperand(I.getOperand(1), true);
1332
1333   } else if (isa<SwitchInst>(I)) {
1334     // Special case switch statement to get formatting nice and correct...
1335     writeOperand(Operand        , true); Out << ',';
1336     writeOperand(I.getOperand(1), true); Out << " [";
1337
1338     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1339       Out << "\n\t\t";
1340       writeOperand(I.getOperand(op  ), true); Out << ',';
1341       writeOperand(I.getOperand(op+1), true);
1342     }
1343     Out << "\n\t]";
1344   } else if (isa<PHINode>(I)) {
1345     Out << ' ';
1346     printType(I.getType());
1347     Out << ' ';
1348
1349     for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1350       if (op) Out << ", ";
1351       Out << '[';
1352       writeOperand(I.getOperand(op  ), false); Out << ',';
1353       writeOperand(I.getOperand(op+1), false); Out << " ]";
1354     }
1355   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1356     writeOperand(I.getOperand(0), true);
1357     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1358       Out << ", " << *i;
1359   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1360     writeOperand(I.getOperand(0), true); Out << ',';
1361     writeOperand(I.getOperand(1), true);
1362     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1363       Out << ", " << *i;
1364   } else if (isa<ReturnInst>(I) && !Operand) {
1365     Out << " void";
1366   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1367     // Print the calling convention being used.
1368     switch (CI->getCallingConv()) {
1369     case CallingConv::C: break;   // default
1370     case CallingConv::Fast:  Out << " fastcc"; break;
1371     case CallingConv::Cold:  Out << " coldcc"; break;
1372     case CallingConv::X86_StdCall:  Out << " x86_stdcallcc"; break;
1373     case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break; 
1374     case CallingConv::X86_SSECall: Out << " x86_ssecallcc"; break; 
1375     default: Out << " cc" << CI->getCallingConv(); break;
1376     }
1377
1378     const PointerType    *PTy = cast<PointerType>(Operand->getType());
1379     const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
1380     const Type         *RetTy = FTy->getReturnType();
1381     const PAListPtr &PAL = CI->getParamAttrs();
1382
1383     // If possible, print out the short form of the call instruction.  We can
1384     // only do this if the first argument is a pointer to a nonvararg function,
1385     // and if the return type is not a pointer to a function.
1386     //
1387     if (!FTy->isVarArg() &&
1388         (!isa<PointerType>(RetTy) ||
1389          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1390       Out << ' '; printType(RetTy);
1391       writeOperand(Operand, false);
1392     } else {
1393       writeOperand(Operand, true);
1394     }
1395     Out << '(';
1396     for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1397       if (op > 1)
1398         Out << ',';
1399       writeParamOperand(I.getOperand(op), PAL.getParamAttrs(op));
1400     }
1401     Out << " )";
1402     if (PAL.getParamAttrs(0) != ParamAttr::None)
1403       Out << ' ' << ParamAttr::getAsString(PAL.getParamAttrs(0));
1404   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1405     const PointerType    *PTy = cast<PointerType>(Operand->getType());
1406     const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
1407     const Type         *RetTy = FTy->getReturnType();
1408     const PAListPtr &PAL = II->getParamAttrs();
1409
1410     // Print the calling convention being used.
1411     switch (II->getCallingConv()) {
1412     case CallingConv::C: break;   // default
1413     case CallingConv::Fast:  Out << " fastcc"; break;
1414     case CallingConv::Cold:  Out << " coldcc"; break;
1415     case CallingConv::X86_StdCall:  Out << "x86_stdcallcc "; break;
1416     case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1417     case CallingConv::X86_SSECall: Out << "x86_ssecallcc "; break;
1418     default: Out << " cc" << II->getCallingConv(); break;
1419     }
1420
1421     // If possible, print out the short form of the invoke instruction. We can
1422     // only do this if the first argument is a pointer to a nonvararg function,
1423     // and if the return type is not a pointer to a function.
1424     //
1425     if (!FTy->isVarArg() &&
1426         (!isa<PointerType>(RetTy) ||
1427          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1428       Out << ' '; printType(RetTy);
1429       writeOperand(Operand, false);
1430     } else {
1431       writeOperand(Operand, true);
1432     }
1433
1434     Out << '(';
1435     for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1436       if (op > 3)
1437         Out << ',';
1438       writeParamOperand(I.getOperand(op), PAL.getParamAttrs(op-2));
1439     }
1440
1441     Out << " )";
1442     if (PAL.getParamAttrs(0) != ParamAttr::None)
1443       Out << ' ' << ParamAttr::getAsString(PAL.getParamAttrs(0));
1444     Out << "\n\t\t\tto";
1445     writeOperand(II->getNormalDest(), true);
1446     Out << " unwind";
1447     writeOperand(II->getUnwindDest(), true);
1448
1449   } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1450     Out << ' ';
1451     printType(AI->getType()->getElementType());
1452     if (AI->isArrayAllocation()) {
1453       Out << ',';
1454       writeOperand(AI->getArraySize(), true);
1455     }
1456     if (AI->getAlignment()) {
1457       Out << ", align " << AI->getAlignment();
1458     }
1459   } else if (isa<CastInst>(I)) {
1460     if (Operand) writeOperand(Operand, true);   // Work with broken code
1461     Out << " to ";
1462     printType(I.getType());
1463   } else if (isa<VAArgInst>(I)) {
1464     if (Operand) writeOperand(Operand, true);   // Work with broken code
1465     Out << ", ";
1466     printType(I.getType());
1467   } else if (Operand) {   // Print the normal way...
1468
1469     // PrintAllTypes - Instructions who have operands of all the same type
1470     // omit the type from all but the first operand.  If the instruction has
1471     // different type operands (for example br), then they are all printed.
1472     bool PrintAllTypes = false;
1473     const Type *TheType = Operand->getType();
1474
1475     // Select, Store and ShuffleVector always print all types.
1476     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1477         || isa<ReturnInst>(I)) {
1478       PrintAllTypes = true;
1479     } else {
1480       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1481         Operand = I.getOperand(i);
1482         if (Operand->getType() != TheType) {
1483           PrintAllTypes = true;    // We have differing types!  Print them all!
1484           break;
1485         }
1486       }
1487     }
1488
1489     if (!PrintAllTypes) {
1490       Out << ' ';
1491       printType(TheType);
1492     }
1493
1494     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1495       if (i) Out << ',';
1496       writeOperand(I.getOperand(i), PrintAllTypes);
1497     }
1498   }
1499   
1500   // Print post operand alignment for load/store
1501   if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1502     Out << ", align " << cast<LoadInst>(I).getAlignment();
1503   } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1504     Out << ", align " << cast<StoreInst>(I).getAlignment();
1505   }
1506
1507   printInfoComment(I);
1508   Out << "\n";
1509 }
1510
1511
1512 //===----------------------------------------------------------------------===//
1513 //                       External Interface declarations
1514 //===----------------------------------------------------------------------===//
1515
1516 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1517   SlotMachine SlotTable(this);
1518   AssemblyWriter W(o, SlotTable, this, AAW);
1519   W.write(this);
1520 }
1521
1522 void GlobalVariable::print(std::ostream &o) const {
1523   SlotMachine SlotTable(getParent());
1524   AssemblyWriter W(o, SlotTable, getParent(), 0);
1525   W.write(this);
1526 }
1527
1528 void GlobalAlias::print(std::ostream &o) const {
1529   SlotMachine SlotTable(getParent());
1530   AssemblyWriter W(o, SlotTable, getParent(), 0);
1531   W.write(this);
1532 }
1533
1534 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1535   SlotMachine SlotTable(getParent());
1536   AssemblyWriter W(o, SlotTable, getParent(), AAW);
1537
1538   W.write(this);
1539 }
1540
1541 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1542   WriteAsOperand(o, this, true, 0);
1543 }
1544
1545 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1546   SlotMachine SlotTable(getParent());
1547   AssemblyWriter W(o, SlotTable,
1548                    getParent() ? getParent()->getParent() : 0, AAW);
1549   W.write(this);
1550 }
1551
1552 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1553   const Function *F = getParent() ? getParent()->getParent() : 0;
1554   SlotMachine SlotTable(F);
1555   AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1556
1557   W.write(this);
1558 }
1559
1560 void Constant::print(std::ostream &o) const {
1561   if (this == 0) { o << "<null> constant value\n"; return; }
1562
1563   o << ' ' << getType()->getDescription() << ' ';
1564
1565   std::map<const Type *, std::string> TypeTable;
1566   WriteConstantInt(o, this, TypeTable, 0);
1567 }
1568
1569 void Type::print(std::ostream &o) const {
1570   if (this == 0)
1571     o << "<null Type>";
1572   else
1573     o << getDescription();
1574 }
1575
1576 void Argument::print(std::ostream &o) const {
1577   WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1578 }
1579
1580 // Value::dump - allow easy printing of  Values from the debugger.
1581 // Located here because so much of the needed functionality is here.
1582 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1583
1584 // Type::dump - allow easy printing of  Values from the debugger.
1585 // Located here because so much of the needed functionality is here.
1586 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }
1587
1588 //===----------------------------------------------------------------------===//
1589 //                         SlotMachine Implementation
1590 //===----------------------------------------------------------------------===//
1591
1592 #if 0
1593 #define SC_DEBUG(X) cerr << X
1594 #else
1595 #define SC_DEBUG(X)
1596 #endif
1597
1598 // Module level constructor. Causes the contents of the Module (sans functions)
1599 // to be added to the slot table.
1600 SlotMachine::SlotMachine(const Module *M)
1601   : TheModule(M)    ///< Saved for lazy initialization.
1602   , TheFunction(0)
1603   , FunctionProcessed(false)
1604   , mNext(0), fNext(0)
1605 {
1606 }
1607
1608 // Function level constructor. Causes the contents of the Module and the one
1609 // function provided to be added to the slot table.
1610 SlotMachine::SlotMachine(const Function *F)
1611   : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1612   , TheFunction(F) ///< Saved for lazy initialization
1613   , FunctionProcessed(false)
1614   , mNext(0), fNext(0)
1615 {
1616 }
1617
1618 inline void SlotMachine::initialize() {
1619   if (TheModule) {
1620     processModule();
1621     TheModule = 0; ///< Prevent re-processing next time we're called.
1622   }
1623   if (TheFunction && !FunctionProcessed)
1624     processFunction();
1625 }
1626
1627 // Iterate through all the global variables, functions, and global
1628 // variable initializers and create slots for them.
1629 void SlotMachine::processModule() {
1630   SC_DEBUG("begin processModule!\n");
1631
1632   // Add all of the unnamed global variables to the value table.
1633   for (Module::const_global_iterator I = TheModule->global_begin(),
1634        E = TheModule->global_end(); I != E; ++I)
1635     if (!I->hasName()) 
1636       CreateModuleSlot(I);
1637
1638   // Add all the unnamed functions to the table.
1639   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1640        I != E; ++I)
1641     if (!I->hasName())
1642       CreateModuleSlot(I);
1643
1644   SC_DEBUG("end processModule!\n");
1645 }
1646
1647
1648 // Process the arguments, basic blocks, and instructions  of a function.
1649 void SlotMachine::processFunction() {
1650   SC_DEBUG("begin processFunction!\n");
1651   fNext = 0;
1652
1653   // Add all the function arguments with no names.
1654   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1655       AE = TheFunction->arg_end(); AI != AE; ++AI)
1656     if (!AI->hasName())
1657       CreateFunctionSlot(AI);
1658
1659   SC_DEBUG("Inserting Instructions:\n");
1660
1661   // Add all of the basic blocks and instructions with no names.
1662   for (Function::const_iterator BB = TheFunction->begin(),
1663        E = TheFunction->end(); BB != E; ++BB) {
1664     if (!BB->hasName())
1665       CreateFunctionSlot(BB);
1666     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1667       if (I->getType() != Type::VoidTy && !I->hasName())
1668         CreateFunctionSlot(I);
1669   }
1670
1671   FunctionProcessed = true;
1672
1673   SC_DEBUG("end processFunction!\n");
1674 }
1675
1676 /// Clean up after incorporating a function. This is the only way to get out of
1677 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1678 /// incorporation state is indicated by TheFunction != 0.
1679 void SlotMachine::purgeFunction() {
1680   SC_DEBUG("begin purgeFunction!\n");
1681   fMap.clear(); // Simply discard the function level map
1682   TheFunction = 0;
1683   FunctionProcessed = false;
1684   SC_DEBUG("end purgeFunction!\n");
1685 }
1686
1687 /// getGlobalSlot - Get the slot number of a global value.
1688 int SlotMachine::getGlobalSlot(const GlobalValue *V) {
1689   // Check for uninitialized state and do lazy initialization.
1690   initialize();
1691   
1692   // Find the type plane in the module map
1693   ValueMap::iterator MI = mMap.find(V);
1694   return MI == mMap.end() ? -1 : MI->second;
1695 }
1696
1697
1698 /// getLocalSlot - Get the slot number for a value that is local to a function.
1699 int SlotMachine::getLocalSlot(const Value *V) {
1700   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1701
1702   // Check for uninitialized state and do lazy initialization.
1703   initialize();
1704
1705   ValueMap::iterator FI = fMap.find(V);
1706   return FI == fMap.end() ? -1 : FI->second;
1707 }
1708
1709
1710 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1711 void SlotMachine::CreateModuleSlot(const GlobalValue *V) {
1712   assert(V && "Can't insert a null Value into SlotMachine!");
1713   assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
1714   assert(!V->hasName() && "Doesn't need a slot!");
1715   
1716   unsigned DestSlot = mNext++;
1717   mMap[V] = DestSlot;
1718   
1719   SC_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1720            DestSlot << " [");
1721   // G = Global, F = Function, A = Alias, o = other
1722   SC_DEBUG((isa<GlobalVariable>(V) ? 'G' :
1723             (isa<Function>(V) ? 'F' :
1724              (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
1725 }
1726
1727
1728 /// CreateSlot - Create a new slot for the specified value if it has no name.
1729 void SlotMachine::CreateFunctionSlot(const Value *V) {
1730   assert(V->getType() != Type::VoidTy && !V->hasName() &&
1731          "Doesn't need a slot!");
1732   
1733   unsigned DestSlot = fNext++;
1734   fMap[V] = DestSlot;
1735   
1736   // G = Global, F = Function, o = other
1737   SC_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1738            DestSlot << " [o]\n");
1739 }