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