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