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