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