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