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