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