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