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