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