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