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