CPPBackend.cpp 74 KB

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