LLVM API Documentation

AsmWriter.cpp
Go to the documentation of this file.
00001 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This library implements the functionality defined in llvm/IR/Writer.h
00011 //
00012 // Note that these routines must be extremely tolerant of various errors in the
00013 // LLVM code, because it can be used for debugging transformations.
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #include "AsmWriter.h"
00018 #include "llvm/ADT/DenseMap.h"
00019 #include "llvm/ADT/STLExtras.h"
00020 #include "llvm/ADT/SmallString.h"
00021 #include "llvm/ADT/StringExtras.h"
00022 #include "llvm/IR/AssemblyAnnotationWriter.h"
00023 #include "llvm/IR/CFG.h"
00024 #include "llvm/IR/CallingConv.h"
00025 #include "llvm/IR/Constants.h"
00026 #include "llvm/IR/DebugInfo.h"
00027 #include "llvm/IR/DerivedTypes.h"
00028 #include "llvm/IR/IRPrintingPasses.h"
00029 #include "llvm/IR/InlineAsm.h"
00030 #include "llvm/IR/IntrinsicInst.h"
00031 #include "llvm/IR/LLVMContext.h"
00032 #include "llvm/IR/Module.h"
00033 #include "llvm/IR/Operator.h"
00034 #include "llvm/IR/TypeFinder.h"
00035 #include "llvm/IR/ValueSymbolTable.h"
00036 #include "llvm/Support/Debug.h"
00037 #include "llvm/Support/Dwarf.h"
00038 #include "llvm/Support/ErrorHandling.h"
00039 #include "llvm/Support/FormattedStream.h"
00040 #include "llvm/Support/MathExtras.h"
00041 #include <algorithm>
00042 #include <cctype>
00043 using namespace llvm;
00044 
00045 // Make virtual table appear in this compilation unit.
00046 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
00047 
00048 //===----------------------------------------------------------------------===//
00049 // Helper Functions
00050 //===----------------------------------------------------------------------===//
00051 
00052 static const Module *getModuleFromVal(const Value *V) {
00053   if (const Argument *MA = dyn_cast<Argument>(V))
00054     return MA->getParent() ? MA->getParent()->getParent() : nullptr;
00055 
00056   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
00057     return BB->getParent() ? BB->getParent()->getParent() : nullptr;
00058 
00059   if (const Instruction *I = dyn_cast<Instruction>(V)) {
00060     const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
00061     return M ? M->getParent() : nullptr;
00062   }
00063 
00064   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
00065     return GV->getParent();
00066   return nullptr;
00067 }
00068 
00069 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
00070   switch (cc) {
00071   default:                         Out << "cc" << cc; break;
00072   case CallingConv::Fast:          Out << "fastcc"; break;
00073   case CallingConv::Cold:          Out << "coldcc"; break;
00074   case CallingConv::WebKit_JS:     Out << "webkit_jscc"; break;
00075   case CallingConv::AnyReg:        Out << "anyregcc"; break;
00076   case CallingConv::PreserveMost:  Out << "preserve_mostcc"; break;
00077   case CallingConv::PreserveAll:   Out << "preserve_allcc"; break;
00078   case CallingConv::X86_StdCall:   Out << "x86_stdcallcc"; break;
00079   case CallingConv::X86_FastCall:  Out << "x86_fastcallcc"; break;
00080   case CallingConv::X86_ThisCall:  Out << "x86_thiscallcc"; break;
00081   case CallingConv::Intel_OCL_BI:  Out << "intel_ocl_bicc"; break;
00082   case CallingConv::ARM_APCS:      Out << "arm_apcscc"; break;
00083   case CallingConv::ARM_AAPCS:     Out << "arm_aapcscc"; break;
00084   case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
00085   case CallingConv::MSP430_INTR:   Out << "msp430_intrcc"; break;
00086   case CallingConv::PTX_Kernel:    Out << "ptx_kernel"; break;
00087   case CallingConv::PTX_Device:    Out << "ptx_device"; break;
00088   case CallingConv::X86_64_SysV:   Out << "x86_64_sysvcc"; break;
00089   case CallingConv::X86_64_Win64:  Out << "x86_64_win64cc"; break;
00090   case CallingConv::SPIR_FUNC:     Out << "spir_func"; break;
00091   case CallingConv::SPIR_KERNEL:   Out << "spir_kernel"; break;
00092   }
00093 }
00094 
00095 // PrintEscapedString - Print each character of the specified string, escaping
00096 // it if it is not printable or if it is an escape char.
00097 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
00098   for (unsigned i = 0, e = Name.size(); i != e; ++i) {
00099     unsigned char C = Name[i];
00100     if (isprint(C) && C != '\\' && C != '"')
00101       Out << C;
00102     else
00103       Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
00104   }
00105 }
00106 
00107 enum PrefixType {
00108   GlobalPrefix,
00109   ComdatPrefix,
00110   LabelPrefix,
00111   LocalPrefix,
00112   NoPrefix
00113 };
00114 
00115 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
00116 /// prefixed with % (if the string only contains simple characters) or is
00117 /// surrounded with ""'s (if it has special chars in it).  Print it out.
00118 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
00119   assert(!Name.empty() && "Cannot get empty name!");
00120   switch (Prefix) {
00121   case NoPrefix: break;
00122   case GlobalPrefix: OS << '@'; break;
00123   case ComdatPrefix: OS << '$'; break;
00124   case LabelPrefix:  break;
00125   case LocalPrefix:  OS << '%'; break;
00126   }
00127 
00128   // Scan the name to see if it needs quotes first.
00129   bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
00130   if (!NeedsQuotes) {
00131     for (unsigned i = 0, e = Name.size(); i != e; ++i) {
00132       // By making this unsigned, the value passed in to isalnum will always be
00133       // in the range 0-255.  This is important when building with MSVC because
00134       // its implementation will assert.  This situation can arise when dealing
00135       // with UTF-8 multibyte characters.
00136       unsigned char C = Name[i];
00137       if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
00138           C != '_') {
00139         NeedsQuotes = true;
00140         break;
00141       }
00142     }
00143   }
00144 
00145   // If we didn't need any quotes, just write out the name in one blast.
00146   if (!NeedsQuotes) {
00147     OS << Name;
00148     return;
00149   }
00150 
00151   // Okay, we need quotes.  Output the quotes and escape any scary characters as
00152   // needed.
00153   OS << '"';
00154   PrintEscapedString(Name, OS);
00155   OS << '"';
00156 }
00157 
00158 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
00159 /// prefixed with % (if the string only contains simple characters) or is
00160 /// surrounded with ""'s (if it has special chars in it).  Print it out.
00161 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
00162   PrintLLVMName(OS, V->getName(),
00163                 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
00164 }
00165 
00166 
00167 namespace llvm {
00168 
00169 void TypePrinting::incorporateTypes(const Module &M) {
00170   NamedTypes.run(M, false);
00171 
00172   // The list of struct types we got back includes all the struct types, split
00173   // the unnamed ones out to a numbering and remove the anonymous structs.
00174   unsigned NextNumber = 0;
00175 
00176   std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
00177   for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
00178     StructType *STy = *I;
00179 
00180     // Ignore anonymous types.
00181     if (STy->isLiteral())
00182       continue;
00183 
00184     if (STy->getName().empty())
00185       NumberedTypes[STy] = NextNumber++;
00186     else
00187       *NextToUse++ = STy;
00188   }
00189 
00190   NamedTypes.erase(NextToUse, NamedTypes.end());
00191 }
00192 
00193 
00194 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
00195 /// use of type names or up references to shorten the type name where possible.
00196 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
00197   switch (Ty->getTypeID()) {
00198   case Type::VoidTyID:      OS << "void"; return;
00199   case Type::HalfTyID:      OS << "half"; return;
00200   case Type::FloatTyID:     OS << "float"; return;
00201   case Type::DoubleTyID:    OS << "double"; return;
00202   case Type::X86_FP80TyID:  OS << "x86_fp80"; return;
00203   case Type::FP128TyID:     OS << "fp128"; return;
00204   case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
00205   case Type::LabelTyID:     OS << "label"; return;
00206   case Type::MetadataTyID:  OS << "metadata"; return;
00207   case Type::X86_MMXTyID:   OS << "x86_mmx"; return;
00208   case Type::IntegerTyID:
00209     OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
00210     return;
00211 
00212   case Type::FunctionTyID: {
00213     FunctionType *FTy = cast<FunctionType>(Ty);
00214     print(FTy->getReturnType(), OS);
00215     OS << " (";
00216     for (FunctionType::param_iterator I = FTy->param_begin(),
00217          E = FTy->param_end(); I != E; ++I) {
00218       if (I != FTy->param_begin())
00219         OS << ", ";
00220       print(*I, OS);
00221     }
00222     if (FTy->isVarArg()) {
00223       if (FTy->getNumParams()) OS << ", ";
00224       OS << "...";
00225     }
00226     OS << ')';
00227     return;
00228   }
00229   case Type::StructTyID: {
00230     StructType *STy = cast<StructType>(Ty);
00231 
00232     if (STy->isLiteral())
00233       return printStructBody(STy, OS);
00234 
00235     if (!STy->getName().empty())
00236       return PrintLLVMName(OS, STy->getName(), LocalPrefix);
00237 
00238     DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
00239     if (I != NumberedTypes.end())
00240       OS << '%' << I->second;
00241     else  // Not enumerated, print the hex address.
00242       OS << "%\"type " << STy << '\"';
00243     return;
00244   }
00245   case Type::PointerTyID: {
00246     PointerType *PTy = cast<PointerType>(Ty);
00247     print(PTy->getElementType(), OS);
00248     if (unsigned AddressSpace = PTy->getAddressSpace())
00249       OS << " addrspace(" << AddressSpace << ')';
00250     OS << '*';
00251     return;
00252   }
00253   case Type::ArrayTyID: {
00254     ArrayType *ATy = cast<ArrayType>(Ty);
00255     OS << '[' << ATy->getNumElements() << " x ";
00256     print(ATy->getElementType(), OS);
00257     OS << ']';
00258     return;
00259   }
00260   case Type::VectorTyID: {
00261     VectorType *PTy = cast<VectorType>(Ty);
00262     OS << "<" << PTy->getNumElements() << " x ";
00263     print(PTy->getElementType(), OS);
00264     OS << '>';
00265     return;
00266   }
00267   }
00268   llvm_unreachable("Invalid TypeID");
00269 }
00270 
00271 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
00272   if (STy->isOpaque()) {
00273     OS << "opaque";
00274     return;
00275   }
00276 
00277   if (STy->isPacked())
00278     OS << '<';
00279 
00280   if (STy->getNumElements() == 0) {
00281     OS << "{}";
00282   } else {
00283     StructType::element_iterator I = STy->element_begin();
00284     OS << "{ ";
00285     print(*I++, OS);
00286     for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
00287       OS << ", ";
00288       print(*I, OS);
00289     }
00290 
00291     OS << " }";
00292   }
00293   if (STy->isPacked())
00294     OS << '>';
00295 }
00296 
00297 //===----------------------------------------------------------------------===//
00298 // SlotTracker Class: Enumerate slot numbers for unnamed values
00299 //===----------------------------------------------------------------------===//
00300 /// This class provides computation of slot numbers for LLVM Assembly writing.
00301 ///
00302 class SlotTracker {
00303 public:
00304   /// ValueMap - A mapping of Values to slot numbers.
00305   typedef DenseMap<const Value*, unsigned> ValueMap;
00306 
00307 private:
00308   /// TheModule - The module for which we are holding slot numbers.
00309   const Module* TheModule;
00310 
00311   /// TheFunction - The function for which we are holding slot numbers.
00312   const Function* TheFunction;
00313   bool FunctionProcessed;
00314 
00315   /// mMap - The slot map for the module level data.
00316   ValueMap mMap;
00317   unsigned mNext;
00318 
00319   /// fMap - The slot map for the function level data.
00320   ValueMap fMap;
00321   unsigned fNext;
00322 
00323   /// mdnMap - Map for MDNodes.
00324   DenseMap<const MDNode*, unsigned> mdnMap;
00325   unsigned mdnNext;
00326 
00327   /// asMap - The slot map for attribute sets.
00328   DenseMap<AttributeSet, unsigned> asMap;
00329   unsigned asNext;
00330 public:
00331   /// Construct from a module
00332   explicit SlotTracker(const Module *M);
00333   /// Construct from a function, starting out in incorp state.
00334   explicit SlotTracker(const Function *F);
00335 
00336   /// Return the slot number of the specified value in it's type
00337   /// plane.  If something is not in the SlotTracker, return -1.
00338   int getLocalSlot(const Value *V);
00339   int getGlobalSlot(const GlobalValue *V);
00340   int getMetadataSlot(const MDNode *N);
00341   int getAttributeGroupSlot(AttributeSet AS);
00342 
00343   /// If you'd like to deal with a function instead of just a module, use
00344   /// this method to get its data into the SlotTracker.
00345   void incorporateFunction(const Function *F) {
00346     TheFunction = F;
00347     FunctionProcessed = false;
00348   }
00349 
00350   /// After calling incorporateFunction, use this method to remove the
00351   /// most recently incorporated function from the SlotTracker. This
00352   /// will reset the state of the machine back to just the module contents.
00353   void purgeFunction();
00354 
00355   /// MDNode map iterators.
00356   typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
00357   mdn_iterator mdn_begin() { return mdnMap.begin(); }
00358   mdn_iterator mdn_end() { return mdnMap.end(); }
00359   unsigned mdn_size() const { return mdnMap.size(); }
00360   bool mdn_empty() const { return mdnMap.empty(); }
00361 
00362   /// AttributeSet map iterators.
00363   typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
00364   as_iterator as_begin()   { return asMap.begin(); }
00365   as_iterator as_end()     { return asMap.end(); }
00366   unsigned as_size() const { return asMap.size(); }
00367   bool as_empty() const    { return asMap.empty(); }
00368 
00369   /// This function does the actual initialization.
00370   inline void initialize();
00371 
00372   // Implementation Details
00373 private:
00374   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
00375   void CreateModuleSlot(const GlobalValue *V);
00376 
00377   /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
00378   void CreateMetadataSlot(const MDNode *N);
00379 
00380   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
00381   void CreateFunctionSlot(const Value *V);
00382 
00383   /// \brief Insert the specified AttributeSet into the slot table.
00384   void CreateAttributeSetSlot(AttributeSet AS);
00385 
00386   /// Add all of the module level global variables (and their initializers)
00387   /// and function declarations, but not the contents of those functions.
00388   void processModule();
00389 
00390   /// Add all of the functions arguments, basic blocks, and instructions.
00391   void processFunction();
00392 
00393   SlotTracker(const SlotTracker &) LLVM_DELETED_FUNCTION;
00394   void operator=(const SlotTracker &) LLVM_DELETED_FUNCTION;
00395 };
00396 
00397 SlotTracker *createSlotTracker(const Module *M) {
00398   return new SlotTracker(M);
00399 }
00400 
00401 static SlotTracker *createSlotTracker(const Value *V) {
00402   if (const Argument *FA = dyn_cast<Argument>(V))
00403     return new SlotTracker(FA->getParent());
00404 
00405   if (const Instruction *I = dyn_cast<Instruction>(V))
00406     if (I->getParent())
00407       return new SlotTracker(I->getParent()->getParent());
00408 
00409   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
00410     return new SlotTracker(BB->getParent());
00411 
00412   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
00413     return new SlotTracker(GV->getParent());
00414 
00415   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
00416     return new SlotTracker(GA->getParent());
00417 
00418   if (const Function *Func = dyn_cast<Function>(V))
00419     return new SlotTracker(Func);
00420 
00421   if (const MDNode *MD = dyn_cast<MDNode>(V)) {
00422     if (!MD->isFunctionLocal())
00423       return new SlotTracker(MD->getFunction());
00424 
00425     return new SlotTracker((Function *)nullptr);
00426   }
00427 
00428   return nullptr;
00429 }
00430 
00431 #if 0
00432 #define ST_DEBUG(X) dbgs() << X
00433 #else
00434 #define ST_DEBUG(X)
00435 #endif
00436 
00437 // Module level constructor. Causes the contents of the Module (sans functions)
00438 // to be added to the slot table.
00439 SlotTracker::SlotTracker(const Module *M)
00440   : TheModule(M), TheFunction(nullptr), FunctionProcessed(false),
00441     mNext(0), fNext(0),  mdnNext(0), asNext(0) {
00442 }
00443 
00444 // Function level constructor. Causes the contents of the Module and the one
00445 // function provided to be added to the slot table.
00446 SlotTracker::SlotTracker(const Function *F)
00447   : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
00448     FunctionProcessed(false), mNext(0), fNext(0), mdnNext(0), asNext(0) {
00449 }
00450 
00451 inline void SlotTracker::initialize() {
00452   if (TheModule) {
00453     processModule();
00454     TheModule = nullptr; ///< Prevent re-processing next time we're called.
00455   }
00456 
00457   if (TheFunction && !FunctionProcessed)
00458     processFunction();
00459 }
00460 
00461 // Iterate through all the global variables, functions, and global
00462 // variable initializers and create slots for them.
00463 void SlotTracker::processModule() {
00464   ST_DEBUG("begin processModule!\n");
00465 
00466   // Add all of the unnamed global variables to the value table.
00467   for (Module::const_global_iterator I = TheModule->global_begin(),
00468          E = TheModule->global_end(); I != E; ++I) {
00469     if (!I->hasName())
00470       CreateModuleSlot(I);
00471   }
00472 
00473   // Add metadata used by named metadata.
00474   for (Module::const_named_metadata_iterator
00475          I = TheModule->named_metadata_begin(),
00476          E = TheModule->named_metadata_end(); I != E; ++I) {
00477     const NamedMDNode *NMD = I;
00478     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
00479       CreateMetadataSlot(NMD->getOperand(i));
00480   }
00481 
00482   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
00483        I != E; ++I) {
00484     if (!I->hasName())
00485       // Add all the unnamed functions to the table.
00486       CreateModuleSlot(I);
00487 
00488     // Add all the function attributes to the table.
00489     // FIXME: Add attributes of other objects?
00490     AttributeSet FnAttrs = I->getAttributes().getFnAttributes();
00491     if (FnAttrs.hasAttributes(AttributeSet::FunctionIndex))
00492       CreateAttributeSetSlot(FnAttrs);
00493   }
00494 
00495   ST_DEBUG("end processModule!\n");
00496 }
00497 
00498 // Process the arguments, basic blocks, and instructions  of a function.
00499 void SlotTracker::processFunction() {
00500   ST_DEBUG("begin processFunction!\n");
00501   fNext = 0;
00502 
00503   // Add all the function arguments with no names.
00504   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
00505       AE = TheFunction->arg_end(); AI != AE; ++AI)
00506     if (!AI->hasName())
00507       CreateFunctionSlot(AI);
00508 
00509   ST_DEBUG("Inserting Instructions:\n");
00510 
00511   SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
00512 
00513   // Add all of the basic blocks and instructions with no names.
00514   for (Function::const_iterator BB = TheFunction->begin(),
00515        E = TheFunction->end(); BB != E; ++BB) {
00516     if (!BB->hasName())
00517       CreateFunctionSlot(BB);
00518 
00519     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
00520          ++I) {
00521       if (!I->getType()->isVoidTy() && !I->hasName())
00522         CreateFunctionSlot(I);
00523 
00524       // Intrinsics can directly use metadata.  We allow direct calls to any
00525       // llvm.foo function here, because the target may not be linked into the
00526       // optimizer.
00527       if (const CallInst *CI = dyn_cast<CallInst>(I)) {
00528         if (Function *F = CI->getCalledFunction())
00529           if (F->isIntrinsic())
00530             for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
00531               if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
00532                 CreateMetadataSlot(N);
00533 
00534         // Add all the call attributes to the table.
00535         AttributeSet Attrs = CI->getAttributes().getFnAttributes();
00536         if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
00537           CreateAttributeSetSlot(Attrs);
00538       } else if (const InvokeInst *II = dyn_cast<InvokeInst>(I)) {
00539         // Add all the call attributes to the table.
00540         AttributeSet Attrs = II->getAttributes().getFnAttributes();
00541         if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
00542           CreateAttributeSetSlot(Attrs);
00543       }
00544 
00545       // Process metadata attached with this instruction.
00546       I->getAllMetadata(MDForInst);
00547       for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
00548         CreateMetadataSlot(MDForInst[i].second);
00549       MDForInst.clear();
00550     }
00551   }
00552 
00553   FunctionProcessed = true;
00554 
00555   ST_DEBUG("end processFunction!\n");
00556 }
00557 
00558 /// Clean up after incorporating a function. This is the only way to get out of
00559 /// the function incorporation state that affects get*Slot/Create*Slot. Function
00560 /// incorporation state is indicated by TheFunction != 0.
00561 void SlotTracker::purgeFunction() {
00562   ST_DEBUG("begin purgeFunction!\n");
00563   fMap.clear(); // Simply discard the function level map
00564   TheFunction = nullptr;
00565   FunctionProcessed = false;
00566   ST_DEBUG("end purgeFunction!\n");
00567 }
00568 
00569 /// getGlobalSlot - Get the slot number of a global value.
00570 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
00571   // Check for uninitialized state and do lazy initialization.
00572   initialize();
00573 
00574   // Find the value in the module map
00575   ValueMap::iterator MI = mMap.find(V);
00576   return MI == mMap.end() ? -1 : (int)MI->second;
00577 }
00578 
00579 /// getMetadataSlot - Get the slot number of a MDNode.
00580 int SlotTracker::getMetadataSlot(const MDNode *N) {
00581   // Check for uninitialized state and do lazy initialization.
00582   initialize();
00583 
00584   // Find the MDNode in the module map
00585   mdn_iterator MI = mdnMap.find(N);
00586   return MI == mdnMap.end() ? -1 : (int)MI->second;
00587 }
00588 
00589 
00590 /// getLocalSlot - Get the slot number for a value that is local to a function.
00591 int SlotTracker::getLocalSlot(const Value *V) {
00592   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
00593 
00594   // Check for uninitialized state and do lazy initialization.
00595   initialize();
00596 
00597   ValueMap::iterator FI = fMap.find(V);
00598   return FI == fMap.end() ? -1 : (int)FI->second;
00599 }
00600 
00601 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
00602   // Check for uninitialized state and do lazy initialization.
00603   initialize();
00604 
00605   // Find the AttributeSet in the module map.
00606   as_iterator AI = asMap.find(AS);
00607   return AI == asMap.end() ? -1 : (int)AI->second;
00608 }
00609 
00610 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
00611 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
00612   assert(V && "Can't insert a null Value into SlotTracker!");
00613   assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
00614   assert(!V->hasName() && "Doesn't need a slot!");
00615 
00616   unsigned DestSlot = mNext++;
00617   mMap[V] = DestSlot;
00618 
00619   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
00620            DestSlot << " [");
00621   // G = Global, F = Function, A = Alias, o = other
00622   ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
00623             (isa<Function>(V) ? 'F' :
00624              (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
00625 }
00626 
00627 /// CreateSlot - Create a new slot for the specified value if it has no name.
00628 void SlotTracker::CreateFunctionSlot(const Value *V) {
00629   assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
00630 
00631   unsigned DestSlot = fNext++;
00632   fMap[V] = DestSlot;
00633 
00634   // G = Global, F = Function, o = other
00635   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
00636            DestSlot << " [o]\n");
00637 }
00638 
00639 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
00640 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
00641   assert(N && "Can't insert a null Value into SlotTracker!");
00642 
00643   // Don't insert if N is a function-local metadata, these are always printed
00644   // inline.
00645   if (!N->isFunctionLocal()) {
00646     mdn_iterator I = mdnMap.find(N);
00647     if (I != mdnMap.end())
00648       return;
00649 
00650     unsigned DestSlot = mdnNext++;
00651     mdnMap[N] = DestSlot;
00652   }
00653 
00654   // Recursively add any MDNodes referenced by operands.
00655   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00656     if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
00657       CreateMetadataSlot(Op);
00658 }
00659 
00660 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
00661   assert(AS.hasAttributes(AttributeSet::FunctionIndex) &&
00662          "Doesn't need a slot!");
00663 
00664   as_iterator I = asMap.find(AS);
00665   if (I != asMap.end())
00666     return;
00667 
00668   unsigned DestSlot = asNext++;
00669   asMap[AS] = DestSlot;
00670 }
00671 
00672 //===----------------------------------------------------------------------===//
00673 // AsmWriter Implementation
00674 //===----------------------------------------------------------------------===//
00675 
00676 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
00677                                    TypePrinting *TypePrinter,
00678                                    SlotTracker *Machine,
00679                                    const Module *Context);
00680 
00681 static const char *getPredicateText(unsigned predicate) {
00682   const char * pred = "unknown";
00683   switch (predicate) {
00684   case FCmpInst::FCMP_FALSE: pred = "false"; break;
00685   case FCmpInst::FCMP_OEQ:   pred = "oeq"; break;
00686   case FCmpInst::FCMP_OGT:   pred = "ogt"; break;
00687   case FCmpInst::FCMP_OGE:   pred = "oge"; break;
00688   case FCmpInst::FCMP_OLT:   pred = "olt"; break;
00689   case FCmpInst::FCMP_OLE:   pred = "ole"; break;
00690   case FCmpInst::FCMP_ONE:   pred = "one"; break;
00691   case FCmpInst::FCMP_ORD:   pred = "ord"; break;
00692   case FCmpInst::FCMP_UNO:   pred = "uno"; break;
00693   case FCmpInst::FCMP_UEQ:   pred = "ueq"; break;
00694   case FCmpInst::FCMP_UGT:   pred = "ugt"; break;
00695   case FCmpInst::FCMP_UGE:   pred = "uge"; break;
00696   case FCmpInst::FCMP_ULT:   pred = "ult"; break;
00697   case FCmpInst::FCMP_ULE:   pred = "ule"; break;
00698   case FCmpInst::FCMP_UNE:   pred = "une"; break;
00699   case FCmpInst::FCMP_TRUE:  pred = "true"; break;
00700   case ICmpInst::ICMP_EQ:    pred = "eq"; break;
00701   case ICmpInst::ICMP_NE:    pred = "ne"; break;
00702   case ICmpInst::ICMP_SGT:   pred = "sgt"; break;
00703   case ICmpInst::ICMP_SGE:   pred = "sge"; break;
00704   case ICmpInst::ICMP_SLT:   pred = "slt"; break;
00705   case ICmpInst::ICMP_SLE:   pred = "sle"; break;
00706   case ICmpInst::ICMP_UGT:   pred = "ugt"; break;
00707   case ICmpInst::ICMP_UGE:   pred = "uge"; break;
00708   case ICmpInst::ICMP_ULT:   pred = "ult"; break;
00709   case ICmpInst::ICMP_ULE:   pred = "ule"; break;
00710   }
00711   return pred;
00712 }
00713 
00714 static void writeAtomicRMWOperation(raw_ostream &Out,
00715                                     AtomicRMWInst::BinOp Op) {
00716   switch (Op) {
00717   default: Out << " <unknown operation " << Op << ">"; break;
00718   case AtomicRMWInst::Xchg: Out << " xchg"; break;
00719   case AtomicRMWInst::Add:  Out << " add"; break;
00720   case AtomicRMWInst::Sub:  Out << " sub"; break;
00721   case AtomicRMWInst::And:  Out << " and"; break;
00722   case AtomicRMWInst::Nand: Out << " nand"; break;
00723   case AtomicRMWInst::Or:   Out << " or"; break;
00724   case AtomicRMWInst::Xor:  Out << " xor"; break;
00725   case AtomicRMWInst::Max:  Out << " max"; break;
00726   case AtomicRMWInst::Min:  Out << " min"; break;
00727   case AtomicRMWInst::UMax: Out << " umax"; break;
00728   case AtomicRMWInst::UMin: Out << " umin"; break;
00729   }
00730 }
00731 
00732 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
00733   if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
00734     // Unsafe algebra implies all the others, no need to write them all out
00735     if (FPO->hasUnsafeAlgebra())
00736       Out << " fast";
00737     else {
00738       if (FPO->hasNoNaNs())
00739         Out << " nnan";
00740       if (FPO->hasNoInfs())
00741         Out << " ninf";
00742       if (FPO->hasNoSignedZeros())
00743         Out << " nsz";
00744       if (FPO->hasAllowReciprocal())
00745         Out << " arcp";
00746     }
00747   }
00748 
00749   if (const OverflowingBinaryOperator *OBO =
00750         dyn_cast<OverflowingBinaryOperator>(U)) {
00751     if (OBO->hasNoUnsignedWrap())
00752       Out << " nuw";
00753     if (OBO->hasNoSignedWrap())
00754       Out << " nsw";
00755   } else if (const PossiblyExactOperator *Div =
00756                dyn_cast<PossiblyExactOperator>(U)) {
00757     if (Div->isExact())
00758       Out << " exact";
00759   } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
00760     if (GEP->isInBounds())
00761       Out << " inbounds";
00762   }
00763 }
00764 
00765 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
00766                                   TypePrinting &TypePrinter,
00767                                   SlotTracker *Machine,
00768                                   const Module *Context) {
00769   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
00770     if (CI->getType()->isIntegerTy(1)) {
00771       Out << (CI->getZExtValue() ? "true" : "false");
00772       return;
00773     }
00774     Out << CI->getValue();
00775     return;
00776   }
00777 
00778   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
00779     if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
00780         &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
00781       // We would like to output the FP constant value in exponential notation,
00782       // but we cannot do this if doing so will lose precision.  Check here to
00783       // make sure that we only output it in exponential format if we can parse
00784       // the value back and get the same value.
00785       //
00786       bool ignored;
00787       bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
00788       bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
00789       bool isInf = CFP->getValueAPF().isInfinity();
00790       bool isNaN = CFP->getValueAPF().isNaN();
00791       if (!isHalf && !isInf && !isNaN) {
00792         double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
00793                                 CFP->getValueAPF().convertToFloat();
00794         SmallString<128> StrVal;
00795         raw_svector_ostream(StrVal) << Val;
00796 
00797         // Check to make sure that the stringized number is not some string like
00798         // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
00799         // that the string matches the "[-+]?[0-9]" regex.
00800         //
00801         if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
00802             ((StrVal[0] == '-' || StrVal[0] == '+') &&
00803              (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
00804           // Reparse stringized version!
00805           if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
00806             Out << StrVal.str();
00807             return;
00808           }
00809         }
00810       }
00811       // Otherwise we could not reparse it to exactly the same value, so we must
00812       // output the string in hexadecimal format!  Note that loading and storing
00813       // floating point types changes the bits of NaNs on some hosts, notably
00814       // x86, so we must not use these types.
00815       static_assert(sizeof(double) == sizeof(uint64_t),
00816                     "assuming that double is 64 bits!");
00817       char Buffer[40];
00818       APFloat apf = CFP->getValueAPF();
00819       // Halves and floats are represented in ASCII IR as double, convert.
00820       if (!isDouble)
00821         apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
00822                           &ignored);
00823       Out << "0x" <<
00824               utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
00825                             Buffer+40);
00826       return;
00827     }
00828 
00829     // Either half, or some form of long double.
00830     // These appear as a magic letter identifying the type, then a
00831     // fixed number of hex digits.
00832     Out << "0x";
00833     // Bit position, in the current word, of the next nibble to print.
00834     int shiftcount;
00835 
00836     if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
00837       Out << 'K';
00838       // api needed to prevent premature destruction
00839       APInt api = CFP->getValueAPF().bitcastToAPInt();
00840       const uint64_t* p = api.getRawData();
00841       uint64_t word = p[1];
00842       shiftcount = 12;
00843       int width = api.getBitWidth();
00844       for (int j=0; j<width; j+=4, shiftcount-=4) {
00845         unsigned int nibble = (word>>shiftcount) & 15;
00846         if (nibble < 10)
00847           Out << (unsigned char)(nibble + '0');
00848         else
00849           Out << (unsigned char)(nibble - 10 + 'A');
00850         if (shiftcount == 0 && j+4 < width) {
00851           word = *p;
00852           shiftcount = 64;
00853           if (width-j-4 < 64)
00854             shiftcount = width-j-4;
00855         }
00856       }
00857       return;
00858     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
00859       shiftcount = 60;
00860       Out << 'L';
00861     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
00862       shiftcount = 60;
00863       Out << 'M';
00864     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
00865       shiftcount = 12;
00866       Out << 'H';
00867     } else
00868       llvm_unreachable("Unsupported floating point type");
00869     // api needed to prevent premature destruction
00870     APInt api = CFP->getValueAPF().bitcastToAPInt();
00871     const uint64_t* p = api.getRawData();
00872     uint64_t word = *p;
00873     int width = api.getBitWidth();
00874     for (int j=0; j<width; j+=4, shiftcount-=4) {
00875       unsigned int nibble = (word>>shiftcount) & 15;
00876       if (nibble < 10)
00877         Out << (unsigned char)(nibble + '0');
00878       else
00879         Out << (unsigned char)(nibble - 10 + 'A');
00880       if (shiftcount == 0 && j+4 < width) {
00881         word = *(++p);
00882         shiftcount = 64;
00883         if (width-j-4 < 64)
00884           shiftcount = width-j-4;
00885       }
00886     }
00887     return;
00888   }
00889 
00890   if (isa<ConstantAggregateZero>(CV)) {
00891     Out << "zeroinitializer";
00892     return;
00893   }
00894 
00895   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
00896     Out << "blockaddress(";
00897     WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
00898                            Context);
00899     Out << ", ";
00900     WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
00901                            Context);
00902     Out << ")";
00903     return;
00904   }
00905 
00906   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
00907     Type *ETy = CA->getType()->getElementType();
00908     Out << '[';
00909     TypePrinter.print(ETy, Out);
00910     Out << ' ';
00911     WriteAsOperandInternal(Out, CA->getOperand(0),
00912                            &TypePrinter, Machine,
00913                            Context);
00914     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
00915       Out << ", ";
00916       TypePrinter.print(ETy, Out);
00917       Out << ' ';
00918       WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
00919                              Context);
00920     }
00921     Out << ']';
00922     return;
00923   }
00924 
00925   if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
00926     // As a special case, print the array as a string if it is an array of
00927     // i8 with ConstantInt values.
00928     if (CA->isString()) {
00929       Out << "c\"";
00930       PrintEscapedString(CA->getAsString(), Out);
00931       Out << '"';
00932       return;
00933     }
00934 
00935     Type *ETy = CA->getType()->getElementType();
00936     Out << '[';
00937     TypePrinter.print(ETy, Out);
00938     Out << ' ';
00939     WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
00940                            &TypePrinter, Machine,
00941                            Context);
00942     for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
00943       Out << ", ";
00944       TypePrinter.print(ETy, Out);
00945       Out << ' ';
00946       WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
00947                              Machine, Context);
00948     }
00949     Out << ']';
00950     return;
00951   }
00952 
00953 
00954   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
00955     if (CS->getType()->isPacked())
00956       Out << '<';
00957     Out << '{';
00958     unsigned N = CS->getNumOperands();
00959     if (N) {
00960       Out << ' ';
00961       TypePrinter.print(CS->getOperand(0)->getType(), Out);
00962       Out << ' ';
00963 
00964       WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
00965                              Context);
00966 
00967       for (unsigned i = 1; i < N; i++) {
00968         Out << ", ";
00969         TypePrinter.print(CS->getOperand(i)->getType(), Out);
00970         Out << ' ';
00971 
00972         WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
00973                                Context);
00974       }
00975       Out << ' ';
00976     }
00977 
00978     Out << '}';
00979     if (CS->getType()->isPacked())
00980       Out << '>';
00981     return;
00982   }
00983 
00984   if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
00985     Type *ETy = CV->getType()->getVectorElementType();
00986     Out << '<';
00987     TypePrinter.print(ETy, Out);
00988     Out << ' ';
00989     WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
00990                            Machine, Context);
00991     for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
00992       Out << ", ";
00993       TypePrinter.print(ETy, Out);
00994       Out << ' ';
00995       WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
00996                              Machine, Context);
00997     }
00998     Out << '>';
00999     return;
01000   }
01001 
01002   if (isa<ConstantPointerNull>(CV)) {
01003     Out << "null";
01004     return;
01005   }
01006 
01007   if (isa<UndefValue>(CV)) {
01008     Out << "undef";
01009     return;
01010   }
01011 
01012   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
01013     Out << CE->getOpcodeName();
01014     WriteOptimizationInfo(Out, CE);
01015     if (CE->isCompare())
01016       Out << ' ' << getPredicateText(CE->getPredicate());
01017     Out << " (";
01018 
01019     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
01020       TypePrinter.print((*OI)->getType(), Out);
01021       Out << ' ';
01022       WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
01023       if (OI+1 != CE->op_end())
01024         Out << ", ";
01025     }
01026 
01027     if (CE->hasIndices()) {
01028       ArrayRef<unsigned> Indices = CE->getIndices();
01029       for (unsigned i = 0, e = Indices.size(); i != e; ++i)
01030         Out << ", " << Indices[i];
01031     }
01032 
01033     if (CE->isCast()) {
01034       Out << " to ";
01035       TypePrinter.print(CE->getType(), Out);
01036     }
01037 
01038     Out << ')';
01039     return;
01040   }
01041 
01042   Out << "<placeholder or erroneous Constant>";
01043 }
01044 
01045 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
01046                                     TypePrinting *TypePrinter,
01047                                     SlotTracker *Machine,
01048                                     const Module *Context) {
01049   Out << "!{";
01050   for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
01051     const Value *V = Node->getOperand(mi);
01052     if (!V)
01053       Out << "null";
01054     else {
01055       TypePrinter->print(V->getType(), Out);
01056       Out << ' ';
01057       WriteAsOperandInternal(Out, Node->getOperand(mi),
01058                              TypePrinter, Machine, Context);
01059     }
01060     if (mi + 1 != me)
01061       Out << ", ";
01062   }
01063 
01064   Out << "}";
01065 }
01066 
01067 // Full implementation of printing a Value as an operand with support for
01068 // TypePrinting, etc.
01069 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
01070                                    TypePrinting *TypePrinter,
01071                                    SlotTracker *Machine,
01072                                    const Module *Context) {
01073   if (V->hasName()) {
01074     PrintLLVMName(Out, V);
01075     return;
01076   }
01077 
01078   const Constant *CV = dyn_cast<Constant>(V);
01079   if (CV && !isa<GlobalValue>(CV)) {
01080     assert(TypePrinter && "Constants require TypePrinting!");
01081     WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
01082     return;
01083   }
01084 
01085   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
01086     Out << "asm ";
01087     if (IA->hasSideEffects())
01088       Out << "sideeffect ";
01089     if (IA->isAlignStack())
01090       Out << "alignstack ";
01091     // We don't emit the AD_ATT dialect as it's the assumed default.
01092     if (IA->getDialect() == InlineAsm::AD_Intel)
01093       Out << "inteldialect ";
01094     Out << '"';
01095     PrintEscapedString(IA->getAsmString(), Out);
01096     Out << "\", \"";
01097     PrintEscapedString(IA->getConstraintString(), Out);
01098     Out << '"';
01099     return;
01100   }
01101 
01102   if (const MDNode *N = dyn_cast<MDNode>(V)) {
01103     if (N->isFunctionLocal()) {
01104       // Print metadata inline, not via slot reference number.
01105       WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
01106       return;
01107     }
01108 
01109     if (!Machine) {
01110       if (N->isFunctionLocal())
01111         Machine = new SlotTracker(N->getFunction());
01112       else
01113         Machine = new SlotTracker(Context);
01114     }
01115     int Slot = Machine->getMetadataSlot(N);
01116     if (Slot == -1)
01117       Out << "<badref>";
01118     else
01119       Out << '!' << Slot;
01120     return;
01121   }
01122 
01123   if (const MDString *MDS = dyn_cast<MDString>(V)) {
01124     Out << "!\"";
01125     PrintEscapedString(MDS->getString(), Out);
01126     Out << '"';
01127     return;
01128   }
01129 
01130   char Prefix = '%';
01131   int Slot;
01132   // If we have a SlotTracker, use it.
01133   if (Machine) {
01134     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
01135       Slot = Machine->getGlobalSlot(GV);
01136       Prefix = '@';
01137     } else {
01138       Slot = Machine->getLocalSlot(V);
01139 
01140       // If the local value didn't succeed, then we may be referring to a value
01141       // from a different function.  Translate it, as this can happen when using
01142       // address of blocks.
01143       if (Slot == -1)
01144         if ((Machine = createSlotTracker(V))) {
01145           Slot = Machine->getLocalSlot(V);
01146           delete Machine;
01147         }
01148     }
01149   } else if ((Machine = createSlotTracker(V))) {
01150     // Otherwise, create one to get the # and then destroy it.
01151     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
01152       Slot = Machine->getGlobalSlot(GV);
01153       Prefix = '@';
01154     } else {
01155       Slot = Machine->getLocalSlot(V);
01156     }
01157     delete Machine;
01158     Machine = nullptr;
01159   } else {
01160     Slot = -1;
01161   }
01162 
01163   if (Slot != -1)
01164     Out << Prefix << Slot;
01165   else
01166     Out << "<badref>";
01167 }
01168 
01169 void AssemblyWriter::init() {
01170   if (!TheModule)
01171     return;
01172   TypePrinter.incorporateTypes(*TheModule);
01173   for (const Function &F : *TheModule)
01174     if (const Comdat *C = F.getComdat())
01175       Comdats.insert(C);
01176   for (const GlobalVariable &GV : TheModule->globals())
01177     if (const Comdat *C = GV.getComdat())
01178       Comdats.insert(C);
01179 }
01180 
01181 
01182 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
01183                                const Module *M,
01184                                AssemblyAnnotationWriter *AAW)
01185   : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW) {
01186   init();
01187 }
01188 
01189 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, const Module *M,
01190                                AssemblyAnnotationWriter *AAW)
01191   : Out(o), TheModule(M), ModuleSlotTracker(createSlotTracker(M)),
01192     Machine(*ModuleSlotTracker), AnnotationWriter(AAW) {
01193   init();
01194 }
01195 
01196 AssemblyWriter::~AssemblyWriter() { }
01197 
01198 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
01199   if (!Operand) {
01200     Out << "<null operand!>";
01201     return;
01202   }
01203   if (PrintType) {
01204     TypePrinter.print(Operand->getType(), Out);
01205     Out << ' ';
01206   }
01207   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
01208 }
01209 
01210 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
01211                                  SynchronizationScope SynchScope) {
01212   if (Ordering == NotAtomic)
01213     return;
01214 
01215   switch (SynchScope) {
01216   case SingleThread: Out << " singlethread"; break;
01217   case CrossThread: break;
01218   }
01219 
01220   switch (Ordering) {
01221   default: Out << " <bad ordering " << int(Ordering) << ">"; break;
01222   case Unordered: Out << " unordered"; break;
01223   case Monotonic: Out << " monotonic"; break;
01224   case Acquire: Out << " acquire"; break;
01225   case Release: Out << " release"; break;
01226   case AcquireRelease: Out << " acq_rel"; break;
01227   case SequentiallyConsistent: Out << " seq_cst"; break;
01228   }
01229 }
01230 
01231 void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
01232                                         AtomicOrdering FailureOrdering,
01233                                         SynchronizationScope SynchScope) {
01234   assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic);
01235 
01236   switch (SynchScope) {
01237   case SingleThread: Out << " singlethread"; break;
01238   case CrossThread: break;
01239   }
01240 
01241   switch (SuccessOrdering) {
01242   default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break;
01243   case Unordered: Out << " unordered"; break;
01244   case Monotonic: Out << " monotonic"; break;
01245   case Acquire: Out << " acquire"; break;
01246   case Release: Out << " release"; break;
01247   case AcquireRelease: Out << " acq_rel"; break;
01248   case SequentiallyConsistent: Out << " seq_cst"; break;
01249   }
01250 
01251   switch (FailureOrdering) {
01252   default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break;
01253   case Unordered: Out << " unordered"; break;
01254   case Monotonic: Out << " monotonic"; break;
01255   case Acquire: Out << " acquire"; break;
01256   case Release: Out << " release"; break;
01257   case AcquireRelease: Out << " acq_rel"; break;
01258   case SequentiallyConsistent: Out << " seq_cst"; break;
01259   }
01260 }
01261 
01262 void AssemblyWriter::writeParamOperand(const Value *Operand,
01263                                        AttributeSet Attrs, unsigned Idx) {
01264   if (!Operand) {
01265     Out << "<null operand!>";
01266     return;
01267   }
01268 
01269   // Print the type
01270   TypePrinter.print(Operand->getType(), Out);
01271   // Print parameter attributes list
01272   if (Attrs.hasAttributes(Idx))
01273     Out << ' ' << Attrs.getAsString(Idx);
01274   Out << ' ';
01275   // Print the operand
01276   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
01277 }
01278 
01279 void AssemblyWriter::printModule(const Module *M) {
01280   Machine.initialize();
01281 
01282   if (!M->getModuleIdentifier().empty() &&
01283       // Don't print the ID if it will start a new line (which would
01284       // require a comment char before it).
01285       M->getModuleIdentifier().find('\n') == std::string::npos)
01286     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
01287 
01288   const std::string &DL = M->getDataLayoutStr();
01289   if (!DL.empty())
01290     Out << "target datalayout = \"" << DL << "\"\n";
01291   if (!M->getTargetTriple().empty())
01292     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
01293 
01294   if (!M->getModuleInlineAsm().empty()) {
01295     // Split the string into lines, to make it easier to read the .ll file.
01296     std::string Asm = M->getModuleInlineAsm();
01297     size_t CurPos = 0;
01298     size_t NewLine = Asm.find_first_of('\n', CurPos);
01299     Out << '\n';
01300     while (NewLine != std::string::npos) {
01301       // We found a newline, print the portion of the asm string from the
01302       // last newline up to this newline.
01303       Out << "module asm \"";
01304       PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
01305                          Out);
01306       Out << "\"\n";
01307       CurPos = NewLine+1;
01308       NewLine = Asm.find_first_of('\n', CurPos);
01309     }
01310     std::string rest(Asm.begin()+CurPos, Asm.end());
01311     if (!rest.empty()) {
01312       Out << "module asm \"";
01313       PrintEscapedString(rest, Out);
01314       Out << "\"\n";
01315     }
01316   }
01317 
01318   printTypeIdentities();
01319 
01320   // Output all comdats.
01321   if (!Comdats.empty())
01322     Out << '\n';
01323   for (const Comdat *C : Comdats) {
01324     printComdat(C);
01325     if (C != Comdats.back())
01326       Out << '\n';
01327   }
01328 
01329   // Output all globals.
01330   if (!M->global_empty()) Out << '\n';
01331   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
01332        I != E; ++I) {
01333     printGlobal(I); Out << '\n';
01334   }
01335 
01336   // Output all aliases.
01337   if (!M->alias_empty()) Out << "\n";
01338   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
01339        I != E; ++I)
01340     printAlias(I);
01341 
01342   // Output all of the functions.
01343   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
01344     printFunction(I);
01345 
01346   // Output all attribute groups.
01347   if (!Machine.as_empty()) {
01348     Out << '\n';
01349     writeAllAttributeGroups();
01350   }
01351 
01352   // Output named metadata.
01353   if (!M->named_metadata_empty()) Out << '\n';
01354 
01355   for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
01356        E = M->named_metadata_end(); I != E; ++I)
01357     printNamedMDNode(I);
01358 
01359   // Output metadata.
01360   if (!Machine.mdn_empty()) {
01361     Out << '\n';
01362     writeAllMDNodes();
01363   }
01364 }
01365 
01366 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
01367   Out << '!';
01368   StringRef Name = NMD->getName();
01369   if (Name.empty()) {
01370     Out << "<empty name> ";
01371   } else {
01372     if (isalpha(static_cast<unsigned char>(Name[0])) ||
01373         Name[0] == '-' || Name[0] == '$' ||
01374         Name[0] == '.' || Name[0] == '_')
01375       Out << Name[0];
01376     else
01377       Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
01378     for (unsigned i = 1, e = Name.size(); i != e; ++i) {
01379       unsigned char C = Name[i];
01380       if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
01381           C == '.' || C == '_')
01382         Out << C;
01383       else
01384         Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
01385     }
01386   }
01387   Out << " = !{";
01388   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
01389     if (i) Out << ", ";
01390     int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
01391     if (Slot == -1)
01392       Out << "<badref>";
01393     else
01394       Out << '!' << Slot;
01395   }
01396   Out << "}\n";
01397 }
01398 
01399 
01400 static void PrintLinkage(GlobalValue::LinkageTypes LT,
01401                          formatted_raw_ostream &Out) {
01402   switch (LT) {
01403   case GlobalValue::ExternalLinkage: break;
01404   case GlobalValue::PrivateLinkage:       Out << "private ";        break;
01405   case GlobalValue::InternalLinkage:      Out << "internal ";       break;
01406   case GlobalValue::LinkOnceAnyLinkage:   Out << "linkonce ";       break;
01407   case GlobalValue::LinkOnceODRLinkage:   Out << "linkonce_odr ";   break;
01408   case GlobalValue::WeakAnyLinkage:       Out << "weak ";           break;
01409   case GlobalValue::WeakODRLinkage:       Out << "weak_odr ";       break;
01410   case GlobalValue::CommonLinkage:        Out << "common ";         break;
01411   case GlobalValue::AppendingLinkage:     Out << "appending ";      break;
01412   case GlobalValue::ExternalWeakLinkage:  Out << "extern_weak ";    break;
01413   case GlobalValue::AvailableExternallyLinkage:
01414     Out << "available_externally ";
01415     break;
01416   }
01417 }
01418 
01419 
01420 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
01421                             formatted_raw_ostream &Out) {
01422   switch (Vis) {
01423   case GlobalValue::DefaultVisibility: break;
01424   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
01425   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
01426   }
01427 }
01428 
01429 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
01430                                  formatted_raw_ostream &Out) {
01431   switch (SCT) {
01432   case GlobalValue::DefaultStorageClass: break;
01433   case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
01434   case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
01435   }
01436 }
01437 
01438 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
01439                                   formatted_raw_ostream &Out) {
01440   switch (TLM) {
01441     case GlobalVariable::NotThreadLocal:
01442       break;
01443     case GlobalVariable::GeneralDynamicTLSModel:
01444       Out << "thread_local ";
01445       break;
01446     case GlobalVariable::LocalDynamicTLSModel:
01447       Out << "thread_local(localdynamic) ";
01448       break;
01449     case GlobalVariable::InitialExecTLSModel:
01450       Out << "thread_local(initialexec) ";
01451       break;
01452     case GlobalVariable::LocalExecTLSModel:
01453       Out << "thread_local(localexec) ";
01454       break;
01455   }
01456 }
01457 
01458 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
01459   if (GV->isMaterializable())
01460     Out << "; Materializable\n";
01461 
01462   WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
01463   Out << " = ";
01464 
01465   if (!GV->hasInitializer() && GV->hasExternalLinkage())
01466     Out << "external ";
01467 
01468   PrintLinkage(GV->getLinkage(), Out);
01469   PrintVisibility(GV->getVisibility(), Out);
01470   PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
01471   PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
01472   if (GV->hasUnnamedAddr())
01473     Out << "unnamed_addr ";
01474 
01475   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
01476     Out << "addrspace(" << AddressSpace << ") ";
01477   if (GV->isExternallyInitialized()) Out << "externally_initialized ";
01478   Out << (GV->isConstant() ? "constant " : "global ");
01479   TypePrinter.print(GV->getType()->getElementType(), Out);
01480 
01481   if (GV->hasInitializer()) {
01482     Out << ' ';
01483     writeOperand(GV->getInitializer(), false);
01484   }
01485 
01486   if (GV->hasSection()) {
01487     Out << ", section \"";
01488     PrintEscapedString(GV->getSection(), Out);
01489     Out << '"';
01490   }
01491   if (GV->hasComdat()) {
01492     Out << ", comdat ";
01493     PrintLLVMName(Out, GV->getComdat()->getName(), ComdatPrefix);
01494   }
01495   if (GV->getAlignment())
01496     Out << ", align " << GV->getAlignment();
01497 
01498   printInfoComment(*GV);
01499 }
01500 
01501 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
01502   if (GA->isMaterializable())
01503     Out << "; Materializable\n";
01504 
01505   // Don't crash when dumping partially built GA
01506   if (!GA->hasName())
01507     Out << "<<nameless>> = ";
01508   else {
01509     PrintLLVMName(Out, GA);
01510     Out << " = ";
01511   }
01512   PrintVisibility(GA->getVisibility(), Out);
01513   PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
01514   PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
01515   if (GA->hasUnnamedAddr())
01516     Out << "unnamed_addr ";
01517 
01518   Out << "alias ";
01519 
01520   PrintLinkage(GA->getLinkage(), Out);
01521 
01522   const Constant *Aliasee = GA->getAliasee();
01523 
01524   if (!Aliasee) {
01525     TypePrinter.print(GA->getType(), Out);
01526     Out << " <<NULL ALIASEE>>";
01527   } else {
01528     writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
01529   }
01530 
01531   printInfoComment(*GA);
01532   Out << '\n';
01533 }
01534 
01535 void AssemblyWriter::printComdat(const Comdat *C) {
01536   C->print(Out);
01537 }
01538 
01539 void AssemblyWriter::printTypeIdentities() {
01540   if (TypePrinter.NumberedTypes.empty() &&
01541       TypePrinter.NamedTypes.empty())
01542     return;
01543 
01544   Out << '\n';
01545 
01546   // We know all the numbers that each type is used and we know that it is a
01547   // dense assignment.  Convert the map to an index table.
01548   std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
01549   for (DenseMap<StructType*, unsigned>::iterator I =
01550        TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
01551        I != E; ++I) {
01552     assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
01553     NumberedTypes[I->second] = I->first;
01554   }
01555 
01556   // Emit all numbered types.
01557   for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
01558     Out << '%' << i << " = type ";
01559 
01560     // Make sure we print out at least one level of the type structure, so
01561     // that we do not get %2 = type %2
01562     TypePrinter.printStructBody(NumberedTypes[i], Out);
01563     Out << '\n';
01564   }
01565 
01566   for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
01567     PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
01568     Out << " = type ";
01569 
01570     // Make sure we print out at least one level of the type structure, so
01571     // that we do not get %FILE = type %FILE
01572     TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
01573     Out << '\n';
01574   }
01575 }
01576 
01577 /// printFunction - Print all aspects of a function.
01578 ///
01579 void AssemblyWriter::printFunction(const Function *F) {
01580   // Print out the return type and name.
01581   Out << '\n';
01582 
01583   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
01584 
01585   if (F->isMaterializable())
01586     Out << "; Materializable\n";
01587 
01588   const AttributeSet &Attrs = F->getAttributes();
01589   if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
01590     AttributeSet AS = Attrs.getFnAttributes();
01591     std::string AttrStr;
01592 
01593     unsigned Idx = 0;
01594     for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
01595       if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
01596         break;
01597 
01598     for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
01599          I != E; ++I) {
01600       Attribute Attr = *I;
01601       if (!Attr.isStringAttribute()) {
01602         if (!AttrStr.empty()) AttrStr += ' ';
01603         AttrStr += Attr.getAsString();
01604       }
01605     }
01606 
01607     if (!AttrStr.empty())
01608       Out << "; Function Attrs: " << AttrStr << '\n';
01609   }
01610 
01611   if (F->isDeclaration())
01612     Out << "declare ";
01613   else
01614     Out << "define ";
01615 
01616   PrintLinkage(F->getLinkage(), Out);
01617   PrintVisibility(F->getVisibility(), Out);
01618   PrintDLLStorageClass(F->getDLLStorageClass(), Out);
01619 
01620   // Print the calling convention.
01621   if (F->getCallingConv() != CallingConv::C) {
01622     PrintCallingConv(F->getCallingConv(), Out);
01623     Out << " ";
01624   }
01625 
01626   FunctionType *FT = F->getFunctionType();
01627   if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
01628     Out <<  Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
01629   TypePrinter.print(F->getReturnType(), Out);
01630   Out << ' ';
01631   WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
01632   Out << '(';
01633   Machine.incorporateFunction(F);
01634 
01635   // Loop over the arguments, printing them...
01636 
01637   unsigned Idx = 1;
01638   if (!F->isDeclaration()) {
01639     // If this isn't a declaration, print the argument names as well.
01640     for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
01641          I != E; ++I) {
01642       // Insert commas as we go... the first arg doesn't get a comma
01643       if (I != F->arg_begin()) Out << ", ";
01644       printArgument(I, Attrs, Idx);
01645       Idx++;
01646     }
01647   } else {
01648     // Otherwise, print the types from the function type.
01649     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
01650       // Insert commas as we go... the first arg doesn't get a comma
01651       if (i) Out << ", ";
01652 
01653       // Output type...
01654       TypePrinter.print(FT->getParamType(i), Out);
01655 
01656       if (Attrs.hasAttributes(i+1))
01657         Out << ' ' << Attrs.getAsString(i+1);
01658     }
01659   }
01660 
01661   // Finish printing arguments...
01662   if (FT->isVarArg()) {
01663     if (FT->getNumParams()) Out << ", ";
01664     Out << "...";  // Output varargs portion of signature!
01665   }
01666   Out << ')';
01667   if (F->hasUnnamedAddr())
01668     Out << " unnamed_addr";
01669   if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
01670     Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
01671   if (F->hasSection()) {
01672     Out << " section \"";
01673     PrintEscapedString(F->getSection(), Out);
01674     Out << '"';
01675   }
01676   if (F->hasComdat()) {
01677     Out << " comdat ";
01678     PrintLLVMName(Out, F->getComdat()->getName(), ComdatPrefix);
01679   }
01680   if (F->getAlignment())
01681     Out << " align " << F->getAlignment();
01682   if (F->hasGC())
01683     Out << " gc \"" << F->getGC() << '"';
01684   if (F->hasPrefixData()) {
01685     Out << " prefix ";
01686     writeOperand(F->getPrefixData(), true);
01687   }
01688   if (F->isDeclaration()) {
01689     Out << '\n';
01690   } else {
01691     Out << " {";
01692     // Output all of the function's basic blocks.
01693     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
01694       printBasicBlock(I);
01695 
01696     Out << "}\n";
01697   }
01698 
01699   Machine.purgeFunction();
01700 }
01701 
01702 /// printArgument - This member is called for every argument that is passed into
01703 /// the function.  Simply print it out
01704 ///
01705 void AssemblyWriter::printArgument(const Argument *Arg,
01706                                    AttributeSet Attrs, unsigned Idx) {
01707   // Output type...
01708   TypePrinter.print(Arg->getType(), Out);
01709 
01710   // Output parameter attributes list
01711   if (Attrs.hasAttributes(Idx))
01712     Out << ' ' << Attrs.getAsString(Idx);
01713 
01714   // Output name, if available...
01715   if (Arg->hasName()) {
01716     Out << ' ';
01717     PrintLLVMName(Out, Arg);
01718   }
01719 }
01720 
01721 /// printBasicBlock - This member is called for each basic block in a method.
01722 ///
01723 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
01724   if (BB->hasName()) {              // Print out the label if it exists...
01725     Out << "\n";
01726     PrintLLVMName(Out, BB->getName(), LabelPrefix);
01727     Out << ':';
01728   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
01729     Out << "\n; <label>:";
01730     int Slot = Machine.getLocalSlot(BB);
01731     if (Slot != -1)
01732       Out << Slot;
01733     else
01734       Out << "<badref>";
01735   }
01736 
01737   if (!BB->getParent()) {
01738     Out.PadToColumn(50);
01739     Out << "; Error: Block without parent!";
01740   } else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
01741     // Output predecessors for the block.
01742     Out.PadToColumn(50);
01743     Out << ";";
01744     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
01745 
01746     if (PI == PE) {
01747       Out << " No predecessors!";
01748     } else {
01749       Out << " preds = ";
01750       writeOperand(*PI, false);
01751       for (++PI; PI != PE; ++PI) {
01752         Out << ", ";
01753         writeOperand(*PI, false);
01754       }
01755     }
01756   }
01757 
01758   Out << "\n";
01759 
01760   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
01761 
01762   // Output all of the instructions in the basic block...
01763   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
01764     printInstructionLine(*I);
01765   }
01766 
01767   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
01768 }
01769 
01770 /// printInstructionLine - Print an instruction and a newline character.
01771 void AssemblyWriter::printInstructionLine(const Instruction &I) {
01772   printInstruction(I);
01773   Out << '\n';
01774 }
01775 
01776 /// printInfoComment - Print a little comment after the instruction indicating
01777 /// which slot it occupies.
01778 ///
01779 void AssemblyWriter::printInfoComment(const Value &V) {
01780   if (AnnotationWriter)
01781     AnnotationWriter->printInfoComment(V, Out);
01782 }
01783 
01784 // This member is called for each Instruction in a function..
01785 void AssemblyWriter::printInstruction(const Instruction &I) {
01786   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
01787 
01788   // Print out indentation for an instruction.
01789   Out << "  ";
01790 
01791   // Print out name if it exists...
01792   if (I.hasName()) {
01793     PrintLLVMName(Out, &I);
01794     Out << " = ";
01795   } else if (!I.getType()->isVoidTy()) {
01796     // Print out the def slot taken.
01797     int SlotNum = Machine.getLocalSlot(&I);
01798     if (SlotNum == -1)
01799       Out << "<badref> = ";
01800     else
01801       Out << '%' << SlotNum << " = ";
01802   }
01803 
01804   if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
01805     if (CI->isMustTailCall())
01806       Out << "musttail ";
01807     else if (CI->isTailCall())
01808       Out << "tail ";
01809   }
01810 
01811   // Print out the opcode...
01812   Out << I.getOpcodeName();
01813 
01814   // If this is an atomic load or store, print out the atomic marker.
01815   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isAtomic()) ||
01816       (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
01817     Out << " atomic";
01818 
01819   if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
01820     Out << " weak";
01821 
01822   // If this is a volatile operation, print out the volatile marker.
01823   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
01824       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
01825       (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
01826       (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
01827     Out << " volatile";
01828 
01829   // Print out optimization information.
01830   WriteOptimizationInfo(Out, &I);
01831 
01832   // Print out the compare instruction predicates
01833   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
01834     Out << ' ' << getPredicateText(CI->getPredicate());
01835 
01836   // Print out the atomicrmw operation
01837   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
01838     writeAtomicRMWOperation(Out, RMWI->getOperation());
01839 
01840   // Print out the type of the operands...
01841   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
01842 
01843   // Special case conditional branches to swizzle the condition out to the front
01844   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
01845     const BranchInst &BI(cast<BranchInst>(I));
01846     Out << ' ';
01847     writeOperand(BI.getCondition(), true);
01848     Out << ", ";
01849     writeOperand(BI.getSuccessor(0), true);
01850     Out << ", ";
01851     writeOperand(BI.getSuccessor(1), true);
01852 
01853   } else if (isa<SwitchInst>(I)) {
01854     const SwitchInst& SI(cast<SwitchInst>(I));
01855     // Special case switch instruction to get formatting nice and correct.
01856     Out << ' ';
01857     writeOperand(SI.getCondition(), true);
01858     Out << ", ";
01859     writeOperand(SI.getDefaultDest(), true);
01860     Out << " [";
01861     for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
01862          i != e; ++i) {
01863       Out << "\n    ";
01864       writeOperand(i.getCaseValue(), true);
01865       Out << ", ";
01866       writeOperand(i.getCaseSuccessor(), true);
01867     }
01868     Out << "\n  ]";
01869   } else if (isa<IndirectBrInst>(I)) {
01870     // Special case indirectbr instruction to get formatting nice and correct.
01871     Out << ' ';
01872     writeOperand(Operand, true);
01873     Out << ", [";
01874 
01875     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
01876       if (i != 1)
01877         Out << ", ";
01878       writeOperand(I.getOperand(i), true);
01879     }
01880     Out << ']';
01881   } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
01882     Out << ' ';
01883     TypePrinter.print(I.getType(), Out);
01884     Out << ' ';
01885 
01886     for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
01887       if (op) Out << ", ";
01888       Out << "[ ";
01889       writeOperand(PN->getIncomingValue(op), false); Out << ", ";
01890       writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
01891     }
01892   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
01893     Out << ' ';
01894     writeOperand(I.getOperand(0), true);
01895     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
01896       Out << ", " << *i;
01897   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
01898     Out << ' ';
01899     writeOperand(I.getOperand(0), true); Out << ", ";
01900     writeOperand(I.getOperand(1), true);
01901     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
01902       Out << ", " << *i;
01903   } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
01904     Out << ' ';
01905     TypePrinter.print(I.getType(), Out);
01906     Out << " personality ";
01907     writeOperand(I.getOperand(0), true); Out << '\n';
01908 
01909     if (LPI->isCleanup())
01910       Out << "          cleanup";
01911 
01912     for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
01913       if (i != 0 || LPI->isCleanup()) Out << "\n";
01914       if (LPI->isCatch(i))
01915         Out << "          catch ";
01916       else
01917         Out << "          filter ";
01918 
01919       writeOperand(LPI->getClause(i), true);
01920     }
01921   } else if (isa<ReturnInst>(I) && !Operand) {
01922     Out << " void";
01923   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
01924     // Print the calling convention being used.
01925     if (CI->getCallingConv() != CallingConv::C) {
01926       Out << " ";
01927       PrintCallingConv(CI->getCallingConv(), Out);
01928     }
01929 
01930     Operand = CI->getCalledValue();
01931     PointerType *PTy = cast<PointerType>(Operand->getType());
01932     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
01933     Type *RetTy = FTy->getReturnType();
01934     const AttributeSet &PAL = CI->getAttributes();
01935 
01936     if (PAL.hasAttributes(AttributeSet::ReturnIndex))
01937       Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
01938 
01939     // If possible, print out the short form of the call instruction.  We can
01940     // only do this if the first argument is a pointer to a nonvararg function,
01941     // and if the return type is not a pointer to a function.
01942     //
01943     Out << ' ';
01944     if (!FTy->isVarArg() &&
01945         (!RetTy->isPointerTy() ||
01946          !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
01947       TypePrinter.print(RetTy, Out);
01948       Out << ' ';
01949       writeOperand(Operand, false);
01950     } else {
01951       writeOperand(Operand, true);
01952     }
01953     Out << '(';
01954     for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
01955       if (op > 0)
01956         Out << ", ";
01957       writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
01958     }
01959     Out << ')';
01960     if (PAL.hasAttributes(AttributeSet::FunctionIndex))
01961       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
01962   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
01963     Operand = II->getCalledValue();
01964     PointerType *PTy = cast<PointerType>(Operand->getType());
01965     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
01966     Type *RetTy = FTy->getReturnType();
01967     const AttributeSet &PAL = II->getAttributes();
01968 
01969     // Print the calling convention being used.
01970     if (II->getCallingConv() != CallingConv::C) {
01971       Out << " ";
01972       PrintCallingConv(II->getCallingConv(), Out);
01973     }
01974 
01975     if (PAL.hasAttributes(AttributeSet::ReturnIndex))
01976       Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
01977 
01978     // If possible, print out the short form of the invoke instruction. We can
01979     // only do this if the first argument is a pointer to a nonvararg function,
01980     // and if the return type is not a pointer to a function.
01981     //
01982     Out << ' ';
01983     if (!FTy->isVarArg() &&
01984         (!RetTy->isPointerTy() ||
01985          !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
01986       TypePrinter.print(RetTy, Out);
01987       Out << ' ';
01988       writeOperand(Operand, false);
01989     } else {
01990       writeOperand(Operand, true);
01991     }
01992     Out << '(';
01993     for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
01994       if (op)
01995         Out << ", ";
01996       writeParamOperand(II->getArgOperand(op), PAL, op + 1);
01997     }
01998 
01999     Out << ')';
02000     if (PAL.hasAttributes(AttributeSet::FunctionIndex))
02001       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
02002 
02003     Out << "\n          to ";
02004     writeOperand(II->getNormalDest(), true);
02005     Out << " unwind ";
02006     writeOperand(II->getUnwindDest(), true);
02007 
02008   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
02009     Out << ' ';
02010     if (AI->isUsedWithInAlloca())
02011       Out << "inalloca ";
02012     TypePrinter.print(AI->getAllocatedType(), Out);
02013     if (!AI->getArraySize() || AI->isArrayAllocation()) {
02014       Out << ", ";
02015       writeOperand(AI->getArraySize(), true);
02016     }
02017     if (AI->getAlignment()) {
02018       Out << ", align " << AI->getAlignment();
02019     }
02020   } else if (isa<CastInst>(I)) {
02021     if (Operand) {
02022       Out << ' ';
02023       writeOperand(Operand, true);   // Work with broken code
02024     }
02025     Out << " to ";
02026     TypePrinter.print(I.getType(), Out);
02027   } else if (isa<VAArgInst>(I)) {
02028     if (Operand) {
02029       Out << ' ';
02030       writeOperand(Operand, true);   // Work with broken code
02031     }
02032     Out << ", ";
02033     TypePrinter.print(I.getType(), Out);
02034   } else if (Operand) {   // Print the normal way.
02035 
02036     // PrintAllTypes - Instructions who have operands of all the same type
02037     // omit the type from all but the first operand.  If the instruction has
02038     // different type operands (for example br), then they are all printed.
02039     bool PrintAllTypes = false;
02040     Type *TheType = Operand->getType();
02041 
02042     // Select, Store and ShuffleVector always print all types.
02043     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
02044         || isa<ReturnInst>(I)) {
02045       PrintAllTypes = true;
02046     } else {
02047       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
02048         Operand = I.getOperand(i);
02049         // note that Operand shouldn't be null, but the test helps make dump()
02050         // more tolerant of malformed IR
02051         if (Operand && Operand->getType() != TheType) {
02052           PrintAllTypes = true;    // We have differing types!  Print them all!
02053           break;
02054         }
02055       }
02056     }
02057 
02058     if (!PrintAllTypes) {
02059       Out << ' ';
02060       TypePrinter.print(TheType, Out);
02061     }
02062 
02063     Out << ' ';
02064     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
02065       if (i) Out << ", ";
02066       writeOperand(I.getOperand(i), PrintAllTypes);
02067     }
02068   }
02069 
02070   // Print atomic ordering/alignment for memory operations
02071   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
02072     if (LI->isAtomic())
02073       writeAtomic(LI->getOrdering(), LI->getSynchScope());
02074     if (LI->getAlignment())
02075       Out << ", align " << LI->getAlignment();
02076   } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
02077     if (SI->isAtomic())
02078       writeAtomic(SI->getOrdering(), SI->getSynchScope());
02079     if (SI->getAlignment())
02080       Out << ", align " << SI->getAlignment();
02081   } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
02082     writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
02083                        CXI->getSynchScope());
02084   } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
02085     writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
02086   } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
02087     writeAtomic(FI->getOrdering(), FI->getSynchScope());
02088   }
02089 
02090   // Print Metadata info.
02091   SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
02092   I.getAllMetadata(InstMD);
02093   if (!InstMD.empty()) {
02094     SmallVector<StringRef, 8> MDNames;
02095     I.getType()->getContext().getMDKindNames(MDNames);
02096     for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
02097       unsigned Kind = InstMD[i].first;
02098        if (Kind < MDNames.size()) {
02099          Out << ", !" << MDNames[Kind];
02100        } else {
02101          Out << ", !<unknown kind #" << Kind << ">";
02102        }
02103       Out << ' ';
02104       WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
02105                              TheModule);
02106     }
02107   }
02108   printInfoComment(I);
02109 }
02110 
02111 static void WriteMDNodeComment(const MDNode *Node,
02112                                formatted_raw_ostream &Out) {
02113   if (Node->getNumOperands() < 1)
02114     return;
02115 
02116   Value *Op = Node->getOperand(0);
02117   if (!Op || !isa<ConstantInt>(Op) || cast<ConstantInt>(Op)->getBitWidth() < 32)
02118     return;
02119 
02120   DIDescriptor Desc(Node);
02121   if (!Desc.Verify())
02122     return;
02123 
02124   unsigned Tag = Desc.getTag();
02125   Out.PadToColumn(50);
02126   if (dwarf::TagString(Tag)) {
02127     Out << "; ";
02128     Desc.print(Out);
02129   } else if (Tag == dwarf::DW_TAG_user_base) {
02130     Out << "; [ DW_TAG_user_base ]";
02131   }
02132 }
02133 
02134 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
02135   Out << '!' << Slot << " = metadata ";
02136   printMDNodeBody(Node);
02137 }
02138 
02139 void AssemblyWriter::writeAllMDNodes() {
02140   SmallVector<const MDNode *, 16> Nodes;
02141   Nodes.resize(Machine.mdn_size());
02142   for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
02143        I != E; ++I)
02144     Nodes[I->second] = cast<MDNode>(I->first);
02145 
02146   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
02147     writeMDNode(i, Nodes[i]);
02148   }
02149 }
02150 
02151 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
02152   WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
02153   WriteMDNodeComment(Node, Out);
02154   Out << "\n";
02155 }
02156 
02157 void AssemblyWriter::writeAllAttributeGroups() {
02158   std::vector<std::pair<AttributeSet, unsigned> > asVec;
02159   asVec.resize(Machine.as_size());
02160 
02161   for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
02162        I != E; ++I)
02163     asVec[I->second] = *I;
02164 
02165   for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
02166          I = asVec.begin(), E = asVec.end(); I != E; ++I)
02167     Out << "attributes #" << I->second << " = { "
02168         << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
02169 }
02170 
02171 } // namespace llvm
02172 
02173 //===----------------------------------------------------------------------===//
02174 //                       External Interface declarations
02175 //===----------------------------------------------------------------------===//
02176 
02177 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
02178   SlotTracker SlotTable(this);
02179   formatted_raw_ostream OS(ROS);
02180   AssemblyWriter W(OS, SlotTable, this, AAW);
02181   W.printModule(this);
02182 }
02183 
02184 void NamedMDNode::print(raw_ostream &ROS) const {
02185   SlotTracker SlotTable(getParent());
02186   formatted_raw_ostream OS(ROS);
02187   AssemblyWriter W(OS, SlotTable, getParent(), nullptr);
02188   W.printNamedMDNode(this);
02189 }
02190 
02191 void Comdat::print(raw_ostream &ROS) const {
02192   PrintLLVMName(ROS, getName(), ComdatPrefix);
02193   ROS << " = comdat ";
02194 
02195   switch (getSelectionKind()) {
02196   case Comdat::Any:
02197     ROS << "any";
02198     break;
02199   case Comdat::ExactMatch:
02200     ROS << "exactmatch";
02201     break;
02202   case Comdat::Largest:
02203     ROS << "largest";
02204     break;
02205   case Comdat::NoDuplicates:
02206     ROS << "noduplicates";
02207     break;
02208   case Comdat::SameSize:
02209     ROS << "samesize";
02210     break;
02211   }
02212 
02213   ROS << '\n';
02214 }
02215 
02216 void Type::print(raw_ostream &OS) const {
02217   TypePrinting TP;
02218   TP.print(const_cast<Type*>(this), OS);
02219 
02220   // If the type is a named struct type, print the body as well.
02221   if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
02222     if (!STy->isLiteral()) {
02223       OS << " = type ";
02224       TP.printStructBody(STy, OS);
02225     }
02226 }
02227 
02228 void Value::print(raw_ostream &ROS) const {
02229   formatted_raw_ostream OS(ROS);
02230   if (const Instruction *I = dyn_cast<Instruction>(this)) {
02231     const Function *F = I->getParent() ? I->getParent()->getParent() : nullptr;
02232     SlotTracker SlotTable(F);
02233     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr);
02234     W.printInstruction(*I);
02235   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
02236     SlotTracker SlotTable(BB->getParent());
02237     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr);
02238     W.printBasicBlock(BB);
02239   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
02240     SlotTracker SlotTable(GV->getParent());
02241     AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr);
02242     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
02243       W.printGlobal(V);
02244     else if (const Function *F = dyn_cast<Function>(GV))
02245       W.printFunction(F);
02246     else
02247       W.printAlias(cast<GlobalAlias>(GV));
02248   } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
02249     const Function *F = N->getFunction();
02250     SlotTracker SlotTable(F);
02251     AssemblyWriter W(OS, SlotTable, F ? F->getParent() : nullptr, nullptr);
02252     W.printMDNodeBody(N);
02253   } else if (const Constant *C = dyn_cast<Constant>(this)) {
02254     TypePrinting TypePrinter;
02255     TypePrinter.print(C->getType(), OS);
02256     OS << ' ';
02257     WriteConstantInternal(OS, C, TypePrinter, nullptr, nullptr);
02258   } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
02259              isa<Argument>(this)) {
02260     this->printAsOperand(OS);
02261   } else {
02262     llvm_unreachable("Unknown value to print out!");
02263   }
02264 }
02265 
02266 void Value::printAsOperand(raw_ostream &O, bool PrintType, const Module *M) const {
02267   // Fast path: Don't construct and populate a TypePrinting object if we
02268   // won't be needing any types printed.
02269   if (!PrintType &&
02270       ((!isa<Constant>(this) && !isa<MDNode>(this)) ||
02271        hasName() || isa<GlobalValue>(this))) {
02272     WriteAsOperandInternal(O, this, nullptr, nullptr, M);
02273     return;
02274   }
02275 
02276   if (!M)
02277     M = getModuleFromVal(this);
02278 
02279   TypePrinting TypePrinter;
02280   if (M)
02281     TypePrinter.incorporateTypes(*M);
02282   if (PrintType) {
02283     TypePrinter.print(getType(), O);
02284     O << ' ';
02285   }
02286 
02287   WriteAsOperandInternal(O, this, &TypePrinter, nullptr, M);
02288 }
02289 
02290 // Value::dump - allow easy printing of Values from the debugger.
02291 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
02292 
02293 // Type::dump - allow easy printing of Types from the debugger.
02294 void Type::dump() const { print(dbgs()); }
02295 
02296 // Module::dump() - Allow printing of Modules from the debugger.
02297 void Module::dump() const { print(dbgs(), nullptr); }
02298 
02299 // \brief Allow printing of Comdats from the debugger.
02300 void Comdat::dump() const { print(dbgs()); }
02301 
02302 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
02303 void NamedMDNode::dump() const { print(dbgs()); }