CPPBackend.cpp 73 KB

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