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