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