AsmWriter.cpp revision e8861b840bf388945d876f97cf2ff6fcbf310790
1//===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// 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/Operator.h"
27#include "llvm/Metadata.h"
28#include "llvm/Module.h"
29#include "llvm/ValueSymbolTable.h"
30#include "llvm/TypeSymbolTable.h"
31#include "llvm/ADT/DenseSet.h"
32#include "llvm/ADT/StringExtras.h"
33#include "llvm/ADT/STLExtras.h"
34#include "llvm/Support/CFG.h"
35#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Support/MathExtras.h"
37#include "llvm/Support/raw_ostream.h"
38#include <algorithm>
39#include <cctype>
40#include <map>
41using namespace llvm;
42
43// Make virtual table appear in this compilation unit.
44AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
45
46//===----------------------------------------------------------------------===//
47// Helper Functions
48//===----------------------------------------------------------------------===//
49
50static const Module *getModuleFromVal(const Value *V) {
51  if (const Argument *MA = dyn_cast<Argument>(V))
52    return MA->getParent() ? MA->getParent()->getParent() : 0;
53
54  if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
55    return BB->getParent() ? BB->getParent()->getParent() : 0;
56
57  if (const Instruction *I = dyn_cast<Instruction>(V)) {
58    const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
59    return M ? M->getParent() : 0;
60  }
61
62  if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
63    return GV->getParent();
64  return 0;
65}
66
67// PrintEscapedString - Print each character of the specified string, escaping
68// it if it is not printable or if it is an escape char.
69static void PrintEscapedString(const StringRef &Name, raw_ostream &Out) {
70  for (unsigned i = 0, e = Name.size(); i != e; ++i) {
71    unsigned char C = Name[i];
72    if (isprint(C) && C != '\\' && C != '"')
73      Out << C;
74    else
75      Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
76  }
77}
78
79enum PrefixType {
80  GlobalPrefix,
81  LabelPrefix,
82  LocalPrefix,
83  NoPrefix
84};
85
86/// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
87/// prefixed with % (if the string only contains simple characters) or is
88/// surrounded with ""'s (if it has special chars in it).  Print it out.
89static void PrintLLVMName(raw_ostream &OS, const StringRef &Name,
90                          PrefixType Prefix) {
91  assert(Name.data() && "Cannot get empty name!");
92  switch (Prefix) {
93  default: llvm_unreachable("Bad prefix!");
94  case NoPrefix: break;
95  case GlobalPrefix: OS << '@'; break;
96  case LabelPrefix:  break;
97  case LocalPrefix:  OS << '%'; break;
98  }
99
100  // Scan the name to see if it needs quotes first.
101  bool NeedsQuotes = isdigit(Name[0]);
102  if (!NeedsQuotes) {
103    for (unsigned i = 0, e = Name.size(); i != e; ++i) {
104      char C = Name[i];
105      if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
106        NeedsQuotes = true;
107        break;
108      }
109    }
110  }
111
112  // If we didn't need any quotes, just write out the name in one blast.
113  if (!NeedsQuotes) {
114    OS << Name;
115    return;
116  }
117
118  // Okay, we need quotes.  Output the quotes and escape any scary characters as
119  // needed.
120  OS << '"';
121  PrintEscapedString(Name, OS);
122  OS << '"';
123}
124
125/// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
126/// prefixed with % (if the string only contains simple characters) or is
127/// surrounded with ""'s (if it has special chars in it).  Print it out.
128static void PrintLLVMName(raw_ostream &OS, const Value *V) {
129  PrintLLVMName(OS, V->getName(),
130                isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
131}
132
133//===----------------------------------------------------------------------===//
134// TypePrinting Class: Type printing machinery
135//===----------------------------------------------------------------------===//
136
137static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) {
138  return *static_cast<DenseMap<const Type *, std::string>*>(M);
139}
140
141void TypePrinting::clear() {
142  getTypeNamesMap(TypeNames).clear();
143}
144
145bool TypePrinting::hasTypeName(const Type *Ty) const {
146  return getTypeNamesMap(TypeNames).count(Ty);
147}
148
149void TypePrinting::addTypeName(const Type *Ty, const std::string &N) {
150  getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N));
151}
152
153
154TypePrinting::TypePrinting() {
155  TypeNames = new DenseMap<const Type *, std::string>();
156}
157
158TypePrinting::~TypePrinting() {
159  delete &getTypeNamesMap(TypeNames);
160}
161
162/// CalcTypeName - Write the specified type to the specified raw_ostream, making
163/// use of type names or up references to shorten the type name where possible.
164void TypePrinting::CalcTypeName(const Type *Ty,
165                                SmallVectorImpl<const Type *> &TypeStack,
166                                raw_ostream &OS, bool IgnoreTopLevelName) {
167  // Check to see if the type is named.
168  if (!IgnoreTopLevelName) {
169    DenseMap<const Type *, std::string> &TM = getTypeNamesMap(TypeNames);
170    DenseMap<const Type *, std::string>::iterator I = TM.find(Ty);
171    if (I != TM.end()) {
172      OS << I->second;
173      return;
174    }
175  }
176
177  // Check to see if the Type is already on the stack...
178  unsigned Slot = 0, CurSize = TypeStack.size();
179  while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
180
181  // This is another base case for the recursion.  In this case, we know
182  // that we have looped back to a type that we have previously visited.
183  // Generate the appropriate upreference to handle this.
184  if (Slot < CurSize) {
185    OS << '\\' << unsigned(CurSize-Slot);     // Here's the upreference
186    return;
187  }
188
189  TypeStack.push_back(Ty);    // Recursive case: Add us to the stack..
190
191  switch (Ty->getTypeID()) {
192  case Type::VoidTyID:      OS << "void"; break;
193  case Type::FloatTyID:     OS << "float"; break;
194  case Type::DoubleTyID:    OS << "double"; break;
195  case Type::X86_FP80TyID:  OS << "x86_fp80"; break;
196  case Type::FP128TyID:     OS << "fp128"; break;
197  case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
198  case Type::LabelTyID:     OS << "label"; break;
199  case Type::MetadataTyID:  OS << "metadata"; break;
200  case Type::IntegerTyID:
201    OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
202    break;
203
204  case Type::FunctionTyID: {
205    const FunctionType *FTy = cast<FunctionType>(Ty);
206    CalcTypeName(FTy->getReturnType(), TypeStack, OS);
207    OS << " (";
208    for (FunctionType::param_iterator I = FTy->param_begin(),
209         E = FTy->param_end(); I != E; ++I) {
210      if (I != FTy->param_begin())
211        OS << ", ";
212      CalcTypeName(*I, TypeStack, OS);
213    }
214    if (FTy->isVarArg()) {
215      if (FTy->getNumParams()) OS << ", ";
216      OS << "...";
217    }
218    OS << ')';
219    break;
220  }
221  case Type::StructTyID: {
222    const StructType *STy = cast<StructType>(Ty);
223    if (STy->isPacked())
224      OS << '<';
225    OS << "{ ";
226    for (StructType::element_iterator I = STy->element_begin(),
227         E = STy->element_end(); I != E; ++I) {
228      CalcTypeName(*I, TypeStack, OS);
229      if (next(I) != STy->element_end())
230        OS << ',';
231      OS << ' ';
232    }
233    OS << '}';
234    if (STy->isPacked())
235      OS << '>';
236    break;
237  }
238  case Type::PointerTyID: {
239    const PointerType *PTy = cast<PointerType>(Ty);
240    CalcTypeName(PTy->getElementType(), TypeStack, OS);
241    if (unsigned AddressSpace = PTy->getAddressSpace())
242      OS << " addrspace(" << AddressSpace << ')';
243    OS << '*';
244    break;
245  }
246  case Type::ArrayTyID: {
247    const ArrayType *ATy = cast<ArrayType>(Ty);
248    OS << '[' << ATy->getNumElements() << " x ";
249    CalcTypeName(ATy->getElementType(), TypeStack, OS);
250    OS << ']';
251    break;
252  }
253  case Type::VectorTyID: {
254    const VectorType *PTy = cast<VectorType>(Ty);
255    OS << "<" << PTy->getNumElements() << " x ";
256    CalcTypeName(PTy->getElementType(), TypeStack, OS);
257    OS << '>';
258    break;
259  }
260  case Type::OpaqueTyID:
261    OS << "opaque";
262    break;
263  default:
264    OS << "<unrecognized-type>";
265    break;
266  }
267
268  TypeStack.pop_back();       // Remove self from stack.
269}
270
271/// printTypeInt - The internal guts of printing out a type that has a
272/// potentially named portion.
273///
274void TypePrinting::print(const Type *Ty, raw_ostream &OS,
275                         bool IgnoreTopLevelName) {
276  // Check to see if the type is named.
277  DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
278  if (!IgnoreTopLevelName) {
279    DenseMap<const Type*, std::string>::iterator I = TM.find(Ty);
280    if (I != TM.end()) {
281      OS << I->second;
282      return;
283    }
284  }
285
286  // Otherwise we have a type that has not been named but is a derived type.
287  // Carefully recurse the type hierarchy to print out any contained symbolic
288  // names.
289  SmallVector<const Type *, 16> TypeStack;
290  std::string TypeName;
291
292  raw_string_ostream TypeOS(TypeName);
293  CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
294  OS << TypeOS.str();
295
296  // Cache type name for later use.
297  if (!IgnoreTopLevelName)
298    TM.insert(std::make_pair(Ty, TypeOS.str()));
299}
300
301namespace {
302  class TypeFinder {
303    // To avoid walking constant expressions multiple times and other IR
304    // objects, we keep several helper maps.
305    DenseSet<const Value*> VisitedConstants;
306    DenseSet<const Type*> VisitedTypes;
307
308    TypePrinting &TP;
309    std::vector<const Type*> &NumberedTypes;
310  public:
311    TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
312      : TP(tp), NumberedTypes(numberedTypes) {}
313
314    void Run(const Module &M) {
315      // Get types from the type symbol table.  This gets opaque types referened
316      // only through derived named types.
317      const TypeSymbolTable &ST = M.getTypeSymbolTable();
318      for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
319           TI != E; ++TI)
320        IncorporateType(TI->second);
321
322      // Get types from global variables.
323      for (Module::const_global_iterator I = M.global_begin(),
324           E = M.global_end(); I != E; ++I) {
325        IncorporateType(I->getType());
326        if (I->hasInitializer())
327          IncorporateValue(I->getInitializer());
328      }
329
330      // Get types from aliases.
331      for (Module::const_alias_iterator I = M.alias_begin(),
332           E = M.alias_end(); I != E; ++I) {
333        IncorporateType(I->getType());
334        IncorporateValue(I->getAliasee());
335      }
336
337      // Get types from functions.
338      for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
339        IncorporateType(FI->getType());
340
341        for (Function::const_iterator BB = FI->begin(), E = FI->end();
342             BB != E;++BB)
343          for (BasicBlock::const_iterator II = BB->begin(),
344               E = BB->end(); II != E; ++II) {
345            const Instruction &I = *II;
346            // Incorporate the type of the instruction and all its operands.
347            IncorporateType(I.getType());
348            for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
349                 OI != OE; ++OI)
350              IncorporateValue(*OI);
351          }
352      }
353    }
354
355  private:
356    void IncorporateType(const Type *Ty) {
357      // Check to see if we're already visited this type.
358      if (!VisitedTypes.insert(Ty).second)
359        return;
360
361      // If this is a structure or opaque type, add a name for the type.
362      if (((isa<StructType>(Ty) && cast<StructType>(Ty)->getNumElements())
363            || isa<OpaqueType>(Ty)) && !TP.hasTypeName(Ty)) {
364        TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
365        NumberedTypes.push_back(Ty);
366      }
367
368      // Recursively walk all contained types.
369      for (Type::subtype_iterator I = Ty->subtype_begin(),
370           E = Ty->subtype_end(); I != E; ++I)
371        IncorporateType(*I);
372    }
373
374    /// IncorporateValue - This method is used to walk operand lists finding
375    /// types hiding in constant expressions and other operands that won't be
376    /// walked in other ways.  GlobalValues, basic blocks, instructions, and
377    /// inst operands are all explicitly enumerated.
378    void IncorporateValue(const Value *V) {
379      if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
380
381      // Already visited?
382      if (!VisitedConstants.insert(V).second)
383        return;
384
385      // Check this type.
386      IncorporateType(V->getType());
387
388      // Look in operands for types.
389      const Constant *C = cast<Constant>(V);
390      for (Constant::const_op_iterator I = C->op_begin(),
391           E = C->op_end(); I != E;++I)
392        IncorporateValue(*I);
393    }
394  };
395} // end anonymous namespace
396
397
398/// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
399/// the specified module to the TypePrinter and all numbered types to it and the
400/// NumberedTypes table.
401static void AddModuleTypesToPrinter(TypePrinting &TP,
402                                    std::vector<const Type*> &NumberedTypes,
403                                    const Module *M) {
404  if (M == 0) return;
405
406  // If the module has a symbol table, take all global types and stuff their
407  // names into the TypeNames map.
408  const TypeSymbolTable &ST = M->getTypeSymbolTable();
409  for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
410       TI != E; ++TI) {
411    const Type *Ty = cast<Type>(TI->second);
412
413    // As a heuristic, don't insert pointer to primitive types, because
414    // they are used too often to have a single useful name.
415    if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
416      const Type *PETy = PTy->getElementType();
417      if ((PETy->isPrimitiveType() || PETy->isInteger()) &&
418          !isa<OpaqueType>(PETy))
419        continue;
420    }
421
422    // Likewise don't insert primitives either.
423    if (Ty->isInteger() || Ty->isPrimitiveType())
424      continue;
425
426    // Get the name as a string and insert it into TypeNames.
427    std::string NameStr;
428    raw_string_ostream NameOS(NameStr);
429    PrintLLVMName(NameOS, TI->first, LocalPrefix);
430    TP.addTypeName(Ty, NameOS.str());
431  }
432
433  // Walk the entire module to find references to unnamed structure and opaque
434  // types.  This is required for correctness by opaque types (because multiple
435  // uses of an unnamed opaque type needs to be referred to by the same ID) and
436  // it shrinks complex recursive structure types substantially in some cases.
437  TypeFinder(TP, NumberedTypes).Run(*M);
438}
439
440
441/// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
442/// type, iff there is an entry in the modules symbol table for the specified
443/// type or one of it's component types.
444///
445void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
446  TypePrinting Printer;
447  std::vector<const Type*> NumberedTypes;
448  AddModuleTypesToPrinter(Printer, NumberedTypes, M);
449  Printer.print(Ty, OS);
450}
451
452//===----------------------------------------------------------------------===//
453// SlotTracker Class: Enumerate slot numbers for unnamed values
454//===----------------------------------------------------------------------===//
455
456namespace {
457
458/// This class provides computation of slot numbers for LLVM Assembly writing.
459///
460class SlotTracker {
461public:
462  /// ValueMap - A mapping of Values to slot numbers.
463  typedef DenseMap<const Value*, unsigned> ValueMap;
464
465private:
466  /// TheModule - The module for which we are holding slot numbers.
467  const Module* TheModule;
468
469  /// TheFunction - The function for which we are holding slot numbers.
470  const Function* TheFunction;
471  bool FunctionProcessed;
472
473  /// TheMDNode - The MDNode for which we are holding slot numbers.
474  const MDNode *TheMDNode;
475
476  /// TheNamedMDNode - The MDNode for which we are holding slot numbers.
477  const NamedMDNode *TheNamedMDNode;
478
479  /// mMap - The TypePlanes map for the module level data.
480  ValueMap mMap;
481  unsigned mNext;
482
483  /// fMap - The TypePlanes map for the function level data.
484  ValueMap fMap;
485  unsigned fNext;
486
487  /// mdnMap - Map for MDNodes.
488  ValueMap mdnMap;
489  unsigned mdnNext;
490public:
491  /// Construct from a module
492  explicit SlotTracker(const Module *M);
493  /// Construct from a function, starting out in incorp state.
494  explicit SlotTracker(const Function *F);
495  /// Construct from a mdnode.
496  explicit SlotTracker(const MDNode *N);
497  /// Construct from a named mdnode.
498  explicit SlotTracker(const NamedMDNode *N);
499
500  /// Return the slot number of the specified value in it's type
501  /// plane.  If something is not in the SlotTracker, return -1.
502  int getLocalSlot(const Value *V);
503  int getGlobalSlot(const GlobalValue *V);
504  int getMetadataSlot(const MDNode *N);
505
506  /// If you'd like to deal with a function instead of just a module, use
507  /// this method to get its data into the SlotTracker.
508  void incorporateFunction(const Function *F) {
509    TheFunction = F;
510    FunctionProcessed = false;
511  }
512
513  /// After calling incorporateFunction, use this method to remove the
514  /// most recently incorporated function from the SlotTracker. This
515  /// will reset the state of the machine back to just the module contents.
516  void purgeFunction();
517
518  /// MDNode map iterators.
519  ValueMap::iterator mdnBegin() { return mdnMap.begin(); }
520  ValueMap::iterator mdnEnd() { return mdnMap.end(); }
521  unsigned mdnSize() { return mdnMap.size(); }
522
523  /// This function does the actual initialization.
524  inline void initialize();
525
526  // Implementation Details
527private:
528  /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
529  void CreateModuleSlot(const GlobalValue *V);
530
531  /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
532  void CreateMetadataSlot(const MDNode *N);
533
534  /// CreateFunctionSlot - Insert the specified Value* into the slot table.
535  void CreateFunctionSlot(const Value *V);
536
537  /// Add all of the module level global variables (and their initializers)
538  /// and function declarations, but not the contents of those functions.
539  void processModule();
540
541  /// Add all of the functions arguments, basic blocks, and instructions.
542  void processFunction();
543
544  /// Add all MDNode operands.
545  void processMDNode();
546
547  /// Add all MDNode operands.
548  void processNamedMDNode();
549
550  SlotTracker(const SlotTracker &);  // DO NOT IMPLEMENT
551  void operator=(const SlotTracker &);  // DO NOT IMPLEMENT
552};
553
554}  // end anonymous namespace
555
556
557static SlotTracker *createSlotTracker(const Value *V) {
558  if (const Argument *FA = dyn_cast<Argument>(V))
559    return new SlotTracker(FA->getParent());
560
561  if (const Instruction *I = dyn_cast<Instruction>(V))
562    return new SlotTracker(I->getParent()->getParent());
563
564  if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
565    return new SlotTracker(BB->getParent());
566
567  if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
568    return new SlotTracker(GV->getParent());
569
570  if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
571    return new SlotTracker(GA->getParent());
572
573  if (const Function *Func = dyn_cast<Function>(V))
574    return new SlotTracker(Func);
575
576  return 0;
577}
578
579#if 0
580#define ST_DEBUG(X) errs() << X
581#else
582#define ST_DEBUG(X)
583#endif
584
585// Module level constructor. Causes the contents of the Module (sans functions)
586// to be added to the slot table.
587SlotTracker::SlotTracker(const Module *M)
588  : TheModule(M), TheFunction(0), FunctionProcessed(false), TheMDNode(0),
589    TheNamedMDNode(0), mNext(0), fNext(0),  mdnNext(0) {
590}
591
592// Function level constructor. Causes the contents of the Module and the one
593// function provided to be added to the slot table.
594SlotTracker::SlotTracker(const Function *F)
595  : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
596    TheMDNode(0), TheNamedMDNode(0), mNext(0), fNext(0), mdnNext(0) {
597}
598
599// Constructor to handle single MDNode.
600SlotTracker::SlotTracker(const MDNode *C)
601  : TheModule(0), TheFunction(0), FunctionProcessed(false), TheMDNode(C),
602    TheNamedMDNode(0), mNext(0), fNext(0),  mdnNext(0) {
603}
604
605// Constructor to handle single NamedMDNode.
606SlotTracker::SlotTracker(const NamedMDNode *N)
607  : TheModule(0), TheFunction(0), FunctionProcessed(false), TheMDNode(0),
608    TheNamedMDNode(N), mNext(0), fNext(0),  mdnNext(0) {
609}
610
611inline void SlotTracker::initialize() {
612  if (TheModule) {
613    processModule();
614    TheModule = 0; ///< Prevent re-processing next time we're called.
615  }
616
617  if (TheFunction && !FunctionProcessed)
618    processFunction();
619
620  if (TheMDNode)
621    processMDNode();
622
623  if (TheNamedMDNode)
624    processNamedMDNode();
625}
626
627// Iterate through all the global variables, functions, and global
628// variable initializers and create slots for them.
629void SlotTracker::processModule() {
630  ST_DEBUG("begin processModule!\n");
631
632  // Add all of the unnamed global variables to the value table.
633  for (Module::const_global_iterator I = TheModule->global_begin(),
634         E = TheModule->global_end(); I != E; ++I) {
635    if (!I->hasName())
636      CreateModuleSlot(I);
637    if (I->hasInitializer()) {
638      if (MDNode *N = dyn_cast<MDNode>(I->getInitializer()))
639        CreateMetadataSlot(N);
640    }
641  }
642
643  // Add metadata used by named metadata.
644  for (Module::const_named_metadata_iterator
645         I = TheModule->named_metadata_begin(),
646         E = TheModule->named_metadata_end(); I != E; ++I) {
647    const NamedMDNode *NMD = I;
648    for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
649      MDNode *MD = dyn_cast_or_null<MDNode>(NMD->getElement(i));
650      if (MD)
651        CreateMetadataSlot(MD);
652    }
653  }
654
655  // Add all the unnamed functions to the table.
656  for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
657       I != E; ++I)
658    if (!I->hasName())
659      CreateModuleSlot(I);
660
661  ST_DEBUG("end processModule!\n");
662}
663
664// Process the arguments, basic blocks, and instructions  of a function.
665void SlotTracker::processFunction() {
666  ST_DEBUG("begin processFunction!\n");
667  fNext = 0;
668
669  // Add all the function arguments with no names.
670  for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
671      AE = TheFunction->arg_end(); AI != AE; ++AI)
672    if (!AI->hasName())
673      CreateFunctionSlot(AI);
674
675  ST_DEBUG("Inserting Instructions:\n");
676
677  // Add all of the basic blocks and instructions with no names.
678  for (Function::const_iterator BB = TheFunction->begin(),
679       E = TheFunction->end(); BB != E; ++BB) {
680    if (!BB->hasName())
681      CreateFunctionSlot(BB);
682    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
683         ++I) {
684      if (I->getType() != Type::VoidTy && !I->hasName())
685        CreateFunctionSlot(I);
686      for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
687        if (MDNode *N = dyn_cast<MDNode>(I->getOperand(i)))
688          CreateMetadataSlot(N);
689    }
690  }
691
692  FunctionProcessed = true;
693
694  ST_DEBUG("end processFunction!\n");
695}
696
697/// processMDNode - Process TheMDNode.
698void SlotTracker::processMDNode() {
699  ST_DEBUG("begin processMDNode!\n");
700  mdnNext = 0;
701  CreateMetadataSlot(TheMDNode);
702  TheMDNode = 0;
703  ST_DEBUG("end processMDNode!\n");
704}
705
706/// processNamedMDNode - Process TheNamedMDNode.
707void SlotTracker::processNamedMDNode() {
708  ST_DEBUG("begin processNamedMDNode!\n");
709  mdnNext = 0;
710  for (unsigned i = 0, e = TheNamedMDNode->getNumElements(); i != e; ++i) {
711    MDNode *MD = dyn_cast_or_null<MDNode>(TheNamedMDNode->getElement(i));
712    if (MD)
713      CreateMetadataSlot(MD);
714  }
715  TheNamedMDNode = 0;
716  ST_DEBUG("end processNamedMDNode!\n");
717}
718
719/// Clean up after incorporating a function. This is the only way to get out of
720/// the function incorporation state that affects get*Slot/Create*Slot. Function
721/// incorporation state is indicated by TheFunction != 0.
722void SlotTracker::purgeFunction() {
723  ST_DEBUG("begin purgeFunction!\n");
724  fMap.clear(); // Simply discard the function level map
725  TheFunction = 0;
726  FunctionProcessed = false;
727  ST_DEBUG("end purgeFunction!\n");
728}
729
730/// getGlobalSlot - Get the slot number of a global value.
731int SlotTracker::getGlobalSlot(const GlobalValue *V) {
732  // Check for uninitialized state and do lazy initialization.
733  initialize();
734
735  // Find the type plane in the module map
736  ValueMap::iterator MI = mMap.find(V);
737  return MI == mMap.end() ? -1 : (int)MI->second;
738}
739
740/// getGlobalSlot - Get the slot number of a MDNode.
741int SlotTracker::getMetadataSlot(const MDNode *N) {
742  // Check for uninitialized state and do lazy initialization.
743  initialize();
744
745  // Find the type plane in the module map
746  ValueMap::iterator MI = mdnMap.find(N);
747  return MI == mdnMap.end() ? -1 : (int)MI->second;
748}
749
750
751/// getLocalSlot - Get the slot number for a value that is local to a function.
752int SlotTracker::getLocalSlot(const Value *V) {
753  assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
754
755  // Check for uninitialized state and do lazy initialization.
756  initialize();
757
758  ValueMap::iterator FI = fMap.find(V);
759  return FI == fMap.end() ? -1 : (int)FI->second;
760}
761
762
763/// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
764void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
765  assert(V && "Can't insert a null Value into SlotTracker!");
766  assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
767  assert(!V->hasName() && "Doesn't need a slot!");
768
769  unsigned DestSlot = mNext++;
770  mMap[V] = DestSlot;
771
772  ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
773           DestSlot << " [");
774  // G = Global, F = Function, A = Alias, o = other
775  ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
776            (isa<Function>(V) ? 'F' :
777             (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
778}
779
780/// CreateSlot - Create a new slot for the specified value if it has no name.
781void SlotTracker::CreateFunctionSlot(const Value *V) {
782  assert(V->getType() != Type::VoidTy && !V->hasName() &&
783         "Doesn't need a slot!");
784
785  unsigned DestSlot = fNext++;
786  fMap[V] = DestSlot;
787
788  // G = Global, F = Function, o = other
789  ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
790           DestSlot << " [o]\n");
791}
792
793/// CreateModuleSlot - Insert the specified MDNode* into the slot table.
794void SlotTracker::CreateMetadataSlot(const MDNode *N) {
795  assert(N && "Can't insert a null Value into SlotTracker!");
796
797  ValueMap::iterator I = mdnMap.find(N);
798  if (I != mdnMap.end())
799    return;
800
801  unsigned DestSlot = mdnNext++;
802  mdnMap[N] = DestSlot;
803
804  for (MDNode::const_elem_iterator MDI = N->elem_begin(),
805         MDE = N->elem_end(); MDI != MDE; ++MDI) {
806    const Value *TV = *MDI;
807    if (TV)
808      if (const MDNode *N2 = dyn_cast<MDNode>(TV))
809        CreateMetadataSlot(N2);
810  }
811}
812
813//===----------------------------------------------------------------------===//
814// AsmWriter Implementation
815//===----------------------------------------------------------------------===//
816
817static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
818                                   TypePrinting &TypePrinter,
819                                   SlotTracker *Machine);
820
821
822
823static const char *getPredicateText(unsigned predicate) {
824  const char * pred = "unknown";
825  switch (predicate) {
826    case FCmpInst::FCMP_FALSE: pred = "false"; break;
827    case FCmpInst::FCMP_OEQ:   pred = "oeq"; break;
828    case FCmpInst::FCMP_OGT:   pred = "ogt"; break;
829    case FCmpInst::FCMP_OGE:   pred = "oge"; break;
830    case FCmpInst::FCMP_OLT:   pred = "olt"; break;
831    case FCmpInst::FCMP_OLE:   pred = "ole"; break;
832    case FCmpInst::FCMP_ONE:   pred = "one"; break;
833    case FCmpInst::FCMP_ORD:   pred = "ord"; break;
834    case FCmpInst::FCMP_UNO:   pred = "uno"; break;
835    case FCmpInst::FCMP_UEQ:   pred = "ueq"; break;
836    case FCmpInst::FCMP_UGT:   pred = "ugt"; break;
837    case FCmpInst::FCMP_UGE:   pred = "uge"; break;
838    case FCmpInst::FCMP_ULT:   pred = "ult"; break;
839    case FCmpInst::FCMP_ULE:   pred = "ule"; break;
840    case FCmpInst::FCMP_UNE:   pred = "une"; break;
841    case FCmpInst::FCMP_TRUE:  pred = "true"; break;
842    case ICmpInst::ICMP_EQ:    pred = "eq"; break;
843    case ICmpInst::ICMP_NE:    pred = "ne"; break;
844    case ICmpInst::ICMP_SGT:   pred = "sgt"; break;
845    case ICmpInst::ICMP_SGE:   pred = "sge"; break;
846    case ICmpInst::ICMP_SLT:   pred = "slt"; break;
847    case ICmpInst::ICMP_SLE:   pred = "sle"; break;
848    case ICmpInst::ICMP_UGT:   pred = "ugt"; break;
849    case ICmpInst::ICMP_UGE:   pred = "uge"; break;
850    case ICmpInst::ICMP_ULT:   pred = "ult"; break;
851    case ICmpInst::ICMP_ULE:   pred = "ule"; break;
852  }
853  return pred;
854}
855
856static void WriteMDNodes(raw_ostream &Out, TypePrinting &TypePrinter,
857                         SlotTracker &Machine) {
858  SmallVector<const MDNode *, 16> Nodes;
859  Nodes.resize(Machine.mdnSize());
860  for (SlotTracker::ValueMap::iterator I =
861         Machine.mdnBegin(), E = Machine.mdnEnd(); I != E; ++I)
862    Nodes[I->second] = cast<MDNode>(I->first);
863
864  for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
865    Out << '!' << i << " = metadata ";
866    const MDNode *Node = Nodes[i];
867    Out << "!{";
868    for (MDNode::const_elem_iterator NI = Node->elem_begin(),
869           NE = Node->elem_end(); NI != NE;) {
870      const Value *V = *NI;
871      if (!V)
872        Out << "null";
873      else if (const MDNode *N = dyn_cast<MDNode>(V)) {
874        Out << "metadata ";
875        Out << '!' << Machine.getMetadataSlot(N);
876      }
877      else {
878        TypePrinter.print((*NI)->getType(), Out);
879        Out << ' ';
880        WriteAsOperandInternal(Out, *NI, TypePrinter, &Machine);
881      }
882      if (++NI != NE)
883        Out << ", ";
884    }
885    Out << "}\n";
886  }
887}
888
889static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
890  if (const OverflowingBinaryOperator *OBO =
891        dyn_cast<OverflowingBinaryOperator>(U)) {
892    if (OBO->hasNoUnsignedOverflow())
893      Out << " nuw";
894    if (OBO->hasNoSignedOverflow())
895      Out << " nsw";
896  } else if (const SDivOperator *Div = dyn_cast<SDivOperator>(U)) {
897    if (Div->isExact())
898      Out << " exact";
899  } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
900    if (GEP->isInBounds())
901      Out << " inbounds";
902  }
903}
904
905static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
906                             TypePrinting &TypePrinter, SlotTracker *Machine) {
907  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
908    if (CI->getType() == Type::Int1Ty) {
909      Out << (CI->getZExtValue() ? "true" : "false");
910      return;
911    }
912    Out << CI->getValue();
913    return;
914  }
915
916  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
917    if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
918        &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
919      // We would like to output the FP constant value in exponential notation,
920      // but we cannot do this if doing so will lose precision.  Check here to
921      // make sure that we only output it in exponential format if we can parse
922      // the value back and get the same value.
923      //
924      bool ignored;
925      bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
926      double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
927                              CFP->getValueAPF().convertToFloat();
928      std::string StrVal = ftostr(CFP->getValueAPF());
929
930      // Check to make sure that the stringized number is not some string like
931      // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
932      // that the string matches the "[-+]?[0-9]" regex.
933      //
934      if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
935          ((StrVal[0] == '-' || StrVal[0] == '+') &&
936           (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
937        // Reparse stringized version!
938        if (atof(StrVal.c_str()) == Val) {
939          Out << StrVal;
940          return;
941        }
942      }
943      // Otherwise we could not reparse it to exactly the same value, so we must
944      // output the string in hexadecimal format!  Note that loading and storing
945      // floating point types changes the bits of NaNs on some hosts, notably
946      // x86, so we must not use these types.
947      assert(sizeof(double) == sizeof(uint64_t) &&
948             "assuming that double is 64 bits!");
949      char Buffer[40];
950      APFloat apf = CFP->getValueAPF();
951      // Floats are represented in ASCII IR as double, convert.
952      if (!isDouble)
953        apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
954                          &ignored);
955      Out << "0x" <<
956              utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
957                            Buffer+40);
958      return;
959    }
960
961    // Some form of long double.  These appear as a magic letter identifying
962    // the type, then a fixed number of hex digits.
963    Out << "0x";
964    if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
965      Out << 'K';
966      // api needed to prevent premature destruction
967      APInt api = CFP->getValueAPF().bitcastToAPInt();
968      const uint64_t* p = api.getRawData();
969      uint64_t word = p[1];
970      int shiftcount=12;
971      int width = api.getBitWidth();
972      for (int j=0; j<width; j+=4, shiftcount-=4) {
973        unsigned int nibble = (word>>shiftcount) & 15;
974        if (nibble < 10)
975          Out << (unsigned char)(nibble + '0');
976        else
977          Out << (unsigned char)(nibble - 10 + 'A');
978        if (shiftcount == 0 && j+4 < width) {
979          word = *p;
980          shiftcount = 64;
981          if (width-j-4 < 64)
982            shiftcount = width-j-4;
983        }
984      }
985      return;
986    } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
987      Out << 'L';
988    else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
989      Out << 'M';
990    else
991      llvm_unreachable("Unsupported floating point type");
992    // api needed to prevent premature destruction
993    APInt api = CFP->getValueAPF().bitcastToAPInt();
994    const uint64_t* p = api.getRawData();
995    uint64_t word = *p;
996    int shiftcount=60;
997    int width = api.getBitWidth();
998    for (int j=0; j<width; j+=4, shiftcount-=4) {
999      unsigned int nibble = (word>>shiftcount) & 15;
1000      if (nibble < 10)
1001        Out << (unsigned char)(nibble + '0');
1002      else
1003        Out << (unsigned char)(nibble - 10 + 'A');
1004      if (shiftcount == 0 && j+4 < width) {
1005        word = *(++p);
1006        shiftcount = 64;
1007        if (width-j-4 < 64)
1008          shiftcount = width-j-4;
1009      }
1010    }
1011    return;
1012  }
1013
1014  if (isa<ConstantAggregateZero>(CV)) {
1015    Out << "zeroinitializer";
1016    return;
1017  }
1018
1019  if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1020    // As a special case, print the array as a string if it is an array of
1021    // i8 with ConstantInt values.
1022    //
1023    const Type *ETy = CA->getType()->getElementType();
1024    if (CA->isString()) {
1025      Out << "c\"";
1026      PrintEscapedString(CA->getAsString(), Out);
1027      Out << '"';
1028    } else {                // Cannot output in string format...
1029      Out << '[';
1030      if (CA->getNumOperands()) {
1031        TypePrinter.print(ETy, Out);
1032        Out << ' ';
1033        WriteAsOperandInternal(Out, CA->getOperand(0),
1034                               TypePrinter, Machine);
1035        for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1036          Out << ", ";
1037          TypePrinter.print(ETy, Out);
1038          Out << ' ';
1039          WriteAsOperandInternal(Out, CA->getOperand(i), TypePrinter, Machine);
1040        }
1041      }
1042      Out << ']';
1043    }
1044    return;
1045  }
1046
1047  if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1048    if (CS->getType()->isPacked())
1049      Out << '<';
1050    Out << '{';
1051    unsigned N = CS->getNumOperands();
1052    if (N) {
1053      Out << ' ';
1054      TypePrinter.print(CS->getOperand(0)->getType(), Out);
1055      Out << ' ';
1056
1057      WriteAsOperandInternal(Out, CS->getOperand(0), TypePrinter, Machine);
1058
1059      for (unsigned i = 1; i < N; i++) {
1060        Out << ", ";
1061        TypePrinter.print(CS->getOperand(i)->getType(), Out);
1062        Out << ' ';
1063
1064        WriteAsOperandInternal(Out, CS->getOperand(i), TypePrinter, Machine);
1065      }
1066      Out << ' ';
1067    }
1068
1069    Out << '}';
1070    if (CS->getType()->isPacked())
1071      Out << '>';
1072    return;
1073  }
1074
1075  if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1076    const Type *ETy = CP->getType()->getElementType();
1077    assert(CP->getNumOperands() > 0 &&
1078           "Number of operands for a PackedConst must be > 0");
1079    Out << '<';
1080    TypePrinter.print(ETy, Out);
1081    Out << ' ';
1082    WriteAsOperandInternal(Out, CP->getOperand(0), TypePrinter, Machine);
1083    for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
1084      Out << ", ";
1085      TypePrinter.print(ETy, Out);
1086      Out << ' ';
1087      WriteAsOperandInternal(Out, CP->getOperand(i), TypePrinter, Machine);
1088    }
1089    Out << '>';
1090    return;
1091  }
1092
1093  if (isa<ConstantPointerNull>(CV)) {
1094    Out << "null";
1095    return;
1096  }
1097
1098  if (isa<UndefValue>(CV)) {
1099    Out << "undef";
1100    return;
1101  }
1102
1103  if (const MDNode *Node = dyn_cast<MDNode>(CV)) {
1104    Out << "!" << Machine->getMetadataSlot(Node);
1105    return;
1106  }
1107
1108  if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1109    Out << CE->getOpcodeName();
1110    WriteOptimizationInfo(Out, CE);
1111    if (CE->isCompare())
1112      Out << ' ' << getPredicateText(CE->getPredicate());
1113    Out << " (";
1114
1115    for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1116      TypePrinter.print((*OI)->getType(), Out);
1117      Out << ' ';
1118      WriteAsOperandInternal(Out, *OI, TypePrinter, Machine);
1119      if (OI+1 != CE->op_end())
1120        Out << ", ";
1121    }
1122
1123    if (CE->hasIndices()) {
1124      const SmallVector<unsigned, 4> &Indices = CE->getIndices();
1125      for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1126        Out << ", " << Indices[i];
1127    }
1128
1129    if (CE->isCast()) {
1130      Out << " to ";
1131      TypePrinter.print(CE->getType(), Out);
1132    }
1133
1134    Out << ')';
1135    return;
1136  }
1137
1138  Out << "<placeholder or erroneous Constant>";
1139}
1140
1141
1142/// WriteAsOperand - Write the name of the specified value out to the specified
1143/// ostream.  This can be useful when you just want to print int %reg126, not
1144/// the whole instruction that generated it.
1145///
1146static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1147                                   TypePrinting &TypePrinter,
1148                                   SlotTracker *Machine) {
1149  if (V->hasName()) {
1150    PrintLLVMName(Out, V);
1151    return;
1152  }
1153
1154  const Constant *CV = dyn_cast<Constant>(V);
1155  if (CV && !isa<GlobalValue>(CV)) {
1156    WriteConstantInt(Out, CV, TypePrinter, Machine);
1157    return;
1158  }
1159
1160  if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1161    Out << "asm ";
1162    if (IA->hasSideEffects())
1163      Out << "sideeffect ";
1164    Out << '"';
1165    PrintEscapedString(IA->getAsmString(), Out);
1166    Out << "\", \"";
1167    PrintEscapedString(IA->getConstraintString(), Out);
1168    Out << '"';
1169    return;
1170  }
1171
1172  if (const MDNode *N = dyn_cast<MDNode>(V)) {
1173    Out << '!' << Machine->getMetadataSlot(N);
1174    return;
1175  }
1176
1177  if (const MDString *MDS = dyn_cast<MDString>(V)) {
1178    Out << "!\"";
1179    PrintEscapedString(MDS->getString(), Out);
1180    Out << '"';
1181    return;
1182  }
1183
1184  char Prefix = '%';
1185  int Slot;
1186  if (Machine) {
1187    if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1188      Slot = Machine->getGlobalSlot(GV);
1189      Prefix = '@';
1190    } else {
1191      Slot = Machine->getLocalSlot(V);
1192    }
1193  } else {
1194    Machine = createSlotTracker(V);
1195    if (Machine) {
1196      if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1197        Slot = Machine->getGlobalSlot(GV);
1198        Prefix = '@';
1199      } else {
1200        Slot = Machine->getLocalSlot(V);
1201      }
1202    } else {
1203      Slot = -1;
1204    }
1205    delete Machine;
1206  }
1207
1208  if (Slot != -1)
1209    Out << Prefix << Slot;
1210  else
1211    Out << "<badref>";
1212}
1213
1214/// WriteAsOperand - Write the name of the specified value out to the specified
1215/// ostream.  This can be useful when you just want to print int %reg126, not
1216/// the whole instruction that generated it.
1217///
1218void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
1219                          const Module *Context) {
1220  raw_os_ostream OS(Out);
1221  WriteAsOperand(OS, V, PrintType, Context);
1222}
1223
1224void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
1225                          const Module *Context) {
1226  if (Context == 0) Context = getModuleFromVal(V);
1227
1228  TypePrinting TypePrinter;
1229  std::vector<const Type*> NumberedTypes;
1230  AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1231  if (PrintType) {
1232    TypePrinter.print(V->getType(), Out);
1233    Out << ' ';
1234  }
1235
1236  WriteAsOperandInternal(Out, V, TypePrinter, 0);
1237}
1238
1239
1240namespace {
1241
1242class AssemblyWriter {
1243  raw_ostream &Out;
1244  SlotTracker &Machine;
1245  const Module *TheModule;
1246  TypePrinting TypePrinter;
1247  AssemblyAnnotationWriter *AnnotationWriter;
1248  std::vector<const Type*> NumberedTypes;
1249
1250  // Each MDNode is assigned unique MetadataIDNo.
1251  std::map<const MDNode *, unsigned> MDNodes;
1252  unsigned MetadataIDNo;
1253public:
1254  inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
1255                        AssemblyAnnotationWriter *AAW)
1256    : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW), MetadataIDNo(0) {
1257    AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1258  }
1259
1260  void write(const Module *M) { printModule(M); }
1261
1262  void write(const GlobalValue *G) {
1263    if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
1264      printGlobal(GV);
1265    else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
1266      printAlias(GA);
1267    else if (const Function *F = dyn_cast<Function>(G))
1268      printFunction(F);
1269    else
1270      llvm_unreachable("Unknown global");
1271  }
1272
1273  void write(const BasicBlock *BB)    { printBasicBlock(BB);  }
1274  void write(const Instruction *I)    { printInstruction(*I); }
1275
1276  void writeOperand(const Value *Op, bool PrintType);
1277  void writeParamOperand(const Value *Operand, Attributes Attrs);
1278
1279  const Module* getModule() { return TheModule; }
1280
1281private:
1282  void printModule(const Module *M);
1283  void printTypeSymbolTable(const TypeSymbolTable &ST);
1284  void printGlobal(const GlobalVariable *GV);
1285  void printAlias(const GlobalAlias *GV);
1286  void printFunction(const Function *F);
1287  void printArgument(const Argument *FA, Attributes Attrs);
1288  void printBasicBlock(const BasicBlock *BB);
1289  void printInstruction(const Instruction &I);
1290
1291  // printInfoComment - Print a little comment after the instruction indicating
1292  // which slot it occupies.
1293  void printInfoComment(const Value &V);
1294};
1295}  // end of anonymous namespace
1296
1297
1298void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1299  if (Operand == 0) {
1300    Out << "<null operand!>";
1301  } else {
1302    if (PrintType) {
1303      TypePrinter.print(Operand->getType(), Out);
1304      Out << ' ';
1305    }
1306    WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1307  }
1308}
1309
1310void AssemblyWriter::writeParamOperand(const Value *Operand,
1311                                       Attributes Attrs) {
1312  if (Operand == 0) {
1313    Out << "<null operand!>";
1314  } else {
1315    // Print the type
1316    TypePrinter.print(Operand->getType(), Out);
1317    // Print parameter attributes list
1318    if (Attrs != Attribute::None)
1319      Out << ' ' << Attribute::getAsString(Attrs);
1320    Out << ' ';
1321    // Print the operand
1322    WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1323  }
1324}
1325
1326void AssemblyWriter::printModule(const Module *M) {
1327  if (!M->getModuleIdentifier().empty() &&
1328      // Don't print the ID if it will start a new line (which would
1329      // require a comment char before it).
1330      M->getModuleIdentifier().find('\n') == std::string::npos)
1331    Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1332
1333  if (!M->getDataLayout().empty())
1334    Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1335  if (!M->getTargetTriple().empty())
1336    Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1337
1338  if (!M->getModuleInlineAsm().empty()) {
1339    // Split the string into lines, to make it easier to read the .ll file.
1340    std::string Asm = M->getModuleInlineAsm();
1341    size_t CurPos = 0;
1342    size_t NewLine = Asm.find_first_of('\n', CurPos);
1343    while (NewLine != std::string::npos) {
1344      // We found a newline, print the portion of the asm string from the
1345      // last newline up to this newline.
1346      Out << "module asm \"";
1347      PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1348                         Out);
1349      Out << "\"\n";
1350      CurPos = NewLine+1;
1351      NewLine = Asm.find_first_of('\n', CurPos);
1352    }
1353    Out << "module asm \"";
1354    PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1355    Out << "\"\n";
1356  }
1357
1358  // Loop over the dependent libraries and emit them.
1359  Module::lib_iterator LI = M->lib_begin();
1360  Module::lib_iterator LE = M->lib_end();
1361  if (LI != LE) {
1362    Out << "deplibs = [ ";
1363    while (LI != LE) {
1364      Out << '"' << *LI << '"';
1365      ++LI;
1366      if (LI != LE)
1367        Out << ", ";
1368    }
1369    Out << " ]\n";
1370  }
1371
1372  // Loop over the symbol table, emitting all id'd types.
1373  printTypeSymbolTable(M->getTypeSymbolTable());
1374
1375  for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1376       I != E; ++I)
1377    printGlobal(I);
1378
1379  // Output all aliases.
1380  if (!M->alias_empty()) Out << "\n";
1381  for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1382       I != E; ++I)
1383    printAlias(I);
1384
1385  // Output all of the functions.
1386  for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1387    printFunction(I);
1388
1389  // Output named metadata.
1390  for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1391         E = M->named_metadata_end(); I != E; ++I) {
1392    const NamedMDNode *NMD = I;
1393    Out << "!" << NMD->getName() << " = !{";
1394    for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1395      if (i) Out << ", ";
1396      MDNode *MD = dyn_cast_or_null<MDNode>(NMD->getElement(i));
1397      Out << '!' << Machine.getMetadataSlot(MD);
1398    }
1399    Out << "}\n";
1400  }
1401
1402  // Output metadata.
1403  WriteMDNodes(Out, TypePrinter, Machine);
1404}
1405
1406static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1407  switch (LT) {
1408  case GlobalValue::ExternalLinkage: break;
1409  case GlobalValue::PrivateLinkage:       Out << "private ";        break;
1410  case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1411  case GlobalValue::InternalLinkage:      Out << "internal ";       break;
1412  case GlobalValue::LinkOnceAnyLinkage:   Out << "linkonce ";       break;
1413  case GlobalValue::LinkOnceODRLinkage:   Out << "linkonce_odr ";   break;
1414  case GlobalValue::WeakAnyLinkage:       Out << "weak ";           break;
1415  case GlobalValue::WeakODRLinkage:       Out << "weak_odr ";       break;
1416  case GlobalValue::CommonLinkage:        Out << "common ";         break;
1417  case GlobalValue::AppendingLinkage:     Out << "appending ";      break;
1418  case GlobalValue::DLLImportLinkage:     Out << "dllimport ";      break;
1419  case GlobalValue::DLLExportLinkage:     Out << "dllexport ";      break;
1420  case GlobalValue::ExternalWeakLinkage:  Out << "extern_weak ";    break;
1421  case GlobalValue::AvailableExternallyLinkage:
1422    Out << "available_externally ";
1423    break;
1424  case GlobalValue::GhostLinkage:
1425    llvm_unreachable("GhostLinkage not allowed in AsmWriter!");
1426  }
1427}
1428
1429
1430static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1431                            raw_ostream &Out) {
1432  switch (Vis) {
1433  default: llvm_unreachable("Invalid visibility style!");
1434  case GlobalValue::DefaultVisibility: break;
1435  case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
1436  case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1437  }
1438}
1439
1440void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1441  if (GV->hasName()) {
1442    PrintLLVMName(Out, GV);
1443    Out << " = ";
1444  }
1445
1446  if (!GV->hasInitializer() && GV->hasExternalLinkage())
1447    Out << "external ";
1448
1449  PrintLinkage(GV->getLinkage(), Out);
1450  PrintVisibility(GV->getVisibility(), Out);
1451
1452  if (GV->isThreadLocal()) Out << "thread_local ";
1453  if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1454    Out << "addrspace(" << AddressSpace << ") ";
1455  Out << (GV->isConstant() ? "constant " : "global ");
1456  TypePrinter.print(GV->getType()->getElementType(), Out);
1457
1458  if (GV->hasInitializer()) {
1459    Out << ' ';
1460    writeOperand(GV->getInitializer(), false);
1461  }
1462
1463  if (GV->hasSection())
1464    Out << ", section \"" << GV->getSection() << '"';
1465  if (GV->getAlignment())
1466    Out << ", align " << GV->getAlignment();
1467
1468  printInfoComment(*GV);
1469  Out << '\n';
1470}
1471
1472void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1473  // Don't crash when dumping partially built GA
1474  if (!GA->hasName())
1475    Out << "<<nameless>> = ";
1476  else {
1477    PrintLLVMName(Out, GA);
1478    Out << " = ";
1479  }
1480  PrintVisibility(GA->getVisibility(), Out);
1481
1482  Out << "alias ";
1483
1484  PrintLinkage(GA->getLinkage(), Out);
1485
1486  const Constant *Aliasee = GA->getAliasee();
1487
1488  if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1489    TypePrinter.print(GV->getType(), Out);
1490    Out << ' ';
1491    PrintLLVMName(Out, GV);
1492  } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1493    TypePrinter.print(F->getFunctionType(), Out);
1494    Out << "* ";
1495
1496    WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1497  } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1498    TypePrinter.print(GA->getType(), Out);
1499    Out << ' ';
1500    PrintLLVMName(Out, GA);
1501  } else {
1502    const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1503    // The only valid GEP is an all zero GEP.
1504    assert((CE->getOpcode() == Instruction::BitCast ||
1505            CE->getOpcode() == Instruction::GetElementPtr) &&
1506           "Unsupported aliasee");
1507    writeOperand(CE, false);
1508  }
1509
1510  printInfoComment(*GA);
1511  Out << '\n';
1512}
1513
1514void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1515  // Emit all numbered types.
1516  for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1517    Out << "\ttype ";
1518
1519    // Make sure we print out at least one level of the type structure, so
1520    // that we do not get %2 = type %2
1521    TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1522    Out << "\t\t; type %" << i << '\n';
1523  }
1524
1525  // Print the named types.
1526  for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1527       TI != TE; ++TI) {
1528    Out << '\t';
1529    PrintLLVMName(Out, TI->first, LocalPrefix);
1530    Out << " = type ";
1531
1532    // Make sure we print out at least one level of the type structure, so
1533    // that we do not get %FILE = type %FILE
1534    TypePrinter.printAtLeastOneLevel(TI->second, Out);
1535    Out << '\n';
1536  }
1537}
1538
1539/// printFunction - Print all aspects of a function.
1540///
1541void AssemblyWriter::printFunction(const Function *F) {
1542  // Print out the return type and name.
1543  Out << '\n';
1544
1545  if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1546
1547  if (F->isDeclaration())
1548    Out << "declare ";
1549  else
1550    Out << "define ";
1551
1552  PrintLinkage(F->getLinkage(), Out);
1553  PrintVisibility(F->getVisibility(), Out);
1554
1555  // Print the calling convention.
1556  switch (F->getCallingConv()) {
1557  case CallingConv::C: break;   // default
1558  case CallingConv::Fast:         Out << "fastcc "; break;
1559  case CallingConv::Cold:         Out << "coldcc "; break;
1560  case CallingConv::X86_StdCall:  Out << "x86_stdcallcc "; break;
1561  case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1562  case CallingConv::ARM_APCS:     Out << "arm_apcscc "; break;
1563  case CallingConv::ARM_AAPCS:    Out << "arm_aapcscc "; break;
1564  case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1565  default: Out << "cc" << F->getCallingConv() << " "; break;
1566  }
1567
1568  const FunctionType *FT = F->getFunctionType();
1569  const AttrListPtr &Attrs = F->getAttributes();
1570  Attributes RetAttrs = Attrs.getRetAttributes();
1571  if (RetAttrs != Attribute::None)
1572    Out <<  Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1573  TypePrinter.print(F->getReturnType(), Out);
1574  Out << ' ';
1575  WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1576  Out << '(';
1577  Machine.incorporateFunction(F);
1578
1579  // Loop over the arguments, printing them...
1580
1581  unsigned Idx = 1;
1582  if (!F->isDeclaration()) {
1583    // If this isn't a declaration, print the argument names as well.
1584    for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1585         I != E; ++I) {
1586      // Insert commas as we go... the first arg doesn't get a comma
1587      if (I != F->arg_begin()) Out << ", ";
1588      printArgument(I, Attrs.getParamAttributes(Idx));
1589      Idx++;
1590    }
1591  } else {
1592    // Otherwise, print the types from the function type.
1593    for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1594      // Insert commas as we go... the first arg doesn't get a comma
1595      if (i) Out << ", ";
1596
1597      // Output type...
1598      TypePrinter.print(FT->getParamType(i), Out);
1599
1600      Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1601      if (ArgAttrs != Attribute::None)
1602        Out << ' ' << Attribute::getAsString(ArgAttrs);
1603    }
1604  }
1605
1606  // Finish printing arguments...
1607  if (FT->isVarArg()) {
1608    if (FT->getNumParams()) Out << ", ";
1609    Out << "...";  // Output varargs portion of signature!
1610  }
1611  Out << ')';
1612  Attributes FnAttrs = Attrs.getFnAttributes();
1613  if (FnAttrs != Attribute::None)
1614    Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1615  if (F->hasSection())
1616    Out << " section \"" << F->getSection() << '"';
1617  if (F->getAlignment())
1618    Out << " align " << F->getAlignment();
1619  if (F->hasGC())
1620    Out << " gc \"" << F->getGC() << '"';
1621  if (F->isDeclaration()) {
1622    Out << "\n";
1623  } else {
1624    Out << " {";
1625
1626    // Output all of its basic blocks... for the function
1627    for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1628      printBasicBlock(I);
1629
1630    Out << "}\n";
1631  }
1632
1633  Machine.purgeFunction();
1634}
1635
1636/// printArgument - This member is called for every argument that is passed into
1637/// the function.  Simply print it out
1638///
1639void AssemblyWriter::printArgument(const Argument *Arg,
1640                                   Attributes Attrs) {
1641  // Output type...
1642  TypePrinter.print(Arg->getType(), Out);
1643
1644  // Output parameter attributes list
1645  if (Attrs != Attribute::None)
1646    Out << ' ' << Attribute::getAsString(Attrs);
1647
1648  // Output name, if available...
1649  if (Arg->hasName()) {
1650    Out << ' ';
1651    PrintLLVMName(Out, Arg);
1652  }
1653}
1654
1655/// printBasicBlock - This member is called for each basic block in a method.
1656///
1657void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1658  if (BB->hasName()) {              // Print out the label if it exists...
1659    Out << "\n";
1660    PrintLLVMName(Out, BB->getName(), LabelPrefix);
1661    Out << ':';
1662  } else if (!BB->use_empty()) {      // Don't print block # of no uses...
1663    Out << "\n; <label>:";
1664    int Slot = Machine.getLocalSlot(BB);
1665    if (Slot != -1)
1666      Out << Slot;
1667    else
1668      Out << "<badref>";
1669  }
1670
1671  if (BB->getParent() == 0)
1672    Out << "\t\t; Error: Block without parent!";
1673  else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
1674    // Output predecessors for the block...
1675    Out << "\t\t;";
1676    pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1677
1678    if (PI == PE) {
1679      Out << " No predecessors!";
1680    } else {
1681      Out << " preds = ";
1682      writeOperand(*PI, false);
1683      for (++PI; PI != PE; ++PI) {
1684        Out << ", ";
1685        writeOperand(*PI, false);
1686      }
1687    }
1688  }
1689
1690  Out << "\n";
1691
1692  if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1693
1694  // Output all of the instructions in the basic block...
1695  for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1696    printInstruction(*I);
1697    Out << '\n';
1698  }
1699
1700  if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1701}
1702
1703
1704/// printInfoComment - Print a little comment after the instruction indicating
1705/// which slot it occupies.
1706///
1707void AssemblyWriter::printInfoComment(const Value &V) {
1708  if (V.getType() != Type::VoidTy) {
1709    Out << "\t\t; <";
1710    TypePrinter.print(V.getType(), Out);
1711    Out << '>';
1712
1713    if (!V.hasName() && !isa<Instruction>(V)) {
1714      int SlotNum;
1715      if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1716        SlotNum = Machine.getGlobalSlot(GV);
1717      else
1718        SlotNum = Machine.getLocalSlot(&V);
1719      if (SlotNum == -1)
1720        Out << ":<badref>";
1721      else
1722        Out << ':' << SlotNum; // Print out the def slot taken.
1723    }
1724    Out << " [#uses=" << V.getNumUses() << ']';  // Output # uses
1725  }
1726}
1727
1728// This member is called for each Instruction in a function..
1729void AssemblyWriter::printInstruction(const Instruction &I) {
1730  if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1731
1732  Out << '\t';
1733
1734  // Print out name if it exists...
1735  if (I.hasName()) {
1736    PrintLLVMName(Out, &I);
1737    Out << " = ";
1738  } else if (I.getType() != Type::VoidTy) {
1739    // Print out the def slot taken.
1740    int SlotNum = Machine.getLocalSlot(&I);
1741    if (SlotNum == -1)
1742      Out << "<badref> = ";
1743    else
1744      Out << '%' << SlotNum << " = ";
1745  }
1746
1747  // If this is a volatile load or store, print out the volatile marker.
1748  if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
1749      (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1750      Out << "volatile ";
1751  } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1752    // If this is a call, check if it's a tail call.
1753    Out << "tail ";
1754  }
1755
1756  // Print out the opcode...
1757  Out << I.getOpcodeName();
1758
1759  // Print out optimization information.
1760  WriteOptimizationInfo(Out, &I);
1761
1762  // Print out the compare instruction predicates
1763  if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1764    Out << ' ' << getPredicateText(CI->getPredicate());
1765
1766  // Print out the type of the operands...
1767  const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1768
1769  // Special case conditional branches to swizzle the condition out to the front
1770  if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1771    BranchInst &BI(cast<BranchInst>(I));
1772    Out << ' ';
1773    writeOperand(BI.getCondition(), true);
1774    Out << ", ";
1775    writeOperand(BI.getSuccessor(0), true);
1776    Out << ", ";
1777    writeOperand(BI.getSuccessor(1), true);
1778
1779  } else if (isa<SwitchInst>(I)) {
1780    // Special case switch statement to get formatting nice and correct...
1781    Out << ' ';
1782    writeOperand(Operand        , true);
1783    Out << ", ";
1784    writeOperand(I.getOperand(1), true);
1785    Out << " [";
1786
1787    for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1788      Out << "\n\t\t";
1789      writeOperand(I.getOperand(op  ), true);
1790      Out << ", ";
1791      writeOperand(I.getOperand(op+1), true);
1792    }
1793    Out << "\n\t]";
1794  } else if (isa<PHINode>(I)) {
1795    Out << ' ';
1796    TypePrinter.print(I.getType(), Out);
1797    Out << ' ';
1798
1799    for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1800      if (op) Out << ", ";
1801      Out << "[ ";
1802      writeOperand(I.getOperand(op  ), false); Out << ", ";
1803      writeOperand(I.getOperand(op+1), false); Out << " ]";
1804    }
1805  } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1806    Out << ' ';
1807    writeOperand(I.getOperand(0), true);
1808    for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1809      Out << ", " << *i;
1810  } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1811    Out << ' ';
1812    writeOperand(I.getOperand(0), true); Out << ", ";
1813    writeOperand(I.getOperand(1), true);
1814    for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1815      Out << ", " << *i;
1816  } else if (isa<ReturnInst>(I) && !Operand) {
1817    Out << " void";
1818  } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1819    // Print the calling convention being used.
1820    switch (CI->getCallingConv()) {
1821    case CallingConv::C: break;   // default
1822    case CallingConv::Fast:  Out << " fastcc"; break;
1823    case CallingConv::Cold:  Out << " coldcc"; break;
1824    case CallingConv::X86_StdCall:  Out << " x86_stdcallcc"; break;
1825    case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1826    case CallingConv::ARM_APCS:     Out << " arm_apcscc "; break;
1827    case CallingConv::ARM_AAPCS:    Out << " arm_aapcscc "; break;
1828    case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1829    default: Out << " cc" << CI->getCallingConv(); break;
1830    }
1831
1832    const PointerType    *PTy = cast<PointerType>(Operand->getType());
1833    const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
1834    const Type         *RetTy = FTy->getReturnType();
1835    const AttrListPtr &PAL = CI->getAttributes();
1836
1837    if (PAL.getRetAttributes() != Attribute::None)
1838      Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1839
1840    // If possible, print out the short form of the call instruction.  We can
1841    // only do this if the first argument is a pointer to a nonvararg function,
1842    // and if the return type is not a pointer to a function.
1843    //
1844    Out << ' ';
1845    if (!FTy->isVarArg() &&
1846        (!isa<PointerType>(RetTy) ||
1847         !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1848      TypePrinter.print(RetTy, Out);
1849      Out << ' ';
1850      writeOperand(Operand, false);
1851    } else {
1852      writeOperand(Operand, true);
1853    }
1854    Out << '(';
1855    for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1856      if (op > 1)
1857        Out << ", ";
1858      writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1859    }
1860    Out << ')';
1861    if (PAL.getFnAttributes() != Attribute::None)
1862      Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1863  } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1864    const PointerType    *PTy = cast<PointerType>(Operand->getType());
1865    const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
1866    const Type         *RetTy = FTy->getReturnType();
1867    const AttrListPtr &PAL = II->getAttributes();
1868
1869    // Print the calling convention being used.
1870    switch (II->getCallingConv()) {
1871    case CallingConv::C: break;   // default
1872    case CallingConv::Fast:  Out << " fastcc"; break;
1873    case CallingConv::Cold:  Out << " coldcc"; break;
1874    case CallingConv::X86_StdCall:  Out << " x86_stdcallcc"; break;
1875    case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1876    case CallingConv::ARM_APCS:     Out << " arm_apcscc "; break;
1877    case CallingConv::ARM_AAPCS:    Out << " arm_aapcscc "; break;
1878    case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1879    default: Out << " cc" << II->getCallingConv(); break;
1880    }
1881
1882    if (PAL.getRetAttributes() != Attribute::None)
1883      Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1884
1885    // If possible, print out the short form of the invoke instruction. We can
1886    // only do this if the first argument is a pointer to a nonvararg function,
1887    // and if the return type is not a pointer to a function.
1888    //
1889    Out << ' ';
1890    if (!FTy->isVarArg() &&
1891        (!isa<PointerType>(RetTy) ||
1892         !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1893      TypePrinter.print(RetTy, Out);
1894      Out << ' ';
1895      writeOperand(Operand, false);
1896    } else {
1897      writeOperand(Operand, true);
1898    }
1899    Out << '(';
1900    for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1901      if (op > 3)
1902        Out << ", ";
1903      writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1904    }
1905
1906    Out << ')';
1907    if (PAL.getFnAttributes() != Attribute::None)
1908      Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1909
1910    Out << "\n\t\t\tto ";
1911    writeOperand(II->getNormalDest(), true);
1912    Out << " unwind ";
1913    writeOperand(II->getUnwindDest(), true);
1914
1915  } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1916    Out << ' ';
1917    TypePrinter.print(AI->getType()->getElementType(), Out);
1918    if (AI->isArrayAllocation()) {
1919      Out << ", ";
1920      writeOperand(AI->getArraySize(), true);
1921    }
1922    if (AI->getAlignment()) {
1923      Out << ", align " << AI->getAlignment();
1924    }
1925  } else if (isa<CastInst>(I)) {
1926    if (Operand) {
1927      Out << ' ';
1928      writeOperand(Operand, true);   // Work with broken code
1929    }
1930    Out << " to ";
1931    TypePrinter.print(I.getType(), Out);
1932  } else if (isa<VAArgInst>(I)) {
1933    if (Operand) {
1934      Out << ' ';
1935      writeOperand(Operand, true);   // Work with broken code
1936    }
1937    Out << ", ";
1938    TypePrinter.print(I.getType(), Out);
1939  } else if (Operand) {   // Print the normal way.
1940
1941    // PrintAllTypes - Instructions who have operands of all the same type
1942    // omit the type from all but the first operand.  If the instruction has
1943    // different type operands (for example br), then they are all printed.
1944    bool PrintAllTypes = false;
1945    const Type *TheType = Operand->getType();
1946
1947    // Select, Store and ShuffleVector always print all types.
1948    if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1949        || isa<ReturnInst>(I)) {
1950      PrintAllTypes = true;
1951    } else {
1952      for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1953        Operand = I.getOperand(i);
1954        // note that Operand shouldn't be null, but the test helps make dump()
1955        // more tolerant of malformed IR
1956        if (Operand && Operand->getType() != TheType) {
1957          PrintAllTypes = true;    // We have differing types!  Print them all!
1958          break;
1959        }
1960      }
1961    }
1962
1963    if (!PrintAllTypes) {
1964      Out << ' ';
1965      TypePrinter.print(TheType, Out);
1966    }
1967
1968    Out << ' ';
1969    for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1970      if (i) Out << ", ";
1971      writeOperand(I.getOperand(i), PrintAllTypes);
1972    }
1973  }
1974
1975  // Print post operand alignment for load/store
1976  if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1977    Out << ", align " << cast<LoadInst>(I).getAlignment();
1978  } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1979    Out << ", align " << cast<StoreInst>(I).getAlignment();
1980  }
1981
1982  printInfoComment(I);
1983}
1984
1985
1986//===----------------------------------------------------------------------===//
1987//                       External Interface declarations
1988//===----------------------------------------------------------------------===//
1989
1990void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1991  raw_os_ostream OS(o);
1992  print(OS, AAW);
1993}
1994void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1995  SlotTracker SlotTable(this);
1996  AssemblyWriter W(OS, SlotTable, this, AAW);
1997  W.write(this);
1998}
1999
2000void Type::print(std::ostream &o) const {
2001  raw_os_ostream OS(o);
2002  print(OS);
2003}
2004
2005void Type::print(raw_ostream &OS) const {
2006  if (this == 0) {
2007    OS << "<null Type>";
2008    return;
2009  }
2010  TypePrinting().print(this, OS);
2011}
2012
2013void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
2014  if (this == 0) {
2015    OS << "printing a <null> value\n";
2016    return;
2017  }
2018  if (const Instruction *I = dyn_cast<Instruction>(this)) {
2019    const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2020    SlotTracker SlotTable(F);
2021    AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
2022    W.write(I);
2023  } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2024    SlotTracker SlotTable(BB->getParent());
2025    AssemblyWriter W(OS, SlotTable,
2026                     BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
2027    W.write(BB);
2028  } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2029    SlotTracker SlotTable(GV->getParent());
2030    AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2031    W.write(GV);
2032  } else if (const MDString *MDS = dyn_cast<MDString>(this)) {
2033    TypePrinting TypePrinter;
2034    TypePrinter.print(MDS->getType(), OS);
2035    OS << ' ';
2036    OS << "!\"";
2037    PrintEscapedString(MDS->getString(), OS);
2038    OS << '"';
2039  } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2040    SlotTracker SlotTable(N);
2041    TypePrinting TypePrinter;
2042    SlotTable.initialize();
2043    WriteMDNodes(OS, TypePrinter, SlotTable);
2044  } else if (const NamedMDNode *N = dyn_cast<NamedMDNode>(this)) {
2045    SlotTracker SlotTable(N);
2046    TypePrinting TypePrinter;
2047    SlotTable.initialize();
2048    OS << "!" << N->getName() << " = !{";
2049    for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) {
2050      if (i) OS << ", ";
2051      MDNode *MD = dyn_cast_or_null<MDNode>(N->getElement(i));
2052      if (MD)
2053        OS << '!' << SlotTable.getMetadataSlot(MD);
2054      else
2055        OS << "null";
2056    }
2057    OS << "}\n";
2058    WriteMDNodes(OS, TypePrinter, SlotTable);
2059  } else if (const Constant *C = dyn_cast<Constant>(this)) {
2060    TypePrinting TypePrinter;
2061    TypePrinter.print(C->getType(), OS);
2062    OS << ' ';
2063    WriteConstantInt(OS, C, TypePrinter, 0);
2064  } else if (const Argument *A = dyn_cast<Argument>(this)) {
2065    WriteAsOperand(OS, this, true,
2066                   A->getParent() ? A->getParent()->getParent() : 0);
2067  } else if (isa<InlineAsm>(this)) {
2068    WriteAsOperand(OS, this, true, 0);
2069  } else {
2070    llvm_unreachable("Unknown value to print out!");
2071  }
2072}
2073
2074void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
2075  raw_os_ostream OS(O);
2076  print(OS, AAW);
2077}
2078
2079// Value::dump - allow easy printing of Values from the debugger.
2080void Value::dump() const { print(errs()); errs() << '\n'; }
2081
2082// Type::dump - allow easy printing of Types from the debugger.
2083// This one uses type names from the given context module
2084void Type::dump(const Module *Context) const {
2085  WriteTypeSymbolic(errs(), this, Context);
2086  errs() << '\n';
2087}
2088
2089// Type::dump - allow easy printing of Types from the debugger.
2090void Type::dump() const { dump(0); }
2091
2092// Module::dump() - Allow printing of Modules from the debugger.
2093void Module::dump() const { print(errs(), 0); }
2094