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