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