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