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