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