CPPBackend.cpp 74 KB

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