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