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