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