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