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