LLVM API Documentation
00001 //===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===// 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 file implements the writing of the LLVM IR as a set of C++ calls to the 00011 // LLVM IR interface. The input module is assumed to be verified. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 #include "CPPTargetMachine.h" 00016 #include "llvm/CallingConv.h" 00017 #include "llvm/Constants.h" 00018 #include "llvm/DerivedTypes.h" 00019 #include "llvm/InlineAsm.h" 00020 #include "llvm/Instruction.h" 00021 #include "llvm/Instructions.h" 00022 #include "llvm/Module.h" 00023 #include "llvm/Pass.h" 00024 #include "llvm/PassManager.h" 00025 #include "llvm/TypeSymbolTable.h" 00026 #include "llvm/ADT/StringExtras.h" 00027 #include "llvm/ADT/STLExtras.h" 00028 #include "llvm/ADT/SmallPtrSet.h" 00029 #include "llvm/Support/CommandLine.h" 00030 #include "llvm/Support/ErrorHandling.h" 00031 #include "llvm/Support/FormattedStream.h" 00032 #include "llvm/Support/Streams.h" 00033 #include "llvm/Target/TargetRegistry.h" 00034 #include "llvm/Config/config.h" 00035 #include <algorithm> 00036 #include <set> 00037 00038 using namespace llvm; 00039 00040 static cl::opt<std::string> 00041 FuncName("cppfname", cl::desc("Specify the name of the generated function"), 00042 cl::value_desc("function name")); 00043 00044 enum WhatToGenerate { 00045 GenProgram, 00046 GenModule, 00047 GenContents, 00048 GenFunction, 00049 GenFunctions, 00050 GenInline, 00051 GenVariable, 00052 GenType 00053 }; 00054 00055 static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional, 00056 cl::desc("Choose what kind of output to generate"), 00057 cl::init(GenProgram), 00058 cl::values( 00059 clEnumValN(GenProgram, "program", "Generate a complete program"), 00060 clEnumValN(GenModule, "module", "Generate a module definition"), 00061 clEnumValN(GenContents, "contents", "Generate contents of a module"), 00062 clEnumValN(GenFunction, "function", "Generate a function definition"), 00063 clEnumValN(GenFunctions,"functions", "Generate all function definitions"), 00064 clEnumValN(GenInline, "inline", "Generate an inline function"), 00065 clEnumValN(GenVariable, "variable", "Generate a variable definition"), 00066 clEnumValN(GenType, "type", "Generate a type definition"), 00067 clEnumValEnd 00068 ) 00069 ); 00070 00071 static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional, 00072 cl::desc("Specify the name of the thing to generate"), 00073 cl::init("!bad!")); 00074 00075 extern "C" void LLVMInitializeCppBackendTarget() { 00076 // Register the target. 00077 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget); 00078 } 00079 00080 namespace { 00081 typedef std::vector<const Type*> TypeList; 00082 typedef std::map<const Type*,std::string> TypeMap; 00083 typedef std::map<const Value*,std::string> ValueMap; 00084 typedef std::set<std::string> NameSet; 00085 typedef std::set<const Type*> TypeSet; 00086 typedef std::set<const Value*> ValueSet; 00087 typedef std::map<const Value*,std::string> ForwardRefMap; 00088 00089 /// CppWriter - This class is the main chunk of code that converts an LLVM 00090 /// module to a C++ translation unit. 00091 class CppWriter : public ModulePass { 00092 formatted_raw_ostream &Out; 00093 const Module *TheModule; 00094 uint64_t uniqueNum; 00095 TypeMap TypeNames; 00096 ValueMap ValueNames; 00097 TypeMap UnresolvedTypes; 00098 TypeList TypeStack; 00099 NameSet UsedNames; 00100 TypeSet DefinedTypes; 00101 ValueSet DefinedValues; 00102 ForwardRefMap ForwardRefs; 00103 bool is_inline; 00104 00105 public: 00106 static char ID; 00107 explicit CppWriter(formatted_raw_ostream &o) : 00108 ModulePass(&ID), Out(o), uniqueNum(0), is_inline(false) {} 00109 00110 virtual const char *getPassName() const { return "C++ backend"; } 00111 00112 bool runOnModule(Module &M); 00113 00114 void printProgram(const std::string& fname, const std::string& modName ); 00115 void printModule(const std::string& fname, const std::string& modName ); 00116 void printContents(const std::string& fname, const std::string& modName ); 00117 void printFunction(const std::string& fname, const std::string& funcName ); 00118 void printFunctions(); 00119 void printInline(const std::string& fname, const std::string& funcName ); 00120 void printVariable(const std::string& fname, const std::string& varName ); 00121 void printType(const std::string& fname, const std::string& typeName ); 00122 00123 void error(const std::string& msg); 00124 00125 private: 00126 void printLinkageType(GlobalValue::LinkageTypes LT); 00127 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes); 00128 void printCallingConv(unsigned cc); 00129 void printEscapedString(const std::string& str); 00130 void printCFP(const ConstantFP* CFP); 00131 00132 std::string getCppName(const Type* val); 00133 inline void printCppName(const Type* val); 00134 00135 std::string getCppName(const Value* val); 00136 inline void printCppName(const Value* val); 00137 00138 void printAttributes(const AttrListPtr &PAL, const std::string &name); 00139 bool printTypeInternal(const Type* Ty); 00140 inline void printType(const Type* Ty); 00141 void printTypes(const Module* M); 00142 00143 void printConstant(const Constant *CPV); 00144 void printConstants(const Module* M); 00145 00146 void printVariableUses(const GlobalVariable *GV); 00147 void printVariableHead(const GlobalVariable *GV); 00148 void printVariableBody(const GlobalVariable *GV); 00149 00150 void printFunctionUses(const Function *F); 00151 void printFunctionHead(const Function *F); 00152 void printFunctionBody(const Function *F); 00153 void printInstruction(const Instruction *I, const std::string& bbname); 00154 std::string getOpName(Value*); 00155 00156 void printModuleBody(); 00157 }; 00158 00159 static unsigned indent_level = 0; 00160 inline formatted_raw_ostream& nl(formatted_raw_ostream& Out, int delta = 0) { 00161 Out << "\n"; 00162 if (delta >= 0 || indent_level >= unsigned(-delta)) 00163 indent_level += delta; 00164 for (unsigned i = 0; i < indent_level; ++i) 00165 Out << " "; 00166 return Out; 00167 } 00168 00169 inline void in() { indent_level++; } 00170 inline void out() { if (indent_level >0) indent_level--; } 00171 00172 inline void 00173 sanitize(std::string& str) { 00174 for (size_t i = 0; i < str.length(); ++i) 00175 if (!isalnum(str[i]) && str[i] != '_') 00176 str[i] = '_'; 00177 } 00178 00179 inline std::string 00180 getTypePrefix(const Type* Ty ) { 00181 switch (Ty->getTypeID()) { 00182 case Type::VoidTyID: return "void_"; 00183 case Type::IntegerTyID: 00184 return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) + 00185 "_"; 00186 case Type::FloatTyID: return "float_"; 00187 case Type::DoubleTyID: return "double_"; 00188 case Type::LabelTyID: return "label_"; 00189 case Type::FunctionTyID: return "func_"; 00190 case Type::StructTyID: return "struct_"; 00191 case Type::ArrayTyID: return "array_"; 00192 case Type::PointerTyID: return "ptr_"; 00193 case Type::VectorTyID: return "packed_"; 00194 case Type::OpaqueTyID: return "opaque_"; 00195 default: return "other_"; 00196 } 00197 return "unknown_"; 00198 } 00199 00200 // Looks up the type in the symbol table and returns a pointer to its name or 00201 // a null pointer if it wasn't found. Note that this isn't the same as the 00202 // Mode::getTypeName function which will return an empty string, not a null 00203 // pointer if the name is not found. 00204 inline const std::string* 00205 findTypeName(const TypeSymbolTable& ST, const Type* Ty) { 00206 TypeSymbolTable::const_iterator TI = ST.begin(); 00207 TypeSymbolTable::const_iterator TE = ST.end(); 00208 for (;TI != TE; ++TI) 00209 if (TI->second == Ty) 00210 return &(TI->first); 00211 return 0; 00212 } 00213 00214 void CppWriter::error(const std::string& msg) { 00215 llvm_report_error(msg); 00216 } 00217 00218 // printCFP - Print a floating point constant .. very carefully :) 00219 // This makes sure that conversion to/from floating yields the same binary 00220 // result so that we don't lose precision. 00221 void CppWriter::printCFP(const ConstantFP *CFP) { 00222 bool ignored; 00223 APFloat APF = APFloat(CFP->getValueAPF()); // copy 00224 if (CFP->getType() == Type::getFloatTy(CFP->getContext())) 00225 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored); 00226 Out << "ConstantFP::get(getGlobalContext(), "; 00227 Out << "APFloat("; 00228 #if HAVE_PRINTF_A 00229 char Buffer[100]; 00230 sprintf(Buffer, "%A", APF.convertToDouble()); 00231 if ((!strncmp(Buffer, "0x", 2) || 00232 !strncmp(Buffer, "-0x", 3) || 00233 !strncmp(Buffer, "+0x", 3)) && 00234 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) { 00235 if (CFP->getType() == Type::getDoubleTy(CFP->getContext())) 00236 Out << "BitsToDouble(" << Buffer << ")"; 00237 else 00238 Out << "BitsToFloat((float)" << Buffer << ")"; 00239 Out << ")"; 00240 } else { 00241 #endif 00242 std::string StrVal = ftostr(CFP->getValueAPF()); 00243 00244 while (StrVal[0] == ' ') 00245 StrVal.erase(StrVal.begin()); 00246 00247 // Check to make sure that the stringized number is not some string like 00248 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex. 00249 if (((StrVal[0] >= '0' && StrVal[0] <= '9') || 00250 ((StrVal[0] == '-' || StrVal[0] == '+') && 00251 (StrVal[1] >= '0' && StrVal[1] <= '9'))) && 00252 (CFP->isExactlyValue(atof(StrVal.c_str())))) { 00253 if (CFP->getType() == Type::getDoubleTy(CFP->getContext())) 00254 Out << StrVal; 00255 else 00256 Out << StrVal << "f"; 00257 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext())) 00258 Out << "BitsToDouble(0x" 00259 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue()) 00260 << "ULL) /* " << StrVal << " */"; 00261 else 00262 Out << "BitsToFloat(0x" 00263 << utohexstr((uint32_t)CFP->getValueAPF(). 00264 bitcastToAPInt().getZExtValue()) 00265 << "U) /* " << StrVal << " */"; 00266 Out << ")"; 00267 #if HAVE_PRINTF_A 00268 } 00269 #endif 00270 Out << ")"; 00271 } 00272 00273 void CppWriter::printCallingConv(unsigned cc){ 00274 // Print the calling convention. 00275 switch (cc) { 00276 case CallingConv::C: Out << "CallingConv::C"; break; 00277 case CallingConv::Fast: Out << "CallingConv::Fast"; break; 00278 case CallingConv::Cold: Out << "CallingConv::Cold"; break; 00279 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break; 00280 default: Out << cc; break; 00281 } 00282 } 00283 00284 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) { 00285 switch (LT) { 00286 case GlobalValue::InternalLinkage: 00287 Out << "GlobalValue::InternalLinkage"; break; 00288 case GlobalValue::PrivateLinkage: 00289 Out << "GlobalValue::PrivateLinkage"; break; 00290 case GlobalValue::LinkerPrivateLinkage: 00291 Out << "GlobalValue::LinkerPrivateLinkage"; break; 00292 case GlobalValue::AvailableExternallyLinkage: 00293 Out << "GlobalValue::AvailableExternallyLinkage "; break; 00294 case GlobalValue::LinkOnceAnyLinkage: 00295 Out << "GlobalValue::LinkOnceAnyLinkage "; break; 00296 case GlobalValue::LinkOnceODRLinkage: 00297 Out << "GlobalValue::LinkOnceODRLinkage "; break; 00298 case GlobalValue::WeakAnyLinkage: 00299 Out << "GlobalValue::WeakAnyLinkage"; break; 00300 case GlobalValue::WeakODRLinkage: 00301 Out << "GlobalValue::WeakODRLinkage"; break; 00302 case GlobalValue::AppendingLinkage: 00303 Out << "GlobalValue::AppendingLinkage"; break; 00304 case GlobalValue::ExternalLinkage: 00305 Out << "GlobalValue::ExternalLinkage"; break; 00306 case GlobalValue::DLLImportLinkage: 00307 Out << "GlobalValue::DLLImportLinkage"; break; 00308 case GlobalValue::DLLExportLinkage: 00309 Out << "GlobalValue::DLLExportLinkage"; break; 00310 case GlobalValue::ExternalWeakLinkage: 00311 Out << "GlobalValue::ExternalWeakLinkage"; break; 00312 case GlobalValue::GhostLinkage: 00313 Out << "GlobalValue::GhostLinkage"; break; 00314 case GlobalValue::CommonLinkage: 00315 Out << "GlobalValue::CommonLinkage"; break; 00316 } 00317 } 00318 00319 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) { 00320 switch (VisType) { 00321 default: llvm_unreachable("Unknown GVar visibility"); 00322 case GlobalValue::DefaultVisibility: 00323 Out << "GlobalValue::DefaultVisibility"; 00324 break; 00325 case GlobalValue::HiddenVisibility: 00326 Out << "GlobalValue::HiddenVisibility"; 00327 break; 00328 case GlobalValue::ProtectedVisibility: 00329 Out << "GlobalValue::ProtectedVisibility"; 00330 break; 00331 } 00332 } 00333 00334 // printEscapedString - Print each character of the specified string, escaping 00335 // it if it is not printable or if it is an escape char. 00336 void CppWriter::printEscapedString(const std::string &Str) { 00337 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 00338 unsigned char C = Str[i]; 00339 if (isprint(C) && C != '"' && C != '\\') { 00340 Out << C; 00341 } else { 00342 Out << "\\x" 00343 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A')) 00344 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A')); 00345 } 00346 } 00347 } 00348 00349 std::string CppWriter::getCppName(const Type* Ty) { 00350 // First, handle the primitive types .. easy 00351 if (Ty->isPrimitiveType() || Ty->isInteger()) { 00352 switch (Ty->getTypeID()) { 00353 case Type::VoidTyID: return "Type::getVoidTy(getGlobalContext())"; 00354 case Type::IntegerTyID: { 00355 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth(); 00356 return "IntegerType::get(getGlobalContext(), " + utostr(BitWidth) + ")"; 00357 } 00358 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(getGlobalContext())"; 00359 case Type::FloatTyID: return "Type::getFloatTy(getGlobalContext())"; 00360 case Type::DoubleTyID: return "Type::getDoubleTy(getGlobalContext())"; 00361 case Type::LabelTyID: return "Type::getLabelTy(getGlobalContext())"; 00362 default: 00363 error("Invalid primitive type"); 00364 break; 00365 } 00366 // shouldn't be returned, but make it sensible 00367 return "Type::getVoidTy(getGlobalContext())"; 00368 } 00369 00370 // Now, see if we've seen the type before and return that 00371 TypeMap::iterator I = TypeNames.find(Ty); 00372 if (I != TypeNames.end()) 00373 return I->second; 00374 00375 // Okay, let's build a new name for this type. Start with a prefix 00376 const char* prefix = 0; 00377 switch (Ty->getTypeID()) { 00378 case Type::FunctionTyID: prefix = "FuncTy_"; break; 00379 case Type::StructTyID: prefix = "StructTy_"; break; 00380 case Type::ArrayTyID: prefix = "ArrayTy_"; break; 00381 case Type::PointerTyID: prefix = "PointerTy_"; break; 00382 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break; 00383 case Type::VectorTyID: prefix = "VectorTy_"; break; 00384 default: prefix = "OtherTy_"; break; // prevent breakage 00385 } 00386 00387 // See if the type has a name in the symboltable and build accordingly 00388 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty); 00389 std::string name; 00390 if (tName) 00391 name = std::string(prefix) + *tName; 00392 else 00393 name = std::string(prefix) + utostr(uniqueNum++); 00394 sanitize(name); 00395 00396 // Save the name 00397 return TypeNames[Ty] = name; 00398 } 00399 00400 void CppWriter::printCppName(const Type* Ty) { 00401 printEscapedString(getCppName(Ty)); 00402 } 00403 00404 std::string CppWriter::getCppName(const Value* val) { 00405 std::string name; 00406 ValueMap::iterator I = ValueNames.find(val); 00407 if (I != ValueNames.end() && I->first == val) 00408 return I->second; 00409 00410 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) { 00411 name = std::string("gvar_") + 00412 getTypePrefix(GV->getType()->getElementType()); 00413 } else if (isa<Function>(val)) { 00414 name = std::string("func_"); 00415 } else if (const Constant* C = dyn_cast<Constant>(val)) { 00416 name = std::string("const_") + getTypePrefix(C->getType()); 00417 } else if (const Argument* Arg = dyn_cast<Argument>(val)) { 00418 if (is_inline) { 00419 unsigned argNum = std::distance(Arg->getParent()->arg_begin(), 00420 Function::const_arg_iterator(Arg)) + 1; 00421 name = std::string("arg_") + utostr(argNum); 00422 NameSet::iterator NI = UsedNames.find(name); 00423 if (NI != UsedNames.end()) 00424 name += std::string("_") + utostr(uniqueNum++); 00425 UsedNames.insert(name); 00426 return ValueNames[val] = name; 00427 } else { 00428 name = getTypePrefix(val->getType()); 00429 } 00430 } else { 00431 name = getTypePrefix(val->getType()); 00432 } 00433 if (val->hasName()) 00434 name += val->getName(); 00435 else 00436 name += utostr(uniqueNum++); 00437 sanitize(name); 00438 NameSet::iterator NI = UsedNames.find(name); 00439 if (NI != UsedNames.end()) 00440 name += std::string("_") + utostr(uniqueNum++); 00441 UsedNames.insert(name); 00442 return ValueNames[val] = name; 00443 } 00444 00445 void CppWriter::printCppName(const Value* val) { 00446 printEscapedString(getCppName(val)); 00447 } 00448 00449 void CppWriter::printAttributes(const AttrListPtr &PAL, 00450 const std::string &name) { 00451 Out << "AttrListPtr " << name << "_PAL;"; 00452 nl(Out); 00453 if (!PAL.isEmpty()) { 00454 Out << '{'; in(); nl(Out); 00455 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out); 00456 Out << "AttributeWithIndex PAWI;"; nl(Out); 00457 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) { 00458 unsigned index = PAL.getSlot(i).Index; 00459 Attributes attrs = PAL.getSlot(i).Attrs; 00460 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 "; 00461 #define HANDLE_ATTR(X) \ 00462 if (attrs & Attribute::X) \ 00463 Out << " | Attribute::" #X; \ 00464 attrs &= ~Attribute::X; 00465 00466 HANDLE_ATTR(SExt); 00467 HANDLE_ATTR(ZExt); 00468 HANDLE_ATTR(NoReturn); 00469 HANDLE_ATTR(InReg); 00470 HANDLE_ATTR(StructRet); 00471 HANDLE_ATTR(NoUnwind); 00472 HANDLE_ATTR(NoAlias); 00473 HANDLE_ATTR(ByVal); 00474 HANDLE_ATTR(Nest); 00475 HANDLE_ATTR(ReadNone); 00476 HANDLE_ATTR(ReadOnly); 00477 HANDLE_ATTR(NoInline); 00478 HANDLE_ATTR(AlwaysInline); 00479 HANDLE_ATTR(OptimizeForSize); 00480 HANDLE_ATTR(StackProtect); 00481 HANDLE_ATTR(StackProtectReq); 00482 HANDLE_ATTR(NoCapture); 00483 #undef HANDLE_ATTR 00484 assert(attrs == 0 && "Unhandled attribute!"); 00485 Out << ";"; 00486 nl(Out); 00487 Out << "Attrs.push_back(PAWI);"; 00488 nl(Out); 00489 } 00490 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());"; 00491 nl(Out); 00492 out(); nl(Out); 00493 Out << '}'; nl(Out); 00494 } 00495 } 00496 00497 bool CppWriter::printTypeInternal(const Type* Ty) { 00498 // We don't print definitions for primitive types 00499 if (Ty->isPrimitiveType() || Ty->isInteger()) 00500 return false; 00501 00502 // If we already defined this type, we don't need to define it again. 00503 if (DefinedTypes.find(Ty) != DefinedTypes.end()) 00504 return false; 00505 00506 // Everything below needs the name for the type so get it now. 00507 std::string typeName(getCppName(Ty)); 00508 00509 // Search the type stack for recursion. If we find it, then generate this 00510 // as an OpaqueType, but make sure not to do this multiple times because 00511 // the type could appear in multiple places on the stack. Once the opaque 00512 // definition is issued, it must not be re-issued. Consequently we have to 00513 // check the UnresolvedTypes list as well. 00514 TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(), 00515 Ty); 00516 if (TI != TypeStack.end()) { 00517 TypeMap::const_iterator I = UnresolvedTypes.find(Ty); 00518 if (I == UnresolvedTypes.end()) { 00519 Out << "PATypeHolder " << typeName; 00520 Out << "_fwd = OpaqueType::get(getGlobalContext());"; 00521 nl(Out); 00522 UnresolvedTypes[Ty] = typeName; 00523 } 00524 return true; 00525 } 00526 00527 // We're going to print a derived type which, by definition, contains other 00528 // types. So, push this one we're printing onto the type stack to assist with 00529 // recursive definitions. 00530 TypeStack.push_back(Ty); 00531 00532 // Print the type definition 00533 switch (Ty->getTypeID()) { 00534 case Type::FunctionTyID: { 00535 const FunctionType* FT = cast<FunctionType>(Ty); 00536 Out << "std::vector<const Type*>" << typeName << "_args;"; 00537 nl(Out); 00538 FunctionType::param_iterator PI = FT->param_begin(); 00539 FunctionType::param_iterator PE = FT->param_end(); 00540 for (; PI != PE; ++PI) { 00541 const Type* argTy = static_cast<const Type*>(*PI); 00542 bool isForward = printTypeInternal(argTy); 00543 std::string argName(getCppName(argTy)); 00544 Out << typeName << "_args.push_back(" << argName; 00545 if (isForward) 00546 Out << "_fwd"; 00547 Out << ");"; 00548 nl(Out); 00549 } 00550 bool isForward = printTypeInternal(FT->getReturnType()); 00551 std::string retTypeName(getCppName(FT->getReturnType())); 00552 Out << "FunctionType* " << typeName << " = FunctionType::get("; 00553 in(); nl(Out) << "/*Result=*/" << retTypeName; 00554 if (isForward) 00555 Out << "_fwd"; 00556 Out << ","; 00557 nl(Out) << "/*Params=*/" << typeName << "_args,"; 00558 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");"; 00559 out(); 00560 nl(Out); 00561 break; 00562 } 00563 case Type::StructTyID: { 00564 const StructType* ST = cast<StructType>(Ty); 00565 Out << "std::vector<const Type*>" << typeName << "_fields;"; 00566 nl(Out); 00567 StructType::element_iterator EI = ST->element_begin(); 00568 StructType::element_iterator EE = ST->element_end(); 00569 for (; EI != EE; ++EI) { 00570 const Type* fieldTy = static_cast<const Type*>(*EI); 00571 bool isForward = printTypeInternal(fieldTy); 00572 std::string fieldName(getCppName(fieldTy)); 00573 Out << typeName << "_fields.push_back(" << fieldName; 00574 if (isForward) 00575 Out << "_fwd"; 00576 Out << ");"; 00577 nl(Out); 00578 } 00579 Out << "StructType* " << typeName << " = StructType::get(" 00580 << "mod->getContext(), " 00581 << typeName << "_fields, /*isPacked=*/" 00582 << (ST->isPacked() ? "true" : "false") << ");"; 00583 nl(Out); 00584 break; 00585 } 00586 case Type::ArrayTyID: { 00587 const ArrayType* AT = cast<ArrayType>(Ty); 00588 const Type* ET = AT->getElementType(); 00589 bool isForward = printTypeInternal(ET); 00590 std::string elemName(getCppName(ET)); 00591 Out << "ArrayType* " << typeName << " = ArrayType::get(" 00592 << elemName << (isForward ? "_fwd" : "") 00593 << ", " << utostr(AT->getNumElements()) << ");"; 00594 nl(Out); 00595 break; 00596 } 00597 case Type::PointerTyID: { 00598 const PointerType* PT = cast<PointerType>(Ty); 00599 const Type* ET = PT->getElementType(); 00600 bool isForward = printTypeInternal(ET); 00601 std::string elemName(getCppName(ET)); 00602 Out << "PointerType* " << typeName << " = PointerType::get(" 00603 << elemName << (isForward ? "_fwd" : "") 00604 << ", " << utostr(PT->getAddressSpace()) << ");"; 00605 nl(Out); 00606 break; 00607 } 00608 case Type::VectorTyID: { 00609 const VectorType* PT = cast<VectorType>(Ty); 00610 const Type* ET = PT->getElementType(); 00611 bool isForward = printTypeInternal(ET); 00612 std::string elemName(getCppName(ET)); 00613 Out << "VectorType* " << typeName << " = VectorType::get(" 00614 << elemName << (isForward ? "_fwd" : "") 00615 << ", " << utostr(PT->getNumElements()) << ");"; 00616 nl(Out); 00617 break; 00618 } 00619 case Type::OpaqueTyID: { 00620 Out << "OpaqueType* " << typeName; 00621 Out << " = OpaqueType::get(getGlobalContext());"; 00622 nl(Out); 00623 break; 00624 } 00625 default: 00626 error("Invalid TypeID"); 00627 } 00628 00629 // If the type had a name, make sure we recreate it. 00630 const std::string* progTypeName = 00631 findTypeName(TheModule->getTypeSymbolTable(),Ty); 00632 if (progTypeName) { 00633 Out << "mod->addTypeName(\"" << *progTypeName << "\", " 00634 << typeName << ");"; 00635 nl(Out); 00636 } 00637 00638 // Pop us off the type stack 00639 TypeStack.pop_back(); 00640 00641 // Indicate that this type is now defined. 00642 DefinedTypes.insert(Ty); 00643 00644 // Early resolve as many unresolved types as possible. Search the unresolved 00645 // types map for the type we just printed. Now that its definition is complete 00646 // we can resolve any previous references to it. This prevents a cascade of 00647 // unresolved types. 00648 TypeMap::iterator I = UnresolvedTypes.find(Ty); 00649 if (I != UnresolvedTypes.end()) { 00650 Out << "cast<OpaqueType>(" << I->second 00651 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");"; 00652 nl(Out); 00653 Out << I->second << " = cast<"; 00654 switch (Ty->getTypeID()) { 00655 case Type::FunctionTyID: Out << "FunctionType"; break; 00656 case Type::ArrayTyID: Out << "ArrayType"; break; 00657 case Type::StructTyID: Out << "StructType"; break; 00658 case Type::VectorTyID: Out << "VectorType"; break; 00659 case Type::PointerTyID: Out << "PointerType"; break; 00660 case Type::OpaqueTyID: Out << "OpaqueType"; break; 00661 default: Out << "NoSuchDerivedType"; break; 00662 } 00663 Out << ">(" << I->second << "_fwd.get());"; 00664 nl(Out); nl(Out); 00665 UnresolvedTypes.erase(I); 00666 } 00667 00668 // Finally, separate the type definition from other with a newline. 00669 nl(Out); 00670 00671 // We weren't a recursive type 00672 return false; 00673 } 00674 00675 // Prints a type definition. Returns true if it could not resolve all the 00676 // types in the definition but had to use a forward reference. 00677 void CppWriter::printType(const Type* Ty) { 00678 assert(TypeStack.empty()); 00679 TypeStack.clear(); 00680 printTypeInternal(Ty); 00681 assert(TypeStack.empty()); 00682 } 00683 00684 void CppWriter::printTypes(const Module* M) { 00685 // Walk the symbol table and print out all its types 00686 const TypeSymbolTable& symtab = M->getTypeSymbolTable(); 00687 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end(); 00688 TI != TE; ++TI) { 00689 00690 // For primitive types and types already defined, just add a name 00691 TypeMap::const_iterator TNI = TypeNames.find(TI->second); 00692 if (TI->second->isInteger() || TI->second->isPrimitiveType() || 00693 TNI != TypeNames.end()) { 00694 Out << "mod->addTypeName(\""; 00695 printEscapedString(TI->first); 00696 Out << "\", " << getCppName(TI->second) << ");"; 00697 nl(Out); 00698 // For everything else, define the type 00699 } else { 00700 printType(TI->second); 00701 } 00702 } 00703 00704 // Add all of the global variables to the value table... 00705 for (Module::const_global_iterator I = TheModule->global_begin(), 00706 E = TheModule->global_end(); I != E; ++I) { 00707 if (I->hasInitializer()) 00708 printType(I->getInitializer()->getType()); 00709 printType(I->getType()); 00710 } 00711 00712 // Add all the functions to the table 00713 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end(); 00714 FI != FE; ++FI) { 00715 printType(FI->getReturnType()); 00716 printType(FI->getFunctionType()); 00717 // Add all the function arguments 00718 for (Function::const_arg_iterator AI = FI->arg_begin(), 00719 AE = FI->arg_end(); AI != AE; ++AI) { 00720 printType(AI->getType()); 00721 } 00722 00723 // Add all of the basic blocks and instructions 00724 for (Function::const_iterator BB = FI->begin(), 00725 E = FI->end(); BB != E; ++BB) { 00726 printType(BB->getType()); 00727 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; 00728 ++I) { 00729 printType(I->getType()); 00730 for (unsigned i = 0; i < I->getNumOperands(); ++i) 00731 printType(I->getOperand(i)->getType()); 00732 } 00733 } 00734 } 00735 } 00736 00737 00738 // printConstant - Print out a constant pool entry... 00739 void CppWriter::printConstant(const Constant *CV) { 00740 // First, if the constant is actually a GlobalValue (variable or function) 00741 // or its already in the constant list then we've printed it already and we 00742 // can just return. 00743 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end()) 00744 return; 00745 00746 std::string constName(getCppName(CV)); 00747 std::string typeName(getCppName(CV->getType())); 00748 00749 if (isa<GlobalValue>(CV)) { 00750 // Skip variables and functions, we emit them elsewhere 00751 return; 00752 } 00753 00754 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 00755 std::string constValue = CI->getValue().toString(10, true); 00756 Out << "ConstantInt* " << constName 00757 << " = ConstantInt::get(getGlobalContext(), APInt(" 00758 << cast<IntegerType>(CI->getType())->getBitWidth() 00759 << ", StringRef(\"" << constValue << "\"), 10));"; 00760 } else if (isa<ConstantAggregateZero>(CV)) { 00761 Out << "ConstantAggregateZero* " << constName 00762 << " = ConstantAggregateZero::get(" << typeName << ");"; 00763 } else if (isa<ConstantPointerNull>(CV)) { 00764 Out << "ConstantPointerNull* " << constName 00765 << " = ConstantPointerNull::get(" << typeName << ");"; 00766 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) { 00767 Out << "ConstantFP* " << constName << " = "; 00768 printCFP(CFP); 00769 Out << ";"; 00770 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) { 00771 if (CA->isString() && 00772 CA->getType()->getElementType() == 00773 Type::getInt8Ty(CA->getContext())) { 00774 Out << "Constant* " << constName << 00775 " = ConstantArray::get(getGlobalContext(), \""; 00776 std::string tmp = CA->getAsString(); 00777 bool nullTerminate = false; 00778 if (tmp[tmp.length()-1] == 0) { 00779 tmp.erase(tmp.length()-1); 00780 nullTerminate = true; 00781 } 00782 printEscapedString(tmp); 00783 // Determine if we want null termination or not. 00784 if (nullTerminate) 00785 Out << "\", true"; // Indicate that the null terminator should be 00786 // added. 00787 else 00788 Out << "\", false";// No null terminator 00789 Out << ");"; 00790 } else { 00791 Out << "std::vector<Constant*> " << constName << "_elems;"; 00792 nl(Out); 00793 unsigned N = CA->getNumOperands(); 00794 for (unsigned i = 0; i < N; ++i) { 00795 printConstant(CA->getOperand(i)); // recurse to print operands 00796 Out << constName << "_elems.push_back(" 00797 << getCppName(CA->getOperand(i)) << ");"; 00798 nl(Out); 00799 } 00800 Out << "Constant* " << constName << " = ConstantArray::get(" 00801 << typeName << ", " << constName << "_elems);"; 00802 } 00803 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) { 00804 Out << "std::vector<Constant*> " << constName << "_fields;"; 00805 nl(Out); 00806 unsigned N = CS->getNumOperands(); 00807 for (unsigned i = 0; i < N; i++) { 00808 printConstant(CS->getOperand(i)); 00809 Out << constName << "_fields.push_back(" 00810 << getCppName(CS->getOperand(i)) << ");"; 00811 nl(Out); 00812 } 00813 Out << "Constant* " << constName << " = ConstantStruct::get(" 00814 << typeName << ", " << constName << "_fields);"; 00815 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) { 00816 Out << "std::vector<Constant*> " << constName << "_elems;"; 00817 nl(Out); 00818 unsigned N = CP->getNumOperands(); 00819 for (unsigned i = 0; i < N; ++i) { 00820 printConstant(CP->getOperand(i)); 00821 Out << constName << "_elems.push_back(" 00822 << getCppName(CP->getOperand(i)) << ");"; 00823 nl(Out); 00824 } 00825 Out << "Constant* " << constName << " = ConstantVector::get(" 00826 << typeName << ", " << constName << "_elems);"; 00827 } else if (isa<UndefValue>(CV)) { 00828 Out << "UndefValue* " << constName << " = UndefValue::get(" 00829 << typeName << ");"; 00830 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 00831 if (CE->getOpcode() == Instruction::GetElementPtr) { 00832 Out << "std::vector<Constant*> " << constName << "_indices;"; 00833 nl(Out); 00834 printConstant(CE->getOperand(0)); 00835 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) { 00836 printConstant(CE->getOperand(i)); 00837 Out << constName << "_indices.push_back(" 00838 << getCppName(CE->getOperand(i)) << ");"; 00839 nl(Out); 00840 } 00841 Out << "Constant* " << constName 00842 << " = ConstantExpr::getGetElementPtr(" 00843 << getCppName(CE->getOperand(0)) << ", " 00844 << "&" << constName << "_indices[0], " 00845 << constName << "_indices.size()" 00846 << " );"; 00847 } else if (CE->isCast()) { 00848 printConstant(CE->getOperand(0)); 00849 Out << "Constant* " << constName << " = ConstantExpr::getCast("; 00850 switch (CE->getOpcode()) { 00851 default: llvm_unreachable("Invalid cast opcode"); 00852 case Instruction::Trunc: Out << "Instruction::Trunc"; break; 00853 case Instruction::ZExt: Out << "Instruction::ZExt"; break; 00854 case Instruction::SExt: Out << "Instruction::SExt"; break; 00855 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break; 00856 case Instruction::FPExt: Out << "Instruction::FPExt"; break; 00857 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break; 00858 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break; 00859 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break; 00860 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break; 00861 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break; 00862 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break; 00863 case Instruction::BitCast: Out << "Instruction::BitCast"; break; 00864 } 00865 Out << ", " << getCppName(CE->getOperand(0)) << ", " 00866 << getCppName(CE->getType()) << ");"; 00867 } else { 00868 unsigned N = CE->getNumOperands(); 00869 for (unsigned i = 0; i < N; ++i ) { 00870 printConstant(CE->getOperand(i)); 00871 } 00872 Out << "Constant* " << constName << " = ConstantExpr::"; 00873 switch (CE->getOpcode()) { 00874 case Instruction::Add: Out << "getAdd("; break; 00875 case Instruction::FAdd: Out << "getFAdd("; break; 00876 case Instruction::Sub: Out << "getSub("; break; 00877 case Instruction::FSub: Out << "getFSub("; break; 00878 case Instruction::Mul: Out << "getMul("; break; 00879 case Instruction::FMul: Out << "getFMul("; break; 00880 case Instruction::UDiv: Out << "getUDiv("; break; 00881 case Instruction::SDiv: Out << "getSDiv("; break; 00882 case Instruction::FDiv: Out << "getFDiv("; break; 00883 case Instruction::URem: Out << "getURem("; break; 00884 case Instruction::SRem: Out << "getSRem("; break; 00885 case Instruction::FRem: Out << "getFRem("; break; 00886 case Instruction::And: Out << "getAnd("; break; 00887 case Instruction::Or: Out << "getOr("; break; 00888 case Instruction::Xor: Out << "getXor("; break; 00889 case Instruction::ICmp: 00890 Out << "getICmp(ICmpInst::ICMP_"; 00891 switch (CE->getPredicate()) { 00892 case ICmpInst::ICMP_EQ: Out << "EQ"; break; 00893 case ICmpInst::ICMP_NE: Out << "NE"; break; 00894 case ICmpInst::ICMP_SLT: Out << "SLT"; break; 00895 case ICmpInst::ICMP_ULT: Out << "ULT"; break; 00896 case ICmpInst::ICMP_SGT: Out << "SGT"; break; 00897 case ICmpInst::ICMP_UGT: Out << "UGT"; break; 00898 case ICmpInst::ICMP_SLE: Out << "SLE"; break; 00899 case ICmpInst::ICMP_ULE: Out << "ULE"; break; 00900 case ICmpInst::ICMP_SGE: Out << "SGE"; break; 00901 case ICmpInst::ICMP_UGE: Out << "UGE"; break; 00902 default: error("Invalid ICmp Predicate"); 00903 } 00904 break; 00905 case Instruction::FCmp: 00906 Out << "getFCmp(FCmpInst::FCMP_"; 00907 switch (CE->getPredicate()) { 00908 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break; 00909 case FCmpInst::FCMP_ORD: Out << "ORD"; break; 00910 case FCmpInst::FCMP_UNO: Out << "UNO"; break; 00911 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break; 00912 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break; 00913 case FCmpInst::FCMP_ONE: Out << "ONE"; break; 00914 case FCmpInst::FCMP_UNE: Out << "UNE"; break; 00915 case FCmpInst::FCMP_OLT: Out << "OLT"; break; 00916 case FCmpInst::FCMP_ULT: Out << "ULT"; break; 00917 case FCmpInst::FCMP_OGT: Out << "OGT"; break; 00918 case FCmpInst::FCMP_UGT: Out << "UGT"; break; 00919 case FCmpInst::FCMP_OLE: Out << "OLE"; break; 00920 case FCmpInst::FCMP_ULE: Out << "ULE"; break; 00921 case FCmpInst::FCMP_OGE: Out << "OGE"; break; 00922 case FCmpInst::FCMP_UGE: Out << "UGE"; break; 00923 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break; 00924 default: error("Invalid FCmp Predicate"); 00925 } 00926 break; 00927 case Instruction::Shl: Out << "getShl("; break; 00928 case Instruction::LShr: Out << "getLShr("; break; 00929 case Instruction::AShr: Out << "getAShr("; break; 00930 case Instruction::Select: Out << "getSelect("; break; 00931 case Instruction::ExtractElement: Out << "getExtractElement("; break; 00932 case Instruction::InsertElement: Out << "getInsertElement("; break; 00933 case Instruction::ShuffleVector: Out << "getShuffleVector("; break; 00934 default: 00935 error("Invalid constant expression"); 00936 break; 00937 } 00938 Out << getCppName(CE->getOperand(0)); 00939 for (unsigned i = 1; i < CE->getNumOperands(); ++i) 00940 Out << ", " << getCppName(CE->getOperand(i)); 00941 Out << ");"; 00942 } 00943 } else { 00944 error("Bad Constant"); 00945 Out << "Constant* " << constName << " = 0; "; 00946 } 00947 nl(Out); 00948 } 00949 00950 void CppWriter::printConstants(const Module* M) { 00951 // Traverse all the global variables looking for constant initializers 00952 for (Module::const_global_iterator I = TheModule->global_begin(), 00953 E = TheModule->global_end(); I != E; ++I) 00954 if (I->hasInitializer()) 00955 printConstant(I->getInitializer()); 00956 00957 // Traverse the LLVM functions looking for constants 00958 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end(); 00959 FI != FE; ++FI) { 00960 // Add all of the basic blocks and instructions 00961 for (Function::const_iterator BB = FI->begin(), 00962 E = FI->end(); BB != E; ++BB) { 00963 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; 00964 ++I) { 00965 for (unsigned i = 0; i < I->getNumOperands(); ++i) { 00966 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) { 00967 printConstant(C); 00968 } 00969 } 00970 } 00971 } 00972 } 00973 } 00974 00975 void CppWriter::printVariableUses(const GlobalVariable *GV) { 00976 nl(Out) << "// Type Definitions"; 00977 nl(Out); 00978 printType(GV->getType()); 00979 if (GV->hasInitializer()) { 00980 Constant* Init = GV->getInitializer(); 00981 printType(Init->getType()); 00982 if (Function* F = dyn_cast<Function>(Init)) { 00983 nl(Out)<< "/ Function Declarations"; nl(Out); 00984 printFunctionHead(F); 00985 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) { 00986 nl(Out) << "// Global Variable Declarations"; nl(Out); 00987 printVariableHead(gv); 00988 } else { 00989 nl(Out) << "// Constant Definitions"; nl(Out); 00990 printConstant(gv); 00991 } 00992 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) { 00993 nl(Out) << "// Global Variable Definitions"; nl(Out); 00994 printVariableBody(gv); 00995 } 00996 } 00997 } 00998 00999 void CppWriter::printVariableHead(const GlobalVariable *GV) { 01000 nl(Out) << "GlobalVariable* " << getCppName(GV); 01001 if (is_inline) { 01002 Out << " = mod->getGlobalVariable(getGlobalContext(), "; 01003 printEscapedString(GV->getName()); 01004 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)"; 01005 nl(Out) << "if (!" << getCppName(GV) << ") {"; 01006 in(); nl(Out) << getCppName(GV); 01007 } 01008 Out << " = new GlobalVariable(/*Module=*/*mod, "; 01009 nl(Out) << "/*Type=*/"; 01010 printCppName(GV->getType()->getElementType()); 01011 Out << ","; 01012 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false"); 01013 Out << ","; 01014 nl(Out) << "/*Linkage=*/"; 01015 printLinkageType(GV->getLinkage()); 01016 Out << ","; 01017 nl(Out) << "/*Initializer=*/0, "; 01018 if (GV->hasInitializer()) { 01019 Out << "// has initializer, specified below"; 01020 } 01021 nl(Out) << "/*Name=*/\""; 01022 printEscapedString(GV->getName()); 01023 Out << "\");"; 01024 nl(Out); 01025 01026 if (GV->hasSection()) { 01027 printCppName(GV); 01028 Out << "->setSection(\""; 01029 printEscapedString(GV->getSection()); 01030 Out << "\");"; 01031 nl(Out); 01032 } 01033 if (GV->getAlignment()) { 01034 printCppName(GV); 01035 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");"; 01036 nl(Out); 01037 } 01038 if (GV->getVisibility() != GlobalValue::DefaultVisibility) { 01039 printCppName(GV); 01040 Out << "->setVisibility("; 01041 printVisibilityType(GV->getVisibility()); 01042 Out << ");"; 01043 nl(Out); 01044 } 01045 if (is_inline) { 01046 out(); Out << "}"; nl(Out); 01047 } 01048 } 01049 01050 void CppWriter::printVariableBody(const GlobalVariable *GV) { 01051 if (GV->hasInitializer()) { 01052 printCppName(GV); 01053 Out << "->setInitializer("; 01054 Out << getCppName(GV->getInitializer()) << ");"; 01055 nl(Out); 01056 } 01057 } 01058 01059 std::string CppWriter::getOpName(Value* V) { 01060 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end()) 01061 return getCppName(V); 01062 01063 // See if its alread in the map of forward references, if so just return the 01064 // name we already set up for it 01065 ForwardRefMap::const_iterator I = ForwardRefs.find(V); 01066 if (I != ForwardRefs.end()) 01067 return I->second; 01068 01069 // This is a new forward reference. Generate a unique name for it 01070 std::string result(std::string("fwdref_") + utostr(uniqueNum++)); 01071 01072 // Yes, this is a hack. An Argument is the smallest instantiable value that 01073 // we can make as a placeholder for the real value. We'll replace these 01074 // Argument instances later. 01075 Out << "Argument* " << result << " = new Argument(" 01076 << getCppName(V->getType()) << ");"; 01077 nl(Out); 01078 ForwardRefs[V] = result; 01079 return result; 01080 } 01081 01082 // printInstruction - This member is called for each Instruction in a function. 01083 void CppWriter::printInstruction(const Instruction *I, 01084 const std::string& bbname) { 01085 std::string iName(getCppName(I)); 01086 01087 // Before we emit this instruction, we need to take care of generating any 01088 // forward references. So, we get the names of all the operands in advance 01089 std::string* opNames = new std::string[I->getNumOperands()]; 01090 for (unsigned i = 0; i < I->getNumOperands(); i++) { 01091 opNames[i] = getOpName(I->getOperand(i)); 01092 } 01093 01094 switch (I->getOpcode()) { 01095 default: 01096 error("Invalid instruction"); 01097 break; 01098 01099 case Instruction::Ret: { 01100 const ReturnInst* ret = cast<ReturnInst>(I); 01101 Out << "ReturnInst::Create(getGlobalContext(), " 01102 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");"; 01103 break; 01104 } 01105 case Instruction::Br: { 01106 const BranchInst* br = cast<BranchInst>(I); 01107 Out << "BranchInst::Create(" ; 01108 if (br->getNumOperands() == 3 ) { 01109 Out << opNames[2] << ", " 01110 << opNames[1] << ", " 01111 << opNames[0] << ", "; 01112 01113 } else if (br->getNumOperands() == 1) { 01114 Out << opNames[0] << ", "; 01115 } else { 01116 error("Branch with 2 operands?"); 01117 } 01118 Out << bbname << ");"; 01119 break; 01120 } 01121 case Instruction::Switch: { 01122 const SwitchInst* sw = cast<SwitchInst>(I); 01123 Out << "SwitchInst* " << iName << " = SwitchInst::Create(" 01124 << opNames[0] << ", " 01125 << opNames[1] << ", " 01126 << sw->getNumCases() << ", " << bbname << ");"; 01127 nl(Out); 01128 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) { 01129 Out << iName << "->addCase(" 01130 << opNames[i] << ", " 01131 << opNames[i+1] << ");"; 01132 nl(Out); 01133 } 01134 break; 01135 } 01136 case Instruction::Invoke: { 01137 const InvokeInst* inv = cast<InvokeInst>(I); 01138 Out << "std::vector<Value*> " << iName << "_params;"; 01139 nl(Out); 01140 for (unsigned i = 3; i < inv->getNumOperands(); ++i) { 01141 Out << iName << "_params.push_back(" 01142 << opNames[i] << ");"; 01143 nl(Out); 01144 } 01145 Out << "InvokeInst *" << iName << " = InvokeInst::Create(" 01146 << opNames[0] << ", " 01147 << opNames[1] << ", " 01148 << opNames[2] << ", " 01149 << iName << "_params.begin(), " << iName << "_params.end(), \""; 01150 printEscapedString(inv->getName()); 01151 Out << "\", " << bbname << ");"; 01152 nl(Out) << iName << "->setCallingConv("; 01153 printCallingConv(inv->getCallingConv()); 01154 Out << ");"; 01155 printAttributes(inv->getAttributes(), iName); 01156 Out << iName << "->setAttributes(" << iName << "_PAL);"; 01157 nl(Out); 01158 break; 01159 } 01160 case Instruction::Unwind: { 01161 Out << "new UnwindInst(" 01162 << bbname << ");"; 01163 break; 01164 } 01165 case Instruction::Unreachable: { 01166 Out << "new UnreachableInst(" 01167 << "getGlobalContext(), " 01168 << bbname << ");"; 01169 break; 01170 } 01171 case Instruction::Add: 01172 case Instruction::FAdd: 01173 case Instruction::Sub: 01174 case Instruction::FSub: 01175 case Instruction::Mul: 01176 case Instruction::FMul: 01177 case Instruction::UDiv: 01178 case Instruction::SDiv: 01179 case Instruction::FDiv: 01180 case Instruction::URem: 01181 case Instruction::SRem: 01182 case Instruction::FRem: 01183 case Instruction::And: 01184 case Instruction::Or: 01185 case Instruction::Xor: 01186 case Instruction::Shl: 01187 case Instruction::LShr: 01188 case Instruction::AShr:{ 01189 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create("; 01190 switch (I->getOpcode()) { 01191 case Instruction::Add: Out << "Instruction::Add"; break; 01192 case Instruction::FAdd: Out << "Instruction::FAdd"; break; 01193 case Instruction::Sub: Out << "Instruction::Sub"; break; 01194 case Instruction::FSub: Out << "Instruction::FSub"; break; 01195 case Instruction::Mul: Out << "Instruction::Mul"; break; 01196 case Instruction::FMul: Out << "Instruction::FMul"; break; 01197 case Instruction::UDiv:Out << "Instruction::UDiv"; break; 01198 case Instruction::SDiv:Out << "Instruction::SDiv"; break; 01199 case Instruction::FDiv:Out << "Instruction::FDiv"; break; 01200 case Instruction::URem:Out << "Instruction::URem"; break; 01201 case Instruction::SRem:Out << "Instruction::SRem"; break; 01202 case Instruction::FRem:Out << "Instruction::FRem"; break; 01203 case Instruction::And: Out << "Instruction::And"; break; 01204 case Instruction::Or: Out << "Instruction::Or"; break; 01205 case Instruction::Xor: Out << "Instruction::Xor"; break; 01206 case Instruction::Shl: Out << "Instruction::Shl"; break; 01207 case Instruction::LShr:Out << "Instruction::LShr"; break; 01208 case Instruction::AShr:Out << "Instruction::AShr"; break; 01209 default: Out << "Instruction::BadOpCode"; break; 01210 } 01211 Out << ", " << opNames[0] << ", " << opNames[1] << ", \""; 01212 printEscapedString(I->getName()); 01213 Out << "\", " << bbname << ");"; 01214 break; 01215 } 01216 case Instruction::FCmp: { 01217 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", "; 01218 switch (cast<FCmpInst>(I)->getPredicate()) { 01219 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break; 01220 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break; 01221 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break; 01222 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break; 01223 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break; 01224 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break; 01225 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break; 01226 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break; 01227 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break; 01228 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break; 01229 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break; 01230 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break; 01231 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break; 01232 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break; 01233 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break; 01234 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break; 01235 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break; 01236 } 01237 Out << ", " << opNames[0] << ", " << opNames[1] << ", \""; 01238 printEscapedString(I->getName()); 01239 Out << "\");"; 01240 break; 01241 } 01242 case Instruction::ICmp: { 01243 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", "; 01244 switch (cast<ICmpInst>(I)->getPredicate()) { 01245 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break; 01246 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break; 01247 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break; 01248 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break; 01249 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break; 01250 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break; 01251 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break; 01252 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break; 01253 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break; 01254 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break; 01255 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break; 01256 } 01257 Out << ", " << opNames[0] << ", " << opNames[1] << ", \""; 01258 printEscapedString(I->getName()); 01259 Out << "\");"; 01260 break; 01261 } 01262 case Instruction::Malloc: { 01263 const MallocInst* mallocI = cast<MallocInst>(I); 01264 Out << "MallocInst* " << iName << " = new MallocInst(" 01265 << getCppName(mallocI->getAllocatedType()) << ", "; 01266 if (mallocI->isArrayAllocation()) 01267 Out << opNames[0] << ", " ; 01268 Out << "\""; 01269 printEscapedString(mallocI->getName()); 01270 Out << "\", " << bbname << ");"; 01271 if (mallocI->getAlignment()) 01272 nl(Out) << iName << "->setAlignment(" 01273 << mallocI->getAlignment() << ");"; 01274 break; 01275 } 01276 case Instruction::Free: { 01277 Out << "FreeInst* " << iName << " = new FreeInst(" 01278 << getCppName(I->getOperand(0)) << ", " << bbname << ");"; 01279 break; 01280 } 01281 case Instruction::Alloca: { 01282 const AllocaInst* allocaI = cast<AllocaInst>(I); 01283 Out << "AllocaInst* " << iName << " = new AllocaInst(" 01284 << getCppName(allocaI->getAllocatedType()) << ", "; 01285 if (allocaI->isArrayAllocation()) 01286 Out << opNames[0] << ", "; 01287 Out << "\""; 01288 printEscapedString(allocaI->getName()); 01289 Out << "\", " << bbname << ");"; 01290 if (allocaI->getAlignment()) 01291 nl(Out) << iName << "->setAlignment(" 01292 << allocaI->getAlignment() << ");"; 01293 break; 01294 } 01295 case Instruction::Load:{ 01296 const LoadInst* load = cast<LoadInst>(I); 01297 Out << "LoadInst* " << iName << " = new LoadInst(" 01298 << opNames[0] << ", \""; 01299 printEscapedString(load->getName()); 01300 Out << "\", " << (load->isVolatile() ? "true" : "false" ) 01301 << ", " << bbname << ");"; 01302 break; 01303 } 01304 case Instruction::Store: { 01305 const StoreInst* store = cast<StoreInst>(I); 01306 Out << " new StoreInst(" 01307 << opNames[0] << ", " 01308 << opNames[1] << ", " 01309 << (store->isVolatile() ? "true" : "false") 01310 << ", " << bbname << ");"; 01311 break; 01312 } 01313 case Instruction::GetElementPtr: { 01314 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I); 01315 if (gep->getNumOperands() <= 2) { 01316 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create(" 01317 << opNames[0]; 01318 if (gep->getNumOperands() == 2) 01319 Out << ", " << opNames[1]; 01320 } else { 01321 Out << "std::vector<Value*> " << iName << "_indices;"; 01322 nl(Out); 01323 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) { 01324 Out << iName << "_indices.push_back(" 01325 << opNames[i] << ");"; 01326 nl(Out); 01327 } 01328 Out << "Instruction* " << iName << " = GetElementPtrInst::Create(" 01329 << opNames[0] << ", " << iName << "_indices.begin(), " 01330 << iName << "_indices.end()"; 01331 } 01332 Out << ", \""; 01333 printEscapedString(gep->getName()); 01334 Out << "\", " << bbname << ");"; 01335 break; 01336 } 01337 case Instruction::PHI: { 01338 const PHINode* phi = cast<PHINode>(I); 01339 01340 Out << "PHINode* " << iName << " = PHINode::Create(" 01341 << getCppName(phi->getType()) << ", \""; 01342 printEscapedString(phi->getName()); 01343 Out << "\", " << bbname << ");"; 01344 nl(Out) << iName << "->reserveOperandSpace(" 01345 << phi->getNumIncomingValues() 01346 << ");"; 01347 nl(Out); 01348 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) { 01349 Out << iName << "->addIncoming(" 01350 << opNames[i] << ", " << opNames[i+1] << ");"; 01351 nl(Out); 01352 } 01353 break; 01354 } 01355 case Instruction::Trunc: 01356 case Instruction::ZExt: 01357 case Instruction::SExt: 01358 case Instruction::FPTrunc: 01359 case Instruction::FPExt: 01360 case Instruction::FPToUI: 01361 case Instruction::FPToSI: 01362 case Instruction::UIToFP: 01363 case Instruction::SIToFP: 01364 case Instruction::PtrToInt: 01365 case Instruction::IntToPtr: 01366 case Instruction::BitCast: { 01367 const CastInst* cst = cast<CastInst>(I); 01368 Out << "CastInst* " << iName << " = new "; 01369 switch (I->getOpcode()) { 01370 case Instruction::Trunc: Out << "TruncInst"; break; 01371 case Instruction::ZExt: Out << "ZExtInst"; break; 01372 case Instruction::SExt: Out << "SExtInst"; break; 01373 case Instruction::FPTrunc: Out << "FPTruncInst"; break; 01374 case Instruction::FPExt: Out << "FPExtInst"; break; 01375 case Instruction::FPToUI: Out << "FPToUIInst"; break; 01376 case Instruction::FPToSI: Out << "FPToSIInst"; break; 01377 case Instruction::UIToFP: Out << "UIToFPInst"; break; 01378 case Instruction::SIToFP: Out << "SIToFPInst"; break; 01379 case Instruction::PtrToInt: Out << "PtrToIntInst"; break; 01380 case Instruction::IntToPtr: Out << "IntToPtrInst"; break; 01381 case Instruction::BitCast: Out << "BitCastInst"; break; 01382 default: assert(!"Unreachable"); break; 01383 } 01384 Out << "(" << opNames[0] << ", " 01385 << getCppName(cst->getType()) << ", \""; 01386 printEscapedString(cst->getName()); 01387 Out << "\", " << bbname << ");"; 01388 break; 01389 } 01390 case Instruction::Call:{ 01391 const CallInst* call = cast<CallInst>(I); 01392 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) { 01393 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get(" 01394 << getCppName(ila->getFunctionType()) << ", \"" 01395 << ila->getAsmString() << "\", \"" 01396 << ila->getConstraintString() << "\"," 01397 << (ila->hasSideEffects() ? "true" : "false") << ");"; 01398 nl(Out); 01399 } 01400 if (call->getNumOperands() > 2) { 01401 Out << "std::vector<Value*> " << iName << "_params;"; 01402 nl(Out); 01403 for (unsigned i = 1; i < call->getNumOperands(); ++i) { 01404 Out << iName << "_params.push_back(" << opNames[i] << ");"; 01405 nl(Out); 01406 } 01407 Out << "CallInst* " << iName << " = CallInst::Create(" 01408 << opNames[0] << ", " << iName << "_params.begin(), " 01409 << iName << "_params.end(), \""; 01410 } else if (call->getNumOperands() == 2) { 01411 Out << "CallInst* " << iName << " = CallInst::Create(" 01412 << opNames[0] << ", " << opNames[1] << ", \""; 01413 } else { 01414 Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0] 01415 << ", \""; 01416 } 01417 printEscapedString(call->getName()); 01418 Out << "\", " << bbname << ");"; 01419 nl(Out) << iName << "->setCallingConv("; 01420 printCallingConv(call->getCallingConv()); 01421 Out << ");"; 01422 nl(Out) << iName << "->setTailCall(" 01423 << (call->isTailCall() ? "true":"false"); 01424 Out << ");"; 01425 printAttributes(call->getAttributes(), iName); 01426 Out << iName << "->setAttributes(" << iName << "_PAL);"; 01427 nl(Out); 01428 break; 01429 } 01430 case Instruction::Select: { 01431 const SelectInst* sel = cast<SelectInst>(I); 01432 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create("; 01433 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \""; 01434 printEscapedString(sel->getName()); 01435 Out << "\", " << bbname << ");"; 01436 break; 01437 } 01438 case Instruction::UserOp1: 01439 /// FALL THROUGH 01440 case Instruction::UserOp2: { 01441 /// FIXME: What should be done here? 01442 break; 01443 } 01444 case Instruction::VAArg: { 01445 const VAArgInst* va = cast<VAArgInst>(I); 01446 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst(" 01447 << opNames[0] << ", " << getCppName(va->getType()) << ", \""; 01448 printEscapedString(va->getName()); 01449 Out << "\", " << bbname << ");"; 01450 break; 01451 } 01452 case Instruction::ExtractElement: { 01453 const ExtractElementInst* eei = cast<ExtractElementInst>(I); 01454 Out << "ExtractElementInst* " << getCppName(eei) 01455 << " = new ExtractElementInst(" << opNames[0] 01456 << ", " << opNames[1] << ", \""; 01457 printEscapedString(eei->getName()); 01458 Out << "\", " << bbname << ");"; 01459 break; 01460 } 01461 case Instruction::InsertElement: { 01462 const InsertElementInst* iei = cast<InsertElementInst>(I); 01463 Out << "InsertElementInst* " << getCppName(iei) 01464 << " = InsertElementInst::Create(" << opNames[0] 01465 << ", " << opNames[1] << ", " << opNames[2] << ", \""; 01466 printEscapedString(iei->getName()); 01467 Out << "\", " << bbname << ");"; 01468 break; 01469 } 01470 case Instruction::ShuffleVector: { 01471 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I); 01472 Out << "ShuffleVectorInst* " << getCppName(svi) 01473 << " = new ShuffleVectorInst(" << opNames[0] 01474 << ", " << opNames[1] << ", " << opNames[2] << ", \""; 01475 printEscapedString(svi->getName()); 01476 Out << "\", " << bbname << ");"; 01477 break; 01478 } 01479 case Instruction::ExtractValue: { 01480 const ExtractValueInst *evi = cast<ExtractValueInst>(I); 01481 Out << "std::vector<unsigned> " << iName << "_indices;"; 01482 nl(Out); 01483 for (unsigned i = 0; i < evi->getNumIndices(); ++i) { 01484 Out << iName << "_indices.push_back(" 01485 << evi->idx_begin()[i] << ");"; 01486 nl(Out); 01487 } 01488 Out << "ExtractValueInst* " << getCppName(evi) 01489 << " = ExtractValueInst::Create(" << opNames[0] 01490 << ", " 01491 << iName << "_indices.begin(), " << iName << "_indices.end(), \""; 01492 printEscapedString(evi->getName()); 01493 Out << "\", " << bbname << ");"; 01494 break; 01495 } 01496 case Instruction::InsertValue: { 01497 const InsertValueInst *ivi = cast<InsertValueInst>(I); 01498 Out << "std::vector<unsigned> " << iName << "_indices;"; 01499 nl(Out); 01500 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) { 01501 Out << iName << "_indices.push_back(" 01502 << ivi->idx_begin()[i] << ");"; 01503 nl(Out); 01504 } 01505 Out << "InsertValueInst* " << getCppName(ivi) 01506 << " = InsertValueInst::Create(" << opNames[0] 01507 << ", " << opNames[1] << ", " 01508 << iName << "_indices.begin(), " << iName << "_indices.end(), \""; 01509 printEscapedString(ivi->getName()); 01510 Out << "\", " << bbname << ");"; 01511 break; 01512 } 01513 } 01514 DefinedValues.insert(I); 01515 nl(Out); 01516 delete [] opNames; 01517 } 01518 01519 // Print out the types, constants and declarations needed by one function 01520 void CppWriter::printFunctionUses(const Function* F) { 01521 nl(Out) << "// Type Definitions"; nl(Out); 01522 if (!is_inline) { 01523 // Print the function's return type 01524 printType(F->getReturnType()); 01525 01526 // Print the function's function type 01527 printType(F->getFunctionType()); 01528 01529 // Print the types of each of the function's arguments 01530 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end(); 01531 AI != AE; ++AI) { 01532 printType(AI->getType()); 01533 } 01534 } 01535 01536 // Print type definitions for every type referenced by an instruction and 01537 // make a note of any global values or constants that are referenced 01538 SmallPtrSet<GlobalValue*,64> gvs; 01539 SmallPtrSet<Constant*,64> consts; 01540 for (Function::const_iterator BB = F->begin(), BE = F->end(); 01541 BB != BE; ++BB){ 01542 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); 01543 I != E; ++I) { 01544 // Print the type of the instruction itself 01545 printType(I->getType()); 01546 01547 // Print the type of each of the instruction's operands 01548 for (unsigned i = 0; i < I->getNumOperands(); ++i) { 01549 Value* operand = I->getOperand(i); 01550 printType(operand->getType()); 01551 01552 // If the operand references a GVal or Constant, make a note of it 01553 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) { 01554 gvs.insert(GV); 01555 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) 01556 if (GVar->hasInitializer()) 01557 consts.insert(GVar->getInitializer()); 01558 } else if (Constant* C = dyn_cast<Constant>(operand)) 01559 consts.insert(C); 01560 } 01561 } 01562 } 01563 01564 // Print the function declarations for any functions encountered 01565 nl(Out) << "// Function Declarations"; nl(Out); 01566 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end(); 01567 I != E; ++I) { 01568 if (Function* Fun = dyn_cast<Function>(*I)) { 01569 if (!is_inline || Fun != F) 01570 printFunctionHead(Fun); 01571 } 01572 } 01573 01574 // Print the global variable declarations for any variables encountered 01575 nl(Out) << "// Global Variable Declarations"; nl(Out); 01576 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end(); 01577 I != E; ++I) { 01578 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I)) 01579 printVariableHead(F); 01580 } 01581 01582 // Print the constants found 01583 nl(Out) << "// Constant Definitions"; nl(Out); 01584 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(), 01585 E = consts.end(); I != E; ++I) { 01586 printConstant(*I); 01587 } 01588 01589 // Process the global variables definitions now that all the constants have 01590 // been emitted. These definitions just couple the gvars with their constant 01591 // initializers. 01592 nl(Out) << "// Global Variable Definitions"; nl(Out); 01593 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end(); 01594 I != E; ++I) { 01595 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I)) 01596 printVariableBody(GV); 01597 } 01598 } 01599 01600 void CppWriter::printFunctionHead(const Function* F) { 01601 nl(Out) << "Function* " << getCppName(F); 01602 if (is_inline) { 01603 Out << " = mod->getFunction(\""; 01604 printEscapedString(F->getName()); 01605 Out << "\", " << getCppName(F->getFunctionType()) << ");"; 01606 nl(Out) << "if (!" << getCppName(F) << ") {"; 01607 nl(Out) << getCppName(F); 01608 } 01609 Out<< " = Function::Create("; 01610 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ","; 01611 nl(Out) << "/*Linkage=*/"; 01612 printLinkageType(F->getLinkage()); 01613 Out << ","; 01614 nl(Out) << "/*Name=*/\""; 01615 printEscapedString(F->getName()); 01616 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : ""); 01617 nl(Out,-1); 01618 printCppName(F); 01619 Out << "->setCallingConv("; 01620 printCallingConv(F->getCallingConv()); 01621 Out << ");"; 01622 nl(Out); 01623 if (F->hasSection()) { 01624 printCppName(F); 01625 Out << "->setSection(\"" << F->getSection() << "\");"; 01626 nl(Out); 01627 } 01628 if (F->getAlignment()) { 01629 printCppName(F); 01630 Out << "->setAlignment(" << F->getAlignment() << ");"; 01631 nl(Out); 01632 } 01633 if (F->getVisibility() != GlobalValue::DefaultVisibility) { 01634 printCppName(F); 01635 Out << "->setVisibility("; 01636 printVisibilityType(F->getVisibility()); 01637 Out << ");"; 01638 nl(Out); 01639 } 01640 if (F->hasGC()) { 01641 printCppName(F); 01642 Out << "->setGC(\"" << F->getGC() << "\");"; 01643 nl(Out); 01644 } 01645 if (is_inline) { 01646 Out << "}"; 01647 nl(Out); 01648 } 01649 printAttributes(F->getAttributes(), getCppName(F)); 01650 printCppName(F); 01651 Out << "->setAttributes(" << getCppName(F) << "_PAL);"; 01652 nl(Out); 01653 } 01654 01655 void CppWriter::printFunctionBody(const Function *F) { 01656 if (F->isDeclaration()) 01657 return; // external functions have no bodies. 01658 01659 // Clear the DefinedValues and ForwardRefs maps because we can't have 01660 // cross-function forward refs 01661 ForwardRefs.clear(); 01662 DefinedValues.clear(); 01663 01664 // Create all the argument values 01665 if (!is_inline) { 01666 if (!F->arg_empty()) { 01667 Out << "Function::arg_iterator args = " << getCppName(F) 01668 << "->arg_begin();"; 01669 nl(Out); 01670 } 01671 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end(); 01672 AI != AE; ++AI) { 01673 Out << "Value* " << getCppName(AI) << " = args++;"; 01674 nl(Out); 01675 if (AI->hasName()) { 01676 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");"; 01677 nl(Out); 01678 } 01679 } 01680 } 01681 01682 // Create all the basic blocks 01683 nl(Out); 01684 for (Function::const_iterator BI = F->begin(), BE = F->end(); 01685 BI != BE; ++BI) { 01686 std::string bbname(getCppName(BI)); 01687 Out << "BasicBlock* " << bbname << 01688 " = BasicBlock::Create(getGlobalContext(), \""; 01689 if (BI->hasName()) 01690 printEscapedString(BI->getName()); 01691 Out << "\"," << getCppName(BI->getParent()) << ",0);"; 01692 nl(Out); 01693 } 01694 01695 // Output all of its basic blocks... for the function 01696 for (Function::const_iterator BI = F->begin(), BE = F->end(); 01697 BI != BE; ++BI) { 01698 std::string bbname(getCppName(BI)); 01699 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")"; 01700 nl(Out); 01701 01702 // Output all of the instructions in the basic block... 01703 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end(); 01704 I != E; ++I) { 01705 printInstruction(I,bbname); 01706 } 01707 } 01708 01709 // Loop over the ForwardRefs and resolve them now that all instructions 01710 // are generated. 01711 if (!ForwardRefs.empty()) { 01712 nl(Out) << "// Resolve Forward References"; 01713 nl(Out); 01714 } 01715 01716 while (!ForwardRefs.empty()) { 01717 ForwardRefMap::iterator I = ForwardRefs.begin(); 01718 Out << I->second << "->replaceAllUsesWith(" 01719 << getCppName(I->first) << "); delete " << I->second << ";"; 01720 nl(Out); 01721 ForwardRefs.erase(I); 01722 } 01723 } 01724 01725 void CppWriter::printInline(const std::string& fname, 01726 const std::string& func) { 01727 const Function* F = TheModule->getFunction(func); 01728 if (!F) { 01729 error(std::string("Function '") + func + "' not found in input module"); 01730 return; 01731 } 01732 if (F->isDeclaration()) { 01733 error(std::string("Function '") + func + "' is external!"); 01734 return; 01735 } 01736 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *" 01737 << getCppName(F); 01738 unsigned arg_count = 1; 01739 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end(); 01740 AI != AE; ++AI) { 01741 Out << ", Value* arg_" << arg_count; 01742 } 01743 Out << ") {"; 01744 nl(Out); 01745 is_inline = true; 01746 printFunctionUses(F); 01747 printFunctionBody(F); 01748 is_inline = false; 01749 Out << "return " << getCppName(F->begin()) << ";"; 01750 nl(Out) << "}"; 01751 nl(Out); 01752 } 01753 01754 void CppWriter::printModuleBody() { 01755 // Print out all the type definitions 01756 nl(Out) << "// Type Definitions"; nl(Out); 01757 printTypes(TheModule); 01758 01759 // Functions can call each other and global variables can reference them so 01760 // define all the functions first before emitting their function bodies. 01761 nl(Out) << "// Function Declarations"; nl(Out); 01762 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end(); 01763 I != E; ++I) 01764 printFunctionHead(I); 01765 01766 // Process the global variables declarations. We can't initialze them until 01767 // after the constants are printed so just print a header for each global 01768 nl(Out) << "// Global Variable Declarations\n"; nl(Out); 01769 for (Module::const_global_iterator I = TheModule->global_begin(), 01770 E = TheModule->global_end(); I != E; ++I) { 01771 printVariableHead(I); 01772 } 01773 01774 // Print out all the constants definitions. Constants don't recurse except 01775 // through GlobalValues. All GlobalValues have been declared at this point 01776 // so we can proceed to generate the constants. 01777 nl(Out) << "// Constant Definitions"; nl(Out); 01778 printConstants(TheModule); 01779 01780 // Process the global variables definitions now that all the constants have 01781 // been emitted. These definitions just couple the gvars with their constant 01782 // initializers. 01783 nl(Out) << "// Global Variable Definitions"; nl(Out); 01784 for (Module::const_global_iterator I = TheModule->global_begin(), 01785 E = TheModule->global_end(); I != E; ++I) { 01786 printVariableBody(I); 01787 } 01788 01789 // Finally, we can safely put out all of the function bodies. 01790 nl(Out) << "// Function Definitions"; nl(Out); 01791 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end(); 01792 I != E; ++I) { 01793 if (!I->isDeclaration()) { 01794 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I) 01795 << ")"; 01796 nl(Out) << "{"; 01797 nl(Out,1); 01798 printFunctionBody(I); 01799 nl(Out,-1) << "}"; 01800 nl(Out); 01801 } 01802 } 01803 } 01804 01805 void CppWriter::printProgram(const std::string& fname, 01806 const std::string& mName) { 01807 Out << "#include <llvm/LLVMContext.h>\n"; 01808 Out << "#include <llvm/Module.h>\n"; 01809 Out << "#include <llvm/DerivedTypes.h>\n"; 01810 Out << "#include <llvm/Constants.h>\n"; 01811 Out << "#include <llvm/GlobalVariable.h>\n"; 01812 Out << "#include <llvm/Function.h>\n"; 01813 Out << "#include <llvm/CallingConv.h>\n"; 01814 Out << "#include <llvm/BasicBlock.h>\n"; 01815 Out << "#include <llvm/Instructions.h>\n"; 01816 Out << "#include <llvm/InlineAsm.h>\n"; 01817 Out << "#include <llvm/Support/FormattedStream.h>\n"; 01818 Out << "#include <llvm/Support/MathExtras.h>\n"; 01819 Out << "#include <llvm/Pass.h>\n"; 01820 Out << "#include <llvm/PassManager.h>\n"; 01821 Out << "#include <llvm/ADT/SmallVector.h>\n"; 01822 Out << "#include <llvm/Analysis/Verifier.h>\n"; 01823 Out << "#include <llvm/Assembly/PrintModulePass.h>\n"; 01824 Out << "#include <algorithm>\n"; 01825 Out << "using namespace llvm;\n\n"; 01826 Out << "Module* " << fname << "();\n\n"; 01827 Out << "int main(int argc, char**argv) {\n"; 01828 Out << " Module* Mod = " << fname << "();\n"; 01829 Out << " verifyModule(*Mod, PrintMessageAction);\n"; 01830 Out << " PassManager PM;\n"; 01831 Out << " PM.add(createPrintModulePass(&outs()));\n"; 01832 Out << " PM.run(*Mod);\n"; 01833 Out << " return 0;\n"; 01834 Out << "}\n\n"; 01835 printModule(fname,mName); 01836 } 01837 01838 void CppWriter::printModule(const std::string& fname, 01839 const std::string& mName) { 01840 nl(Out) << "Module* " << fname << "() {"; 01841 nl(Out,1) << "// Module Construction"; 01842 nl(Out) << "Module* mod = new Module(\""; 01843 printEscapedString(mName); 01844 Out << "\", getGlobalContext());"; 01845 if (!TheModule->getTargetTriple().empty()) { 01846 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");"; 01847 } 01848 if (!TheModule->getTargetTriple().empty()) { 01849 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple() 01850 << "\");"; 01851 } 01852 01853 if (!TheModule->getModuleInlineAsm().empty()) { 01854 nl(Out) << "mod->setModuleInlineAsm(\""; 01855 printEscapedString(TheModule->getModuleInlineAsm()); 01856 Out << "\");"; 01857 } 01858 nl(Out); 01859 01860 // Loop over the dependent libraries and emit them. 01861 Module::lib_iterator LI = TheModule->lib_begin(); 01862 Module::lib_iterator LE = TheModule->lib_end(); 01863 while (LI != LE) { 01864 Out << "mod->addLibrary(\"" << *LI << "\");"; 01865 nl(Out); 01866 ++LI; 01867 } 01868 printModuleBody(); 01869 nl(Out) << "return mod;"; 01870 nl(Out,-1) << "}"; 01871 nl(Out); 01872 } 01873 01874 void CppWriter::printContents(const std::string& fname, 01875 const std::string& mName) { 01876 Out << "\nModule* " << fname << "(Module *mod) {\n"; 01877 Out << "\nmod->setModuleIdentifier(\""; 01878 printEscapedString(mName); 01879 Out << "\");\n"; 01880 printModuleBody(); 01881 Out << "\nreturn mod;\n"; 01882 Out << "\n}\n"; 01883 } 01884 01885 void CppWriter::printFunction(const std::string& fname, 01886 const std::string& funcName) { 01887 const Function* F = TheModule->getFunction(funcName); 01888 if (!F) { 01889 error(std::string("Function '") + funcName + "' not found in input module"); 01890 return; 01891 } 01892 Out << "\nFunction* " << fname << "(Module *mod) {\n"; 01893 printFunctionUses(F); 01894 printFunctionHead(F); 01895 printFunctionBody(F); 01896 Out << "return " << getCppName(F) << ";\n"; 01897 Out << "}\n"; 01898 } 01899 01900 void CppWriter::printFunctions() { 01901 const Module::FunctionListType &funcs = TheModule->getFunctionList(); 01902 Module::const_iterator I = funcs.begin(); 01903 Module::const_iterator IE = funcs.end(); 01904 01905 for (; I != IE; ++I) { 01906 const Function &func = *I; 01907 if (!func.isDeclaration()) { 01908 std::string name("define_"); 01909 name += func.getName(); 01910 printFunction(name, func.getName()); 01911 } 01912 } 01913 } 01914 01915 void CppWriter::printVariable(const std::string& fname, 01916 const std::string& varName) { 01917 const GlobalVariable* GV = TheModule->getNamedGlobal(varName); 01918 01919 if (!GV) { 01920 error(std::string("Variable '") + varName + "' not found in input module"); 01921 return; 01922 } 01923 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n"; 01924 printVariableUses(GV); 01925 printVariableHead(GV); 01926 printVariableBody(GV); 01927 Out << "return " << getCppName(GV) << ";\n"; 01928 Out << "}\n"; 01929 } 01930 01931 void CppWriter::printType(const std::string& fname, 01932 const std::string& typeName) { 01933 const Type* Ty = TheModule->getTypeByName(typeName); 01934 if (!Ty) { 01935 error(std::string("Type '") + typeName + "' not found in input module"); 01936 return; 01937 } 01938 Out << "\nType* " << fname << "(Module *mod) {\n"; 01939 printType(Ty); 01940 Out << "return " << getCppName(Ty) << ";\n"; 01941 Out << "}\n"; 01942 } 01943 01944 bool CppWriter::runOnModule(Module &M) { 01945 TheModule = &M; 01946 01947 // Emit a header 01948 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n"; 01949 01950 // Get the name of the function we're supposed to generate 01951 std::string fname = FuncName.getValue(); 01952 01953 // Get the name of the thing we are to generate 01954 std::string tgtname = NameToGenerate.getValue(); 01955 if (GenerationType == GenModule || 01956 GenerationType == GenContents || 01957 GenerationType == GenProgram || 01958 GenerationType == GenFunctions) { 01959 if (tgtname == "!bad!") { 01960 if (M.getModuleIdentifier() == "-") 01961 tgtname = "<stdin>"; 01962 else 01963 tgtname = M.getModuleIdentifier(); 01964 } 01965 } else if (tgtname == "!bad!") 01966 error("You must use the -for option with -gen-{function,variable,type}"); 01967 01968 switch (WhatToGenerate(GenerationType)) { 01969 case GenProgram: 01970 if (fname.empty()) 01971 fname = "makeLLVMModule"; 01972 printProgram(fname,tgtname); 01973 break; 01974 case GenModule: 01975 if (fname.empty()) 01976 fname = "makeLLVMModule"; 01977 printModule(fname,tgtname); 01978 break; 01979 case GenContents: 01980 if (fname.empty()) 01981 fname = "makeLLVMModuleContents"; 01982 printContents(fname,tgtname); 01983 break; 01984 case GenFunction: 01985 if (fname.empty()) 01986 fname = "makeLLVMFunction"; 01987 printFunction(fname,tgtname); 01988 break; 01989 case GenFunctions: 01990 printFunctions(); 01991 break; 01992 case GenInline: 01993 if (fname.empty()) 01994 fname = "makeLLVMInline"; 01995 printInline(fname,tgtname); 01996 break; 01997 case GenVariable: 01998 if (fname.empty()) 01999 fname = "makeLLVMVariable"; 02000 printVariable(fname,tgtname); 02001 break; 02002 case GenType: 02003 if (fname.empty()) 02004 fname = "makeLLVMType"; 02005 printType(fname,tgtname); 02006 break; 02007 default: 02008 error("Invalid generation option"); 02009 } 02010 02011 return false; 02012 } 02013 } 02014 02015 char CppWriter::ID = 0; 02016 02017 //===----------------------------------------------------------------------===// 02018 // External Interface declaration 02019 //===----------------------------------------------------------------------===// 02020 02021 bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM, 02022 formatted_raw_ostream &o, 02023 CodeGenFileType FileType, 02024 CodeGenOpt::Level OptLevel) { 02025 if (FileType != TargetMachine::AssemblyFile) return true; 02026 PM.add(new CppWriter(o)); 02027 return false; 02028 }