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