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