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