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