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