CPPBackend.cpp 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019
  1. //===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the writing of the LLVM IR as a set of C++ calls to the
  11. // LLVM IR interface. The input module is assumed to be verified.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "CPPTargetMachine.h"
  15. #include "llvm/CallingConv.h"
  16. #include "llvm/Constants.h"
  17. #include "llvm/DerivedTypes.h"
  18. #include "llvm/InlineAsm.h"
  19. #include "llvm/Instruction.h"
  20. #include "llvm/Instructions.h"
  21. #include "llvm/Module.h"
  22. #include "llvm/Pass.h"
  23. #include "llvm/PassManager.h"
  24. #include "llvm/TypeSymbolTable.h"
  25. #include "llvm/ADT/SmallPtrSet.h"
  26. #include "llvm/Support/CommandLine.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include "llvm/Support/FormattedStream.h"
  29. #include "llvm/Target/TargetRegistry.h"
  30. #include "llvm/ADT/StringExtras.h"
  31. #include "llvm/Config/config.h"
  32. #include <algorithm>
  33. #include <set>
  34. using namespace llvm;
  35. static cl::opt<std::string>
  36. FuncName("cppfname", cl::desc("Specify the name of the generated function"),
  37. cl::value_desc("function name"));
  38. enum WhatToGenerate {
  39. GenProgram,
  40. GenModule,
  41. GenContents,
  42. GenFunction,
  43. GenFunctions,
  44. GenInline,
  45. GenVariable,
  46. GenType
  47. };
  48. static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
  49. cl::desc("Choose what kind of output to generate"),
  50. cl::init(GenProgram),
  51. cl::values(
  52. clEnumValN(GenProgram, "program", "Generate a complete program"),
  53. clEnumValN(GenModule, "module", "Generate a module definition"),
  54. clEnumValN(GenContents, "contents", "Generate contents of a module"),
  55. clEnumValN(GenFunction, "function", "Generate a function definition"),
  56. clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
  57. clEnumValN(GenInline, "inline", "Generate an inline function"),
  58. clEnumValN(GenVariable, "variable", "Generate a variable definition"),
  59. clEnumValN(GenType, "type", "Generate a type definition"),
  60. clEnumValEnd
  61. )
  62. );
  63. static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
  64. cl::desc("Specify the name of the thing to generate"),
  65. cl::init("!bad!"));
  66. extern "C" void LLVMInitializeCppBackendTarget() {
  67. // Register the target.
  68. RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
  69. }
  70. namespace {
  71. typedef std::vector<const Type*> TypeList;
  72. typedef std::map<const Type*,std::string> TypeMap;
  73. typedef std::map<const Value*,std::string> ValueMap;
  74. typedef std::set<std::string> NameSet;
  75. typedef std::set<const Type*> TypeSet;
  76. typedef std::set<const Value*> ValueSet;
  77. typedef std::map<const Value*,std::string> ForwardRefMap;
  78. /// CppWriter - This class is the main chunk of code that converts an LLVM
  79. /// module to a C++ translation unit.
  80. class CppWriter : public ModulePass {
  81. formatted_raw_ostream &Out;
  82. const Module *TheModule;
  83. uint64_t uniqueNum;
  84. TypeMap TypeNames;
  85. ValueMap ValueNames;
  86. TypeMap UnresolvedTypes;
  87. TypeList TypeStack;
  88. NameSet UsedNames;
  89. TypeSet DefinedTypes;
  90. ValueSet DefinedValues;
  91. ForwardRefMap ForwardRefs;
  92. bool is_inline;
  93. public:
  94. static char ID;
  95. explicit CppWriter(formatted_raw_ostream &o) :
  96. ModulePass(&ID), Out(o), uniqueNum(0), is_inline(false) {}
  97. virtual const char *getPassName() const { return "C++ backend"; }
  98. bool runOnModule(Module &M);
  99. void printProgram(const std::string& fname, const std::string& modName );
  100. void printModule(const std::string& fname, const std::string& modName );
  101. void printContents(const std::string& fname, const std::string& modName );
  102. void printFunction(const std::string& fname, const std::string& funcName );
  103. void printFunctions();
  104. void printInline(const std::string& fname, const std::string& funcName );
  105. void printVariable(const std::string& fname, const std::string& varName );
  106. void printType(const std::string& fname, const std::string& typeName );
  107. void error(const std::string& msg);
  108. private:
  109. void printLinkageType(GlobalValue::LinkageTypes LT);
  110. void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
  111. void printCallingConv(CallingConv::ID cc);
  112. void printEscapedString(const std::string& str);
  113. void printCFP(const ConstantFP* CFP);
  114. std::string getCppName(const Type* val);
  115. inline void printCppName(const Type* val);
  116. std::string getCppName(const Value* val);
  117. inline void printCppName(const Value* val);
  118. void printAttributes(const AttrListPtr &PAL, const std::string &name);
  119. bool printTypeInternal(const Type* Ty);
  120. inline void printType(const Type* Ty);
  121. void printTypes(const Module* M);
  122. void printConstant(const Constant *CPV);
  123. void printConstants(const Module* M);
  124. void printVariableUses(const GlobalVariable *GV);
  125. void printVariableHead(const GlobalVariable *GV);
  126. void printVariableBody(const GlobalVariable *GV);
  127. void printFunctionUses(const Function *F);
  128. void printFunctionHead(const Function *F);
  129. void printFunctionBody(const Function *F);
  130. void printInstruction(const Instruction *I, const std::string& bbname);
  131. std::string getOpName(Value*);
  132. void printModuleBody();
  133. };
  134. static unsigned indent_level = 0;
  135. inline formatted_raw_ostream& nl(formatted_raw_ostream& Out, int delta = 0) {
  136. Out << "\n";
  137. if (delta >= 0 || indent_level >= unsigned(-delta))
  138. indent_level += delta;
  139. for (unsigned i = 0; i < indent_level; ++i)
  140. Out << " ";
  141. return Out;
  142. }
  143. inline void in() { indent_level++; }
  144. inline void out() { if (indent_level >0) indent_level--; }
  145. inline void
  146. sanitize(std::string& str) {
  147. for (size_t i = 0; i < str.length(); ++i)
  148. if (!isalnum(str[i]) && str[i] != '_')
  149. str[i] = '_';
  150. }
  151. inline std::string
  152. getTypePrefix(const Type* Ty ) {
  153. switch (Ty->getTypeID()) {
  154. case Type::VoidTyID: return "void_";
  155. case Type::IntegerTyID:
  156. return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
  157. "_";
  158. case Type::FloatTyID: return "float_";
  159. case Type::DoubleTyID: return "double_";
  160. case Type::LabelTyID: return "label_";
  161. case Type::FunctionTyID: return "func_";
  162. case Type::StructTyID: return "struct_";
  163. case Type::ArrayTyID: return "array_";
  164. case Type::PointerTyID: return "ptr_";
  165. case Type::VectorTyID: return "packed_";
  166. case Type::OpaqueTyID: return "opaque_";
  167. default: return "other_";
  168. }
  169. return "unknown_";
  170. }
  171. // Looks up the type in the symbol table and returns a pointer to its name or
  172. // a null pointer if it wasn't found. Note that this isn't the same as the
  173. // Mode::getTypeName function which will return an empty string, not a null
  174. // pointer if the name is not found.
  175. inline const std::string*
  176. findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
  177. TypeSymbolTable::const_iterator TI = ST.begin();
  178. TypeSymbolTable::const_iterator TE = ST.end();
  179. for (;TI != TE; ++TI)
  180. if (TI->second == Ty)
  181. return &(TI->first);
  182. return 0;
  183. }
  184. void CppWriter::error(const std::string& msg) {
  185. llvm_report_error(msg);
  186. }
  187. // printCFP - Print a floating point constant .. very carefully :)
  188. // This makes sure that conversion to/from floating yields the same binary
  189. // result so that we don't lose precision.
  190. void CppWriter::printCFP(const ConstantFP *CFP) {
  191. bool ignored;
  192. APFloat APF = APFloat(CFP->getValueAPF()); // copy
  193. if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
  194. APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
  195. Out << "ConstantFP::get(getGlobalContext(), ";
  196. Out << "APFloat(";
  197. #if HAVE_PRINTF_A
  198. char Buffer[100];
  199. sprintf(Buffer, "%A", APF.convertToDouble());
  200. if ((!strncmp(Buffer, "0x", 2) ||
  201. !strncmp(Buffer, "-0x", 3) ||
  202. !strncmp(Buffer, "+0x", 3)) &&
  203. APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
  204. if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
  205. Out << "BitsToDouble(" << Buffer << ")";
  206. else
  207. Out << "BitsToFloat((float)" << Buffer << ")";
  208. Out << ")";
  209. } else {
  210. #endif
  211. std::string StrVal = ftostr(CFP->getValueAPF());
  212. while (StrVal[0] == ' ')
  213. StrVal.erase(StrVal.begin());
  214. // Check to make sure that the stringized number is not some string like
  215. // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
  216. if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
  217. ((StrVal[0] == '-' || StrVal[0] == '+') &&
  218. (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
  219. (CFP->isExactlyValue(atof(StrVal.c_str())))) {
  220. if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
  221. Out << StrVal;
  222. else
  223. Out << StrVal << "f";
  224. } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
  225. Out << "BitsToDouble(0x"
  226. << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
  227. << "ULL) /* " << StrVal << " */";
  228. else
  229. Out << "BitsToFloat(0x"
  230. << utohexstr((uint32_t)CFP->getValueAPF().
  231. bitcastToAPInt().getZExtValue())
  232. << "U) /* " << StrVal << " */";
  233. Out << ")";
  234. #if HAVE_PRINTF_A
  235. }
  236. #endif
  237. Out << ")";
  238. }
  239. void CppWriter::printCallingConv(CallingConv::ID cc){
  240. // Print the calling convention.
  241. switch (cc) {
  242. case CallingConv::C: Out << "CallingConv::C"; break;
  243. case CallingConv::Fast: Out << "CallingConv::Fast"; break;
  244. case CallingConv::Cold: Out << "CallingConv::Cold"; break;
  245. case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
  246. default: Out << cc; break;
  247. }
  248. }
  249. void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
  250. switch (LT) {
  251. case GlobalValue::InternalLinkage:
  252. Out << "GlobalValue::InternalLinkage"; break;
  253. case GlobalValue::PrivateLinkage:
  254. Out << "GlobalValue::PrivateLinkage"; break;
  255. case GlobalValue::LinkerPrivateLinkage:
  256. Out << "GlobalValue::LinkerPrivateLinkage"; break;
  257. case GlobalValue::AvailableExternallyLinkage:
  258. Out << "GlobalValue::AvailableExternallyLinkage "; break;
  259. case GlobalValue::LinkOnceAnyLinkage:
  260. Out << "GlobalValue::LinkOnceAnyLinkage "; break;
  261. case GlobalValue::LinkOnceODRLinkage:
  262. Out << "GlobalValue::LinkOnceODRLinkage "; break;
  263. case GlobalValue::WeakAnyLinkage:
  264. Out << "GlobalValue::WeakAnyLinkage"; break;
  265. case GlobalValue::WeakODRLinkage:
  266. Out << "GlobalValue::WeakODRLinkage"; break;
  267. case GlobalValue::AppendingLinkage:
  268. Out << "GlobalValue::AppendingLinkage"; break;
  269. case GlobalValue::ExternalLinkage:
  270. Out << "GlobalValue::ExternalLinkage"; break;
  271. case GlobalValue::DLLImportLinkage:
  272. Out << "GlobalValue::DLLImportLinkage"; break;
  273. case GlobalValue::DLLExportLinkage:
  274. Out << "GlobalValue::DLLExportLinkage"; break;
  275. case GlobalValue::ExternalWeakLinkage:
  276. Out << "GlobalValue::ExternalWeakLinkage"; break;
  277. case GlobalValue::GhostLinkage:
  278. Out << "GlobalValue::GhostLinkage"; break;
  279. case GlobalValue::CommonLinkage:
  280. Out << "GlobalValue::CommonLinkage"; break;
  281. }
  282. }
  283. void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
  284. switch (VisType) {
  285. default: llvm_unreachable("Unknown GVar visibility");
  286. case GlobalValue::DefaultVisibility:
  287. Out << "GlobalValue::DefaultVisibility";
  288. break;
  289. case GlobalValue::HiddenVisibility:
  290. Out << "GlobalValue::HiddenVisibility";
  291. break;
  292. case GlobalValue::ProtectedVisibility:
  293. Out << "GlobalValue::ProtectedVisibility";
  294. break;
  295. }
  296. }
  297. // printEscapedString - Print each character of the specified string, escaping
  298. // it if it is not printable or if it is an escape char.
  299. void CppWriter::printEscapedString(const std::string &Str) {
  300. for (unsigned i = 0, e = Str.size(); i != e; ++i) {
  301. unsigned char C = Str[i];
  302. if (isprint(C) && C != '"' && C != '\\') {
  303. Out << C;
  304. } else {
  305. Out << "\\x"
  306. << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
  307. << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
  308. }
  309. }
  310. }
  311. std::string CppWriter::getCppName(const Type* Ty) {
  312. // First, handle the primitive types .. easy
  313. if (Ty->isPrimitiveType() || Ty->isInteger()) {
  314. switch (Ty->getTypeID()) {
  315. case Type::VoidTyID: return "Type::getVoidTy(getGlobalContext())";
  316. case Type::IntegerTyID: {
  317. unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
  318. return "IntegerType::get(getGlobalContext(), " + utostr(BitWidth) + ")";
  319. }
  320. case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(getGlobalContext())";
  321. case Type::FloatTyID: return "Type::getFloatTy(getGlobalContext())";
  322. case Type::DoubleTyID: return "Type::getDoubleTy(getGlobalContext())";
  323. case Type::LabelTyID: return "Type::getLabelTy(getGlobalContext())";
  324. default:
  325. error("Invalid primitive type");
  326. break;
  327. }
  328. // shouldn't be returned, but make it sensible
  329. return "Type::getVoidTy(getGlobalContext())";
  330. }
  331. // Now, see if we've seen the type before and return that
  332. TypeMap::iterator I = TypeNames.find(Ty);
  333. if (I != TypeNames.end())
  334. return I->second;
  335. // Okay, let's build a new name for this type. Start with a prefix
  336. const char* prefix = 0;
  337. switch (Ty->getTypeID()) {
  338. case Type::FunctionTyID: prefix = "FuncTy_"; break;
  339. case Type::StructTyID: prefix = "StructTy_"; break;
  340. case Type::ArrayTyID: prefix = "ArrayTy_"; break;
  341. case Type::PointerTyID: prefix = "PointerTy_"; break;
  342. case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
  343. case Type::VectorTyID: prefix = "VectorTy_"; break;
  344. default: prefix = "OtherTy_"; break; // prevent breakage
  345. }
  346. // See if the type has a name in the symboltable and build accordingly
  347. const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
  348. std::string name;
  349. if (tName)
  350. name = std::string(prefix) + *tName;
  351. else
  352. name = std::string(prefix) + utostr(uniqueNum++);
  353. sanitize(name);
  354. // Save the name
  355. return TypeNames[Ty] = name;
  356. }
  357. void CppWriter::printCppName(const Type* Ty) {
  358. printEscapedString(getCppName(Ty));
  359. }
  360. std::string CppWriter::getCppName(const Value* val) {
  361. std::string name;
  362. ValueMap::iterator I = ValueNames.find(val);
  363. if (I != ValueNames.end() && I->first == val)
  364. return I->second;
  365. if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
  366. name = std::string("gvar_") +
  367. getTypePrefix(GV->getType()->getElementType());
  368. } else if (isa<Function>(val)) {
  369. name = std::string("func_");
  370. } else if (const Constant* C = dyn_cast<Constant>(val)) {
  371. name = std::string("const_") + getTypePrefix(C->getType());
  372. } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
  373. if (is_inline) {
  374. unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
  375. Function::const_arg_iterator(Arg)) + 1;
  376. name = std::string("arg_") + utostr(argNum);
  377. NameSet::iterator NI = UsedNames.find(name);
  378. if (NI != UsedNames.end())
  379. name += std::string("_") + utostr(uniqueNum++);
  380. UsedNames.insert(name);
  381. return ValueNames[val] = name;
  382. } else {
  383. name = getTypePrefix(val->getType());
  384. }
  385. } else {
  386. name = getTypePrefix(val->getType());
  387. }
  388. if (val->hasName())
  389. name += val->getName();
  390. else
  391. name += utostr(uniqueNum++);
  392. sanitize(name);
  393. NameSet::iterator NI = UsedNames.find(name);
  394. if (NI != UsedNames.end())
  395. name += std::string("_") + utostr(uniqueNum++);
  396. UsedNames.insert(name);
  397. return ValueNames[val] = name;
  398. }
  399. void CppWriter::printCppName(const Value* val) {
  400. printEscapedString(getCppName(val));
  401. }
  402. void CppWriter::printAttributes(const AttrListPtr &PAL,
  403. const std::string &name) {
  404. Out << "AttrListPtr " << name << "_PAL;";
  405. nl(Out);
  406. if (!PAL.isEmpty()) {
  407. Out << '{'; in(); nl(Out);
  408. Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
  409. Out << "AttributeWithIndex PAWI;"; nl(Out);
  410. for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
  411. unsigned index = PAL.getSlot(i).Index;
  412. Attributes attrs = PAL.getSlot(i).Attrs;
  413. Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
  414. #define HANDLE_ATTR(X) \
  415. if (attrs & Attribute::X) \
  416. Out << " | Attribute::" #X; \
  417. attrs &= ~Attribute::X;
  418. HANDLE_ATTR(SExt);
  419. HANDLE_ATTR(ZExt);
  420. HANDLE_ATTR(NoReturn);
  421. HANDLE_ATTR(InReg);
  422. HANDLE_ATTR(StructRet);
  423. HANDLE_ATTR(NoUnwind);
  424. HANDLE_ATTR(NoAlias);
  425. HANDLE_ATTR(ByVal);
  426. HANDLE_ATTR(Nest);
  427. HANDLE_ATTR(ReadNone);
  428. HANDLE_ATTR(ReadOnly);
  429. HANDLE_ATTR(InlineHint);
  430. HANDLE_ATTR(NoInline);
  431. HANDLE_ATTR(AlwaysInline);
  432. HANDLE_ATTR(OptimizeForSize);
  433. HANDLE_ATTR(StackProtect);
  434. HANDLE_ATTR(StackProtectReq);
  435. HANDLE_ATTR(NoCapture);
  436. #undef HANDLE_ATTR
  437. assert(attrs == 0 && "Unhandled attribute!");
  438. Out << ";";
  439. nl(Out);
  440. Out << "Attrs.push_back(PAWI);";
  441. nl(Out);
  442. }
  443. Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
  444. nl(Out);
  445. out(); nl(Out);
  446. Out << '}'; nl(Out);
  447. }
  448. }
  449. bool CppWriter::printTypeInternal(const Type* Ty) {
  450. // We don't print definitions for primitive types
  451. if (Ty->isPrimitiveType() || Ty->isInteger())
  452. return false;
  453. // If we already defined this type, we don't need to define it again.
  454. if (DefinedTypes.find(Ty) != DefinedTypes.end())
  455. return false;
  456. // Everything below needs the name for the type so get it now.
  457. std::string typeName(getCppName(Ty));
  458. // Search the type stack for recursion. If we find it, then generate this
  459. // as an OpaqueType, but make sure not to do this multiple times because
  460. // the type could appear in multiple places on the stack. Once the opaque
  461. // definition is issued, it must not be re-issued. Consequently we have to
  462. // check the UnresolvedTypes list as well.
  463. TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
  464. Ty);
  465. if (TI != TypeStack.end()) {
  466. TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
  467. if (I == UnresolvedTypes.end()) {
  468. Out << "PATypeHolder " << typeName;
  469. Out << "_fwd = OpaqueType::get(getGlobalContext());";
  470. nl(Out);
  471. UnresolvedTypes[Ty] = typeName;
  472. }
  473. return true;
  474. }
  475. // We're going to print a derived type which, by definition, contains other
  476. // types. So, push this one we're printing onto the type stack to assist with
  477. // recursive definitions.
  478. TypeStack.push_back(Ty);
  479. // Print the type definition
  480. switch (Ty->getTypeID()) {
  481. case Type::FunctionTyID: {
  482. const FunctionType* FT = cast<FunctionType>(Ty);
  483. Out << "std::vector<const Type*>" << typeName << "_args;";
  484. nl(Out);
  485. FunctionType::param_iterator PI = FT->param_begin();
  486. FunctionType::param_iterator PE = FT->param_end();
  487. for (; PI != PE; ++PI) {
  488. const Type* argTy = static_cast<const Type*>(*PI);
  489. bool isForward = printTypeInternal(argTy);
  490. std::string argName(getCppName(argTy));
  491. Out << typeName << "_args.push_back(" << argName;
  492. if (isForward)
  493. Out << "_fwd";
  494. Out << ");";
  495. nl(Out);
  496. }
  497. bool isForward = printTypeInternal(FT->getReturnType());
  498. std::string retTypeName(getCppName(FT->getReturnType()));
  499. Out << "FunctionType* " << typeName << " = FunctionType::get(";
  500. in(); nl(Out) << "/*Result=*/" << retTypeName;
  501. if (isForward)
  502. Out << "_fwd";
  503. Out << ",";
  504. nl(Out) << "/*Params=*/" << typeName << "_args,";
  505. nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
  506. out();
  507. nl(Out);
  508. break;
  509. }
  510. case Type::StructTyID: {
  511. const StructType* ST = cast<StructType>(Ty);
  512. Out << "std::vector<const Type*>" << typeName << "_fields;";
  513. nl(Out);
  514. StructType::element_iterator EI = ST->element_begin();
  515. StructType::element_iterator EE = ST->element_end();
  516. for (; EI != EE; ++EI) {
  517. const Type* fieldTy = static_cast<const Type*>(*EI);
  518. bool isForward = printTypeInternal(fieldTy);
  519. std::string fieldName(getCppName(fieldTy));
  520. Out << typeName << "_fields.push_back(" << fieldName;
  521. if (isForward)
  522. Out << "_fwd";
  523. Out << ");";
  524. nl(Out);
  525. }
  526. Out << "StructType* " << typeName << " = StructType::get("
  527. << "mod->getContext(), "
  528. << typeName << "_fields, /*isPacked=*/"
  529. << (ST->isPacked() ? "true" : "false") << ");";
  530. nl(Out);
  531. break;
  532. }
  533. case Type::ArrayTyID: {
  534. const ArrayType* AT = cast<ArrayType>(Ty);
  535. const Type* ET = AT->getElementType();
  536. bool isForward = printTypeInternal(ET);
  537. std::string elemName(getCppName(ET));
  538. Out << "ArrayType* " << typeName << " = ArrayType::get("
  539. << elemName << (isForward ? "_fwd" : "")
  540. << ", " << utostr(AT->getNumElements()) << ");";
  541. nl(Out);
  542. break;
  543. }
  544. case Type::PointerTyID: {
  545. const PointerType* PT = cast<PointerType>(Ty);
  546. const Type* ET = PT->getElementType();
  547. bool isForward = printTypeInternal(ET);
  548. std::string elemName(getCppName(ET));
  549. Out << "PointerType* " << typeName << " = PointerType::get("
  550. << elemName << (isForward ? "_fwd" : "")
  551. << ", " << utostr(PT->getAddressSpace()) << ");";
  552. nl(Out);
  553. break;
  554. }
  555. case Type::VectorTyID: {
  556. const VectorType* PT = cast<VectorType>(Ty);
  557. const Type* ET = PT->getElementType();
  558. bool isForward = printTypeInternal(ET);
  559. std::string elemName(getCppName(ET));
  560. Out << "VectorType* " << typeName << " = VectorType::get("
  561. << elemName << (isForward ? "_fwd" : "")
  562. << ", " << utostr(PT->getNumElements()) << ");";
  563. nl(Out);
  564. break;
  565. }
  566. case Type::OpaqueTyID: {
  567. Out << "OpaqueType* " << typeName;
  568. Out << " = OpaqueType::get(getGlobalContext());";
  569. nl(Out);
  570. break;
  571. }
  572. default:
  573. error("Invalid TypeID");
  574. }
  575. // If the type had a name, make sure we recreate it.
  576. const std::string* progTypeName =
  577. findTypeName(TheModule->getTypeSymbolTable(),Ty);
  578. if (progTypeName) {
  579. Out << "mod->addTypeName(\"" << *progTypeName << "\", "
  580. << typeName << ");";
  581. nl(Out);
  582. }
  583. // Pop us off the type stack
  584. TypeStack.pop_back();
  585. // Indicate that this type is now defined.
  586. DefinedTypes.insert(Ty);
  587. // Early resolve as many unresolved types as possible. Search the unresolved
  588. // types map for the type we just printed. Now that its definition is complete
  589. // we can resolve any previous references to it. This prevents a cascade of
  590. // unresolved types.
  591. TypeMap::iterator I = UnresolvedTypes.find(Ty);
  592. if (I != UnresolvedTypes.end()) {
  593. Out << "cast<OpaqueType>(" << I->second
  594. << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
  595. nl(Out);
  596. Out << I->second << " = cast<";
  597. switch (Ty->getTypeID()) {
  598. case Type::FunctionTyID: Out << "FunctionType"; break;
  599. case Type::ArrayTyID: Out << "ArrayType"; break;
  600. case Type::StructTyID: Out << "StructType"; break;
  601. case Type::VectorTyID: Out << "VectorType"; break;
  602. case Type::PointerTyID: Out << "PointerType"; break;
  603. case Type::OpaqueTyID: Out << "OpaqueType"; break;
  604. default: Out << "NoSuchDerivedType"; break;
  605. }
  606. Out << ">(" << I->second << "_fwd.get());";
  607. nl(Out); nl(Out);
  608. UnresolvedTypes.erase(I);
  609. }
  610. // Finally, separate the type definition from other with a newline.
  611. nl(Out);
  612. // We weren't a recursive type
  613. return false;
  614. }
  615. // Prints a type definition. Returns true if it could not resolve all the
  616. // types in the definition but had to use a forward reference.
  617. void CppWriter::printType(const Type* Ty) {
  618. assert(TypeStack.empty());
  619. TypeStack.clear();
  620. printTypeInternal(Ty);
  621. assert(TypeStack.empty());
  622. }
  623. void CppWriter::printTypes(const Module* M) {
  624. // Walk the symbol table and print out all its types
  625. const TypeSymbolTable& symtab = M->getTypeSymbolTable();
  626. for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
  627. TI != TE; ++TI) {
  628. // For primitive types and types already defined, just add a name
  629. TypeMap::const_iterator TNI = TypeNames.find(TI->second);
  630. if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
  631. TNI != TypeNames.end()) {
  632. Out << "mod->addTypeName(\"";
  633. printEscapedString(TI->first);
  634. Out << "\", " << getCppName(TI->second) << ");";
  635. nl(Out);
  636. // For everything else, define the type
  637. } else {
  638. printType(TI->second);
  639. }
  640. }
  641. // Add all of the global variables to the value table...
  642. for (Module::const_global_iterator I = TheModule->global_begin(),
  643. E = TheModule->global_end(); I != E; ++I) {
  644. if (I->hasInitializer())
  645. printType(I->getInitializer()->getType());
  646. printType(I->getType());
  647. }
  648. // Add all the functions to the table
  649. for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
  650. FI != FE; ++FI) {
  651. printType(FI->getReturnType());
  652. printType(FI->getFunctionType());
  653. // Add all the function arguments
  654. for (Function::const_arg_iterator AI = FI->arg_begin(),
  655. AE = FI->arg_end(); AI != AE; ++AI) {
  656. printType(AI->getType());
  657. }
  658. // Add all of the basic blocks and instructions
  659. for (Function::const_iterator BB = FI->begin(),
  660. E = FI->end(); BB != E; ++BB) {
  661. printType(BB->getType());
  662. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
  663. ++I) {
  664. printType(I->getType());
  665. for (unsigned i = 0; i < I->getNumOperands(); ++i)
  666. printType(I->getOperand(i)->getType());
  667. }
  668. }
  669. }
  670. }
  671. // printConstant - Print out a constant pool entry...
  672. void CppWriter::printConstant(const Constant *CV) {
  673. // First, if the constant is actually a GlobalValue (variable or function)
  674. // or its already in the constant list then we've printed it already and we
  675. // can just return.
  676. if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
  677. return;
  678. std::string constName(getCppName(CV));
  679. std::string typeName(getCppName(CV->getType()));
  680. if (isa<GlobalValue>(CV)) {
  681. // Skip variables and functions, we emit them elsewhere
  682. return;
  683. }
  684. if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
  685. std::string constValue = CI->getValue().toString(10, true);
  686. Out << "ConstantInt* " << constName
  687. << " = ConstantInt::get(getGlobalContext(), APInt("
  688. << cast<IntegerType>(CI->getType())->getBitWidth()
  689. << ", StringRef(\"" << constValue << "\"), 10));";
  690. } else if (isa<ConstantAggregateZero>(CV)) {
  691. Out << "ConstantAggregateZero* " << constName
  692. << " = ConstantAggregateZero::get(" << typeName << ");";
  693. } else if (isa<ConstantPointerNull>(CV)) {
  694. Out << "ConstantPointerNull* " << constName
  695. << " = ConstantPointerNull::get(" << typeName << ");";
  696. } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
  697. Out << "ConstantFP* " << constName << " = ";
  698. printCFP(CFP);
  699. Out << ";";
  700. } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
  701. if (CA->isString() &&
  702. CA->getType()->getElementType() ==
  703. Type::getInt8Ty(CA->getContext())) {
  704. Out << "Constant* " << constName <<
  705. " = ConstantArray::get(getGlobalContext(), \"";
  706. std::string tmp = CA->getAsString();
  707. bool nullTerminate = false;
  708. if (tmp[tmp.length()-1] == 0) {
  709. tmp.erase(tmp.length()-1);
  710. nullTerminate = true;
  711. }
  712. printEscapedString(tmp);
  713. // Determine if we want null termination or not.
  714. if (nullTerminate)
  715. Out << "\", true"; // Indicate that the null terminator should be
  716. // added.
  717. else
  718. Out << "\", false";// No null terminator
  719. Out << ");";
  720. } else {
  721. Out << "std::vector<Constant*> " << constName << "_elems;";
  722. nl(Out);
  723. unsigned N = CA->getNumOperands();
  724. for (unsigned i = 0; i < N; ++i) {
  725. printConstant(CA->getOperand(i)); // recurse to print operands
  726. Out << constName << "_elems.push_back("
  727. << getCppName(CA->getOperand(i)) << ");";
  728. nl(Out);
  729. }
  730. Out << "Constant* " << constName << " = ConstantArray::get("
  731. << typeName << ", " << constName << "_elems);";
  732. }
  733. } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
  734. Out << "std::vector<Constant*> " << constName << "_fields;";
  735. nl(Out);
  736. unsigned N = CS->getNumOperands();
  737. for (unsigned i = 0; i < N; i++) {
  738. printConstant(CS->getOperand(i));
  739. Out << constName << "_fields.push_back("
  740. << getCppName(CS->getOperand(i)) << ");";
  741. nl(Out);
  742. }
  743. Out << "Constant* " << constName << " = ConstantStruct::get("
  744. << typeName << ", " << constName << "_fields);";
  745. } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
  746. Out << "std::vector<Constant*> " << constName << "_elems;";
  747. nl(Out);
  748. unsigned N = CP->getNumOperands();
  749. for (unsigned i = 0; i < N; ++i) {
  750. printConstant(CP->getOperand(i));
  751. Out << constName << "_elems.push_back("
  752. << getCppName(CP->getOperand(i)) << ");";
  753. nl(Out);
  754. }
  755. Out << "Constant* " << constName << " = ConstantVector::get("
  756. << typeName << ", " << constName << "_elems);";
  757. } else if (isa<UndefValue>(CV)) {
  758. Out << "UndefValue* " << constName << " = UndefValue::get("
  759. << typeName << ");";
  760. } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
  761. if (CE->getOpcode() == Instruction::GetElementPtr) {
  762. Out << "std::vector<Constant*> " << constName << "_indices;";
  763. nl(Out);
  764. printConstant(CE->getOperand(0));
  765. for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
  766. printConstant(CE->getOperand(i));
  767. Out << constName << "_indices.push_back("
  768. << getCppName(CE->getOperand(i)) << ");";
  769. nl(Out);
  770. }
  771. Out << "Constant* " << constName
  772. << " = ConstantExpr::getGetElementPtr("
  773. << getCppName(CE->getOperand(0)) << ", "
  774. << "&" << constName << "_indices[0], "
  775. << constName << "_indices.size()"
  776. << ");";
  777. } else if (CE->isCast()) {
  778. printConstant(CE->getOperand(0));
  779. Out << "Constant* " << constName << " = ConstantExpr::getCast(";
  780. switch (CE->getOpcode()) {
  781. default: llvm_unreachable("Invalid cast opcode");
  782. case Instruction::Trunc: Out << "Instruction::Trunc"; break;
  783. case Instruction::ZExt: Out << "Instruction::ZExt"; break;
  784. case Instruction::SExt: Out << "Instruction::SExt"; break;
  785. case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
  786. case Instruction::FPExt: Out << "Instruction::FPExt"; break;
  787. case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
  788. case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
  789. case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
  790. case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
  791. case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
  792. case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
  793. case Instruction::BitCast: Out << "Instruction::BitCast"; break;
  794. }
  795. Out << ", " << getCppName(CE->getOperand(0)) << ", "
  796. << getCppName(CE->getType()) << ");";
  797. } else {
  798. unsigned N = CE->getNumOperands();
  799. for (unsigned i = 0; i < N; ++i ) {
  800. printConstant(CE->getOperand(i));
  801. }
  802. Out << "Constant* " << constName << " = ConstantExpr::";
  803. switch (CE->getOpcode()) {
  804. case Instruction::Add: Out << "getAdd("; break;
  805. case Instruction::FAdd: Out << "getFAdd("; break;
  806. case Instruction::Sub: Out << "getSub("; break;
  807. case Instruction::FSub: Out << "getFSub("; break;
  808. case Instruction::Mul: Out << "getMul("; break;
  809. case Instruction::FMul: Out << "getFMul("; break;
  810. case Instruction::UDiv: Out << "getUDiv("; break;
  811. case Instruction::SDiv: Out << "getSDiv("; break;
  812. case Instruction::FDiv: Out << "getFDiv("; break;
  813. case Instruction::URem: Out << "getURem("; break;
  814. case Instruction::SRem: Out << "getSRem("; break;
  815. case Instruction::FRem: Out << "getFRem("; break;
  816. case Instruction::And: Out << "getAnd("; break;
  817. case Instruction::Or: Out << "getOr("; break;
  818. case Instruction::Xor: Out << "getXor("; break;
  819. case Instruction::ICmp:
  820. Out << "getICmp(ICmpInst::ICMP_";
  821. switch (CE->getPredicate()) {
  822. case ICmpInst::ICMP_EQ: Out << "EQ"; break;
  823. case ICmpInst::ICMP_NE: Out << "NE"; break;
  824. case ICmpInst::ICMP_SLT: Out << "SLT"; break;
  825. case ICmpInst::ICMP_ULT: Out << "ULT"; break;
  826. case ICmpInst::ICMP_SGT: Out << "SGT"; break;
  827. case ICmpInst::ICMP_UGT: Out << "UGT"; break;
  828. case ICmpInst::ICMP_SLE: Out << "SLE"; break;
  829. case ICmpInst::ICMP_ULE: Out << "ULE"; break;
  830. case ICmpInst::ICMP_SGE: Out << "SGE"; break;
  831. case ICmpInst::ICMP_UGE: Out << "UGE"; break;
  832. default: error("Invalid ICmp Predicate");
  833. }
  834. break;
  835. case Instruction::FCmp:
  836. Out << "getFCmp(FCmpInst::FCMP_";
  837. switch (CE->getPredicate()) {
  838. case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
  839. case FCmpInst::FCMP_ORD: Out << "ORD"; break;
  840. case FCmpInst::FCMP_UNO: Out << "UNO"; break;
  841. case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
  842. case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
  843. case FCmpInst::FCMP_ONE: Out << "ONE"; break;
  844. case FCmpInst::FCMP_UNE: Out << "UNE"; break;
  845. case FCmpInst::FCMP_OLT: Out << "OLT"; break;
  846. case FCmpInst::FCMP_ULT: Out << "ULT"; break;
  847. case FCmpInst::FCMP_OGT: Out << "OGT"; break;
  848. case FCmpInst::FCMP_UGT: Out << "UGT"; break;
  849. case FCmpInst::FCMP_OLE: Out << "OLE"; break;
  850. case FCmpInst::FCMP_ULE: Out << "ULE"; break;
  851. case FCmpInst::FCMP_OGE: Out << "OGE"; break;
  852. case FCmpInst::FCMP_UGE: Out << "UGE"; break;
  853. case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
  854. default: error("Invalid FCmp Predicate");
  855. }
  856. break;
  857. case Instruction::Shl: Out << "getShl("; break;
  858. case Instruction::LShr: Out << "getLShr("; break;
  859. case Instruction::AShr: Out << "getAShr("; break;
  860. case Instruction::Select: Out << "getSelect("; break;
  861. case Instruction::ExtractElement: Out << "getExtractElement("; break;
  862. case Instruction::InsertElement: Out << "getInsertElement("; break;
  863. case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
  864. default:
  865. error("Invalid constant expression");
  866. break;
  867. }
  868. Out << getCppName(CE->getOperand(0));
  869. for (unsigned i = 1; i < CE->getNumOperands(); ++i)
  870. Out << ", " << getCppName(CE->getOperand(i));
  871. Out << ");";
  872. }
  873. } else {
  874. error("Bad Constant");
  875. Out << "Constant* " << constName << " = 0; ";
  876. }
  877. nl(Out);
  878. }
  879. void CppWriter::printConstants(const Module* M) {
  880. // Traverse all the global variables looking for constant initializers
  881. for (Module::const_global_iterator I = TheModule->global_begin(),
  882. E = TheModule->global_end(); I != E; ++I)
  883. if (I->hasInitializer())
  884. printConstant(I->getInitializer());
  885. // Traverse the LLVM functions looking for constants
  886. for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
  887. FI != FE; ++FI) {
  888. // Add all of the basic blocks and instructions
  889. for (Function::const_iterator BB = FI->begin(),
  890. E = FI->end(); BB != E; ++BB) {
  891. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
  892. ++I) {
  893. for (unsigned i = 0; i < I->getNumOperands(); ++i) {
  894. if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
  895. printConstant(C);
  896. }
  897. }
  898. }
  899. }
  900. }
  901. }
  902. void CppWriter::printVariableUses(const GlobalVariable *GV) {
  903. nl(Out) << "// Type Definitions";
  904. nl(Out);
  905. printType(GV->getType());
  906. if (GV->hasInitializer()) {
  907. Constant* Init = GV->getInitializer();
  908. printType(Init->getType());
  909. if (Function* F = dyn_cast<Function>(Init)) {
  910. nl(Out)<< "/ Function Declarations"; nl(Out);
  911. printFunctionHead(F);
  912. } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
  913. nl(Out) << "// Global Variable Declarations"; nl(Out);
  914. printVariableHead(gv);
  915. } else {
  916. nl(Out) << "// Constant Definitions"; nl(Out);
  917. printConstant(gv);
  918. }
  919. if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
  920. nl(Out) << "// Global Variable Definitions"; nl(Out);
  921. printVariableBody(gv);
  922. }
  923. }
  924. }
  925. void CppWriter::printVariableHead(const GlobalVariable *GV) {
  926. nl(Out) << "GlobalVariable* " << getCppName(GV);
  927. if (is_inline) {
  928. Out << " = mod->getGlobalVariable(getGlobalContext(), ";
  929. printEscapedString(GV->getName());
  930. Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
  931. nl(Out) << "if (!" << getCppName(GV) << ") {";
  932. in(); nl(Out) << getCppName(GV);
  933. }
  934. Out << " = new GlobalVariable(/*Module=*/*mod, ";
  935. nl(Out) << "/*Type=*/";
  936. printCppName(GV->getType()->getElementType());
  937. Out << ",";
  938. nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
  939. Out << ",";
  940. nl(Out) << "/*Linkage=*/";
  941. printLinkageType(GV->getLinkage());
  942. Out << ",";
  943. nl(Out) << "/*Initializer=*/0, ";
  944. if (GV->hasInitializer()) {
  945. Out << "// has initializer, specified below";
  946. }
  947. nl(Out) << "/*Name=*/\"";
  948. printEscapedString(GV->getName());
  949. Out << "\");";
  950. nl(Out);
  951. if (GV->hasSection()) {
  952. printCppName(GV);
  953. Out << "->setSection(\"";
  954. printEscapedString(GV->getSection());
  955. Out << "\");";
  956. nl(Out);
  957. }
  958. if (GV->getAlignment()) {
  959. printCppName(GV);
  960. Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
  961. nl(Out);
  962. }
  963. if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
  964. printCppName(GV);
  965. Out << "->setVisibility(";
  966. printVisibilityType(GV->getVisibility());
  967. Out << ");";
  968. nl(Out);
  969. }
  970. if (is_inline) {
  971. out(); Out << "}"; nl(Out);
  972. }
  973. }
  974. void CppWriter::printVariableBody(const GlobalVariable *GV) {
  975. if (GV->hasInitializer()) {
  976. printCppName(GV);
  977. Out << "->setInitializer(";
  978. Out << getCppName(GV->getInitializer()) << ");";
  979. nl(Out);
  980. }
  981. }
  982. std::string CppWriter::getOpName(Value* V) {
  983. if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
  984. return getCppName(V);
  985. // See if its alread in the map of forward references, if so just return the
  986. // name we already set up for it
  987. ForwardRefMap::const_iterator I = ForwardRefs.find(V);
  988. if (I != ForwardRefs.end())
  989. return I->second;
  990. // This is a new forward reference. Generate a unique name for it
  991. std::string result(std::string("fwdref_") + utostr(uniqueNum++));
  992. // Yes, this is a hack. An Argument is the smallest instantiable value that
  993. // we can make as a placeholder for the real value. We'll replace these
  994. // Argument instances later.
  995. Out << "Argument* " << result << " = new Argument("
  996. << getCppName(V->getType()) << ");";
  997. nl(Out);
  998. ForwardRefs[V] = result;
  999. return result;
  1000. }
  1001. // printInstruction - This member is called for each Instruction in a function.
  1002. void CppWriter::printInstruction(const Instruction *I,
  1003. const std::string& bbname) {
  1004. std::string iName(getCppName(I));
  1005. // Before we emit this instruction, we need to take care of generating any
  1006. // forward references. So, we get the names of all the operands in advance
  1007. std::string* opNames = new std::string[I->getNumOperands()];
  1008. for (unsigned i = 0; i < I->getNumOperands(); i++) {
  1009. opNames[i] = getOpName(I->getOperand(i));
  1010. }
  1011. switch (I->getOpcode()) {
  1012. default:
  1013. error("Invalid instruction");
  1014. break;
  1015. case Instruction::Ret: {
  1016. const ReturnInst* ret = cast<ReturnInst>(I);
  1017. Out << "ReturnInst::Create(getGlobalContext(), "
  1018. << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
  1019. break;
  1020. }
  1021. case Instruction::Br: {
  1022. const BranchInst* br = cast<BranchInst>(I);
  1023. Out << "BranchInst::Create(" ;
  1024. if (br->getNumOperands() == 3 ) {
  1025. Out << opNames[2] << ", "
  1026. << opNames[1] << ", "
  1027. << opNames[0] << ", ";
  1028. } else if (br->getNumOperands() == 1) {
  1029. Out << opNames[0] << ", ";
  1030. } else {
  1031. error("Branch with 2 operands?");
  1032. }
  1033. Out << bbname << ");";
  1034. break;
  1035. }
  1036. case Instruction::Switch: {
  1037. const SwitchInst *SI = cast<SwitchInst>(I);
  1038. Out << "SwitchInst* " << iName << " = SwitchInst::Create("
  1039. << opNames[0] << ", "
  1040. << opNames[1] << ", "
  1041. << SI->getNumCases() << ", " << bbname << ");";
  1042. nl(Out);
  1043. for (unsigned i = 2; i != SI->getNumOperands(); i += 2) {
  1044. Out << iName << "->addCase("
  1045. << opNames[i] << ", "
  1046. << opNames[i+1] << ");";
  1047. nl(Out);
  1048. }
  1049. break;
  1050. }
  1051. case Instruction::IndirectBr: {
  1052. const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
  1053. Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
  1054. << opNames[0] << ", " << IBI->getNumDestinations() << ");";
  1055. nl(Out);
  1056. for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
  1057. Out << iName << "->addDestination(" << opNames[i] << ");";
  1058. nl(Out);
  1059. }
  1060. break;
  1061. }
  1062. case Instruction::Invoke: {
  1063. const InvokeInst* inv = cast<InvokeInst>(I);
  1064. Out << "std::vector<Value*> " << iName << "_params;";
  1065. nl(Out);
  1066. for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
  1067. Out << iName << "_params.push_back("
  1068. << opNames[i] << ");";
  1069. nl(Out);
  1070. }
  1071. Out << "InvokeInst *" << iName << " = InvokeInst::Create("
  1072. << opNames[0] << ", "
  1073. << opNames[1] << ", "
  1074. << opNames[2] << ", "
  1075. << iName << "_params.begin(), " << iName << "_params.end(), \"";
  1076. printEscapedString(inv->getName());
  1077. Out << "\", " << bbname << ");";
  1078. nl(Out) << iName << "->setCallingConv(";
  1079. printCallingConv(inv->getCallingConv());
  1080. Out << ");";
  1081. printAttributes(inv->getAttributes(), iName);
  1082. Out << iName << "->setAttributes(" << iName << "_PAL);";
  1083. nl(Out);
  1084. break;
  1085. }
  1086. case Instruction::Unwind: {
  1087. Out << "new UnwindInst("
  1088. << bbname << ");";
  1089. break;
  1090. }
  1091. case Instruction::Unreachable: {
  1092. Out << "new UnreachableInst("
  1093. << "getGlobalContext(), "
  1094. << bbname << ");";
  1095. break;
  1096. }
  1097. case Instruction::Add:
  1098. case Instruction::FAdd:
  1099. case Instruction::Sub:
  1100. case Instruction::FSub:
  1101. case Instruction::Mul:
  1102. case Instruction::FMul:
  1103. case Instruction::UDiv:
  1104. case Instruction::SDiv:
  1105. case Instruction::FDiv:
  1106. case Instruction::URem:
  1107. case Instruction::SRem:
  1108. case Instruction::FRem:
  1109. case Instruction::And:
  1110. case Instruction::Or:
  1111. case Instruction::Xor:
  1112. case Instruction::Shl:
  1113. case Instruction::LShr:
  1114. case Instruction::AShr:{
  1115. Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
  1116. switch (I->getOpcode()) {
  1117. case Instruction::Add: Out << "Instruction::Add"; break;
  1118. case Instruction::FAdd: Out << "Instruction::FAdd"; break;
  1119. case Instruction::Sub: Out << "Instruction::Sub"; break;
  1120. case Instruction::FSub: Out << "Instruction::FSub"; break;
  1121. case Instruction::Mul: Out << "Instruction::Mul"; break;
  1122. case Instruction::FMul: Out << "Instruction::FMul"; break;
  1123. case Instruction::UDiv:Out << "Instruction::UDiv"; break;
  1124. case Instruction::SDiv:Out << "Instruction::SDiv"; break;
  1125. case Instruction::FDiv:Out << "Instruction::FDiv"; break;
  1126. case Instruction::URem:Out << "Instruction::URem"; break;
  1127. case Instruction::SRem:Out << "Instruction::SRem"; break;
  1128. case Instruction::FRem:Out << "Instruction::FRem"; break;
  1129. case Instruction::And: Out << "Instruction::And"; break;
  1130. case Instruction::Or: Out << "Instruction::Or"; break;
  1131. case Instruction::Xor: Out << "Instruction::Xor"; break;
  1132. case Instruction::Shl: Out << "Instruction::Shl"; break;
  1133. case Instruction::LShr:Out << "Instruction::LShr"; break;
  1134. case Instruction::AShr:Out << "Instruction::AShr"; break;
  1135. default: Out << "Instruction::BadOpCode"; break;
  1136. }
  1137. Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
  1138. printEscapedString(I->getName());
  1139. Out << "\", " << bbname << ");";
  1140. break;
  1141. }
  1142. case Instruction::FCmp: {
  1143. Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
  1144. switch (cast<FCmpInst>(I)->getPredicate()) {
  1145. case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
  1146. case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
  1147. case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
  1148. case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
  1149. case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
  1150. case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
  1151. case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
  1152. case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
  1153. case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
  1154. case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
  1155. case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
  1156. case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
  1157. case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
  1158. case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
  1159. case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
  1160. case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
  1161. default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
  1162. }
  1163. Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
  1164. printEscapedString(I->getName());
  1165. Out << "\");";
  1166. break;
  1167. }
  1168. case Instruction::ICmp: {
  1169. Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
  1170. switch (cast<ICmpInst>(I)->getPredicate()) {
  1171. case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
  1172. case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
  1173. case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
  1174. case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
  1175. case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
  1176. case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
  1177. case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
  1178. case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
  1179. case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
  1180. case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
  1181. default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
  1182. }
  1183. Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
  1184. printEscapedString(I->getName());
  1185. Out << "\");";
  1186. break;
  1187. }
  1188. case Instruction::Alloca: {
  1189. const AllocaInst* allocaI = cast<AllocaInst>(I);
  1190. Out << "AllocaInst* " << iName << " = new AllocaInst("
  1191. << getCppName(allocaI->getAllocatedType()) << ", ";
  1192. if (allocaI->isArrayAllocation())
  1193. Out << opNames[0] << ", ";
  1194. Out << "\"";
  1195. printEscapedString(allocaI->getName());
  1196. Out << "\", " << bbname << ");";
  1197. if (allocaI->getAlignment())
  1198. nl(Out) << iName << "->setAlignment("
  1199. << allocaI->getAlignment() << ");";
  1200. break;
  1201. }
  1202. case Instruction::Load:{
  1203. const LoadInst* load = cast<LoadInst>(I);
  1204. Out << "LoadInst* " << iName << " = new LoadInst("
  1205. << opNames[0] << ", \"";
  1206. printEscapedString(load->getName());
  1207. Out << "\", " << (load->isVolatile() ? "true" : "false" )
  1208. << ", " << bbname << ");";
  1209. break;
  1210. }
  1211. case Instruction::Store: {
  1212. const StoreInst* store = cast<StoreInst>(I);
  1213. Out << " new StoreInst("
  1214. << opNames[0] << ", "
  1215. << opNames[1] << ", "
  1216. << (store->isVolatile() ? "true" : "false")
  1217. << ", " << bbname << ");";
  1218. break;
  1219. }
  1220. case Instruction::GetElementPtr: {
  1221. const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
  1222. if (gep->getNumOperands() <= 2) {
  1223. Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
  1224. << opNames[0];
  1225. if (gep->getNumOperands() == 2)
  1226. Out << ", " << opNames[1];
  1227. } else {
  1228. Out << "std::vector<Value*> " << iName << "_indices;";
  1229. nl(Out);
  1230. for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
  1231. Out << iName << "_indices.push_back("
  1232. << opNames[i] << ");";
  1233. nl(Out);
  1234. }
  1235. Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
  1236. << opNames[0] << ", " << iName << "_indices.begin(), "
  1237. << iName << "_indices.end()";
  1238. }
  1239. Out << ", \"";
  1240. printEscapedString(gep->getName());
  1241. Out << "\", " << bbname << ");";
  1242. break;
  1243. }
  1244. case Instruction::PHI: {
  1245. const PHINode* phi = cast<PHINode>(I);
  1246. Out << "PHINode* " << iName << " = PHINode::Create("
  1247. << getCppName(phi->getType()) << ", \"";
  1248. printEscapedString(phi->getName());
  1249. Out << "\", " << bbname << ");";
  1250. nl(Out) << iName << "->reserveOperandSpace("
  1251. << phi->getNumIncomingValues()
  1252. << ");";
  1253. nl(Out);
  1254. for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
  1255. Out << iName << "->addIncoming("
  1256. << opNames[i] << ", " << opNames[i+1] << ");";
  1257. nl(Out);
  1258. }
  1259. break;
  1260. }
  1261. case Instruction::Trunc:
  1262. case Instruction::ZExt:
  1263. case Instruction::SExt:
  1264. case Instruction::FPTrunc:
  1265. case Instruction::FPExt:
  1266. case Instruction::FPToUI:
  1267. case Instruction::FPToSI:
  1268. case Instruction::UIToFP:
  1269. case Instruction::SIToFP:
  1270. case Instruction::PtrToInt:
  1271. case Instruction::IntToPtr:
  1272. case Instruction::BitCast: {
  1273. const CastInst* cst = cast<CastInst>(I);
  1274. Out << "CastInst* " << iName << " = new ";
  1275. switch (I->getOpcode()) {
  1276. case Instruction::Trunc: Out << "TruncInst"; break;
  1277. case Instruction::ZExt: Out << "ZExtInst"; break;
  1278. case Instruction::SExt: Out << "SExtInst"; break;
  1279. case Instruction::FPTrunc: Out << "FPTruncInst"; break;
  1280. case Instruction::FPExt: Out << "FPExtInst"; break;
  1281. case Instruction::FPToUI: Out << "FPToUIInst"; break;
  1282. case Instruction::FPToSI: Out << "FPToSIInst"; break;
  1283. case Instruction::UIToFP: Out << "UIToFPInst"; break;
  1284. case Instruction::SIToFP: Out << "SIToFPInst"; break;
  1285. case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
  1286. case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
  1287. case Instruction::BitCast: Out << "BitCastInst"; break;
  1288. default: assert(!"Unreachable"); break;
  1289. }
  1290. Out << "(" << opNames[0] << ", "
  1291. << getCppName(cst->getType()) << ", \"";
  1292. printEscapedString(cst->getName());
  1293. Out << "\", " << bbname << ");";
  1294. break;
  1295. }
  1296. case Instruction::Call:{
  1297. const CallInst* call = cast<CallInst>(I);
  1298. if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
  1299. Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
  1300. << getCppName(ila->getFunctionType()) << ", \""
  1301. << ila->getAsmString() << "\", \""
  1302. << ila->getConstraintString() << "\","
  1303. << (ila->hasSideEffects() ? "true" : "false") << ");";
  1304. nl(Out);
  1305. }
  1306. if (call->getNumOperands() > 2) {
  1307. Out << "std::vector<Value*> " << iName << "_params;";
  1308. nl(Out);
  1309. for (unsigned i = 1; i < call->getNumOperands(); ++i) {
  1310. Out << iName << "_params.push_back(" << opNames[i] << ");";
  1311. nl(Out);
  1312. }
  1313. Out << "CallInst* " << iName << " = CallInst::Create("
  1314. << opNames[0] << ", " << iName << "_params.begin(), "
  1315. << iName << "_params.end(), \"";
  1316. } else if (call->getNumOperands() == 2) {
  1317. Out << "CallInst* " << iName << " = CallInst::Create("
  1318. << opNames[0] << ", " << opNames[1] << ", \"";
  1319. } else {
  1320. Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
  1321. << ", \"";
  1322. }
  1323. printEscapedString(call->getName());
  1324. Out << "\", " << bbname << ");";
  1325. nl(Out) << iName << "->setCallingConv(";
  1326. printCallingConv(call->getCallingConv());
  1327. Out << ");";
  1328. nl(Out) << iName << "->setTailCall("
  1329. << (call->isTailCall() ? "true":"false");
  1330. Out << ");";
  1331. printAttributes(call->getAttributes(), iName);
  1332. Out << iName << "->setAttributes(" << iName << "_PAL);";
  1333. nl(Out);
  1334. break;
  1335. }
  1336. case Instruction::Select: {
  1337. const SelectInst* sel = cast<SelectInst>(I);
  1338. Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
  1339. Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
  1340. printEscapedString(sel->getName());
  1341. Out << "\", " << bbname << ");";
  1342. break;
  1343. }
  1344. case Instruction::UserOp1:
  1345. /// FALL THROUGH
  1346. case Instruction::UserOp2: {
  1347. /// FIXME: What should be done here?
  1348. break;
  1349. }
  1350. case Instruction::VAArg: {
  1351. const VAArgInst* va = cast<VAArgInst>(I);
  1352. Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
  1353. << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
  1354. printEscapedString(va->getName());
  1355. Out << "\", " << bbname << ");";
  1356. break;
  1357. }
  1358. case Instruction::ExtractElement: {
  1359. const ExtractElementInst* eei = cast<ExtractElementInst>(I);
  1360. Out << "ExtractElementInst* " << getCppName(eei)
  1361. << " = new ExtractElementInst(" << opNames[0]
  1362. << ", " << opNames[1] << ", \"";
  1363. printEscapedString(eei->getName());
  1364. Out << "\", " << bbname << ");";
  1365. break;
  1366. }
  1367. case Instruction::InsertElement: {
  1368. const InsertElementInst* iei = cast<InsertElementInst>(I);
  1369. Out << "InsertElementInst* " << getCppName(iei)
  1370. << " = InsertElementInst::Create(" << opNames[0]
  1371. << ", " << opNames[1] << ", " << opNames[2] << ", \"";
  1372. printEscapedString(iei->getName());
  1373. Out << "\", " << bbname << ");";
  1374. break;
  1375. }
  1376. case Instruction::ShuffleVector: {
  1377. const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
  1378. Out << "ShuffleVectorInst* " << getCppName(svi)
  1379. << " = new ShuffleVectorInst(" << opNames[0]
  1380. << ", " << opNames[1] << ", " << opNames[2] << ", \"";
  1381. printEscapedString(svi->getName());
  1382. Out << "\", " << bbname << ");";
  1383. break;
  1384. }
  1385. case Instruction::ExtractValue: {
  1386. const ExtractValueInst *evi = cast<ExtractValueInst>(I);
  1387. Out << "std::vector<unsigned> " << iName << "_indices;";
  1388. nl(Out);
  1389. for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
  1390. Out << iName << "_indices.push_back("
  1391. << evi->idx_begin()[i] << ");";
  1392. nl(Out);
  1393. }
  1394. Out << "ExtractValueInst* " << getCppName(evi)
  1395. << " = ExtractValueInst::Create(" << opNames[0]
  1396. << ", "
  1397. << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
  1398. printEscapedString(evi->getName());
  1399. Out << "\", " << bbname << ");";
  1400. break;
  1401. }
  1402. case Instruction::InsertValue: {
  1403. const InsertValueInst *ivi = cast<InsertValueInst>(I);
  1404. Out << "std::vector<unsigned> " << iName << "_indices;";
  1405. nl(Out);
  1406. for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
  1407. Out << iName << "_indices.push_back("
  1408. << ivi->idx_begin()[i] << ");";
  1409. nl(Out);
  1410. }
  1411. Out << "InsertValueInst* " << getCppName(ivi)
  1412. << " = InsertValueInst::Create(" << opNames[0]
  1413. << ", " << opNames[1] << ", "
  1414. << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
  1415. printEscapedString(ivi->getName());
  1416. Out << "\", " << bbname << ");";
  1417. break;
  1418. }
  1419. }
  1420. DefinedValues.insert(I);
  1421. nl(Out);
  1422. delete [] opNames;
  1423. }
  1424. // Print out the types, constants and declarations needed by one function
  1425. void CppWriter::printFunctionUses(const Function* F) {
  1426. nl(Out) << "// Type Definitions"; nl(Out);
  1427. if (!is_inline) {
  1428. // Print the function's return type
  1429. printType(F->getReturnType());
  1430. // Print the function's function type
  1431. printType(F->getFunctionType());
  1432. // Print the types of each of the function's arguments
  1433. for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
  1434. AI != AE; ++AI) {
  1435. printType(AI->getType());
  1436. }
  1437. }
  1438. // Print type definitions for every type referenced by an instruction and
  1439. // make a note of any global values or constants that are referenced
  1440. SmallPtrSet<GlobalValue*,64> gvs;
  1441. SmallPtrSet<Constant*,64> consts;
  1442. for (Function::const_iterator BB = F->begin(), BE = F->end();
  1443. BB != BE; ++BB){
  1444. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
  1445. I != E; ++I) {
  1446. // Print the type of the instruction itself
  1447. printType(I->getType());
  1448. // Print the type of each of the instruction's operands
  1449. for (unsigned i = 0; i < I->getNumOperands(); ++i) {
  1450. Value* operand = I->getOperand(i);
  1451. printType(operand->getType());
  1452. // If the operand references a GVal or Constant, make a note of it
  1453. if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
  1454. gvs.insert(GV);
  1455. if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
  1456. if (GVar->hasInitializer())
  1457. consts.insert(GVar->getInitializer());
  1458. } else if (Constant* C = dyn_cast<Constant>(operand))
  1459. consts.insert(C);
  1460. }
  1461. }
  1462. }
  1463. // Print the function declarations for any functions encountered
  1464. nl(Out) << "// Function Declarations"; nl(Out);
  1465. for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
  1466. I != E; ++I) {
  1467. if (Function* Fun = dyn_cast<Function>(*I)) {
  1468. if (!is_inline || Fun != F)
  1469. printFunctionHead(Fun);
  1470. }
  1471. }
  1472. // Print the global variable declarations for any variables encountered
  1473. nl(Out) << "// Global Variable Declarations"; nl(Out);
  1474. for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
  1475. I != E; ++I) {
  1476. if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
  1477. printVariableHead(F);
  1478. }
  1479. // Print the constants found
  1480. nl(Out) << "// Constant Definitions"; nl(Out);
  1481. for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
  1482. E = consts.end(); I != E; ++I) {
  1483. printConstant(*I);
  1484. }
  1485. // Process the global variables definitions now that all the constants have
  1486. // been emitted. These definitions just couple the gvars with their constant
  1487. // initializers.
  1488. nl(Out) << "// Global Variable Definitions"; nl(Out);
  1489. for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
  1490. I != E; ++I) {
  1491. if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
  1492. printVariableBody(GV);
  1493. }
  1494. }
  1495. void CppWriter::printFunctionHead(const Function* F) {
  1496. nl(Out) << "Function* " << getCppName(F);
  1497. if (is_inline) {
  1498. Out << " = mod->getFunction(\"";
  1499. printEscapedString(F->getName());
  1500. Out << "\", " << getCppName(F->getFunctionType()) << ");";
  1501. nl(Out) << "if (!" << getCppName(F) << ") {";
  1502. nl(Out) << getCppName(F);
  1503. }
  1504. Out<< " = Function::Create(";
  1505. nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
  1506. nl(Out) << "/*Linkage=*/";
  1507. printLinkageType(F->getLinkage());
  1508. Out << ",";
  1509. nl(Out) << "/*Name=*/\"";
  1510. printEscapedString(F->getName());
  1511. Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
  1512. nl(Out,-1);
  1513. printCppName(F);
  1514. Out << "->setCallingConv(";
  1515. printCallingConv(F->getCallingConv());
  1516. Out << ");";
  1517. nl(Out);
  1518. if (F->hasSection()) {
  1519. printCppName(F);
  1520. Out << "->setSection(\"" << F->getSection() << "\");";
  1521. nl(Out);
  1522. }
  1523. if (F->getAlignment()) {
  1524. printCppName(F);
  1525. Out << "->setAlignment(" << F->getAlignment() << ");";
  1526. nl(Out);
  1527. }
  1528. if (F->getVisibility() != GlobalValue::DefaultVisibility) {
  1529. printCppName(F);
  1530. Out << "->setVisibility(";
  1531. printVisibilityType(F->getVisibility());
  1532. Out << ");";
  1533. nl(Out);
  1534. }
  1535. if (F->hasGC()) {
  1536. printCppName(F);
  1537. Out << "->setGC(\"" << F->getGC() << "\");";
  1538. nl(Out);
  1539. }
  1540. if (is_inline) {
  1541. Out << "}";
  1542. nl(Out);
  1543. }
  1544. printAttributes(F->getAttributes(), getCppName(F));
  1545. printCppName(F);
  1546. Out << "->setAttributes(" << getCppName(F) << "_PAL);";
  1547. nl(Out);
  1548. }
  1549. void CppWriter::printFunctionBody(const Function *F) {
  1550. if (F->isDeclaration())
  1551. return; // external functions have no bodies.
  1552. // Clear the DefinedValues and ForwardRefs maps because we can't have
  1553. // cross-function forward refs
  1554. ForwardRefs.clear();
  1555. DefinedValues.clear();
  1556. // Create all the argument values
  1557. if (!is_inline) {
  1558. if (!F->arg_empty()) {
  1559. Out << "Function::arg_iterator args = " << getCppName(F)
  1560. << "->arg_begin();";
  1561. nl(Out);
  1562. }
  1563. for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
  1564. AI != AE; ++AI) {
  1565. Out << "Value* " << getCppName(AI) << " = args++;";
  1566. nl(Out);
  1567. if (AI->hasName()) {
  1568. Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
  1569. nl(Out);
  1570. }
  1571. }
  1572. }
  1573. // Create all the basic blocks
  1574. nl(Out);
  1575. for (Function::const_iterator BI = F->begin(), BE = F->end();
  1576. BI != BE; ++BI) {
  1577. std::string bbname(getCppName(BI));
  1578. Out << "BasicBlock* " << bbname <<
  1579. " = BasicBlock::Create(getGlobalContext(), \"";
  1580. if (BI->hasName())
  1581. printEscapedString(BI->getName());
  1582. Out << "\"," << getCppName(BI->getParent()) << ",0);";
  1583. nl(Out);
  1584. }
  1585. // Output all of its basic blocks... for the function
  1586. for (Function::const_iterator BI = F->begin(), BE = F->end();
  1587. BI != BE; ++BI) {
  1588. std::string bbname(getCppName(BI));
  1589. nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
  1590. nl(Out);
  1591. // Output all of the instructions in the basic block...
  1592. for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
  1593. I != E; ++I) {
  1594. printInstruction(I,bbname);
  1595. }
  1596. }
  1597. // Loop over the ForwardRefs and resolve them now that all instructions
  1598. // are generated.
  1599. if (!ForwardRefs.empty()) {
  1600. nl(Out) << "// Resolve Forward References";
  1601. nl(Out);
  1602. }
  1603. while (!ForwardRefs.empty()) {
  1604. ForwardRefMap::iterator I = ForwardRefs.begin();
  1605. Out << I->second << "->replaceAllUsesWith("
  1606. << getCppName(I->first) << "); delete " << I->second << ";";
  1607. nl(Out);
  1608. ForwardRefs.erase(I);
  1609. }
  1610. }
  1611. void CppWriter::printInline(const std::string& fname,
  1612. const std::string& func) {
  1613. const Function* F = TheModule->getFunction(func);
  1614. if (!F) {
  1615. error(std::string("Function '") + func + "' not found in input module");
  1616. return;
  1617. }
  1618. if (F->isDeclaration()) {
  1619. error(std::string("Function '") + func + "' is external!");
  1620. return;
  1621. }
  1622. nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
  1623. << getCppName(F);
  1624. unsigned arg_count = 1;
  1625. for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
  1626. AI != AE; ++AI) {
  1627. Out << ", Value* arg_" << arg_count;
  1628. }
  1629. Out << ") {";
  1630. nl(Out);
  1631. is_inline = true;
  1632. printFunctionUses(F);
  1633. printFunctionBody(F);
  1634. is_inline = false;
  1635. Out << "return " << getCppName(F->begin()) << ";";
  1636. nl(Out) << "}";
  1637. nl(Out);
  1638. }
  1639. void CppWriter::printModuleBody() {
  1640. // Print out all the type definitions
  1641. nl(Out) << "// Type Definitions"; nl(Out);
  1642. printTypes(TheModule);
  1643. // Functions can call each other and global variables can reference them so
  1644. // define all the functions first before emitting their function bodies.
  1645. nl(Out) << "// Function Declarations"; nl(Out);
  1646. for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
  1647. I != E; ++I)
  1648. printFunctionHead(I);
  1649. // Process the global variables declarations. We can't initialze them until
  1650. // after the constants are printed so just print a header for each global
  1651. nl(Out) << "// Global Variable Declarations\n"; nl(Out);
  1652. for (Module::const_global_iterator I = TheModule->global_begin(),
  1653. E = TheModule->global_end(); I != E; ++I) {
  1654. printVariableHead(I);
  1655. }
  1656. // Print out all the constants definitions. Constants don't recurse except
  1657. // through GlobalValues. All GlobalValues have been declared at this point
  1658. // so we can proceed to generate the constants.
  1659. nl(Out) << "// Constant Definitions"; nl(Out);
  1660. printConstants(TheModule);
  1661. // Process the global variables definitions now that all the constants have
  1662. // been emitted. These definitions just couple the gvars with their constant
  1663. // initializers.
  1664. nl(Out) << "// Global Variable Definitions"; nl(Out);
  1665. for (Module::const_global_iterator I = TheModule->global_begin(),
  1666. E = TheModule->global_end(); I != E; ++I) {
  1667. printVariableBody(I);
  1668. }
  1669. // Finally, we can safely put out all of the function bodies.
  1670. nl(Out) << "// Function Definitions"; nl(Out);
  1671. for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
  1672. I != E; ++I) {
  1673. if (!I->isDeclaration()) {
  1674. nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
  1675. << ")";
  1676. nl(Out) << "{";
  1677. nl(Out,1);
  1678. printFunctionBody(I);
  1679. nl(Out,-1) << "}";
  1680. nl(Out);
  1681. }
  1682. }
  1683. }
  1684. void CppWriter::printProgram(const std::string& fname,
  1685. const std::string& mName) {
  1686. Out << "#include <llvm/LLVMContext.h>\n";
  1687. Out << "#include <llvm/Module.h>\n";
  1688. Out << "#include <llvm/DerivedTypes.h>\n";
  1689. Out << "#include <llvm/Constants.h>\n";
  1690. Out << "#include <llvm/GlobalVariable.h>\n";
  1691. Out << "#include <llvm/Function.h>\n";
  1692. Out << "#include <llvm/CallingConv.h>\n";
  1693. Out << "#include <llvm/BasicBlock.h>\n";
  1694. Out << "#include <llvm/Instructions.h>\n";
  1695. Out << "#include <llvm/InlineAsm.h>\n";
  1696. Out << "#include <llvm/Support/FormattedStream.h>\n";
  1697. Out << "#include <llvm/Support/MathExtras.h>\n";
  1698. Out << "#include <llvm/Pass.h>\n";
  1699. Out << "#include <llvm/PassManager.h>\n";
  1700. Out << "#include <llvm/ADT/SmallVector.h>\n";
  1701. Out << "#include <llvm/Analysis/Verifier.h>\n";
  1702. Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
  1703. Out << "#include <algorithm>\n";
  1704. Out << "using namespace llvm;\n\n";
  1705. Out << "Module* " << fname << "();\n\n";
  1706. Out << "int main(int argc, char**argv) {\n";
  1707. Out << " Module* Mod = " << fname << "();\n";
  1708. Out << " verifyModule(*Mod, PrintMessageAction);\n";
  1709. Out << " PassManager PM;\n";
  1710. Out << " PM.add(createPrintModulePass(&outs()));\n";
  1711. Out << " PM.run(*Mod);\n";
  1712. Out << " return 0;\n";
  1713. Out << "}\n\n";
  1714. printModule(fname,mName);
  1715. }
  1716. void CppWriter::printModule(const std::string& fname,
  1717. const std::string& mName) {
  1718. nl(Out) << "Module* " << fname << "() {";
  1719. nl(Out,1) << "// Module Construction";
  1720. nl(Out) << "Module* mod = new Module(\"";
  1721. printEscapedString(mName);
  1722. Out << "\", getGlobalContext());";
  1723. if (!TheModule->getTargetTriple().empty()) {
  1724. nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
  1725. }
  1726. if (!TheModule->getTargetTriple().empty()) {
  1727. nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
  1728. << "\");";
  1729. }
  1730. if (!TheModule->getModuleInlineAsm().empty()) {
  1731. nl(Out) << "mod->setModuleInlineAsm(\"";
  1732. printEscapedString(TheModule->getModuleInlineAsm());
  1733. Out << "\");";
  1734. }
  1735. nl(Out);
  1736. // Loop over the dependent libraries and emit them.
  1737. Module::lib_iterator LI = TheModule->lib_begin();
  1738. Module::lib_iterator LE = TheModule->lib_end();
  1739. while (LI != LE) {
  1740. Out << "mod->addLibrary(\"" << *LI << "\");";
  1741. nl(Out);
  1742. ++LI;
  1743. }
  1744. printModuleBody();
  1745. nl(Out) << "return mod;";
  1746. nl(Out,-1) << "}";
  1747. nl(Out);
  1748. }
  1749. void CppWriter::printContents(const std::string& fname,
  1750. const std::string& mName) {
  1751. Out << "\nModule* " << fname << "(Module *mod) {\n";
  1752. Out << "\nmod->setModuleIdentifier(\"";
  1753. printEscapedString(mName);
  1754. Out << "\");\n";
  1755. printModuleBody();
  1756. Out << "\nreturn mod;\n";
  1757. Out << "\n}\n";
  1758. }
  1759. void CppWriter::printFunction(const std::string& fname,
  1760. const std::string& funcName) {
  1761. const Function* F = TheModule->getFunction(funcName);
  1762. if (!F) {
  1763. error(std::string("Function '") + funcName + "' not found in input module");
  1764. return;
  1765. }
  1766. Out << "\nFunction* " << fname << "(Module *mod) {\n";
  1767. printFunctionUses(F);
  1768. printFunctionHead(F);
  1769. printFunctionBody(F);
  1770. Out << "return " << getCppName(F) << ";\n";
  1771. Out << "}\n";
  1772. }
  1773. void CppWriter::printFunctions() {
  1774. const Module::FunctionListType &funcs = TheModule->getFunctionList();
  1775. Module::const_iterator I = funcs.begin();
  1776. Module::const_iterator IE = funcs.end();
  1777. for (; I != IE; ++I) {
  1778. const Function &func = *I;
  1779. if (!func.isDeclaration()) {
  1780. std::string name("define_");
  1781. name += func.getName();
  1782. printFunction(name, func.getName());
  1783. }
  1784. }
  1785. }
  1786. void CppWriter::printVariable(const std::string& fname,
  1787. const std::string& varName) {
  1788. const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
  1789. if (!GV) {
  1790. error(std::string("Variable '") + varName + "' not found in input module");
  1791. return;
  1792. }
  1793. Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
  1794. printVariableUses(GV);
  1795. printVariableHead(GV);
  1796. printVariableBody(GV);
  1797. Out << "return " << getCppName(GV) << ";\n";
  1798. Out << "}\n";
  1799. }
  1800. void CppWriter::printType(const std::string& fname,
  1801. const std::string& typeName) {
  1802. const Type* Ty = TheModule->getTypeByName(typeName);
  1803. if (!Ty) {
  1804. error(std::string("Type '") + typeName + "' not found in input module");
  1805. return;
  1806. }
  1807. Out << "\nType* " << fname << "(Module *mod) {\n";
  1808. printType(Ty);
  1809. Out << "return " << getCppName(Ty) << ";\n";
  1810. Out << "}\n";
  1811. }
  1812. bool CppWriter::runOnModule(Module &M) {
  1813. TheModule = &M;
  1814. // Emit a header
  1815. Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
  1816. // Get the name of the function we're supposed to generate
  1817. std::string fname = FuncName.getValue();
  1818. // Get the name of the thing we are to generate
  1819. std::string tgtname = NameToGenerate.getValue();
  1820. if (GenerationType == GenModule ||
  1821. GenerationType == GenContents ||
  1822. GenerationType == GenProgram ||
  1823. GenerationType == GenFunctions) {
  1824. if (tgtname == "!bad!") {
  1825. if (M.getModuleIdentifier() == "-")
  1826. tgtname = "<stdin>";
  1827. else
  1828. tgtname = M.getModuleIdentifier();
  1829. }
  1830. } else if (tgtname == "!bad!")
  1831. error("You must use the -for option with -gen-{function,variable,type}");
  1832. switch (WhatToGenerate(GenerationType)) {
  1833. case GenProgram:
  1834. if (fname.empty())
  1835. fname = "makeLLVMModule";
  1836. printProgram(fname,tgtname);
  1837. break;
  1838. case GenModule:
  1839. if (fname.empty())
  1840. fname = "makeLLVMModule";
  1841. printModule(fname,tgtname);
  1842. break;
  1843. case GenContents:
  1844. if (fname.empty())
  1845. fname = "makeLLVMModuleContents";
  1846. printContents(fname,tgtname);
  1847. break;
  1848. case GenFunction:
  1849. if (fname.empty())
  1850. fname = "makeLLVMFunction";
  1851. printFunction(fname,tgtname);
  1852. break;
  1853. case GenFunctions:
  1854. printFunctions();
  1855. break;
  1856. case GenInline:
  1857. if (fname.empty())
  1858. fname = "makeLLVMInline";
  1859. printInline(fname,tgtname);
  1860. break;
  1861. case GenVariable:
  1862. if (fname.empty())
  1863. fname = "makeLLVMVariable";
  1864. printVariable(fname,tgtname);
  1865. break;
  1866. case GenType:
  1867. if (fname.empty())
  1868. fname = "makeLLVMType";
  1869. printType(fname,tgtname);
  1870. break;
  1871. default:
  1872. error("Invalid generation option");
  1873. }
  1874. return false;
  1875. }
  1876. }
  1877. char CppWriter::ID = 0;
  1878. //===----------------------------------------------------------------------===//
  1879. // External Interface declaration
  1880. //===----------------------------------------------------------------------===//
  1881. bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
  1882. formatted_raw_ostream &o,
  1883. CodeGenFileType FileType,
  1884. CodeGenOpt::Level OptLevel) {
  1885. if (FileType != TargetMachine::AssemblyFile) return true;
  1886. PM.add(new CppWriter(o));
  1887. return false;
  1888. }