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