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