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