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 was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This library implements the functionality defined in llvm/Assembly/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 "llvm/Assembly/CachedWriter.h"
00018 #include "llvm/Assembly/Writer.h"
00019 #include "llvm/Assembly/PrintModulePass.h"
00020 #include "llvm/Assembly/AsmAnnotationWriter.h"
00021 #include "llvm/CallingConv.h"
00022 #include "llvm/Constants.h"
00023 #include "llvm/DerivedTypes.h"
00024 #include "llvm/InlineAsm.h"
00025 #include "llvm/Instruction.h"
00026 #include "llvm/Instructions.h"
00027 #include "llvm/Module.h"
00028 #include "llvm/SymbolTable.h"
00029 #include "llvm/Support/CFG.h"
00030 #include "llvm/ADT/StringExtras.h"
00031 #include "llvm/ADT/STLExtras.h"
00032 #include "llvm/Support/MathExtras.h"
00033 #include <algorithm>
00034 using namespace llvm;
00035 
00036 namespace llvm {
00037 
00038 // Make virtual table appear in this compilation unit.
00039 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
00040 
00041 /// This class provides computation of slot numbers for LLVM Assembly writing.
00042 /// @brief LLVM Assembly Writing Slot Computation.
00043 class SlotMachine {
00044 
00045 /// @name Types
00046 /// @{
00047 public:
00048 
00049   /// @brief A mapping of Values to slot numbers
00050   typedef std::map<const Value*, unsigned> ValueMap;
00051   typedef std::map<const Type*, unsigned> TypeMap;
00052 
00053   /// @brief A plane with next slot number and ValueMap
00054   struct ValuePlane {
00055     unsigned next_slot;        ///< The next slot number to use
00056     ValueMap map;              ///< The map of Value* -> unsigned
00057     ValuePlane() { next_slot = 0; } ///< Make sure we start at 0
00058   };
00059 
00060   struct TypePlane {
00061     unsigned next_slot;
00062     TypeMap map;
00063     TypePlane() { next_slot = 0; }
00064     void clear() { map.clear(); next_slot = 0; }
00065   };
00066 
00067   /// @brief The map of planes by Type
00068   typedef std::map<const Type*, ValuePlane> TypedPlanes;
00069 
00070 /// @}
00071 /// @name Constructors
00072 /// @{
00073 public:
00074   /// @brief Construct from a module
00075   SlotMachine(const Module *M );
00076 
00077   /// @brief Construct from a function, starting out in incorp state.
00078   SlotMachine(const Function *F );
00079 
00080 /// @}
00081 /// @name Accessors
00082 /// @{
00083 public:
00084   /// Return the slot number of the specified value in it's type
00085   /// plane.  Its an error to ask for something not in the SlotMachine.
00086   /// Its an error to ask for a Type*
00087   int getSlot(const Value *V);
00088   int getSlot(const Type*Ty);
00089 
00090   /// Determine if a Value has a slot or not
00091   bool hasSlot(const Value* V);
00092   bool hasSlot(const Type* Ty);
00093 
00094 /// @}
00095 /// @name Mutators
00096 /// @{
00097 public:
00098   /// If you'd like to deal with a function instead of just a module, use
00099   /// this method to get its data into the SlotMachine.
00100   void incorporateFunction(const Function *F) {
00101     TheFunction = F;
00102     FunctionProcessed = false;
00103   }
00104 
00105   /// After calling incorporateFunction, use this method to remove the
00106   /// most recently incorporated function from the SlotMachine. This
00107   /// will reset the state of the machine back to just the module contents.
00108   void purgeFunction();
00109 
00110 /// @}
00111 /// @name Implementation Details
00112 /// @{
00113 private:
00114   /// This function does the actual initialization.
00115   inline void initialize();
00116 
00117   /// Values can be crammed into here at will. If they haven't
00118   /// been inserted already, they get inserted, otherwise they are ignored.
00119   /// Either way, the slot number for the Value* is returned.
00120   unsigned createSlot(const Value *V);
00121   unsigned createSlot(const Type* Ty);
00122 
00123   /// Insert a value into the value table. Return the slot number
00124   /// that it now occupies.  BadThings(TM) will happen if you insert a
00125   /// Value that's already been inserted.
00126   unsigned insertValue( const Value *V );
00127   unsigned insertValue( const Type* Ty);
00128 
00129   /// Add all of the module level global variables (and their initializers)
00130   /// and function declarations, but not the contents of those functions.
00131   void processModule();
00132 
00133   /// Add all of the functions arguments, basic blocks, and instructions
00134   void processFunction();
00135 
00136   SlotMachine(const SlotMachine &);  // DO NOT IMPLEMENT
00137   void operator=(const SlotMachine &);  // DO NOT IMPLEMENT
00138 
00139 /// @}
00140 /// @name Data
00141 /// @{
00142 public:
00143 
00144   /// @brief The module for which we are holding slot numbers
00145   const Module* TheModule;
00146 
00147   /// @brief The function for which we are holding slot numbers
00148   const Function* TheFunction;
00149   bool FunctionProcessed;
00150 
00151   /// @brief The TypePlanes map for the module level data
00152   TypedPlanes mMap;
00153   TypePlane mTypes;
00154 
00155   /// @brief The TypePlanes map for the function level data
00156   TypedPlanes fMap;
00157   TypePlane fTypes;
00158 
00159 /// @}
00160 
00161 };
00162 
00163 }  // end namespace llvm
00164 
00165 static RegisterPass<PrintModulePass>
00166 X("printm", "Print module to stderr",PassInfo::Analysis|PassInfo::Optimization);
00167 static RegisterPass<PrintFunctionPass>
00168 Y("print","Print function to stderr",PassInfo::Analysis|PassInfo::Optimization);
00169 
00170 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
00171                                    bool PrintName,
00172                                  std::map<const Type *, std::string> &TypeTable,
00173                                    SlotMachine *Machine);
00174 
00175 static void WriteAsOperandInternal(std::ostream &Out, const Type *T,
00176                                    bool PrintName,
00177                                  std::map<const Type *, std::string> &TypeTable,
00178                                    SlotMachine *Machine);
00179 
00180 static const Module *getModuleFromVal(const Value *V) {
00181   if (const Argument *MA = dyn_cast<Argument>(V))
00182     return MA->getParent() ? MA->getParent()->getParent() : 0;
00183   else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
00184     return BB->getParent() ? BB->getParent()->getParent() : 0;
00185   else if (const Instruction *I = dyn_cast<Instruction>(V)) {
00186     const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
00187     return M ? M->getParent() : 0;
00188   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
00189     return GV->getParent();
00190   return 0;
00191 }
00192 
00193 static SlotMachine *createSlotMachine(const Value *V) {
00194   if (const Argument *FA = dyn_cast<Argument>(V)) {
00195     return new SlotMachine(FA->getParent());
00196   } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
00197     return new SlotMachine(I->getParent()->getParent());
00198   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
00199     return new SlotMachine(BB->getParent());
00200   } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
00201     return new SlotMachine(GV->getParent());
00202   } else if (const Function *Func = dyn_cast<Function>(V)) {
00203     return new SlotMachine(Func);
00204   }
00205   return 0;
00206 }
00207 
00208 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
00209 // prefixed with % (if the string only contains simple characters) or is
00210 // surrounded with ""'s (if it has special chars in it).
00211 static std::string getLLVMName(const std::string &Name,
00212                                bool prefixName = true) {
00213   assert(!Name.empty() && "Cannot get empty name!");
00214 
00215   // First character cannot start with a number...
00216   if (Name[0] >= '0' && Name[0] <= '9')
00217     return "\"" + Name + "\"";
00218 
00219   // Scan to see if we have any characters that are not on the "white list"
00220   for (unsigned i = 0, e = Name.size(); i != e; ++i) {
00221     char C = Name[i];
00222     assert(C != '"' && "Illegal character in LLVM value name!");
00223     if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
00224         C != '-' && C != '.' && C != '_')
00225       return "\"" + Name + "\"";
00226   }
00227 
00228   // If we get here, then the identifier is legal to use as a "VarID".
00229   if (prefixName)
00230     return "%"+Name;
00231   else
00232     return Name;
00233 }
00234 
00235 
00236 /// fillTypeNameTable - If the module has a symbol table, take all global types
00237 /// and stuff their names into the TypeNames map.
00238 ///
00239 static void fillTypeNameTable(const Module *M,
00240                               std::map<const Type *, std::string> &TypeNames) {
00241   if (!M) return;
00242   const SymbolTable &ST = M->getSymbolTable();
00243   SymbolTable::type_const_iterator TI = ST.type_begin();
00244   for (; TI != ST.type_end(); ++TI ) {
00245     // As a heuristic, don't insert pointer to primitive types, because
00246     // they are used too often to have a single useful name.
00247     //
00248     const Type *Ty = cast<Type>(TI->second);
00249     if (!isa<PointerType>(Ty) ||
00250         !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
00251         isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
00252       TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
00253   }
00254 }
00255 
00256 
00257 
00258 static void calcTypeName(const Type *Ty,
00259                          std::vector<const Type *> &TypeStack,
00260                          std::map<const Type *, std::string> &TypeNames,
00261                          std::string & Result){
00262   if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) {
00263     Result += Ty->getDescription();  // Base case
00264     return;
00265   }
00266 
00267   // Check to see if the type is named.
00268   std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
00269   if (I != TypeNames.end()) {
00270     Result += I->second;
00271     return;
00272   }
00273 
00274   if (isa<OpaqueType>(Ty)) {
00275     Result += "opaque";
00276     return;
00277   }
00278 
00279   // Check to see if the Type is already on the stack...
00280   unsigned Slot = 0, CurSize = TypeStack.size();
00281   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
00282 
00283   // This is another base case for the recursion.  In this case, we know
00284   // that we have looped back to a type that we have previously visited.
00285   // Generate the appropriate upreference to handle this.
00286   if (Slot < CurSize) {
00287     Result += "\\" + utostr(CurSize-Slot);     // Here's the upreference
00288     return;
00289   }
00290 
00291   TypeStack.push_back(Ty);    // Recursive case: Add us to the stack..
00292 
00293   switch (Ty->getTypeID()) {
00294   case Type::FunctionTyID: {
00295     const FunctionType *FTy = cast<FunctionType>(Ty);
00296     calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
00297     Result += " (";
00298     for (FunctionType::param_iterator I = FTy->param_begin(),
00299            E = FTy->param_end(); I != E; ++I) {
00300       if (I != FTy->param_begin())
00301         Result += ", ";
00302       calcTypeName(*I, TypeStack, TypeNames, Result);
00303     }
00304     if (FTy->isVarArg()) {
00305       if (FTy->getNumParams()) Result += ", ";
00306       Result += "...";
00307     }
00308     Result += ")";
00309     break;
00310   }
00311   case Type::StructTyID: {
00312     const StructType *STy = cast<StructType>(Ty);
00313     Result += "{ ";
00314     for (StructType::element_iterator I = STy->element_begin(),
00315            E = STy->element_end(); I != E; ++I) {
00316       if (I != STy->element_begin())
00317         Result += ", ";
00318       calcTypeName(*I, TypeStack, TypeNames, Result);
00319     }
00320     Result += " }";
00321     break;
00322   }
00323   case Type::PointerTyID:
00324     calcTypeName(cast<PointerType>(Ty)->getElementType(),
00325                           TypeStack, TypeNames, Result);
00326     Result += "*";
00327     break;
00328   case Type::ArrayTyID: {
00329     const ArrayType *ATy = cast<ArrayType>(Ty);
00330     Result += "[" + utostr(ATy->getNumElements()) + " x ";
00331     calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
00332     Result += "]";
00333     break;
00334   }
00335   case Type::PackedTyID: {
00336     const PackedType *PTy = cast<PackedType>(Ty);
00337     Result += "<" + utostr(PTy->getNumElements()) + " x ";
00338     calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
00339     Result += ">";
00340     break;
00341   }
00342   case Type::OpaqueTyID:
00343     Result += "opaque";
00344     break;
00345   default:
00346     Result += "<unrecognized-type>";
00347   }
00348 
00349   TypeStack.pop_back();       // Remove self from stack...
00350   return;
00351 }
00352 
00353 
00354 /// printTypeInt - The internal guts of printing out a type that has a
00355 /// potentially named portion.
00356 ///
00357 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
00358                               std::map<const Type *, std::string> &TypeNames) {
00359   // Primitive types always print out their description, regardless of whether
00360   // they have been named or not.
00361   //
00362   if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
00363     return Out << Ty->getDescription();
00364 
00365   // Check to see if the type is named.
00366   std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
00367   if (I != TypeNames.end()) return Out << I->second;
00368 
00369   // Otherwise we have a type that has not been named but is a derived type.
00370   // Carefully recurse the type hierarchy to print out any contained symbolic
00371   // names.
00372   //
00373   std::vector<const Type *> TypeStack;
00374   std::string TypeName;
00375   calcTypeName(Ty, TypeStack, TypeNames, TypeName);
00376   TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
00377   return (Out << TypeName);
00378 }
00379 
00380 
00381 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
00382 /// type, iff there is an entry in the modules symbol table for the specified
00383 /// type or one of it's component types. This is slower than a simple x << Type
00384 ///
00385 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
00386                                       const Module *M) {
00387   Out << ' ';
00388 
00389   // If they want us to print out a type, attempt to make it symbolic if there
00390   // is a symbol table in the module...
00391   if (M) {
00392     std::map<const Type *, std::string> TypeNames;
00393     fillTypeNameTable(M, TypeNames);
00394 
00395     return printTypeInt(Out, Ty, TypeNames);
00396   } else {
00397     return Out << Ty->getDescription();
00398   }
00399 }
00400 
00401 // PrintEscapedString - Print each character of the specified string, escaping
00402 // it if it is not printable or if it is an escape char.
00403 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
00404   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
00405     unsigned char C = Str[i];
00406     if (isprint(C) && C != '"' && C != '\\') {
00407       Out << C;
00408     } else {
00409       Out << '\\'
00410           << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
00411           << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
00412     }
00413   }
00414 }
00415 
00416 /// @brief Internal constant writer.
00417 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
00418                              bool PrintName,
00419                              std::map<const Type *, std::string> &TypeTable,
00420                              SlotMachine *Machine) {
00421   const int IndentSize = 4;
00422   static std::string Indent = "\n";
00423   if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
00424     Out << (CB == ConstantBool::True ? "true" : "false");
00425   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
00426     Out << CI->getValue();
00427   } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
00428     Out << CI->getValue();
00429   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
00430     // We would like to output the FP constant value in exponential notation,
00431     // but we cannot do this if doing so will lose precision.  Check here to
00432     // make sure that we only output it in exponential format if we can parse
00433     // the value back and get the same value.
00434     //
00435     std::string StrVal = ftostr(CFP->getValue());
00436 
00437     // Check to make sure that the stringized number is not some string like
00438     // "Inf" or NaN, that atof will accept, but the lexer will not.  Check that
00439     // the string matches the "[-+]?[0-9]" regex.
00440     //
00441     if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
00442         ((StrVal[0] == '-' || StrVal[0] == '+') &&
00443          (StrVal[1] >= '0' && StrVal[1] <= '9')))
00444       // Reparse stringized version!
00445       if (atof(StrVal.c_str()) == CFP->getValue()) {
00446         Out << StrVal;
00447         return;
00448       }
00449 
00450     // Otherwise we could not reparse it to exactly the same value, so we must
00451     // output the string in hexadecimal format!
00452     assert(sizeof(double) == sizeof(uint64_t) &&
00453            "assuming that double is 64 bits!");
00454     Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
00455 
00456   } else if (isa<ConstantAggregateZero>(CV)) {
00457     Out << "zeroinitializer";
00458   } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
00459     // As a special case, print the array as a string if it is an array of
00460     // ubytes or an array of sbytes with positive values.
00461     //
00462     const Type *ETy = CA->getType()->getElementType();
00463     if (CA->isString()) {
00464       Out << "c\"";
00465       PrintEscapedString(CA->getAsString(), Out);
00466       Out << "\"";
00467 
00468     } else {                // Cannot output in string format...
00469       Out << '[';
00470       if (CA->getNumOperands()) {
00471         Out << ' ';
00472         printTypeInt(Out, ETy, TypeTable);
00473         WriteAsOperandInternal(Out, CA->getOperand(0),
00474                                PrintName, TypeTable, Machine);
00475         for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
00476           Out << ", ";
00477           printTypeInt(Out, ETy, TypeTable);
00478           WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
00479                                  TypeTable, Machine);
00480         }
00481       }
00482       Out << " ]";
00483     }
00484   } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
00485     Out << '{';
00486     unsigned N = CS->getNumOperands();
00487     if (N) {
00488       if (N > 2) {
00489         Indent += std::string(IndentSize, ' ');
00490         Out << Indent;
00491       } else {
00492         Out << ' ';
00493       }
00494       printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
00495 
00496       WriteAsOperandInternal(Out, CS->getOperand(0),
00497                              PrintName, TypeTable, Machine);
00498 
00499       for (unsigned i = 1; i < N; i++) {
00500         Out << ", ";
00501         if (N > 2) Out << Indent;
00502         printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
00503 
00504         WriteAsOperandInternal(Out, CS->getOperand(i),
00505                                PrintName, TypeTable, Machine);
00506       }
00507       if (N > 2) Indent.resize(Indent.size() - IndentSize);
00508     }
00509  
00510     Out << " }";
00511   } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
00512       const Type *ETy = CP->getType()->getElementType();
00513       assert(CP->getNumOperands() > 0 &&
00514              "Number of operands for a PackedConst must be > 0");
00515       Out << '<';
00516       Out << ' ';
00517       printTypeInt(Out, ETy, TypeTable);
00518       WriteAsOperandInternal(Out, CP->getOperand(0),
00519                              PrintName, TypeTable, Machine);
00520       for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
00521           Out << ", ";
00522           printTypeInt(Out, ETy, TypeTable);
00523           WriteAsOperandInternal(Out, CP->getOperand(i), PrintName,
00524                                  TypeTable, Machine);
00525       }
00526       Out << " >";
00527   } else if (isa<ConstantPointerNull>(CV)) {
00528     Out << "null";
00529 
00530   } else if (isa<UndefValue>(CV)) {
00531     Out << "undef";
00532 
00533   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
00534     Out << CE->getOpcodeName() << " (";
00535 
00536     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
00537       printTypeInt(Out, (*OI)->getType(), TypeTable);
00538       WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Machine);
00539       if (OI+1 != CE->op_end())
00540         Out << ", ";
00541     }
00542 
00543     if (CE->getOpcode() == Instruction::Cast) {
00544       Out << " to ";
00545       printTypeInt(Out, CE->getType(), TypeTable);
00546     }
00547     Out << ')';
00548 
00549   } else {
00550     Out << "<placeholder or erroneous Constant>";
00551   }
00552 }
00553 
00554 
00555 /// WriteAsOperand - Write the name of the specified value out to the specified
00556 /// ostream.  This can be useful when you just want to print int %reg126, not
00557 /// the whole instruction that generated it.
00558 ///
00559 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
00560                                    bool PrintName,
00561                                   std::map<const Type*, std::string> &TypeTable,
00562                                    SlotMachine *Machine) {
00563   Out << ' ';
00564   if ((PrintName || isa<GlobalValue>(V)) && V->hasName())
00565     Out << getLLVMName(V->getName());
00566   else {
00567     const Constant *CV = dyn_cast<Constant>(V);
00568     if (CV && !isa<GlobalValue>(CV)) {
00569       WriteConstantInt(Out, CV, PrintName, TypeTable, Machine);
00570     } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
00571       Out << "asm ";
00572       if (IA->hasSideEffects())
00573         Out << "sideeffect ";
00574       Out << '"';
00575       PrintEscapedString(IA->getAsmString(), Out);
00576       Out << "\", \"";
00577       PrintEscapedString(IA->getConstraintString(), Out);
00578       Out << '"';
00579     } else {
00580       int Slot;
00581       if (Machine) {
00582         Slot = Machine->getSlot(V);
00583       } else {
00584         Machine = createSlotMachine(V);
00585         if (Machine == 0)
00586           Slot = Machine->getSlot(V);
00587         else
00588           Slot = -1;
00589         delete Machine;
00590       }
00591       if (Slot != -1)
00592         Out << '%' << Slot;
00593       else
00594         Out << "<badref>";
00595     }
00596   }
00597 }
00598 
00599 /// WriteAsOperand - Write the name of the specified value out to the specified
00600 /// ostream.  This can be useful when you just want to print int %reg126, not
00601 /// the whole instruction that generated it.
00602 ///
00603 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
00604                                    bool PrintType, bool PrintName,
00605                                    const Module *Context) {
00606   std::map<const Type *, std::string> TypeNames;
00607   if (Context == 0) Context = getModuleFromVal(V);
00608 
00609   if (Context)
00610     fillTypeNameTable(Context, TypeNames);
00611 
00612   if (PrintType)
00613     printTypeInt(Out, V->getType(), TypeNames);
00614 
00615   WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
00616   return Out;
00617 }
00618 
00619 /// WriteAsOperandInternal - Write the name of the specified value out to
00620 /// the specified ostream.  This can be useful when you just want to print
00621 /// int %reg126, not the whole instruction that generated it.
00622 ///
00623 static void WriteAsOperandInternal(std::ostream &Out, const Type *T,
00624                                    bool PrintName,
00625                                   std::map<const Type*, std::string> &TypeTable,
00626                                    SlotMachine *Machine) {
00627   Out << ' ';
00628   int Slot;
00629   if (Machine) {
00630     Slot = Machine->getSlot(T);
00631     if (Slot != -1)
00632       Out << '%' << Slot;
00633     else
00634       Out << "<badref>";
00635   } else {
00636     Out << T->getDescription();
00637   }
00638 }
00639 
00640 /// WriteAsOperand - Write the name of the specified value out to the specified
00641 /// ostream.  This can be useful when you just want to print int %reg126, not
00642 /// the whole instruction that generated it.
00643 ///
00644 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Type *Ty,
00645                                    bool PrintType, bool PrintName,
00646                                    const Module *Context) {
00647   std::map<const Type *, std::string> TypeNames;
00648   assert(Context != 0 && "Can't write types as operand without module context");
00649 
00650   fillTypeNameTable(Context, TypeNames);
00651 
00652   // if (PrintType)
00653     // printTypeInt(Out, V->getType(), TypeNames);
00654 
00655   printTypeInt(Out, Ty, TypeNames);
00656 
00657   WriteAsOperandInternal(Out, Ty, PrintName, TypeNames, 0);
00658   return Out;
00659 }
00660 
00661 namespace llvm {
00662 
00663 class AssemblyWriter {
00664   std::ostream &Out;
00665   SlotMachine &Machine;
00666   const Module *TheModule;
00667   std::map<const Type *, std::string> TypeNames;
00668   AssemblyAnnotationWriter *AnnotationWriter;
00669 public:
00670   inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
00671                         AssemblyAnnotationWriter *AAW)
00672     : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
00673 
00674     // If the module has a symbol table, take all global types and stuff their
00675     // names into the TypeNames map.
00676     //
00677     fillTypeNameTable(M, TypeNames);
00678   }
00679 
00680   inline void write(const Module *M)         { printModule(M);      }
00681   inline void write(const GlobalVariable *G) { printGlobal(G);      }
00682   inline void write(const Function *F)       { printFunction(F);    }
00683   inline void write(const BasicBlock *BB)    { printBasicBlock(BB); }
00684   inline void write(const Instruction *I)    { printInstruction(*I); }
00685   inline void write(const Constant *CPV)     { printConstant(CPV);  }
00686   inline void write(const Type *Ty)          { printType(Ty);       }
00687 
00688   void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
00689 
00690   const Module* getModule() { return TheModule; }
00691 
00692 private:
00693   void printModule(const Module *M);
00694   void printSymbolTable(const SymbolTable &ST);
00695   void printConstant(const Constant *CPV);
00696   void printGlobal(const GlobalVariable *GV);
00697   void printFunction(const Function *F);
00698   void printArgument(const Argument *FA);
00699   void printBasicBlock(const BasicBlock *BB);
00700   void printInstruction(const Instruction &I);
00701 
00702   // printType - Go to extreme measures to attempt to print out a short,
00703   // symbolic version of a type name.
00704   //
00705   std::ostream &printType(const Type *Ty) {
00706     return printTypeInt(Out, Ty, TypeNames);
00707   }
00708 
00709   // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
00710   // without considering any symbolic types that we may have equal to it.
00711   //
00712   std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
00713 
00714   // printInfoComment - Print a little comment after the instruction indicating
00715   // which slot it occupies.
00716   void printInfoComment(const Value &V);
00717 };
00718 }  // end of llvm namespace
00719 
00720 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
00721 /// without considering any symbolic types that we may have equal to it.
00722 ///
00723 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
00724   if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
00725     printType(FTy->getReturnType()) << " (";
00726     for (FunctionType::param_iterator I = FTy->param_begin(),
00727            E = FTy->param_end(); I != E; ++I) {
00728       if (I != FTy->param_begin())
00729         Out << ", ";
00730       printType(*I);
00731     }
00732     if (FTy->isVarArg()) {
00733       if (FTy->getNumParams()) Out << ", ";
00734       Out << "...";
00735     }
00736     Out << ')';
00737   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
00738     Out << "{ ";
00739     for (StructType::element_iterator I = STy->element_begin(),
00740            E = STy->element_end(); I != E; ++I) {
00741       if (I != STy->element_begin())
00742         Out << ", ";
00743       printType(*I);
00744     }
00745     Out << " }";
00746   } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
00747     printType(PTy->getElementType()) << '*';
00748   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
00749     Out << '[' << ATy->getNumElements() << " x ";
00750     printType(ATy->getElementType()) << ']';
00751   } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
00752     Out << '<' << PTy->getNumElements() << " x ";
00753     printType(PTy->getElementType()) << '>';
00754   }
00755   else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
00756     Out << "opaque";
00757   } else {
00758     if (!Ty->isPrimitiveType())
00759       Out << "<unknown derived type>";
00760     printType(Ty);
00761   }
00762   return Out;
00763 }
00764 
00765 
00766 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
00767                                   bool PrintName) {
00768   if (Operand != 0) {
00769     if (PrintType) { Out << ' '; printType(Operand->getType()); }
00770     WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Machine);
00771   } else {
00772     Out << "<null operand!>";
00773   }
00774 }
00775 
00776 
00777 void AssemblyWriter::printModule(const Module *M) {
00778   if (!M->getModuleIdentifier().empty() &&
00779       // Don't print the ID if it will start a new line (which would
00780       // require a comment char before it).
00781       M->getModuleIdentifier().find('\n') == std::string::npos)
00782     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
00783 
00784   switch (M->getEndianness()) {
00785   case Module::LittleEndian: Out << "target endian = little\n"; break;
00786   case Module::BigEndian:    Out << "target endian = big\n";    break;
00787   case Module::AnyEndianness: break;
00788   }
00789   switch (M->getPointerSize()) {
00790   case Module::Pointer32:    Out << "target pointersize = 32\n"; break;
00791   case Module::Pointer64:    Out << "target pointersize = 64\n"; break;
00792   case Module::AnyPointerSize: break;
00793   }
00794   if (!M->getTargetTriple().empty())
00795     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
00796 
00797   if (!M->getModuleInlineAsm().empty()) {
00798     // Split the string into lines, to make it easier to read the .ll file.
00799     std::string Asm = M->getModuleInlineAsm();
00800     size_t CurPos = 0;
00801     size_t NewLine = Asm.find_first_of('\n', CurPos);
00802     while (NewLine != std::string::npos) {
00803       // We found a newline, print the portion of the asm string from the
00804       // last newline up to this newline.
00805       Out << "module asm \"";
00806       PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
00807                          Out);
00808       Out << "\"\n";
00809       CurPos = NewLine+1;
00810       NewLine = Asm.find_first_of('\n', CurPos);
00811     }
00812     Out << "module asm \"";
00813     PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
00814     Out << "\"\n";
00815   }
00816   
00817   // Loop over the dependent libraries and emit them.
00818   Module::lib_iterator LI = M->lib_begin();
00819   Module::lib_iterator LE = M->lib_end();
00820   if (LI != LE) {
00821     Out << "deplibs = [ ";
00822     while (LI != LE) {
00823       Out << '"' << *LI << '"';
00824       ++LI;
00825       if (LI != LE)
00826         Out << ", ";
00827     }
00828     Out << " ]\n";
00829   }
00830 
00831   // Loop over the symbol table, emitting all named constants.
00832   printSymbolTable(M->getSymbolTable());
00833 
00834   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end(); I != E; ++I)
00835     printGlobal(I);
00836 
00837   Out << "\nimplementation   ; Functions:\n";
00838 
00839   // Output all of the functions.
00840   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
00841     printFunction(I);
00842 }
00843 
00844 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
00845   if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
00846 
00847   if (!GV->hasInitializer())
00848     Out << "external ";
00849   else
00850     switch (GV->getLinkage()) {
00851     case GlobalValue::InternalLinkage:  Out << "internal "; break;
00852     case GlobalValue::LinkOnceLinkage:  Out << "linkonce "; break;
00853     case GlobalValue::WeakLinkage:      Out << "weak "; break;
00854     case GlobalValue::AppendingLinkage: Out << "appending "; break;
00855     case GlobalValue::ExternalLinkage: break;
00856     case GlobalValue::GhostLinkage:
00857       std::cerr << "GhostLinkage not allowed in AsmWriter!\n";
00858       abort();
00859     }
00860 
00861   Out << (GV->isConstant() ? "constant " : "global ");
00862   printType(GV->getType()->getElementType());
00863 
00864   if (GV->hasInitializer()) {
00865     Constant* C = cast<Constant>(GV->getInitializer());
00866     assert(C &&  "GlobalVar initializer isn't constant?");
00867     writeOperand(GV->getInitializer(), false, isa<GlobalValue>(C));
00868   }
00869   
00870   if (GV->hasSection())
00871     Out << ", section \"" << GV->getSection() << '"';
00872   if (GV->getAlignment())
00873     Out << ", align " << GV->getAlignment();
00874   
00875   printInfoComment(*GV);
00876   Out << "\n";
00877 }
00878 
00879 
00880 // printSymbolTable - Run through symbol table looking for constants
00881 // and types. Emit their declarations.
00882 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
00883 
00884   // Print the types.
00885   for (SymbolTable::type_const_iterator TI = ST.type_begin();
00886        TI != ST.type_end(); ++TI ) {
00887     Out << "\t" << getLLVMName(TI->first) << " = type ";
00888 
00889     // Make sure we print out at least one level of the type structure, so
00890     // that we do not get %FILE = type %FILE
00891     //
00892     printTypeAtLeastOneLevel(TI->second) << "\n";
00893   }
00894 
00895   // Print the constants, in type plane order.
00896   for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
00897        PI != ST.plane_end(); ++PI ) {
00898     SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
00899     SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
00900 
00901     for (; VI != VE; ++VI) {
00902       const Value* V = VI->second;
00903       const Constant *CPV = dyn_cast<Constant>(V) ;
00904       if (CPV && !isa<GlobalValue>(V)) {
00905         printConstant(CPV);
00906       }
00907     }
00908   }
00909 }
00910 
00911 
00912 /// printConstant - Print out a constant pool entry...
00913 ///
00914 void AssemblyWriter::printConstant(const Constant *CPV) {
00915   // Don't print out unnamed constants, they will be inlined
00916   if (!CPV->hasName()) return;
00917 
00918   // Print out name...
00919   Out << "\t" << getLLVMName(CPV->getName()) << " =";
00920 
00921   // Write the value out now...
00922   writeOperand(CPV, true, false);
00923 
00924   printInfoComment(*CPV);
00925   Out << "\n";
00926 }
00927 
00928 /// printFunction - Print all aspects of a function.
00929 ///
00930 void AssemblyWriter::printFunction(const Function *F) {
00931   // Print out the return type and name...
00932   Out << "\n";
00933 
00934   // Ensure that no local symbols conflict with global symbols.
00935   const_cast<Function*>(F)->renameLocalSymbols();
00936 
00937   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
00938 
00939   if (F->isExternal())
00940     Out << "declare ";
00941   else
00942     switch (F->getLinkage()) {
00943     case GlobalValue::InternalLinkage:  Out << "internal "; break;
00944     case GlobalValue::LinkOnceLinkage:  Out << "linkonce "; break;
00945     case GlobalValue::WeakLinkage:      Out << "weak "; break;
00946     case GlobalValue::AppendingLinkage: Out << "appending "; break;
00947     case GlobalValue::ExternalLinkage: break;
00948     case GlobalValue::GhostLinkage:
00949       std::cerr << "GhostLinkage not allowed in AsmWriter!\n";
00950       abort();
00951     }
00952 
00953   // Print the calling convention.
00954   switch (F->getCallingConv()) {
00955   case CallingConv::C: break;   // default
00956   case CallingConv::Fast: Out << "fastcc "; break;
00957   case CallingConv::Cold: Out << "coldcc "; break;
00958   default: Out << "cc" << F->getCallingConv() << " "; break;
00959   }
00960 
00961   printType(F->getReturnType()) << ' ';
00962   if (!F->getName().empty())
00963     Out << getLLVMName(F->getName());
00964   else
00965     Out << "\"\"";
00966   Out << '(';
00967   Machine.incorporateFunction(F);
00968 
00969   // Loop over the arguments, printing them...
00970   const FunctionType *FT = F->getFunctionType();
00971 
00972   for(Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
00973     printArgument(I);
00974 
00975   // Finish printing arguments...
00976   if (FT->isVarArg()) {
00977     if (FT->getNumParams()) Out << ", ";
00978     Out << "...";  // Output varargs portion of signature!
00979   }
00980   Out << ')';
00981 
00982   if (F->hasSection())
00983     Out << " section \"" << F->getSection() << '"';
00984   if (F->getAlignment())
00985     Out << " align " << F->getAlignment();
00986 
00987   if (F->isExternal()) {
00988     Out << "\n";
00989   } else {
00990     Out << " {";
00991 
00992     // Output all of its basic blocks... for the function
00993     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
00994       printBasicBlock(I);
00995 
00996     Out << "}\n";
00997   }
00998 
00999   Machine.purgeFunction();
01000 }
01001 
01002 /// printArgument - This member is called for every argument that is passed into
01003 /// the function.  Simply print it out
01004 ///
01005 void AssemblyWriter::printArgument(const Argument *Arg) {
01006   // Insert commas as we go... the first arg doesn't get a comma
01007   if (Arg != Arg->getParent()->arg_begin()) Out << ", ";
01008 
01009   // Output type...
01010   printType(Arg->getType());
01011 
01012   // Output name, if available...
01013   if (Arg->hasName())
01014     Out << ' ' << getLLVMName(Arg->getName());
01015 }
01016 
01017 /// printBasicBlock - This member is called for each basic block in a method.
01018 ///
01019 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
01020   if (BB->hasName()) {              // Print out the label if it exists...
01021     Out << "\n" << getLLVMName(BB->getName(), false) << ':';
01022   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
01023     Out << "\n; <label>:";
01024     int Slot = Machine.getSlot(BB);
01025     if (Slot != -1)
01026       Out << Slot;
01027     else
01028       Out << "<badref>";
01029   }
01030 
01031   if (BB->getParent() == 0)
01032     Out << "\t\t; Error: Block without parent!";
01033   else {
01034     if (BB != &BB->getParent()->front()) {  // Not the entry block?
01035       // Output predecessors for the block...
01036       Out << "\t\t;";
01037       pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
01038 
01039       if (PI == PE) {
01040         Out << " No predecessors!";
01041       } else {
01042         Out << " preds =";
01043         writeOperand(*PI, false, true);
01044         for (++PI; PI != PE; ++PI) {
01045           Out << ',';
01046           writeOperand(*PI, false, true);
01047         }
01048       }
01049     }
01050   }
01051 
01052   Out << "\n";
01053 
01054   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
01055 
01056   // Output all of the instructions in the basic block...
01057   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
01058     printInstruction(*I);
01059 
01060   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
01061 }
01062 
01063 
01064 /// printInfoComment - Print a little comment after the instruction indicating
01065 /// which slot it occupies.
01066 ///
01067 void AssemblyWriter::printInfoComment(const Value &V) {
01068   if (V.getType() != Type::VoidTy) {
01069     Out << "\t\t; <";
01070     printType(V.getType()) << '>';
01071 
01072     if (!V.hasName()) {
01073       int SlotNum = Machine.getSlot(&V);
01074       if (SlotNum == -1)
01075         Out << ":<badref>";
01076       else
01077         Out << ':' << SlotNum; // Print out the def slot taken.
01078     }
01079     Out << " [#uses=" << V.getNumUses() << ']';  // Output # uses
01080   }
01081 }
01082 
01083 /// printInstruction - This member is called for each Instruction in a function..
01084 ///
01085 void AssemblyWriter::printInstruction(const Instruction &I) {
01086   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
01087 
01088   Out << "\t";
01089 
01090   // Print out name if it exists...
01091   if (I.hasName())
01092     Out << getLLVMName(I.getName()) << " = ";
01093 
01094   // If this is a volatile load or store, print out the volatile marker.
01095   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
01096       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
01097       Out << "volatile ";
01098   } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
01099     // If this is a call, check if it's a tail call.
01100     Out << "tail ";
01101   }
01102 
01103   // Print out the opcode...
01104   Out << I.getOpcodeName();
01105 
01106   // Print out the type of the operands...
01107   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
01108 
01109   // Special case conditional branches to swizzle the condition out to the front
01110   if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
01111     writeOperand(I.getOperand(2), true);
01112     Out << ',';
01113     writeOperand(Operand, true);
01114     Out << ',';
01115     writeOperand(I.getOperand(1), true);
01116 
01117   } else if (isa<SwitchInst>(I)) {
01118     // Special case switch statement to get formatting nice and correct...
01119     writeOperand(Operand        , true); Out << ',';
01120     writeOperand(I.getOperand(1), true); Out << " [";
01121 
01122     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
01123       Out << "\n\t\t";
01124       writeOperand(I.getOperand(op  ), true); Out << ',';
01125       writeOperand(I.getOperand(op+1), true);
01126     }
01127     Out << "\n\t]";
01128   } else if (isa<PHINode>(I)) {
01129     Out << ' ';
01130     printType(I.getType());
01131     Out << ' ';
01132 
01133     for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
01134       if (op) Out << ", ";
01135       Out << '[';
01136       writeOperand(I.getOperand(op  ), false); Out << ',';
01137       writeOperand(I.getOperand(op+1), false); Out << " ]";
01138     }
01139   } else if (isa<ReturnInst>(I) && !Operand) {
01140     Out << " void";
01141   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
01142     // Print the calling convention being used.
01143     switch (CI->getCallingConv()) {
01144     case CallingConv::C: break;   // default
01145     case CallingConv::Fast: Out << " fastcc"; break;
01146     case CallingConv::Cold: Out << " coldcc"; break;
01147     default: Out << " cc" << CI->getCallingConv(); break;
01148     }
01149 
01150     const PointerType  *PTy = cast<PointerType>(Operand->getType());
01151     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
01152     const Type       *RetTy = FTy->getReturnType();
01153 
01154     // If possible, print out the short form of the call instruction.  We can
01155     // only do this if the first argument is a pointer to a nonvararg function,
01156     // and if the return type is not a pointer to a function.
01157     //
01158     if (!FTy->isVarArg() &&
01159         (!isa<PointerType>(RetTy) ||
01160          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
01161       Out << ' '; printType(RetTy);
01162       writeOperand(Operand, false);
01163     } else {
01164       writeOperand(Operand, true);
01165     }
01166     Out << '(';
01167     if (CI->getNumOperands() > 1) writeOperand(CI->getOperand(1), true);
01168     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
01169       Out << ',';
01170       writeOperand(I.getOperand(op), true);
01171     }
01172 
01173     Out << " )";
01174   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
01175     const PointerType  *PTy = cast<PointerType>(Operand->getType());
01176     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
01177     const Type       *RetTy = FTy->getReturnType();
01178 
01179     // Print the calling convention being used.
01180     switch (II->getCallingConv()) {
01181     case CallingConv::C: break;   // default
01182     case CallingConv::Fast: Out << " fastcc"; break;
01183     case CallingConv::Cold: Out << " coldcc"; break;
01184     default: Out << " cc" << II->getCallingConv(); break;
01185     }
01186 
01187     // If possible, print out the short form of the invoke instruction. We can
01188     // only do this if the first argument is a pointer to a nonvararg function,
01189     // and if the return type is not a pointer to a function.
01190     //
01191     if (!FTy->isVarArg() &&
01192         (!isa<PointerType>(RetTy) ||
01193          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
01194       Out << ' '; printType(RetTy);
01195       writeOperand(Operand, false);
01196     } else {
01197       writeOperand(Operand, true);
01198     }
01199 
01200     Out << '(';
01201     if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
01202     for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
01203       Out << ',';
01204       writeOperand(I.getOperand(op), true);
01205     }
01206 
01207     Out << " )\n\t\t\tto";
01208     writeOperand(II->getNormalDest(), true);
01209     Out << " unwind";
01210     writeOperand(II->getUnwindDest(), true);
01211 
01212   } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
01213     Out << ' ';
01214     printType(AI->getType()->getElementType());
01215     if (AI->isArrayAllocation()) {
01216       Out << ',';
01217       writeOperand(AI->getArraySize(), true);
01218     }
01219     if (AI->getAlignment()) {
01220       Out << ", align " << AI->getAlignment();
01221     }
01222   } else if (isa<CastInst>(I)) {
01223     if (Operand) writeOperand(Operand, true);   // Work with broken code
01224     Out << " to ";
01225     printType(I.getType());
01226   } else if (isa<VAArgInst>(I)) {
01227     if (Operand) writeOperand(Operand, true);   // Work with broken code
01228     Out << ", ";
01229     printType(I.getType());
01230   } else if (Operand) {   // Print the normal way...
01231 
01232     // PrintAllTypes - Instructions who have operands of all the same type
01233     // omit the type from all but the first operand.  If the instruction has
01234     // different type operands (for example br), then they are all printed.
01235     bool PrintAllTypes = false;
01236     const Type *TheType = Operand->getType();
01237 
01238     // Shift Left & Right print both types even for Ubyte LHS, and select prints
01239     // types even if all operands are bools.
01240     if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I) ||
01241         isa<ShuffleVectorInst>(I)) {
01242       PrintAllTypes = true;
01243     } else {
01244       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
01245         Operand = I.getOperand(i);
01246         if (Operand->getType() != TheType) {
01247           PrintAllTypes = true;    // We have differing types!  Print them all!
01248           break;
01249         }
01250       }
01251     }
01252 
01253     if (!PrintAllTypes) {
01254       Out << ' ';
01255       printType(TheType);
01256     }
01257 
01258     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
01259       if (i) Out << ',';
01260       writeOperand(I.getOperand(i), PrintAllTypes);
01261     }
01262   }
01263 
01264   printInfoComment(I);
01265   Out << "\n";
01266 }
01267 
01268 
01269 //===----------------------------------------------------------------------===//
01270 //                       External Interface declarations
01271 //===----------------------------------------------------------------------===//
01272 
01273 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
01274   SlotMachine SlotTable(this);
01275   AssemblyWriter W(o, SlotTable, this, AAW);
01276   W.write(this);
01277 }
01278 
01279 void GlobalVariable::print(std::ostream &o) const {
01280   SlotMachine SlotTable(getParent());
01281   AssemblyWriter W(o, SlotTable, getParent(), 0);
01282   W.write(this);
01283 }
01284 
01285 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
01286   SlotMachine SlotTable(getParent());
01287   AssemblyWriter W(o, SlotTable, getParent(), AAW);
01288 
01289   W.write(this);
01290 }
01291 
01292 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
01293   WriteAsOperand(o, this, true, true, 0);
01294 }
01295 
01296 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
01297   SlotMachine SlotTable(getParent());
01298   AssemblyWriter W(o, SlotTable,
01299                    getParent() ? getParent()->getParent() : 0, AAW);
01300   W.write(this);
01301 }
01302 
01303 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
01304   const Function *F = getParent() ? getParent()->getParent() : 0;
01305   SlotMachine SlotTable(F);
01306   AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
01307 
01308   W.write(this);
01309 }
01310 
01311 void Constant::print(std::ostream &o) const {
01312   if (this == 0) { o << "<null> constant value\n"; return; }
01313 
01314   o << ' ' << getType()->getDescription() << ' ';
01315 
01316   std::map<const Type *, std::string> TypeTable;
01317   WriteConstantInt(o, this, false, TypeTable, 0);
01318 }
01319 
01320 void Type::print(std::ostream &o) const {
01321   if (this == 0)
01322     o << "<null Type>";
01323   else
01324     o << getDescription();
01325 }
01326 
01327 void Argument::print(std::ostream &o) const {
01328   WriteAsOperand(o, this, true, true,
01329                  getParent() ? getParent()->getParent() : 0);
01330 }
01331 
01332 // Value::dump - allow easy printing of  Values from the debugger.
01333 // Located here because so much of the needed functionality is here.
01334 void Value::dump() const { print(std::cerr); }
01335 
01336 // Type::dump - allow easy printing of  Values from the debugger.
01337 // Located here because so much of the needed functionality is here.
01338 void Type::dump() const { print(std::cerr); }
01339 
01340 //===----------------------------------------------------------------------===//
01341 //  CachedWriter Class Implementation
01342 //===----------------------------------------------------------------------===//
01343 
01344 void CachedWriter::setModule(const Module *M) {
01345   delete SC; delete AW;
01346   if (M) {
01347     SC = new SlotMachine(M );
01348     AW = new AssemblyWriter(Out, *SC, M, 0);
01349   } else {
01350     SC = 0; AW = 0;
01351   }
01352 }
01353 
01354 CachedWriter::~CachedWriter() {
01355   delete AW;
01356   delete SC;
01357 }
01358 
01359 CachedWriter &CachedWriter::operator<<(const Value &V) {
01360   assert(AW && SC && "CachedWriter does not have a current module!");
01361   if (const Instruction *I = dyn_cast<Instruction>(&V))
01362     AW->write(I);
01363   else if (const BasicBlock *BB = dyn_cast<BasicBlock>(&V))
01364     AW->write(BB);
01365   else if (const Function *F = dyn_cast<Function>(&V))
01366     AW->write(F);
01367   else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(&V))
01368     AW->write(GV);
01369   else
01370     AW->writeOperand(&V, true, true);
01371   return *this;
01372 }
01373 
01374 CachedWriter& CachedWriter::operator<<(const Type &Ty) {
01375   if (SymbolicTypes) {
01376     const Module *M = AW->getModule();
01377     if (M) WriteTypeSymbolic(Out, &Ty, M);
01378   } else {
01379     AW->write(&Ty);
01380   }
01381   return *this;
01382 }
01383 
01384 //===----------------------------------------------------------------------===//
01385 //===--                    SlotMachine Implementation
01386 //===----------------------------------------------------------------------===//
01387 
01388 #if 0
01389 #define SC_DEBUG(X) std::cerr << X
01390 #else
01391 #define SC_DEBUG(X)
01392 #endif
01393 
01394 // Module level constructor. Causes the contents of the Module (sans functions)
01395 // to be added to the slot table.
01396 SlotMachine::SlotMachine(const Module *M)
01397   : TheModule(M)    ///< Saved for lazy initialization.
01398   , TheFunction(0)
01399   , FunctionProcessed(false)
01400   , mMap()
01401   , mTypes()
01402   , fMap()
01403   , fTypes()
01404 {
01405 }
01406 
01407 // Function level constructor. Causes the contents of the Module and the one
01408 // function provided to be added to the slot table.
01409 SlotMachine::SlotMachine(const Function *F )
01410   : TheModule( F ? F->getParent() : 0 ) ///< Saved for lazy initialization
01411   , TheFunction(F) ///< Saved for lazy initialization
01412   , FunctionProcessed(false)
01413   , mMap()
01414   , mTypes()
01415   , fMap()
01416   , fTypes()
01417 {
01418 }
01419 
01420 inline void SlotMachine::initialize(void) {
01421   if ( TheModule) {
01422     processModule();
01423     TheModule = 0; ///< Prevent re-processing next time we're called.
01424   }
01425   if ( TheFunction && ! FunctionProcessed) {
01426     processFunction();
01427   }
01428 }
01429 
01430 // Iterate through all the global variables, functions, and global
01431 // variable initializers and create slots for them.
01432 void SlotMachine::processModule() {
01433   SC_DEBUG("begin processModule!\n");
01434 
01435   // Add all of the global variables to the value table...
01436   for (Module::const_global_iterator I = TheModule->global_begin(), E = TheModule->global_end();
01437        I != E; ++I)
01438     createSlot(I);
01439 
01440   // Add all the functions to the table
01441   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
01442        I != E; ++I)
01443     createSlot(I);
01444 
01445   SC_DEBUG("end processModule!\n");
01446 }
01447 
01448 
01449 // Process the arguments, basic blocks, and instructions  of a function.
01450 void SlotMachine::processFunction() {
01451   SC_DEBUG("begin processFunction!\n");
01452 
01453   // Add all the function arguments
01454   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
01455       AE = TheFunction->arg_end(); AI != AE; ++AI)
01456     createSlot(AI);
01457 
01458   SC_DEBUG("Inserting Instructions:\n");
01459 
01460   // Add all of the basic blocks and instructions
01461   for (Function::const_iterator BB = TheFunction->begin(),
01462        E = TheFunction->end(); BB != E; ++BB) {
01463     createSlot(BB);
01464     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
01465       createSlot(I);
01466     }
01467   }
01468 
01469   FunctionProcessed = true;
01470 
01471   SC_DEBUG("end processFunction!\n");
01472 }
01473 
01474 // Clean up after incorporating a function. This is the only way
01475 // to get out of the function incorporation state that affects the
01476 // getSlot/createSlot lock. Function incorporation state is indicated
01477 // by TheFunction != 0.
01478 void SlotMachine::purgeFunction() {
01479   SC_DEBUG("begin purgeFunction!\n");
01480   fMap.clear(); // Simply discard the function level map
01481   fTypes.clear();
01482   TheFunction = 0;
01483   FunctionProcessed = false;
01484   SC_DEBUG("end purgeFunction!\n");
01485 }
01486 
01487 /// Get the slot number for a value. This function will assert if you
01488 /// ask for a Value that hasn't previously been inserted with createSlot.
01489 /// Types are forbidden because Type does not inherit from Value (any more).
01490 int SlotMachine::getSlot(const Value *V) {
01491   assert( V && "Can't get slot for null Value" );
01492   assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
01493     "Can't insert a non-GlobalValue Constant into SlotMachine");
01494 
01495   // Check for uninitialized state and do lazy initialization
01496   this->initialize();
01497 
01498   // Get the type of the value
01499   const Type* VTy = V->getType();
01500 
01501   // Find the type plane in the module map
01502   TypedPlanes::const_iterator MI = mMap.find(VTy);
01503 
01504   if ( TheFunction ) {
01505     // Lookup the type in the function map too
01506     TypedPlanes::const_iterator FI = fMap.find(VTy);
01507     // If there is a corresponding type plane in the function map
01508     if ( FI != fMap.end() ) {
01509       // Lookup the Value in the function map
01510       ValueMap::const_iterator FVI = FI->second.map.find(V);
01511       // If the value doesn't exist in the function map
01512       if ( FVI == FI->second.map.end() ) {
01513         // Look up the value in the module map.
01514         if (MI == mMap.end()) return -1;
01515         ValueMap::const_iterator MVI = MI->second.map.find(V);
01516         // If we didn't find it, it wasn't inserted
01517         if (MVI == MI->second.map.end()) return -1;
01518         assert( MVI != MI->second.map.end() && "Value not found");
01519         // We found it only at the module level
01520         return MVI->second;
01521 
01522       // else the value exists in the function map
01523       } else {
01524         // Return the slot number as the module's contribution to
01525         // the type plane plus the index in the function's contribution
01526         // to the type plane.
01527         if (MI != mMap.end())
01528           return MI->second.next_slot + FVI->second;
01529         else
01530           return FVI->second;
01531       }
01532     }
01533   }
01534 
01535   // N.B. Can get here only if either !TheFunction or the function doesn't
01536   // have a corresponding type plane for the Value
01537 
01538   // Make sure the type plane exists
01539   if (MI == mMap.end()) return -1;
01540   // Lookup the value in the module's map
01541   ValueMap::const_iterator MVI = MI->second.map.find(V);
01542   // Make sure we found it.
01543   if (MVI == MI->second.map.end()) return -1;
01544   // Return it.
01545   return MVI->second;
01546 }
01547 
01548 /// Get the slot number for a value. This function will assert if you
01549 /// ask for a Value that hasn't previously been inserted with createSlot.
01550 /// Types are forbidden because Type does not inherit from Value (any more).
01551 int SlotMachine::getSlot(const Type *Ty) {
01552   assert( Ty && "Can't get slot for null Type" );
01553 
01554   // Check for uninitialized state and do lazy initialization
01555   this->initialize();
01556 
01557   if ( TheFunction ) {
01558     // Lookup the Type in the function map
01559     TypeMap::const_iterator FTI = fTypes.map.find(Ty);
01560     // If the Type doesn't exist in the function map
01561     if ( FTI == fTypes.map.end() ) {
01562       TypeMap::const_iterator MTI = mTypes.map.find(Ty);
01563       // If we didn't find it, it wasn't inserted
01564       if (MTI == mTypes.map.end())
01565         return -1;
01566       // We found it only at the module level
01567       return MTI->second;
01568 
01569     // else the value exists in the function map
01570     } else {
01571       // Return the slot number as the module's contribution to
01572       // the type plane plus the index in the function's contribution
01573       // to the type plane.
01574       return mTypes.next_slot + FTI->second;
01575     }
01576   }
01577 
01578   // N.B. Can get here only if either !TheFunction
01579 
01580   // Lookup the value in the module's map
01581   TypeMap::const_iterator MTI = mTypes.map.find(Ty);
01582   // Make sure we found it.
01583   if (MTI == mTypes.map.end()) return -1;
01584   // Return it.
01585   return MTI->second;
01586 }
01587 
01588 // Create a new slot, or return the existing slot if it is already
01589 // inserted. Note that the logic here parallels getSlot but instead
01590 // of asserting when the Value* isn't found, it inserts the value.
01591 unsigned SlotMachine::createSlot(const Value *V) {
01592   assert( V && "Can't insert a null Value to SlotMachine");
01593   assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
01594     "Can't insert a non-GlobalValue Constant into SlotMachine");
01595 
01596   const Type* VTy = V->getType();
01597 
01598   // Just ignore void typed things
01599   if (VTy == Type::VoidTy) return 0; // FIXME: Wrong return value!
01600 
01601   // Look up the type plane for the Value's type from the module map
01602   TypedPlanes::const_iterator MI = mMap.find(VTy);
01603 
01604   if ( TheFunction ) {
01605     // Get the type plane for the Value's type from the function map
01606     TypedPlanes::const_iterator FI = fMap.find(VTy);
01607     // If there is a corresponding type plane in the function map
01608     if ( FI != fMap.end() ) {
01609       // Lookup the Value in the function map
01610       ValueMap::const_iterator FVI = FI->second.map.find(V);
01611       // If the value doesn't exist in the function map
01612       if ( FVI == FI->second.map.end() ) {
01613         // If there is no corresponding type plane in the module map
01614         if ( MI == mMap.end() )
01615           return insertValue(V);
01616         // Look up the value in the module map
01617         ValueMap::const_iterator MVI = MI->second.map.find(V);
01618         // If we didn't find it, it wasn't inserted
01619         if ( MVI == MI->second.map.end() )
01620           return insertValue(V);
01621         else
01622           // We found it only at the module level
01623           return MVI->second;
01624 
01625       // else the value exists in the function map
01626       } else {
01627         if ( MI == mMap.end() )
01628           return FVI->second;
01629         else
01630           // Return the slot number as the module's contribution to
01631           // the type plane plus the index in the function's contribution
01632           // to the type plane.
01633           return MI->second.next_slot + FVI->second;
01634       }
01635 
01636     // else there is not a corresponding type plane in the function map
01637     } else {
01638       // If the type plane doesn't exists at the module level
01639       if ( MI == mMap.end() ) {
01640         return insertValue(V);
01641       // else type plane exists at the module level, examine it
01642       } else {
01643         // Look up the value in the module's map
01644         ValueMap::const_iterator MVI = MI->second.map.find(V);
01645         // If we didn't find it there either
01646         if ( MVI == MI->second.map.end() )
01647           // Return the slot number as the module's contribution to
01648           // the type plane plus the index of the function map insertion.
01649           return MI->second.next_slot + insertValue(V);
01650         else
01651           return MVI->second;
01652       }
01653     }
01654   }
01655 
01656   // N.B. Can only get here if !TheFunction
01657 
01658   // If the module map's type plane is not for the Value's type
01659   if ( MI != mMap.end() ) {
01660     // Lookup the value in the module's map
01661     ValueMap::const_iterator MVI = MI->second.map.find(V);
01662     if ( MVI != MI->second.map.end() )
01663       return MVI->second;
01664   }
01665 
01666   return insertValue(V);
01667 }
01668 
01669 // Create a new slot, or return the existing slot if it is already
01670 // inserted. Note that the logic here parallels getSlot but instead
01671 // of asserting when the Value* isn't found, it inserts the value.
01672 unsigned SlotMachine::createSlot(const Type *Ty) {
01673   assert( Ty && "Can't insert a null Type to SlotMachine");
01674 
01675   if ( TheFunction ) {
01676     // Lookup the Type in the function map
01677     TypeMap::const_iterator FTI = fTypes.map.find(Ty);
01678     // If the type doesn't exist in the function map
01679     if ( FTI == fTypes.map.end() ) {
01680       // Look up the type in the module map
01681       TypeMap::const_iterator MTI = mTypes.map.find(Ty);
01682       // If we didn't find it, it wasn't inserted
01683       if ( MTI == mTypes.map.end() )
01684         return insertValue(Ty);
01685       else
01686         // We found it only at the module level
01687         return MTI->second;
01688 
01689     // else the value exists in the function map
01690     } else {
01691       // Return the slot number as the module's contribution to
01692       // the type plane plus the index in the function's contribution
01693       // to the type plane.
01694       return mTypes.next_slot + FTI->second;
01695     }
01696   }
01697 
01698   // N.B. Can only get here if !TheFunction
01699 
01700   // Lookup the type in the module's map
01701   TypeMap::const_iterator MTI = mTypes.map.find(Ty);
01702   if ( MTI != mTypes.map.end() )
01703     return MTI->second;
01704 
01705   return insertValue(Ty);
01706 }
01707 
01708 // Low level insert function. Minimal checking is done. This
01709 // function is just for the convenience of createSlot (above).
01710 unsigned SlotMachine::insertValue(const Value *V ) {
01711   assert(V && "Can't insert a null Value into SlotMachine!");
01712   assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
01713     "Can't insert a non-GlobalValue Constant into SlotMachine");
01714 
01715   // If this value does not contribute to a plane (is void)
01716   // or if the value already has a name then ignore it.
01717   if (V->getType() == Type::VoidTy || V->hasName() ) {
01718       SC_DEBUG("ignored value " << *V << "\n");
01719       return 0;   // FIXME: Wrong return value
01720   }
01721 
01722   const Type *VTy = V->getType();
01723   unsigned DestSlot = 0;
01724 
01725   if ( TheFunction ) {
01726     TypedPlanes::iterator I = fMap.find( VTy );
01727     if ( I == fMap.end() )
01728       I = fMap.insert(std::make_pair(VTy,ValuePlane())).first;
01729     DestSlot = I->second.map[V] = I->second.next_slot++;
01730   } else {
01731     TypedPlanes::iterator I = mMap.find( VTy );
01732     if ( I == mMap.end() )
01733       I = mMap.insert(std::make_pair(VTy,ValuePlane())).first;
01734     DestSlot = I->second.map[V] = I->second.next_slot++;
01735   }
01736 
01737   SC_DEBUG("  Inserting value [" << VTy << "] = " << V << " slot=" <<
01738            DestSlot << " [");
01739   // G = Global, C = Constant, T = Type, F = Function, o = other
01740   SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' :
01741            (isa<Constant>(V) ? 'C' : 'o'))));
01742   SC_DEBUG("]\n");
01743   return DestSlot;
01744 }
01745 
01746 // Low level insert function. Minimal checking is done. This
01747 // function is just for the convenience of createSlot (above).
01748 unsigned SlotMachine::insertValue(const Type *Ty ) {
01749   assert(Ty && "Can't insert a null Type into SlotMachine!");
01750 
01751   unsigned DestSlot = 0;
01752 
01753   if ( TheFunction ) {
01754     DestSlot = fTypes.map[Ty] = fTypes.next_slot++;
01755   } else {
01756     DestSlot = fTypes.map[Ty] = fTypes.next_slot++;
01757   }
01758   SC_DEBUG("  Inserting type [" << DestSlot << "] = " << Ty << "\n");
01759   return DestSlot;
01760 }
01761 
01762 // vim: sw=2