[pr19844] Add thread local mode to aliases.
[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   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.
117 static 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.
159 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
160   PrintLLVMName(OS, V->getName(),
161                 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
162 }
163
164
165 namespace llvm {
166
167 void 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.
194 void 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
269 void 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 ///
300 class SlotTracker {
301 public:
302   /// ValueMap - A mapping of Values to slot numbers.
303   typedef DenseMap<const Value*, unsigned> ValueMap;
304
305 private:
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;
328 public:
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
371 private:
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
395 SlotTracker *createSlotTracker(const Module *M) {
396   return new SlotTracker(M);
397 }
398
399 static 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.
437 SlotTracker::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.
444 SlotTracker::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
449 inline 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.
461 void 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.
497 void 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.
559 void 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.
568 int 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.
578 int 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.
589 int 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
599 int 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.
609 void 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.
626 void 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.
638 void 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
658 void 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
674 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
675                                    TypePrinting *TypePrinter,
676                                    SlotTracker *Machine,
677                                    const Module *Context);
678
679 static 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
712 static 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
730 static 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
763 static 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
1043 static 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.
1067 static 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
1167 void AssemblyWriter::init() {
1168   if (TheModule)
1169     TypePrinter.incorporateTypes(*TheModule);
1170 }
1171
1172
1173 AssemblyWriter::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
1180 AssemblyWriter::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
1187 AssemblyWriter::~AssemblyWriter() { }
1188
1189 void 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
1201 void 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
1222 void 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
1253 void 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
1270 void 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
1348 void 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
1382 static 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
1402 static 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
1411 static 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
1420 static 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
1440 void 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
1478 void 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   PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
1492
1493   Out << "alias ";
1494
1495   PrintLinkage(GA->getLinkage(), Out);
1496
1497   PointerType *Ty = GA->getType();
1498   const Constant *Aliasee = GA->getAliasee();
1499   if (!Aliasee || Ty != Aliasee->getType()) {
1500     if (unsigned AddressSpace = Ty->getAddressSpace())
1501       Out << "addrspace(" << AddressSpace << ") ";
1502     TypePrinter.print(Ty->getElementType(), Out);
1503     Out << ", ";
1504   }
1505
1506   if (!Aliasee) {
1507     Out << " <<NULL ALIASEE>>";
1508   } else {
1509     writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
1510   }
1511
1512   printInfoComment(*GA);
1513   Out << '\n';
1514 }
1515
1516 void AssemblyWriter::printTypeIdentities() {
1517   if (TypePrinter.NumberedTypes.empty() &&
1518       TypePrinter.NamedTypes.empty())
1519     return;
1520
1521   Out << '\n';
1522
1523   // We know all the numbers that each type is used and we know that it is a
1524   // dense assignment.  Convert the map to an index table.
1525   std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
1526   for (DenseMap<StructType*, unsigned>::iterator I =
1527        TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
1528        I != E; ++I) {
1529     assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
1530     NumberedTypes[I->second] = I->first;
1531   }
1532
1533   // Emit all numbered types.
1534   for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1535     Out << '%' << i << " = type ";
1536
1537     // Make sure we print out at least one level of the type structure, so
1538     // that we do not get %2 = type %2
1539     TypePrinter.printStructBody(NumberedTypes[i], Out);
1540     Out << '\n';
1541   }
1542
1543   for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
1544     PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
1545     Out << " = type ";
1546
1547     // Make sure we print out at least one level of the type structure, so
1548     // that we do not get %FILE = type %FILE
1549     TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
1550     Out << '\n';
1551   }
1552 }
1553
1554 /// printFunction - Print all aspects of a function.
1555 ///
1556 void AssemblyWriter::printFunction(const Function *F) {
1557   // Print out the return type and name.
1558   Out << '\n';
1559
1560   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1561
1562   if (F->isMaterializable())
1563     Out << "; Materializable\n";
1564
1565   const AttributeSet &Attrs = F->getAttributes();
1566   if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
1567     AttributeSet AS = Attrs.getFnAttributes();
1568     std::string AttrStr;
1569
1570     unsigned Idx = 0;
1571     for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
1572       if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
1573         break;
1574
1575     for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
1576          I != E; ++I) {
1577       Attribute Attr = *I;
1578       if (!Attr.isStringAttribute()) {
1579         if (!AttrStr.empty()) AttrStr += ' ';
1580         AttrStr += Attr.getAsString();
1581       }
1582     }
1583
1584     if (!AttrStr.empty())
1585       Out << "; Function Attrs: " << AttrStr << '\n';
1586   }
1587
1588   if (F->isDeclaration())
1589     Out << "declare ";
1590   else
1591     Out << "define ";
1592
1593   PrintLinkage(F->getLinkage(), Out);
1594   PrintVisibility(F->getVisibility(), Out);
1595   PrintDLLStorageClass(F->getDLLStorageClass(), Out);
1596
1597   // Print the calling convention.
1598   if (F->getCallingConv() != CallingConv::C) {
1599     PrintCallingConv(F->getCallingConv(), Out);
1600     Out << " ";
1601   }
1602
1603   FunctionType *FT = F->getFunctionType();
1604   if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
1605     Out <<  Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
1606   TypePrinter.print(F->getReturnType(), Out);
1607   Out << ' ';
1608   WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1609   Out << '(';
1610   Machine.incorporateFunction(F);
1611
1612   // Loop over the arguments, printing them...
1613
1614   unsigned Idx = 1;
1615   if (!F->isDeclaration()) {
1616     // If this isn't a declaration, print the argument names as well.
1617     for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1618          I != E; ++I) {
1619       // Insert commas as we go... the first arg doesn't get a comma
1620       if (I != F->arg_begin()) Out << ", ";
1621       printArgument(I, Attrs, Idx);
1622       Idx++;
1623     }
1624   } else {
1625     // Otherwise, print the types from the function type.
1626     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1627       // Insert commas as we go... the first arg doesn't get a comma
1628       if (i) Out << ", ";
1629
1630       // Output type...
1631       TypePrinter.print(FT->getParamType(i), Out);
1632
1633       if (Attrs.hasAttributes(i+1))
1634         Out << ' ' << Attrs.getAsString(i+1);
1635     }
1636   }
1637
1638   // Finish printing arguments...
1639   if (FT->isVarArg()) {
1640     if (FT->getNumParams()) Out << ", ";
1641     Out << "...";  // Output varargs portion of signature!
1642   }
1643   Out << ')';
1644   if (F->hasUnnamedAddr())
1645     Out << " unnamed_addr";
1646   if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
1647     Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
1648   if (F->hasSection()) {
1649     Out << " section \"";
1650     PrintEscapedString(F->getSection(), Out);
1651     Out << '"';
1652   }
1653   if (F->getAlignment())
1654     Out << " align " << F->getAlignment();
1655   if (F->hasGC())
1656     Out << " gc \"" << F->getGC() << '"';
1657   if (F->hasPrefixData()) {
1658     Out << " prefix ";
1659     writeOperand(F->getPrefixData(), true);
1660   }
1661   if (F->isDeclaration()) {
1662     Out << '\n';
1663   } else {
1664     Out << " {";
1665     // Output all of the function's basic blocks.
1666     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1667       printBasicBlock(I);
1668
1669     Out << "}\n";
1670   }
1671
1672   Machine.purgeFunction();
1673 }
1674
1675 /// printArgument - This member is called for every argument that is passed into
1676 /// the function.  Simply print it out
1677 ///
1678 void AssemblyWriter::printArgument(const Argument *Arg,
1679                                    AttributeSet Attrs, unsigned Idx) {
1680   // Output type...
1681   TypePrinter.print(Arg->getType(), Out);
1682
1683   // Output parameter attributes list
1684   if (Attrs.hasAttributes(Idx))
1685     Out << ' ' << Attrs.getAsString(Idx);
1686
1687   // Output name, if available...
1688   if (Arg->hasName()) {
1689     Out << ' ';
1690     PrintLLVMName(Out, Arg);
1691   }
1692 }
1693
1694 /// printBasicBlock - This member is called for each basic block in a method.
1695 ///
1696 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1697   if (BB->hasName()) {              // Print out the label if it exists...
1698     Out << "\n";
1699     PrintLLVMName(Out, BB->getName(), LabelPrefix);
1700     Out << ':';
1701   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
1702     Out << "\n; <label>:";
1703     int Slot = Machine.getLocalSlot(BB);
1704     if (Slot != -1)
1705       Out << Slot;
1706     else
1707       Out << "<badref>";
1708   }
1709
1710   if (!BB->getParent()) {
1711     Out.PadToColumn(50);
1712     Out << "; Error: Block without parent!";
1713   } else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
1714     // Output predecessors for the block.
1715     Out.PadToColumn(50);
1716     Out << ";";
1717     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1718
1719     if (PI == PE) {
1720       Out << " No predecessors!";
1721     } else {
1722       Out << " preds = ";
1723       writeOperand(*PI, false);
1724       for (++PI; PI != PE; ++PI) {
1725         Out << ", ";
1726         writeOperand(*PI, false);
1727       }
1728     }
1729   }
1730
1731   Out << "\n";
1732
1733   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1734
1735   // Output all of the instructions in the basic block...
1736   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1737     printInstructionLine(*I);
1738   }
1739
1740   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1741 }
1742
1743 /// printInstructionLine - Print an instruction and a newline character.
1744 void AssemblyWriter::printInstructionLine(const Instruction &I) {
1745   printInstruction(I);
1746   Out << '\n';
1747 }
1748
1749 /// printInfoComment - Print a little comment after the instruction indicating
1750 /// which slot it occupies.
1751 ///
1752 void AssemblyWriter::printInfoComment(const Value &V) {
1753   if (AnnotationWriter)
1754     AnnotationWriter->printInfoComment(V, Out);
1755 }
1756
1757 // This member is called for each Instruction in a function..
1758 void AssemblyWriter::printInstruction(const Instruction &I) {
1759   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1760
1761   // Print out indentation for an instruction.
1762   Out << "  ";
1763
1764   // Print out name if it exists...
1765   if (I.hasName()) {
1766     PrintLLVMName(Out, &I);
1767     Out << " = ";
1768   } else if (!I.getType()->isVoidTy()) {
1769     // Print out the def slot taken.
1770     int SlotNum = Machine.getLocalSlot(&I);
1771     if (SlotNum == -1)
1772       Out << "<badref> = ";
1773     else
1774       Out << '%' << SlotNum << " = ";
1775   }
1776
1777   if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1778     if (CI->isMustTailCall())
1779       Out << "musttail ";
1780     else if (CI->isTailCall())
1781       Out << "tail ";
1782   }
1783
1784   // Print out the opcode...
1785   Out << I.getOpcodeName();
1786
1787   // If this is an atomic load or store, print out the atomic marker.
1788   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isAtomic()) ||
1789       (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
1790     Out << " atomic";
1791
1792   // If this is a volatile operation, print out the volatile marker.
1793   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
1794       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
1795       (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
1796       (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
1797     Out << " volatile";
1798
1799   // Print out optimization information.
1800   WriteOptimizationInfo(Out, &I);
1801
1802   // Print out the compare instruction predicates
1803   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1804     Out << ' ' << getPredicateText(CI->getPredicate());
1805
1806   // Print out the atomicrmw operation
1807   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
1808     writeAtomicRMWOperation(Out, RMWI->getOperation());
1809
1810   // Print out the type of the operands...
1811   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
1812
1813   // Special case conditional branches to swizzle the condition out to the front
1814   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1815     const BranchInst &BI(cast<BranchInst>(I));
1816     Out << ' ';
1817     writeOperand(BI.getCondition(), true);
1818     Out << ", ";
1819     writeOperand(BI.getSuccessor(0), true);
1820     Out << ", ";
1821     writeOperand(BI.getSuccessor(1), true);
1822
1823   } else if (isa<SwitchInst>(I)) {
1824     const SwitchInst& SI(cast<SwitchInst>(I));
1825     // Special case switch instruction to get formatting nice and correct.
1826     Out << ' ';
1827     writeOperand(SI.getCondition(), true);
1828     Out << ", ";
1829     writeOperand(SI.getDefaultDest(), true);
1830     Out << " [";
1831     for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1832          i != e; ++i) {
1833       Out << "\n    ";
1834       writeOperand(i.getCaseValue(), true);
1835       Out << ", ";
1836       writeOperand(i.getCaseSuccessor(), true);
1837     }
1838     Out << "\n  ]";
1839   } else if (isa<IndirectBrInst>(I)) {
1840     // Special case indirectbr instruction to get formatting nice and correct.
1841     Out << ' ';
1842     writeOperand(Operand, true);
1843     Out << ", [";
1844
1845     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1846       if (i != 1)
1847         Out << ", ";
1848       writeOperand(I.getOperand(i), true);
1849     }
1850     Out << ']';
1851   } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
1852     Out << ' ';
1853     TypePrinter.print(I.getType(), Out);
1854     Out << ' ';
1855
1856     for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
1857       if (op) Out << ", ";
1858       Out << "[ ";
1859       writeOperand(PN->getIncomingValue(op), false); Out << ", ";
1860       writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
1861     }
1862   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1863     Out << ' ';
1864     writeOperand(I.getOperand(0), true);
1865     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1866       Out << ", " << *i;
1867   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1868     Out << ' ';
1869     writeOperand(I.getOperand(0), true); Out << ", ";
1870     writeOperand(I.getOperand(1), true);
1871     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1872       Out << ", " << *i;
1873   } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
1874     Out << ' ';
1875     TypePrinter.print(I.getType(), Out);
1876     Out << " personality ";
1877     writeOperand(I.getOperand(0), true); Out << '\n';
1878
1879     if (LPI->isCleanup())
1880       Out << "          cleanup";
1881
1882     for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
1883       if (i != 0 || LPI->isCleanup()) Out << "\n";
1884       if (LPI->isCatch(i))
1885         Out << "          catch ";
1886       else
1887         Out << "          filter ";
1888
1889       writeOperand(LPI->getClause(i), true);
1890     }
1891   } else if (isa<ReturnInst>(I) && !Operand) {
1892     Out << " void";
1893   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1894     // Print the calling convention being used.
1895     if (CI->getCallingConv() != CallingConv::C) {
1896       Out << " ";
1897       PrintCallingConv(CI->getCallingConv(), Out);
1898     }
1899
1900     Operand = CI->getCalledValue();
1901     PointerType *PTy = cast<PointerType>(Operand->getType());
1902     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1903     Type *RetTy = FTy->getReturnType();
1904     const AttributeSet &PAL = CI->getAttributes();
1905
1906     if (PAL.hasAttributes(AttributeSet::ReturnIndex))
1907       Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
1908
1909     // If possible, print out the short form of the call instruction.  We can
1910     // only do this if the first argument is a pointer to a nonvararg function,
1911     // and if the return type is not a pointer to a function.
1912     //
1913     Out << ' ';
1914     if (!FTy->isVarArg() &&
1915         (!RetTy->isPointerTy() ||
1916          !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1917       TypePrinter.print(RetTy, Out);
1918       Out << ' ';
1919       writeOperand(Operand, false);
1920     } else {
1921       writeOperand(Operand, true);
1922     }
1923     Out << '(';
1924     for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1925       if (op > 0)
1926         Out << ", ";
1927       writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
1928     }
1929     Out << ')';
1930     if (PAL.hasAttributes(AttributeSet::FunctionIndex))
1931       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
1932   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1933     Operand = II->getCalledValue();
1934     PointerType *PTy = cast<PointerType>(Operand->getType());
1935     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1936     Type *RetTy = FTy->getReturnType();
1937     const AttributeSet &PAL = II->getAttributes();
1938
1939     // Print the calling convention being used.
1940     if (II->getCallingConv() != CallingConv::C) {
1941       Out << " ";
1942       PrintCallingConv(II->getCallingConv(), Out);
1943     }
1944
1945     if (PAL.hasAttributes(AttributeSet::ReturnIndex))
1946       Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
1947
1948     // If possible, print out the short form of the invoke instruction. We can
1949     // only do this if the first argument is a pointer to a nonvararg function,
1950     // and if the return type is not a pointer to a function.
1951     //
1952     Out << ' ';
1953     if (!FTy->isVarArg() &&
1954         (!RetTy->isPointerTy() ||
1955          !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1956       TypePrinter.print(RetTy, Out);
1957       Out << ' ';
1958       writeOperand(Operand, false);
1959     } else {
1960       writeOperand(Operand, true);
1961     }
1962     Out << '(';
1963     for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
1964       if (op)
1965         Out << ", ";
1966       writeParamOperand(II->getArgOperand(op), PAL, op + 1);
1967     }
1968
1969     Out << ')';
1970     if (PAL.hasAttributes(AttributeSet::FunctionIndex))
1971       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
1972
1973     Out << "\n          to ";
1974     writeOperand(II->getNormalDest(), true);
1975     Out << " unwind ";
1976     writeOperand(II->getUnwindDest(), true);
1977
1978   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1979     Out << ' ';
1980     if (AI->isUsedWithInAlloca())
1981       Out << "inalloca ";
1982     TypePrinter.print(AI->getAllocatedType(), Out);
1983     if (!AI->getArraySize() || AI->isArrayAllocation()) {
1984       Out << ", ";
1985       writeOperand(AI->getArraySize(), true);
1986     }
1987     if (AI->getAlignment()) {
1988       Out << ", align " << AI->getAlignment();
1989     }
1990   } else if (isa<CastInst>(I)) {
1991     if (Operand) {
1992       Out << ' ';
1993       writeOperand(Operand, true);   // Work with broken code
1994     }
1995     Out << " to ";
1996     TypePrinter.print(I.getType(), Out);
1997   } else if (isa<VAArgInst>(I)) {
1998     if (Operand) {
1999       Out << ' ';
2000       writeOperand(Operand, true);   // Work with broken code
2001     }
2002     Out << ", ";
2003     TypePrinter.print(I.getType(), Out);
2004   } else if (Operand) {   // Print the normal way.
2005
2006     // PrintAllTypes - Instructions who have operands of all the same type
2007     // omit the type from all but the first operand.  If the instruction has
2008     // different type operands (for example br), then they are all printed.
2009     bool PrintAllTypes = false;
2010     Type *TheType = Operand->getType();
2011
2012     // Select, Store and ShuffleVector always print all types.
2013     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
2014         || isa<ReturnInst>(I)) {
2015       PrintAllTypes = true;
2016     } else {
2017       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
2018         Operand = I.getOperand(i);
2019         // note that Operand shouldn't be null, but the test helps make dump()
2020         // more tolerant of malformed IR
2021         if (Operand && Operand->getType() != TheType) {
2022           PrintAllTypes = true;    // We have differing types!  Print them all!
2023           break;
2024         }
2025       }
2026     }
2027
2028     if (!PrintAllTypes) {
2029       Out << ' ';
2030       TypePrinter.print(TheType, Out);
2031     }
2032
2033     Out << ' ';
2034     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
2035       if (i) Out << ", ";
2036       writeOperand(I.getOperand(i), PrintAllTypes);
2037     }
2038   }
2039
2040   // Print atomic ordering/alignment for memory operations
2041   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
2042     if (LI->isAtomic())
2043       writeAtomic(LI->getOrdering(), LI->getSynchScope());
2044     if (LI->getAlignment())
2045       Out << ", align " << LI->getAlignment();
2046   } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
2047     if (SI->isAtomic())
2048       writeAtomic(SI->getOrdering(), SI->getSynchScope());
2049     if (SI->getAlignment())
2050       Out << ", align " << SI->getAlignment();
2051   } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
2052     writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
2053                        CXI->getSynchScope());
2054   } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
2055     writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
2056   } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
2057     writeAtomic(FI->getOrdering(), FI->getSynchScope());
2058   }
2059
2060   // Print Metadata info.
2061   SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
2062   I.getAllMetadata(InstMD);
2063   if (!InstMD.empty()) {
2064     SmallVector<StringRef, 8> MDNames;
2065     I.getType()->getContext().getMDKindNames(MDNames);
2066     for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
2067       unsigned Kind = InstMD[i].first;
2068        if (Kind < MDNames.size()) {
2069          Out << ", !" << MDNames[Kind];
2070        } else {
2071          Out << ", !<unknown kind #" << Kind << ">";
2072        }
2073       Out << ' ';
2074       WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
2075                              TheModule);
2076     }
2077   }
2078   printInfoComment(I);
2079 }
2080
2081 static void WriteMDNodeComment(const MDNode *Node,
2082                                formatted_raw_ostream &Out) {
2083   if (Node->getNumOperands() < 1)
2084     return;
2085
2086   Value *Op = Node->getOperand(0);
2087   if (!Op || !isa<ConstantInt>(Op) || cast<ConstantInt>(Op)->getBitWidth() < 32)
2088     return;
2089
2090   DIDescriptor Desc(Node);
2091   if (!Desc.Verify())
2092     return;
2093
2094   unsigned Tag = Desc.getTag();
2095   Out.PadToColumn(50);
2096   if (dwarf::TagString(Tag)) {
2097     Out << "; ";
2098     Desc.print(Out);
2099   } else if (Tag == dwarf::DW_TAG_user_base) {
2100     Out << "; [ DW_TAG_user_base ]";
2101   }
2102 }
2103
2104 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
2105   Out << '!' << Slot << " = metadata ";
2106   printMDNodeBody(Node);
2107 }
2108
2109 void AssemblyWriter::writeAllMDNodes() {
2110   SmallVector<const MDNode *, 16> Nodes;
2111   Nodes.resize(Machine.mdn_size());
2112   for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2113        I != E; ++I)
2114     Nodes[I->second] = cast<MDNode>(I->first);
2115
2116   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2117     writeMDNode(i, Nodes[i]);
2118   }
2119 }
2120
2121 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2122   WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
2123   WriteMDNodeComment(Node, Out);
2124   Out << "\n";
2125 }
2126
2127 void AssemblyWriter::writeAllAttributeGroups() {
2128   std::vector<std::pair<AttributeSet, unsigned> > asVec;
2129   asVec.resize(Machine.as_size());
2130
2131   for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
2132        I != E; ++I)
2133     asVec[I->second] = *I;
2134
2135   for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
2136          I = asVec.begin(), E = asVec.end(); I != E; ++I)
2137     Out << "attributes #" << I->second << " = { "
2138         << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
2139 }
2140
2141 } // namespace llvm
2142
2143 //===----------------------------------------------------------------------===//
2144 //                       External Interface declarations
2145 //===----------------------------------------------------------------------===//
2146
2147 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2148   SlotTracker SlotTable(this);
2149   formatted_raw_ostream OS(ROS);
2150   AssemblyWriter W(OS, SlotTable, this, AAW);
2151   W.printModule(this);
2152 }
2153
2154 void NamedMDNode::print(raw_ostream &ROS) const {
2155   SlotTracker SlotTable(getParent());
2156   formatted_raw_ostream OS(ROS);
2157   AssemblyWriter W(OS, SlotTable, getParent(), nullptr);
2158   W.printNamedMDNode(this);
2159 }
2160
2161 void Type::print(raw_ostream &OS) const {
2162   if (!this) {
2163     OS << "<null Type>";
2164     return;
2165   }
2166   TypePrinting TP;
2167   TP.print(const_cast<Type*>(this), OS);
2168
2169   // If the type is a named struct type, print the body as well.
2170   if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
2171     if (!STy->isLiteral()) {
2172       OS << " = type ";
2173       TP.printStructBody(STy, OS);
2174     }
2175 }
2176
2177 void Value::print(raw_ostream &ROS) const {
2178   if (!this) {
2179     ROS << "printing a <null> value\n";
2180     return;
2181   }
2182   formatted_raw_ostream OS(ROS);
2183   if (const Instruction *I = dyn_cast<Instruction>(this)) {
2184     const Function *F = I->getParent() ? I->getParent()->getParent() : nullptr;
2185     SlotTracker SlotTable(F);
2186     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr);
2187     W.printInstruction(*I);
2188   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2189     SlotTracker SlotTable(BB->getParent());
2190     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr);
2191     W.printBasicBlock(BB);
2192   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2193     SlotTracker SlotTable(GV->getParent());
2194     AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr);
2195     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2196       W.printGlobal(V);
2197     else if (const Function *F = dyn_cast<Function>(GV))
2198       W.printFunction(F);
2199     else
2200       W.printAlias(cast<GlobalAlias>(GV));
2201   } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2202     const Function *F = N->getFunction();
2203     SlotTracker SlotTable(F);
2204     AssemblyWriter W(OS, SlotTable, F ? F->getParent() : nullptr, nullptr);
2205     W.printMDNodeBody(N);
2206   } else if (const Constant *C = dyn_cast<Constant>(this)) {
2207     TypePrinting TypePrinter;
2208     TypePrinter.print(C->getType(), OS);
2209     OS << ' ';
2210     WriteConstantInternal(OS, C, TypePrinter, nullptr, nullptr);
2211   } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2212              isa<Argument>(this)) {
2213     this->printAsOperand(OS);
2214   } else {
2215     llvm_unreachable("Unknown value to print out!");
2216   }
2217 }
2218
2219 void Value::printAsOperand(raw_ostream &O, bool PrintType, const Module *M) const {
2220   // Fast path: Don't construct and populate a TypePrinting object if we
2221   // won't be needing any types printed.
2222   if (!PrintType &&
2223       ((!isa<Constant>(this) && !isa<MDNode>(this)) ||
2224        hasName() || isa<GlobalValue>(this))) {
2225     WriteAsOperandInternal(O, this, nullptr, nullptr, M);
2226     return;
2227   }
2228
2229   if (!M)
2230     M = getModuleFromVal(this);
2231
2232   TypePrinting TypePrinter;
2233   if (M)
2234     TypePrinter.incorporateTypes(*M);
2235   if (PrintType) {
2236     TypePrinter.print(getType(), O);
2237     O << ' ';
2238   }
2239
2240   WriteAsOperandInternal(O, this, &TypePrinter, nullptr, M);
2241 }
2242
2243 // Value::dump - allow easy printing of Values from the debugger.
2244 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2245
2246 // Type::dump - allow easy printing of Types from the debugger.
2247 void Type::dump() const { print(dbgs()); }
2248
2249 // Module::dump() - Allow printing of Modules from the debugger.
2250 void Module::dump() const { print(dbgs(), nullptr); }
2251
2252 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
2253 void NamedMDNode::dump() const { print(dbgs()); }