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