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