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