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