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