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