CPPBackend.cpp 74 KB

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