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