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