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