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