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