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