blob: 36c9394404632a7005c1f2ba09baaaa2d56ccb97 [file] [log] [blame]
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001//===-- CppWriter.cpp - Printing LLVM IR as a C++ Source File -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Reid Spencere0d133f2006-05-29 18:08:06 +00005// This file was developed by Reid Spencer and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00007//
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
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/SymbolTable.h"
23#include "llvm/Support/CFG.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/Support/MathExtras.h"
Reid Spencer15f7e012006-05-30 21:18:23 +000027#include "llvm/Support/CommandLine.h"
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000028#include <algorithm>
29#include <iostream>
Reid Spencer66c87342006-05-30 03:43:49 +000030#include <set>
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000031
32using namespace llvm;
33
Reid Spencer15f7e012006-05-30 21:18:23 +000034static cl::opt<std::string>
Reid Spencer15f7e012006-05-30 21:18:23 +000035FuncName("funcname", cl::desc("Specify the name of the generated function"),
36 cl::value_desc("function name"));
37
Reid Spencer12803f52006-05-31 17:31:38 +000038enum WhatToGenerate {
39 GenProgram,
40 GenModule,
41 GenContents,
42 GenFunction,
43 GenVariable,
44 GenType
45};
46
47static cl::opt<WhatToGenerate> GenerationType(cl::Optional,
48 cl::desc("Choose what kind of output to generate"),
49 cl::init(GenProgram),
50 cl::values(
51 clEnumValN(GenProgram, "gen-program", "Generate a complete program"),
52 clEnumValN(GenModule, "gen-module", "Generate a module definition"),
53 clEnumValN(GenContents,"gen-contents", "Generate contents of a module"),
54 clEnumValN(GenFunction,"gen-function", "Generate a function definition"),
55 clEnumValN(GenVariable,"gen-variable", "Generate a variable definition"),
56 clEnumValN(GenType, "gen-type", "Generate a type definition"),
57 clEnumValEnd
58 )
59);
60
61static cl::opt<std::string> NameToGenerate("for", cl::Optional,
62 cl::desc("Specify the name of the thing to generate"),
63 cl::init("!bad!"));
Reid Spencer15f7e012006-05-30 21:18:23 +000064
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000065namespace {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000066typedef std::vector<const Type*> TypeList;
67typedef std::map<const Type*,std::string> TypeMap;
68typedef std::map<const Value*,std::string> ValueMap;
Reid Spencer66c87342006-05-30 03:43:49 +000069typedef std::set<std::string> NameSet;
Reid Spencer15f7e012006-05-30 21:18:23 +000070typedef std::set<const Type*> TypeSet;
71typedef std::set<const Value*> ValueSet;
72typedef std::map<const Value*,std::string> ForwardRefMap;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000073
Reid Spencere0d133f2006-05-29 18:08:06 +000074class CppWriter {
Reid Spencer12803f52006-05-31 17:31:38 +000075 const char* progname;
Reid Spencere0d133f2006-05-29 18:08:06 +000076 std::ostream &Out;
77 const Module *TheModule;
Andrew Lenharth539d8712006-05-31 20:18:56 +000078 uint64_t uniqueNum;
Reid Spencere0d133f2006-05-29 18:08:06 +000079 TypeMap TypeNames;
80 ValueMap ValueNames;
81 TypeMap UnresolvedTypes;
82 TypeList TypeStack;
Reid Spencer66c87342006-05-30 03:43:49 +000083 NameSet UsedNames;
Reid Spencer15f7e012006-05-30 21:18:23 +000084 TypeSet DefinedTypes;
85 ValueSet DefinedValues;
86 ForwardRefMap ForwardRefs;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000087
Reid Spencere0d133f2006-05-29 18:08:06 +000088public:
Reid Spencer12803f52006-05-31 17:31:38 +000089 inline CppWriter(std::ostream &o, const Module *M, const char* pn="llvm2cpp")
90 : progname(pn), Out(o), TheModule(M), uniqueNum(0), TypeNames(),
Reid Spencere0d133f2006-05-29 18:08:06 +000091 ValueNames(), UnresolvedTypes(), TypeStack() { }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000092
Reid Spencere0d133f2006-05-29 18:08:06 +000093 const Module* getModule() { return TheModule; }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000094
Reid Spencer12803f52006-05-31 17:31:38 +000095 void printProgram(const std::string& fname, const std::string& modName );
96 void printModule(const std::string& fname, const std::string& modName );
97 void printContents(const std::string& fname, const std::string& modName );
98 void printFunction(const std::string& fname, const std::string& funcName );
99 void printVariable(const std::string& fname, const std::string& varName );
100 void printType(const std::string& fname, const std::string& typeName );
101
102 void error(const std::string& msg);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000103
Reid Spencere0d133f2006-05-29 18:08:06 +0000104private:
Reid Spencer12803f52006-05-31 17:31:38 +0000105 void printLinkageType(GlobalValue::LinkageTypes LT);
106 void printCallingConv(unsigned cc);
107 void printEscapedString(const std::string& str);
108 void printCFP(const ConstantFP* CFP);
109
110 std::string getCppName(const Type* val);
111 inline void printCppName(const Type* val);
112
113 std::string getCppName(const Value* val);
114 inline void printCppName(const Value* val);
115
116 bool printTypeInternal(const Type* Ty);
117 inline void printType(const Type* Ty);
Reid Spencere0d133f2006-05-29 18:08:06 +0000118 void printTypes(const Module* M);
Reid Spencer12803f52006-05-31 17:31:38 +0000119
Reid Spencere0d133f2006-05-29 18:08:06 +0000120 void printConstant(const Constant *CPV);
Reid Spencer12803f52006-05-31 17:31:38 +0000121 void printConstants(const Module* M);
122
123 void printVariableUses(const GlobalVariable *GV);
124 void printVariableHead(const GlobalVariable *GV);
125 void printVariableBody(const GlobalVariable *GV);
126
127 void printFunctionUses(const Function *F);
Reid Spencer66c87342006-05-30 03:43:49 +0000128 void printFunctionHead(const Function *F);
129 void printFunctionBody(const Function *F);
Reid Spencere0d133f2006-05-29 18:08:06 +0000130 void printInstruction(const Instruction *I, const std::string& bbname);
Reid Spencer15f7e012006-05-30 21:18:23 +0000131 std::string getOpName(Value*);
132
Reid Spencer12803f52006-05-31 17:31:38 +0000133 void printModuleBody();
134
Reid Spencere0d133f2006-05-29 18:08:06 +0000135};
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000136
Reid Spencer12803f52006-05-31 17:31:38 +0000137inline void
138sanitize(std::string& str) {
139 for (size_t i = 0; i < str.length(); ++i)
140 if (!isalnum(str[i]) && str[i] != '_')
141 str[i] = '_';
142}
143
144inline const char*
145getTypePrefix(const Type* Ty ) {
146 const char* prefix;
147 switch (Ty->getTypeID()) {
148 case Type::VoidTyID: prefix = "void_"; break;
149 case Type::BoolTyID: prefix = "bool_"; break;
150 case Type::UByteTyID: prefix = "ubyte_"; break;
151 case Type::SByteTyID: prefix = "sbyte_"; break;
152 case Type::UShortTyID: prefix = "ushort_"; break;
153 case Type::ShortTyID: prefix = "short_"; break;
154 case Type::UIntTyID: prefix = "uint_"; break;
155 case Type::IntTyID: prefix = "int_"; break;
156 case Type::ULongTyID: prefix = "ulong_"; break;
157 case Type::LongTyID: prefix = "long_"; break;
158 case Type::FloatTyID: prefix = "float_"; break;
159 case Type::DoubleTyID: prefix = "double_"; break;
160 case Type::LabelTyID: prefix = "label_"; break;
161 case Type::FunctionTyID: prefix = "func_"; break;
162 case Type::StructTyID: prefix = "struct_"; break;
163 case Type::ArrayTyID: prefix = "array_"; break;
164 case Type::PointerTyID: prefix = "ptr_"; break;
165 case Type::PackedTyID: prefix = "packed_"; break;
166 case Type::OpaqueTyID: prefix = "opaque_"; break;
167 default: prefix = "other_"; break;
168 }
169 return prefix;
170}
171
172// Looks up the type in the symbol table and returns a pointer to its name or
173// a null pointer if it wasn't found. Note that this isn't the same as the
174// Mode::getTypeName function which will return an empty string, not a null
175// pointer if the name is not found.
176inline const std::string*
177findTypeName(const SymbolTable& ST, const Type* Ty)
178{
179 SymbolTable::type_const_iterator TI = ST.type_begin();
180 SymbolTable::type_const_iterator TE = ST.type_end();
181 for (;TI != TE; ++TI)
182 if (TI->second == Ty)
183 return &(TI->first);
184 return 0;
185}
186
187void
188CppWriter::error(const std::string& msg) {
189 std::cerr << progname << ": " << msg << "\n";
190 exit(2);
191}
192
Reid Spencer15f7e012006-05-30 21:18:23 +0000193// printCFP - Print a floating point constant .. very carefully :)
194// This makes sure that conversion to/from floating yields the same binary
195// result so that we don't lose precision.
196void
197CppWriter::printCFP(const ConstantFP *CFP) {
198#if HAVE_PRINTF_A
199 char Buffer[100];
200 sprintf(Buffer, "%A", CFP->getValue());
201 if ((!strncmp(Buffer, "0x", 2) ||
202 !strncmp(Buffer, "-0x", 3) ||
203 !strncmp(Buffer, "+0x", 3)) &&
204 (atof(Buffer) == CFP->getValue()))
205 Out << Buffer;
206 else {
207#else
208 std::string StrVal = ftostr(CFP->getValue());
209
210 while (StrVal[0] == ' ')
211 StrVal.erase(StrVal.begin());
212
213 // Check to make sure that the stringized number is not some string like "Inf"
214 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
215 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
216 ((StrVal[0] == '-' || StrVal[0] == '+') &&
217 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
218 (atof(StrVal.c_str()) == CFP->getValue()))
219 Out << StrVal;
220 else if (CFP->getType() == Type::DoubleTy) {
221 Out << "0x" << std::hex << DoubleToBits(CFP->getValue()) << std::dec
222 << "ULL /* " << StrVal << " */";
223 } else {
224 Out << "0x" << std::hex << FloatToBits(CFP->getValue()) << std::dec
225 << "U /* " << StrVal << " */";
226 }
227#endif
228#if HAVE_PRINTF_A
229 }
230#endif
231}
232
Reid Spencer12803f52006-05-31 17:31:38 +0000233void
234CppWriter::printCallingConv(unsigned cc){
235 // Print the calling convention.
236 switch (cc) {
237 case CallingConv::C: Out << "CallingConv::C"; break;
238 case CallingConv::CSRet: Out << "CallingConv::CSRet"; 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}
Reid Spencer15f7e012006-05-30 21:18:23 +0000245
Reid Spencer12803f52006-05-31 17:31:38 +0000246void
247CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
248 switch (LT) {
249 case GlobalValue::InternalLinkage:
250 Out << "GlobalValue::InternalLinkage"; break;
251 case GlobalValue::LinkOnceLinkage:
252 Out << "GlobalValue::LinkOnceLinkage "; break;
253 case GlobalValue::WeakLinkage:
254 Out << "GlobalValue::WeakLinkage"; break;
255 case GlobalValue::AppendingLinkage:
256 Out << "GlobalValue::AppendingLinkage"; break;
257 case GlobalValue::ExternalLinkage:
258 Out << "GlobalValue::ExternalLinkage"; break;
259 case GlobalValue::GhostLinkage:
260 Out << "GlobalValue::GhostLinkage"; break;
261 }
Reid Spencer15f7e012006-05-30 21:18:23 +0000262}
263
Reid Spencere0d133f2006-05-29 18:08:06 +0000264// printEscapedString - Print each character of the specified string, escaping
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000265// it if it is not printable or if it is an escape char.
Reid Spencere0d133f2006-05-29 18:08:06 +0000266void
267CppWriter::printEscapedString(const std::string &Str) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000268 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
269 unsigned char C = Str[i];
270 if (isprint(C) && C != '"' && C != '\\') {
271 Out << C;
272 } else {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000273 Out << "\\x"
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000274 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
275 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
276 }
277 }
278}
279
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000280std::string
281CppWriter::getCppName(const Type* Ty)
282{
283 // First, handle the primitive types .. easy
284 if (Ty->isPrimitiveType()) {
285 switch (Ty->getTypeID()) {
286 case Type::VoidTyID: return "Type::VoidTy";
287 case Type::BoolTyID: return "Type::BoolTy";
288 case Type::UByteTyID: return "Type::UByteTy";
289 case Type::SByteTyID: return "Type::SByteTy";
290 case Type::UShortTyID: return "Type::UShortTy";
291 case Type::ShortTyID: return "Type::ShortTy";
292 case Type::UIntTyID: return "Type::UIntTy";
293 case Type::IntTyID: return "Type::IntTy";
294 case Type::ULongTyID: return "Type::ULongTy";
295 case Type::LongTyID: return "Type::LongTy";
296 case Type::FloatTyID: return "Type::FloatTy";
297 case Type::DoubleTyID: return "Type::DoubleTy";
298 case Type::LabelTyID: return "Type::LabelTy";
299 default:
Reid Spencer12803f52006-05-31 17:31:38 +0000300 error("Invalid primitive type");
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000301 break;
302 }
303 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
304 }
305
306 // Now, see if we've seen the type before and return that
307 TypeMap::iterator I = TypeNames.find(Ty);
308 if (I != TypeNames.end())
309 return I->second;
310
311 // Okay, let's build a new name for this type. Start with a prefix
312 const char* prefix = 0;
313 switch (Ty->getTypeID()) {
314 case Type::FunctionTyID: prefix = "FuncTy_"; break;
315 case Type::StructTyID: prefix = "StructTy_"; break;
316 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
317 case Type::PointerTyID: prefix = "PointerTy_"; break;
318 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
319 case Type::PackedTyID: prefix = "PackedTy_"; break;
320 default: prefix = "OtherTy_"; break; // prevent breakage
321 }
322
323 // See if the type has a name in the symboltable and build accordingly
324 const std::string* tName = findTypeName(TheModule->getSymbolTable(), Ty);
325 std::string name;
326 if (tName)
327 name = std::string(prefix) + *tName;
328 else
329 name = std::string(prefix) + utostr(uniqueNum++);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000330 sanitize(name);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000331
332 // Save the name
333 return TypeNames[Ty] = name;
334}
335
Reid Spencer12803f52006-05-31 17:31:38 +0000336void
337CppWriter::printCppName(const Type* Ty)
338{
339 printEscapedString(getCppName(Ty));
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000340}
341
Reid Spencer12803f52006-05-31 17:31:38 +0000342std::string
343CppWriter::getCppName(const Value* val) {
344 std::string name;
345 ValueMap::iterator I = ValueNames.find(val);
346 if (I != ValueNames.end() && I->first == val)
347 return I->second;
Reid Spencer25edc352006-05-31 04:43:19 +0000348
Reid Spencer12803f52006-05-31 17:31:38 +0000349 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
350 name = std::string("gvar_") +
351 getTypePrefix(GV->getType()->getElementType());
352 } else if (const Function* F = dyn_cast<Function>(val)) {
353 name = std::string("func_");
354 } else if (const Constant* C = dyn_cast<Constant>(val)) {
355 name = std::string("const_") + getTypePrefix(C->getType());
356 } else {
357 name = getTypePrefix(val->getType());
Reid Spencer25edc352006-05-31 04:43:19 +0000358 }
Reid Spencer12803f52006-05-31 17:31:38 +0000359 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
360 sanitize(name);
361 NameSet::iterator NI = UsedNames.find(name);
362 if (NI != UsedNames.end())
363 name += std::string("_") + utostr(uniqueNum++);
364 UsedNames.insert(name);
365 return ValueNames[val] = name;
Reid Spencer25edc352006-05-31 04:43:19 +0000366}
367
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000368void
Reid Spencer12803f52006-05-31 17:31:38 +0000369CppWriter::printCppName(const Value* val) {
370 printEscapedString(getCppName(val));
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000371}
372
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000373bool
Reid Spencer12803f52006-05-31 17:31:38 +0000374CppWriter::printTypeInternal(const Type* Ty) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000375 // We don't print definitions for primitive types
376 if (Ty->isPrimitiveType())
377 return false;
378
Reid Spencer15f7e012006-05-30 21:18:23 +0000379 // If we already defined this type, we don't need to define it again.
380 if (DefinedTypes.find(Ty) != DefinedTypes.end())
381 return false;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000382
Reid Spencer15f7e012006-05-30 21:18:23 +0000383 // Everything below needs the name for the type so get it now.
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000384 std::string typeName(getCppName(Ty));
385
386 // Search the type stack for recursion. If we find it, then generate this
387 // as an OpaqueType, but make sure not to do this multiple times because
388 // the type could appear in multiple places on the stack. Once the opaque
Reid Spencer15f7e012006-05-30 21:18:23 +0000389 // definition is issued, it must not be re-issued. Consequently we have to
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000390 // check the UnresolvedTypes list as well.
Reid Spencer12803f52006-05-31 17:31:38 +0000391 TypeList::const_iterator TI = std::find(TypeStack.begin(),TypeStack.end(),Ty);
392 if (TI != TypeStack.end()) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000393 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
394 if (I == UnresolvedTypes.end()) {
395 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();\n";
396 UnresolvedTypes[Ty] = typeName;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000397 }
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000398 return true;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000399 }
400
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000401 // We're going to print a derived type which, by definition, contains other
402 // types. So, push this one we're printing onto the type stack to assist with
403 // recursive definitions.
Reid Spencer15f7e012006-05-30 21:18:23 +0000404 TypeStack.push_back(Ty);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000405
406 // Print the type definition
407 switch (Ty->getTypeID()) {
408 case Type::FunctionTyID: {
409 const FunctionType* FT = cast<FunctionType>(Ty);
410 Out << "std::vector<const Type*>" << typeName << "_args;\n";
411 FunctionType::param_iterator PI = FT->param_begin();
412 FunctionType::param_iterator PE = FT->param_end();
413 for (; PI != PE; ++PI) {
414 const Type* argTy = static_cast<const Type*>(*PI);
Reid Spencer12803f52006-05-31 17:31:38 +0000415 bool isForward = printTypeInternal(argTy);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000416 std::string argName(getCppName(argTy));
417 Out << typeName << "_args.push_back(" << argName;
418 if (isForward)
419 Out << "_fwd";
420 Out << ");\n";
421 }
Reid Spencer12803f52006-05-31 17:31:38 +0000422 bool isForward = printTypeInternal(FT->getReturnType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000423 std::string retTypeName(getCppName(FT->getReturnType()));
424 Out << "FunctionType* " << typeName << " = FunctionType::get(\n"
425 << " /*Result=*/" << retTypeName;
426 if (isForward)
427 Out << "_fwd";
428 Out << ",\n /*Params=*/" << typeName << "_args,\n /*isVarArg=*/"
429 << (FT->isVarArg() ? "true" : "false") << ");\n";
430 break;
431 }
432 case Type::StructTyID: {
433 const StructType* ST = cast<StructType>(Ty);
434 Out << "std::vector<const Type*>" << typeName << "_fields;\n";
435 StructType::element_iterator EI = ST->element_begin();
436 StructType::element_iterator EE = ST->element_end();
437 for (; EI != EE; ++EI) {
438 const Type* fieldTy = static_cast<const Type*>(*EI);
Reid Spencer12803f52006-05-31 17:31:38 +0000439 bool isForward = printTypeInternal(fieldTy);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000440 std::string fieldName(getCppName(fieldTy));
441 Out << typeName << "_fields.push_back(" << fieldName;
442 if (isForward)
443 Out << "_fwd";
444 Out << ");\n";
445 }
446 Out << "StructType* " << typeName << " = StructType::get("
447 << typeName << "_fields);\n";
448 break;
449 }
450 case Type::ArrayTyID: {
451 const ArrayType* AT = cast<ArrayType>(Ty);
452 const Type* ET = AT->getElementType();
Reid Spencer12803f52006-05-31 17:31:38 +0000453 bool isForward = printTypeInternal(ET);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000454 std::string elemName(getCppName(ET));
455 Out << "ArrayType* " << typeName << " = ArrayType::get("
456 << elemName << (isForward ? "_fwd" : "")
457 << ", " << utostr(AT->getNumElements()) << ");\n";
458 break;
459 }
460 case Type::PointerTyID: {
461 const PointerType* PT = cast<PointerType>(Ty);
462 const Type* ET = PT->getElementType();
Reid Spencer12803f52006-05-31 17:31:38 +0000463 bool isForward = printTypeInternal(ET);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000464 std::string elemName(getCppName(ET));
465 Out << "PointerType* " << typeName << " = PointerType::get("
466 << elemName << (isForward ? "_fwd" : "") << ");\n";
467 break;
468 }
469 case Type::PackedTyID: {
470 const PackedType* PT = cast<PackedType>(Ty);
471 const Type* ET = PT->getElementType();
Reid Spencer12803f52006-05-31 17:31:38 +0000472 bool isForward = printTypeInternal(ET);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000473 std::string elemName(getCppName(ET));
474 Out << "PackedType* " << typeName << " = PackedType::get("
475 << elemName << (isForward ? "_fwd" : "")
476 << ", " << utostr(PT->getNumElements()) << ");\n";
477 break;
478 }
479 case Type::OpaqueTyID: {
480 const OpaqueType* OT = cast<OpaqueType>(Ty);
481 Out << "OpaqueType* " << typeName << " = OpaqueType::get();\n";
482 break;
483 }
484 default:
Reid Spencer12803f52006-05-31 17:31:38 +0000485 error("Invalid TypeID");
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000486 }
487
Reid Spencer74e032a2006-05-29 02:58:15 +0000488 // If the type had a name, make sure we recreate it.
489 const std::string* progTypeName =
490 findTypeName(TheModule->getSymbolTable(),Ty);
491 if (progTypeName)
492 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
493 << typeName << ");\n";
494
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000495 // Pop us off the type stack
496 TypeStack.pop_back();
Reid Spencer15f7e012006-05-30 21:18:23 +0000497
498 // Indicate that this type is now defined.
499 DefinedTypes.insert(Ty);
500
501 // Early resolve as many unresolved types as possible. Search the unresolved
502 // types map for the type we just printed. Now that its definition is complete
503 // we can resolve any previous references to it. This prevents a cascade of
504 // unresolved types.
505 TypeMap::iterator I = UnresolvedTypes.find(Ty);
506 if (I != UnresolvedTypes.end()) {
507 Out << "cast<OpaqueType>(" << I->second
508 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");\n";
509 Out << I->second << " = cast<";
510 switch (Ty->getTypeID()) {
511 case Type::FunctionTyID: Out << "FunctionType"; break;
512 case Type::ArrayTyID: Out << "ArrayType"; break;
513 case Type::StructTyID: Out << "StructType"; break;
514 case Type::PackedTyID: Out << "PackedType"; break;
515 case Type::PointerTyID: Out << "PointerType"; break;
516 case Type::OpaqueTyID: Out << "OpaqueType"; break;
517 default: Out << "NoSuchDerivedType"; break;
518 }
519 Out << ">(" << I->second << "_fwd.get());\n\n";
520 UnresolvedTypes.erase(I);
521 }
522
523 // Finally, separate the type definition from other with a newline.
Reid Spencere0d133f2006-05-29 18:08:06 +0000524 Out << "\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000525
526 // We weren't a recursive type
527 return false;
528}
529
Reid Spencer12803f52006-05-31 17:31:38 +0000530// Prints a type definition. Returns true if it could not resolve all the types
531// in the definition but had to use a forward reference.
532void
533CppWriter::printType(const Type* Ty) {
534 assert(TypeStack.empty());
535 TypeStack.clear();
536 printTypeInternal(Ty);
537 assert(TypeStack.empty());
538}
539
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000540void
541CppWriter::printTypes(const Module* M) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000542
543 // Walk the symbol table and print out all its types
544 const SymbolTable& symtab = M->getSymbolTable();
545 for (SymbolTable::type_const_iterator TI = symtab.type_begin(),
546 TE = symtab.type_end(); TI != TE; ++TI) {
547
548 // For primitive types and types already defined, just add a name
549 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
550 if (TI->second->isPrimitiveType() || TNI != TypeNames.end()) {
551 Out << "mod->addTypeName(\"";
552 printEscapedString(TI->first);
553 Out << "\", " << getCppName(TI->second) << ");\n";
554 // For everything else, define the type
555 } else {
Reid Spencer12803f52006-05-31 17:31:38 +0000556 printType(TI->second);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000557 }
558 }
559
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000560 // Add all of the global variables to the value table...
561 for (Module::const_global_iterator I = TheModule->global_begin(),
562 E = TheModule->global_end(); I != E; ++I) {
563 if (I->hasInitializer())
Reid Spencer12803f52006-05-31 17:31:38 +0000564 printType(I->getInitializer()->getType());
565 printType(I->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000566 }
567
568 // Add all the functions to the table
569 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
570 FI != FE; ++FI) {
Reid Spencer12803f52006-05-31 17:31:38 +0000571 printType(FI->getReturnType());
572 printType(FI->getFunctionType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000573 // Add all the function arguments
574 for(Function::const_arg_iterator AI = FI->arg_begin(),
575 AE = FI->arg_end(); AI != AE; ++AI) {
Reid Spencer12803f52006-05-31 17:31:38 +0000576 printType(AI->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000577 }
578
579 // Add all of the basic blocks and instructions
580 for (Function::const_iterator BB = FI->begin(),
581 E = FI->end(); BB != E; ++BB) {
Reid Spencer12803f52006-05-31 17:31:38 +0000582 printType(BB->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000583 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
584 ++I) {
Reid Spencer12803f52006-05-31 17:31:38 +0000585 printType(I->getType());
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000586 for (unsigned i = 0; i < I->getNumOperands(); ++i)
Reid Spencer12803f52006-05-31 17:31:38 +0000587 printType(I->getOperand(i)->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000588 }
589 }
590 }
591}
592
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000593
Reid Spencere0d133f2006-05-29 18:08:06 +0000594// printConstant - Print out a constant pool entry...
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000595void CppWriter::printConstant(const Constant *CV) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000596 // First, if the constant is actually a GlobalValue (variable or function) or
597 // its already in the constant list then we've printed it already and we can
598 // just return.
599 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
Reid Spencere0d133f2006-05-29 18:08:06 +0000600 return;
601
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000602 const int IndentSize = 2;
603 static std::string Indent = "\n";
604 std::string constName(getCppName(CV));
605 std::string typeName(getCppName(CV->getType()));
606 if (CV->isNullValue()) {
607 Out << "Constant* " << constName << " = Constant::getNullValue("
608 << typeName << ");\n";
609 return;
610 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000611 if (isa<GlobalValue>(CV)) {
612 // Skip variables and functions, we emit them elsewhere
613 return;
614 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000615 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000616 Out << "ConstantBool* " << constName << " = ConstantBool::get("
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000617 << (CB == ConstantBool::True ? "true" : "false")
618 << ");";
619 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000620 Out << "ConstantSInt* " << constName << " = ConstantSInt::get("
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000621 << typeName << ", " << CI->getValue() << ");";
622 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000623 Out << "ConstantUInt* " << constName << " = ConstantUInt::get("
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000624 << typeName << ", " << CI->getValue() << ");";
625 } else if (isa<ConstantAggregateZero>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000626 Out << "ConstantAggregateZero* " << constName
627 << " = ConstantAggregateZero::get(" << typeName << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000628 } else if (isa<ConstantPointerNull>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000629 Out << "ConstantPointerNull* " << constName
630 << " = ConstanPointerNull::get(" << typeName << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000631 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000632 Out << "ConstantFP* " << constName << " = ConstantFP::get(" << typeName
633 << ", ";
Reid Spencer12803f52006-05-31 17:31:38 +0000634 printCFP(CFP);
Reid Spencer15f7e012006-05-30 21:18:23 +0000635 Out << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000636 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000637 if (CA->isString() && CA->getType()->getElementType() == Type::SByteTy) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000638 Out << "Constant* " << constName << " = ConstantArray::get(\"";
Reid Spencere0d133f2006-05-29 18:08:06 +0000639 printEscapedString(CA->getAsString());
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000640 // Determine if we want null termination or not.
641 if (CA->getType()->getNumElements() <= CA->getAsString().length())
Reid Spencer15f7e012006-05-30 21:18:23 +0000642 Out << "\", false";// No null terminator
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000643 else
Reid Spencer15f7e012006-05-30 21:18:23 +0000644 Out << "\", true"; // Indicate that the null terminator should be added.
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000645 Out << ");";
646 } else {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000647 Out << "std::vector<Constant*> " << constName << "_elems;\n";
648 unsigned N = CA->getNumOperands();
649 for (unsigned i = 0; i < N; ++i) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000650 printConstant(CA->getOperand(i)); // recurse to print operands
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000651 Out << constName << "_elems.push_back("
652 << getCppName(CA->getOperand(i)) << ");\n";
653 }
654 Out << "Constant* " << constName << " = ConstantArray::get("
655 << typeName << ", " << constName << "_elems);";
656 }
657 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
658 Out << "std::vector<Constant*> " << constName << "_fields;\n";
659 unsigned N = CS->getNumOperands();
660 for (unsigned i = 0; i < N; i++) {
661 printConstant(CS->getOperand(i));
662 Out << constName << "_fields.push_back("
Reid Spencer66c87342006-05-30 03:43:49 +0000663 << getCppName(CS->getOperand(i)) << ");\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000664 }
665 Out << "Constant* " << constName << " = ConstantStruct::get("
666 << typeName << ", " << constName << "_fields);";
667 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
668 Out << "std::vector<Constant*> " << constName << "_elems;\n";
669 unsigned N = CP->getNumOperands();
670 for (unsigned i = 0; i < N; ++i) {
671 printConstant(CP->getOperand(i));
672 Out << constName << "_elems.push_back("
673 << getCppName(CP->getOperand(i)) << ");\n";
674 }
675 Out << "Constant* " << constName << " = ConstantPacked::get("
676 << typeName << ", " << constName << "_elems);";
677 } else if (isa<UndefValue>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000678 Out << "UndefValue* " << constName << " = UndefValue::get("
Reid Spencere0d133f2006-05-29 18:08:06 +0000679 << typeName << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000680 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000681 if (CE->getOpcode() == Instruction::GetElementPtr) {
682 Out << "std::vector<Constant*> " << constName << "_indices;\n";
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000683 printConstant(CE->getOperand(0));
Reid Spencere0d133f2006-05-29 18:08:06 +0000684 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000685 printConstant(CE->getOperand(i));
Reid Spencere0d133f2006-05-29 18:08:06 +0000686 Out << constName << "_indices.push_back("
687 << getCppName(CE->getOperand(i)) << ");\n";
688 }
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000689 Out << "Constant* " << constName
690 << " = ConstantExpr::getGetElementPtr("
691 << getCppName(CE->getOperand(0)) << ", "
692 << constName << "_indices);";
Reid Spencere0d133f2006-05-29 18:08:06 +0000693 } else if (CE->getOpcode() == Instruction::Cast) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000694 printConstant(CE->getOperand(0));
Reid Spencere0d133f2006-05-29 18:08:06 +0000695 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
696 Out << getCppName(CE->getOperand(0)) << ", " << getCppName(CE->getType())
697 << ");";
698 } else {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000699 unsigned N = CE->getNumOperands();
700 for (unsigned i = 0; i < N; ++i ) {
701 printConstant(CE->getOperand(i));
702 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000703 Out << "Constant* " << constName << " = ConstantExpr::";
704 switch (CE->getOpcode()) {
705 case Instruction::Add: Out << "getAdd"; break;
706 case Instruction::Sub: Out << "getSub"; break;
707 case Instruction::Mul: Out << "getMul"; break;
708 case Instruction::Div: Out << "getDiv"; break;
709 case Instruction::Rem: Out << "getRem"; break;
710 case Instruction::And: Out << "getAnd"; break;
711 case Instruction::Or: Out << "getOr"; break;
712 case Instruction::Xor: Out << "getXor"; break;
713 case Instruction::SetEQ: Out << "getSetEQ"; break;
714 case Instruction::SetNE: Out << "getSetNE"; break;
715 case Instruction::SetLE: Out << "getSetLE"; break;
716 case Instruction::SetGE: Out << "getSetGE"; break;
717 case Instruction::SetLT: Out << "getSetLT"; break;
718 case Instruction::SetGT: Out << "getSetGT"; break;
719 case Instruction::Shl: Out << "getShl"; break;
720 case Instruction::Shr: Out << "getShr"; break;
721 case Instruction::Select: Out << "getSelect"; break;
722 case Instruction::ExtractElement: Out << "getExtractElement"; break;
723 case Instruction::InsertElement: Out << "getInsertElement"; break;
724 case Instruction::ShuffleVector: Out << "getShuffleVector"; break;
725 default:
Reid Spencer12803f52006-05-31 17:31:38 +0000726 error("Invalid constant expression");
Reid Spencere0d133f2006-05-29 18:08:06 +0000727 break;
728 }
729 Out << getCppName(CE->getOperand(0));
730 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
731 Out << ", " << getCppName(CE->getOperand(i));
732 Out << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000733 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000734 } else {
Reid Spencer12803f52006-05-31 17:31:38 +0000735 error("Bad Constant");
Reid Spencere0d133f2006-05-29 18:08:06 +0000736 Out << "Constant* " << constName << " = 0; ";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000737 }
738 Out << "\n";
739}
740
Reid Spencer12803f52006-05-31 17:31:38 +0000741void
742CppWriter::printConstants(const Module* M) {
743 // Traverse all the global variables looking for constant initializers
744 for (Module::const_global_iterator I = TheModule->global_begin(),
745 E = TheModule->global_end(); I != E; ++I)
746 if (I->hasInitializer())
747 printConstant(I->getInitializer());
748
749 // Traverse the LLVM functions looking for constants
750 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
751 FI != FE; ++FI) {
752 // Add all of the basic blocks and instructions
753 for (Function::const_iterator BB = FI->begin(),
754 E = FI->end(); BB != E; ++BB) {
755 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
756 ++I) {
757 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
758 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
759 printConstant(C);
760 }
761 }
762 }
763 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000764 }
Reid Spencer66c87342006-05-30 03:43:49 +0000765}
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000766
Reid Spencer12803f52006-05-31 17:31:38 +0000767void CppWriter::printVariableUses(const GlobalVariable *GV) {
768 Out << "\n// Type Definitions\n";
769 printType(GV->getType());
770 if (GV->hasInitializer()) {
771 Constant* Init = GV->getInitializer();
772 printType(Init->getType());
773 if (Function* F = dyn_cast<Function>(Init)) {
774 Out << "\n// Function Declarations\n";
775 printFunctionHead(F);
776 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
777 Out << "\n// Global Variable Declarations\n";
778 printVariableHead(gv);
779 } else {
780 Out << "\n// Constant Definitions\n";
781 printConstant(gv);
782 }
783 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
784 Out << "\n// Global Variable Definitions\n";
785 printVariableBody(gv);
Reid Spencere0d133f2006-05-29 18:08:06 +0000786 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000787 }
Reid Spencer12803f52006-05-31 17:31:38 +0000788}
Reid Spencer15f7e012006-05-30 21:18:23 +0000789
Reid Spencer12803f52006-05-31 17:31:38 +0000790void CppWriter::printVariableHead(const GlobalVariable *GV) {
791 Out << "\n";
792 Out << "GlobalVariable* ";
793 printCppName(GV);
794 Out << " = new GlobalVariable(\n";
795 Out << " /*Type=*/";
796 printCppName(GV->getType()->getElementType());
797 Out << ",\n";
798 Out << " /*isConstant=*/" << (GV->isConstant()?"true":"false")
799 << ",\n /*Linkage=*/";
800 printLinkageType(GV->getLinkage());
801 Out << ",\n /*Initializer=*/0, ";
802 if (GV->hasInitializer()) {
803 Out << "// has initializer, specified below";
Reid Spencer15f7e012006-05-30 21:18:23 +0000804 }
Reid Spencer12803f52006-05-31 17:31:38 +0000805 Out << "\n /*Name=*/\"";
806 printEscapedString(GV->getName());
807 Out << "\",\n mod);\n";
808
809 if (GV->hasSection()) {
810 printCppName(GV);
811 Out << "->setSection(\"";
812 printEscapedString(GV->getSection());
813 Out << "\");\n";
814 }
815 if (GV->getAlignment()) {
816 printCppName(GV);
817 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");\n";
818 };
819}
820
821void
822CppWriter::printVariableBody(const GlobalVariable *GV) {
823 if (GV->hasInitializer()) {
824 printCppName(GV);
825 Out << "->setInitializer(";
826 //if (!isa<GlobalValue(GV->getInitializer()))
827 //else
828 Out << getCppName(GV->getInitializer()) << ");\n";
829 }
830}
831
832std::string
833CppWriter::getOpName(Value* V) {
834 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
835 return getCppName(V);
836
837 // See if its alread in the map of forward references, if so just return the
838 // name we already set up for it
839 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
840 if (I != ForwardRefs.end())
841 return I->second;
842
843 // This is a new forward reference. Generate a unique name for it
844 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
845
846 // Yes, this is a hack. An Argument is the smallest instantiable value that
847 // we can make as a placeholder for the real value. We'll replace these
848 // Argument instances later.
849 Out << " Argument* " << result << " = new Argument("
850 << getCppName(V->getType()) << ");\n";
851 ForwardRefs[V] = result;
852 return result;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000853}
854
Reid Spencere0d133f2006-05-29 18:08:06 +0000855// printInstruction - This member is called for each Instruction in a function.
856void
Reid Spencer12803f52006-05-31 17:31:38 +0000857CppWriter::printInstruction(const Instruction *I, const std::string& bbname) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000858 std::string iName(getCppName(I));
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000859
Reid Spencer15f7e012006-05-30 21:18:23 +0000860 // Before we emit this instruction, we need to take care of generating any
861 // forward references. So, we get the names of all the operands in advance
862 std::string* opNames = new std::string[I->getNumOperands()];
863 for (unsigned i = 0; i < I->getNumOperands(); i++) {
864 opNames[i] = getOpName(I->getOperand(i));
865 }
866
Reid Spencere0d133f2006-05-29 18:08:06 +0000867 switch (I->getOpcode()) {
868 case Instruction::Ret: {
869 const ReturnInst* ret = cast<ReturnInst>(I);
Reid Spencer15f7e012006-05-30 21:18:23 +0000870 Out << " ReturnInst* " << iName << " = new ReturnInst("
871 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
Reid Spencere0d133f2006-05-29 18:08:06 +0000872 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000873 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000874 case Instruction::Br: {
875 const BranchInst* br = cast<BranchInst>(I);
Reid Spencer66c87342006-05-30 03:43:49 +0000876 Out << " BranchInst* " << iName << " = new BranchInst(" ;
Reid Spencere0d133f2006-05-29 18:08:06 +0000877 if (br->getNumOperands() == 3 ) {
Reid Spencer15f7e012006-05-30 21:18:23 +0000878 Out << opNames[0] << ", "
879 << opNames[1] << ", "
880 << opNames[2] << ", ";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000881
Reid Spencere0d133f2006-05-29 18:08:06 +0000882 } else if (br->getNumOperands() == 1) {
Reid Spencer15f7e012006-05-30 21:18:23 +0000883 Out << opNames[0] << ", ";
Reid Spencere0d133f2006-05-29 18:08:06 +0000884 } else {
Reid Spencer12803f52006-05-31 17:31:38 +0000885 error("Branch with 2 operands?");
Reid Spencere0d133f2006-05-29 18:08:06 +0000886 }
887 Out << bbname << ");";
888 break;
889 }
Reid Spencer66c87342006-05-30 03:43:49 +0000890 case Instruction::Switch: {
891 const SwitchInst* sw = cast<SwitchInst>(I);
892 Out << " SwitchInst* " << iName << " = new SwitchInst("
Reid Spencer15f7e012006-05-30 21:18:23 +0000893 << opNames[0] << ", "
894 << opNames[1] << ", "
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000895 << sw->getNumCases() << ", " << bbname << ");\n";
Reid Spencer15f7e012006-05-30 21:18:23 +0000896 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
Reid Spencer66c87342006-05-30 03:43:49 +0000897 Out << " " << iName << "->addCase("
Reid Spencer15f7e012006-05-30 21:18:23 +0000898 << opNames[i] << ", "
899 << opNames[i+1] << ");\n";
Reid Spencer66c87342006-05-30 03:43:49 +0000900 }
901 break;
902 }
903 case Instruction::Invoke: {
904 const InvokeInst* inv = cast<InvokeInst>(I);
905 Out << " std::vector<Value*> " << iName << "_params;\n";
906 for (unsigned i = 3; i < inv->getNumOperands(); ++i)
907 Out << " " << iName << "_params.push_back("
Reid Spencer15f7e012006-05-30 21:18:23 +0000908 << opNames[i] << ");\n";
Reid Spencer66c87342006-05-30 03:43:49 +0000909 Out << " InvokeInst* " << iName << " = new InvokeInst("
Reid Spencer15f7e012006-05-30 21:18:23 +0000910 << opNames[0] << ", "
911 << opNames[1] << ", "
912 << opNames[2] << ", "
Reid Spencer66c87342006-05-30 03:43:49 +0000913 << iName << "_params, \"";
914 printEscapedString(inv->getName());
915 Out << "\", " << bbname << ");\n";
916 Out << iName << "->setCallingConv(";
917 printCallingConv(inv->getCallingConv());
918 Out << ");";
919 break;
920 }
921 case Instruction::Unwind: {
922 Out << " UnwindInst* " << iName << " = new UnwindInst("
923 << bbname << ");";
924 break;
925 }
926 case Instruction::Unreachable:{
927 Out << " UnreachableInst* " << iName << " = new UnreachableInst("
928 << bbname << ");";
929 break;
930 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000931 case Instruction::Add:
932 case Instruction::Sub:
933 case Instruction::Mul:
934 case Instruction::Div:
935 case Instruction::Rem:
936 case Instruction::And:
937 case Instruction::Or:
938 case Instruction::Xor:
Reid Spencer66c87342006-05-30 03:43:49 +0000939 case Instruction::Shl:
940 case Instruction::Shr:{
941 Out << " BinaryOperator* " << iName << " = BinaryOperator::create(";
942 switch (I->getOpcode()) {
943 case Instruction::Add: Out << "Instruction::Add"; break;
944 case Instruction::Sub: Out << "Instruction::Sub"; break;
945 case Instruction::Mul: Out << "Instruction::Mul"; break;
946 case Instruction::Div: Out << "Instruction::Div"; break;
947 case Instruction::Rem: Out << "Instruction::Rem"; break;
948 case Instruction::And: Out << "Instruction::And"; break;
949 case Instruction::Or: Out << "Instruction::Or"; break;
950 case Instruction::Xor: Out << "Instruction::Xor"; break;
951 case Instruction::Shl: Out << "Instruction::Shl"; break;
952 case Instruction::Shr: Out << "Instruction::Shr"; break;
953 default: Out << "Instruction::BadOpCode"; break;
954 }
Reid Spencer15f7e012006-05-30 21:18:23 +0000955 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +0000956 printEscapedString(I->getName());
957 Out << "\", " << bbname << ");";
958 break;
959 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000960 case Instruction::SetEQ:
961 case Instruction::SetNE:
962 case Instruction::SetLE:
963 case Instruction::SetGE:
964 case Instruction::SetLT:
Reid Spencer66c87342006-05-30 03:43:49 +0000965 case Instruction::SetGT: {
966 Out << " SetCondInst* " << iName << " = new SetCondInst(";
967 switch (I->getOpcode()) {
968 case Instruction::SetEQ: Out << "Instruction::SetEQ"; break;
969 case Instruction::SetNE: Out << "Instruction::SetNE"; break;
970 case Instruction::SetLE: Out << "Instruction::SetLE"; break;
971 case Instruction::SetGE: Out << "Instruction::SetGE"; break;
972 case Instruction::SetLT: Out << "Instruction::SetLT"; break;
973 case Instruction::SetGT: Out << "Instruction::SetGT"; break;
974 default: Out << "Instruction::BadOpCode"; break;
975 }
Reid Spencer15f7e012006-05-30 21:18:23 +0000976 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +0000977 printEscapedString(I->getName());
978 Out << "\", " << bbname << ");";
979 break;
980 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000981 case Instruction::Malloc: {
982 const MallocInst* mallocI = cast<MallocInst>(I);
Reid Spencer66c87342006-05-30 03:43:49 +0000983 Out << " MallocInst* " << iName << " = new MallocInst("
Reid Spencere0d133f2006-05-29 18:08:06 +0000984 << getCppName(mallocI->getAllocatedType()) << ", ";
985 if (mallocI->isArrayAllocation())
Reid Spencer15f7e012006-05-30 21:18:23 +0000986 Out << opNames[0] << ", " ;
Reid Spencere0d133f2006-05-29 18:08:06 +0000987 Out << "\"";
988 printEscapedString(mallocI->getName());
989 Out << "\", " << bbname << ");";
990 if (mallocI->getAlignment())
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000991 Out << "\n " << iName << "->setAlignment("
Reid Spencere0d133f2006-05-29 18:08:06 +0000992 << mallocI->getAlignment() << ");";
993 break;
994 }
Reid Spencer66c87342006-05-30 03:43:49 +0000995 case Instruction::Free: {
996 Out << " FreeInst* " << iName << " = new FreeInst("
997 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
998 break;
999 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001000 case Instruction::Alloca: {
1001 const AllocaInst* allocaI = cast<AllocaInst>(I);
Reid Spencer66c87342006-05-30 03:43:49 +00001002 Out << " AllocaInst* " << iName << " = new AllocaInst("
Reid Spencere0d133f2006-05-29 18:08:06 +00001003 << getCppName(allocaI->getAllocatedType()) << ", ";
1004 if (allocaI->isArrayAllocation())
Reid Spencer15f7e012006-05-30 21:18:23 +00001005 Out << opNames[0] << ", ";
Reid Spencere0d133f2006-05-29 18:08:06 +00001006 Out << "\"";
1007 printEscapedString(allocaI->getName());
1008 Out << "\", " << bbname << ");";
1009 if (allocaI->getAlignment())
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001010 Out << "\n " << iName << "->setAlignment("
Reid Spencere0d133f2006-05-29 18:08:06 +00001011 << allocaI->getAlignment() << ");";
1012 break;
1013 }
Reid Spencer66c87342006-05-30 03:43:49 +00001014 case Instruction::Load:{
1015 const LoadInst* load = cast<LoadInst>(I);
1016 Out << " LoadInst* " << iName << " = new LoadInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001017 << opNames[0] << ", \"";
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001018 printEscapedString(load->getName());
1019 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1020 << ", " << bbname << ");\n";
Reid Spencer66c87342006-05-30 03:43:49 +00001021 break;
1022 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001023 case Instruction::Store: {
1024 const StoreInst* store = cast<StoreInst>(I);
Reid Spencer66c87342006-05-30 03:43:49 +00001025 Out << " StoreInst* " << iName << " = new StoreInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001026 << opNames[0] << ", "
1027 << opNames[1] << ", "
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001028 << (store->isVolatile() ? "true" : "false")
1029 << ", " << bbname << ");\n";
Reid Spencere0d133f2006-05-29 18:08:06 +00001030 break;
1031 }
1032 case Instruction::GetElementPtr: {
1033 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1034 if (gep->getNumOperands() <= 2) {
Reid Spencer66c87342006-05-30 03:43:49 +00001035 Out << " GetElementPtrInst* " << iName << " = new GetElementPtrInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001036 << opNames[0];
Reid Spencere0d133f2006-05-29 18:08:06 +00001037 if (gep->getNumOperands() == 2)
Reid Spencer15f7e012006-05-30 21:18:23 +00001038 Out << ", " << opNames[1];
Reid Spencere0d133f2006-05-29 18:08:06 +00001039 } else {
Reid Spencer66c87342006-05-30 03:43:49 +00001040 Out << " std::vector<Value*> " << iName << "_indices;\n";
Reid Spencere0d133f2006-05-29 18:08:06 +00001041 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
Reid Spencer66c87342006-05-30 03:43:49 +00001042 Out << " " << iName << "_indices.push_back("
Reid Spencer15f7e012006-05-30 21:18:23 +00001043 << opNames[i] << ");\n";
Reid Spencere0d133f2006-05-29 18:08:06 +00001044 }
Reid Spencer66c87342006-05-30 03:43:49 +00001045 Out << " Instruction* " << iName << " = new GetElementPtrInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001046 << opNames[0] << ", " << iName << "_indices";
Reid Spencere0d133f2006-05-29 18:08:06 +00001047 }
1048 Out << ", \"";
1049 printEscapedString(gep->getName());
1050 Out << "\", " << bbname << ");";
1051 break;
1052 }
Reid Spencer66c87342006-05-30 03:43:49 +00001053 case Instruction::PHI: {
1054 const PHINode* phi = cast<PHINode>(I);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001055
Reid Spencer66c87342006-05-30 03:43:49 +00001056 Out << " PHINode* " << iName << " = new PHINode("
1057 << getCppName(phi->getType()) << ", \"";
1058 printEscapedString(phi->getName());
1059 Out << "\", " << bbname << ");\n";
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001060 Out << " " << iName << "->reserveOperandSpace("
1061 << phi->getNumIncomingValues()
Reid Spencer66c87342006-05-30 03:43:49 +00001062 << ");\n";
Reid Spencer15f7e012006-05-30 21:18:23 +00001063 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001064 Out << " " << iName << "->addIncoming("
Reid Spencer15f7e012006-05-30 21:18:23 +00001065 << opNames[i] << ", " << opNames[i+1] << ");\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001066 }
Reid Spencer66c87342006-05-30 03:43:49 +00001067 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001068 }
Reid Spencer66c87342006-05-30 03:43:49 +00001069 case Instruction::Cast: {
1070 const CastInst* cst = cast<CastInst>(I);
1071 Out << " CastInst* " << iName << " = new CastInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001072 << opNames[0] << ", "
Reid Spencer66c87342006-05-30 03:43:49 +00001073 << getCppName(cst->getType()) << ", \"";
1074 printEscapedString(cst->getName());
1075 Out << "\", " << bbname << ");\n";
1076 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001077 }
Reid Spencer66c87342006-05-30 03:43:49 +00001078 case Instruction::Call:{
1079 const CallInst* call = cast<CallInst>(I);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001080 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1081 Out << " InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1082 << getCppName(ila->getFunctionType()) << ", \""
1083 << ila->getAsmString() << "\", \""
1084 << ila->getConstraintString() << "\","
1085 << (ila->hasSideEffects() ? "true" : "false") << ");\n";
1086 }
Reid Spencer66c87342006-05-30 03:43:49 +00001087 if (call->getNumOperands() > 3) {
1088 Out << " std::vector<Value*> " << iName << "_params;\n";
Reid Spencer15f7e012006-05-30 21:18:23 +00001089 for (unsigned i = 1; i < call->getNumOperands(); ++i)
1090 Out << " " << iName << "_params.push_back(" << opNames[i] << ");\n";
Reid Spencer66c87342006-05-30 03:43:49 +00001091 Out << " CallInst* " << iName << " = new CallInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001092 << opNames[0] << ", " << iName << "_params, \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001093 } else if (call->getNumOperands() == 3) {
1094 Out << " CallInst* " << iName << " = new CallInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001095 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001096 } else if (call->getNumOperands() == 2) {
1097 Out << " CallInst* " << iName << " = new CallInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001098 << opNames[0] << ", " << opNames[1] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001099 } else {
Reid Spencer15f7e012006-05-30 21:18:23 +00001100 Out << " CallInst* " << iName << " = new CallInst(" << opNames[0]
1101 << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001102 }
1103 printEscapedString(call->getName());
1104 Out << "\", " << bbname << ");\n";
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001105 Out << " " << iName << "->setCallingConv(";
Reid Spencer66c87342006-05-30 03:43:49 +00001106 printCallingConv(call->getCallingConv());
1107 Out << ");\n";
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001108 Out << " " << iName << "->setTailCall("
1109 << (call->isTailCall() ? "true":"false");
Reid Spencer66c87342006-05-30 03:43:49 +00001110 Out << ");";
1111 break;
1112 }
1113 case Instruction::Select: {
1114 const SelectInst* sel = cast<SelectInst>(I);
1115 Out << " SelectInst* " << getCppName(sel) << " = new SelectInst(";
Reid Spencer15f7e012006-05-30 21:18:23 +00001116 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001117 printEscapedString(sel->getName());
1118 Out << "\", " << bbname << ");\n";
1119 break;
1120 }
1121 case Instruction::UserOp1:
1122 /// FALL THROUGH
1123 case Instruction::UserOp2: {
1124 /// FIXME: What should be done here?
1125 break;
1126 }
1127 case Instruction::VAArg: {
1128 const VAArgInst* va = cast<VAArgInst>(I);
1129 Out << " VAArgInst* " << getCppName(va) << " = new VAArgInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001130 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001131 printEscapedString(va->getName());
1132 Out << "\", " << bbname << ");\n";
1133 break;
1134 }
1135 case Instruction::ExtractElement: {
1136 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1137 Out << " ExtractElementInst* " << getCppName(eei)
Reid Spencer15f7e012006-05-30 21:18:23 +00001138 << " = new ExtractElementInst(" << opNames[0]
1139 << ", " << opNames[1] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001140 printEscapedString(eei->getName());
1141 Out << "\", " << bbname << ");\n";
1142 break;
1143 }
1144 case Instruction::InsertElement: {
1145 const InsertElementInst* iei = cast<InsertElementInst>(I);
1146 Out << " InsertElementInst* " << getCppName(iei)
Reid Spencer15f7e012006-05-30 21:18:23 +00001147 << " = new InsertElementInst(" << opNames[0]
1148 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001149 printEscapedString(iei->getName());
1150 Out << "\", " << bbname << ");\n";
1151 break;
1152 }
1153 case Instruction::ShuffleVector: {
1154 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1155 Out << " ShuffleVectorInst* " << getCppName(svi)
Reid Spencer15f7e012006-05-30 21:18:23 +00001156 << " = new ShuffleVectorInst(" << opNames[0]
1157 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001158 printEscapedString(svi->getName());
1159 Out << "\", " << bbname << ");\n";
1160 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001161 }
1162 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001163 Out << "\n";
Reid Spencer15f7e012006-05-30 21:18:23 +00001164 delete [] opNames;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001165}
1166
Reid Spencer12803f52006-05-31 17:31:38 +00001167// Print out the types, constants and declarations needed by one function
1168void CppWriter::printFunctionUses(const Function* F) {
1169
1170 Out << "\n// Type Definitions\n";
1171 // Print the function's return type
1172 printType(F->getReturnType());
1173
1174 // Print the function's function type
1175 printType(F->getFunctionType());
1176
1177 // Print the types of each of the function's arguments
1178 for(Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1179 AI != AE; ++AI) {
1180 printType(AI->getType());
1181 }
1182
1183 // Print type definitions for every type referenced by an instruction and
1184 // make a note of any global values or constants that are referenced
1185 std::vector<GlobalValue*> gvs;
1186 std::vector<Constant*> consts;
1187 for (Function::const_iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB){
1188 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1189 I != E; ++I) {
1190 // Print the type of the instruction itself
1191 printType(I->getType());
1192
1193 // Print the type of each of the instruction's operands
1194 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1195 Value* operand = I->getOperand(i);
1196 printType(operand->getType());
1197 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand))
1198 gvs.push_back(GV);
1199 else if (Constant* C = dyn_cast<Constant>(operand))
1200 consts.push_back(C);
1201 }
1202 }
1203 }
1204
1205 // Print the function declarations for any functions encountered
1206 Out << "\n// Function Declarations\n";
1207 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1208 I != E; ++I) {
1209 if (Function* F = dyn_cast<Function>(*I))
1210 printFunctionHead(F);
1211 }
1212
1213 // Print the global variable declarations for any variables encountered
1214 Out << "\n// Global Variable Declarations\n";
1215 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1216 I != E; ++I) {
1217 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1218 printVariableHead(F);
1219 }
1220
1221 // Print the constants found
1222 Out << "\n// Constant Definitions\n";
1223 for (std::vector<Constant*>::iterator I = consts.begin(), E = consts.end();
1224 I != E; ++I) {
1225 printConstant(F);
1226 }
1227
1228 // Process the global variables definitions now that all the constants have
1229 // been emitted. These definitions just couple the gvars with their constant
1230 // initializers.
1231 Out << "\n// Global Variable Definitions\n";
1232 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1233 I != E; ++I) {
1234 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1235 printVariableBody(GV);
1236 }
1237}
1238
1239void CppWriter::printFunctionHead(const Function* F) {
1240 Out << "\nFunction* " << getCppName(F) << " = new Function(\n"
1241 << " /*Type=*/" << getCppName(F->getFunctionType()) << ",\n"
1242 << " /*Linkage=*/";
1243 printLinkageType(F->getLinkage());
1244 Out << ",\n /*Name=*/\"";
1245 printEscapedString(F->getName());
1246 Out << "\", mod); "
1247 << (F->isExternal()? "// (external, no body)" : "") << "\n";
1248 printCppName(F);
1249 Out << "->setCallingConv(";
1250 printCallingConv(F->getCallingConv());
1251 Out << ");\n";
1252 if (F->hasSection()) {
1253 printCppName(F);
1254 Out << "->setSection(\"" << F->getSection() << "\");\n";
1255 }
1256 if (F->getAlignment()) {
1257 printCppName(F);
1258 Out << "->setAlignment(" << F->getAlignment() << ");\n";
1259 }
1260}
1261
1262void CppWriter::printFunctionBody(const Function *F) {
1263 if (F->isExternal())
1264 return; // external functions have no bodies.
1265
1266 // Clear the DefinedValues and ForwardRefs maps because we can't have
1267 // cross-function forward refs
1268 ForwardRefs.clear();
1269 DefinedValues.clear();
1270
1271 // Create all the argument values
1272 if (!F->arg_empty()) {
1273 Out << " Function::arg_iterator args = " << getCppName(F)
1274 << "->arg_begin();\n";
1275 }
1276 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1277 AI != AE; ++AI) {
1278 Out << " Value* " << getCppName(AI) << " = args++;\n";
1279 if (AI->hasName())
1280 Out << " " << getCppName(AI) << "->setName(\"" << AI->getName()
1281 << "\");\n";
1282 }
1283
1284 // Create all the basic blocks
1285 Out << "\n";
1286 for (Function::const_iterator BI = F->begin(), BE = F->end();
1287 BI != BE; ++BI) {
1288 std::string bbname(getCppName(BI));
1289 Out << " BasicBlock* " << bbname << " = new BasicBlock(\"";
1290 if (BI->hasName())
1291 printEscapedString(BI->getName());
1292 Out << "\"," << getCppName(BI->getParent()) << ",0);\n";
1293 }
1294
1295 // Output all of its basic blocks... for the function
1296 for (Function::const_iterator BI = F->begin(), BE = F->end();
1297 BI != BE; ++BI) {
1298 std::string bbname(getCppName(BI));
1299 Out << "\n // Block " << BI->getName() << " (" << bbname << ")\n";
1300
1301 // Output all of the instructions in the basic block...
1302 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1303 I != E; ++I) {
1304 printInstruction(I,bbname);
1305 }
1306 }
1307
1308 // Loop over the ForwardRefs and resolve them now that all instructions
1309 // are generated.
1310 if (!ForwardRefs.empty())
1311 Out << "\n // Resolve Forward References\n";
1312 while (!ForwardRefs.empty()) {
1313 ForwardRefMap::iterator I = ForwardRefs.begin();
1314 Out << " " << I->second << "->replaceAllUsesWith("
1315 << getCppName(I->first) << "); delete " << I->second << ";\n";
1316 ForwardRefs.erase(I);
1317 }
1318}
1319
1320void CppWriter::printModuleBody() {
1321 // Print out all the type definitions
1322 Out << "\n// Type Definitions\n";
1323 printTypes(TheModule);
1324
1325 // Functions can call each other and global variables can reference them so
1326 // define all the functions first before emitting their function bodies.
1327 Out << "\n// Function Declarations\n";
1328 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1329 I != E; ++I)
1330 printFunctionHead(I);
1331
1332 // Process the global variables declarations. We can't initialze them until
1333 // after the constants are printed so just print a header for each global
1334 Out << "\n// Global Variable Declarations\n";
1335 for (Module::const_global_iterator I = TheModule->global_begin(),
1336 E = TheModule->global_end(); I != E; ++I) {
1337 printVariableHead(I);
1338 }
1339
1340 // Print out all the constants definitions. Constants don't recurse except
1341 // through GlobalValues. All GlobalValues have been declared at this point
1342 // so we can proceed to generate the constants.
1343 Out << "\n// Constant Definitions\n";
1344 printConstants(TheModule);
1345
1346 // Process the global variables definitions now that all the constants have
1347 // been emitted. These definitions just couple the gvars with their constant
1348 // initializers.
1349 Out << "\n// Global Variable Definitions\n";
1350 for (Module::const_global_iterator I = TheModule->global_begin(),
1351 E = TheModule->global_end(); I != E; ++I) {
1352 printVariableBody(I);
1353 }
1354
1355 // Finally, we can safely put out all of the function bodies.
1356 Out << "\n// Function Definitions\n";
1357 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1358 I != E; ++I) {
1359 if (!I->isExternal()) {
1360 Out << "\n// Function: " << I->getName() << " (" << getCppName(I)
1361 << ")\n{\n";
1362 printFunctionBody(I);
1363 Out << "}\n";
1364 }
1365 }
1366}
1367
1368void CppWriter::printProgram(
1369 const std::string& fname,
1370 const std::string& mName
1371) {
1372 Out << "#include <llvm/Module.h>\n";
1373 Out << "#include <llvm/DerivedTypes.h>\n";
1374 Out << "#include <llvm/Constants.h>\n";
1375 Out << "#include <llvm/GlobalVariable.h>\n";
1376 Out << "#include <llvm/Function.h>\n";
1377 Out << "#include <llvm/CallingConv.h>\n";
1378 Out << "#include <llvm/BasicBlock.h>\n";
1379 Out << "#include <llvm/Instructions.h>\n";
1380 Out << "#include <llvm/InlineAsm.h>\n";
1381 Out << "#include <llvm/Pass.h>\n";
1382 Out << "#include <llvm/PassManager.h>\n";
1383 Out << "#include <llvm/Analysis/Verifier.h>\n";
1384 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1385 Out << "#include <algorithm>\n";
1386 Out << "#include <iostream>\n\n";
1387 Out << "using namespace llvm;\n\n";
1388 Out << "Module* " << fname << "();\n\n";
1389 Out << "int main(int argc, char**argv) {\n";
1390 Out << " Module* Mod = makeLLVMModule();\n";
1391 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1392 Out << " std::cerr.flush();\n";
1393 Out << " std::cout.flush();\n";
1394 Out << " PassManager PM;\n";
1395 Out << " PM.add(new PrintModulePass(&std::cout));\n";
1396 Out << " PM.run(*Mod);\n";
1397 Out << " return 0;\n";
1398 Out << "}\n\n";
1399 printModule(fname,mName);
1400}
1401
1402void CppWriter::printModule(
1403 const std::string& fname,
1404 const std::string& mName
1405) {
1406 Out << "\nModule* " << fname << "() {\n";
1407 Out << "\n// Module Construction\n";
1408 Out << "\nmod = new Module(\"" << mName << "\");\n";
1409 Out << "mod->setEndianness(";
1410 switch (TheModule->getEndianness()) {
1411 case Module::LittleEndian: Out << "Module::LittleEndian);\n"; break;
1412 case Module::BigEndian: Out << "Module::BigEndian);\n"; break;
1413 case Module::AnyEndianness:Out << "Module::AnyEndianness);\n"; break;
1414 }
1415 Out << "mod->setPointerSize(";
1416 switch (TheModule->getPointerSize()) {
1417 case Module::Pointer32: Out << "Module::Pointer32);\n"; break;
1418 case Module::Pointer64: Out << "Module::Pointer64);\n"; break;
1419 case Module::AnyPointerSize: Out << "Module::AnyPointerSize);\n"; break;
1420 }
1421 if (!TheModule->getTargetTriple().empty())
1422 Out << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1423 << "\");\n";
1424
1425 if (!TheModule->getModuleInlineAsm().empty()) {
1426 Out << "mod->setModuleInlineAsm(\"";
1427 printEscapedString(TheModule->getModuleInlineAsm());
1428 Out << "\");\n";
1429 }
1430
1431 // Loop over the dependent libraries and emit them.
1432 Module::lib_iterator LI = TheModule->lib_begin();
1433 Module::lib_iterator LE = TheModule->lib_end();
1434 while (LI != LE) {
1435 Out << "mod->addLibrary(\"" << *LI << "\");\n";
1436 ++LI;
1437 }
1438 printModuleBody();
1439 Out << "\nreturn mod;\n";
1440 Out << "}\n";
1441}
1442
1443void CppWriter::printContents(
1444 const std::string& fname, // Name of generated function
1445 const std::string& mName // Name of module generated module
1446) {
1447 Out << "\nModule* " << fname << "(Module *mod) {\n";
1448 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
Reid Spencer12803f52006-05-31 17:31:38 +00001449 printModuleBody();
1450 Out << "\nreturn mod;\n";
1451 Out << "\n}\n";
1452}
1453
1454void CppWriter::printFunction(
1455 const std::string& fname, // Name of generated function
1456 const std::string& funcName // Name of function to generate
1457) {
1458 const Function* F = TheModule->getNamedFunction(funcName);
1459 if (!F) {
1460 error(std::string("Function '") + funcName + "' not found in input module");
1461 return;
1462 }
1463 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1464 printFunctionUses(F);
1465 printFunctionHead(F);
1466 printFunctionBody(F);
1467 Out << "return " << getCppName(F) << ";\n";
1468 Out << "}\n";
1469}
1470
1471void CppWriter::printVariable(
1472 const std::string& fname, /// Name of generated function
1473 const std::string& varName // Name of variable to generate
1474) {
1475 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1476
1477 if (!GV) {
1478 error(std::string("Variable '") + varName + "' not found in input module");
1479 return;
1480 }
1481 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1482 printVariableUses(GV);
1483 printVariableHead(GV);
1484 printVariableBody(GV);
1485 Out << "return " << getCppName(GV) << ";\n";
1486 Out << "}\n";
1487}
1488
1489void CppWriter::printType(
1490 const std::string& fname, /// Name of generated function
1491 const std::string& typeName // Name of type to generate
1492) {
1493 const Type* Ty = TheModule->getTypeByName(typeName);
1494 if (!Ty) {
1495 error(std::string("Type '") + typeName + "' not found in input module");
1496 return;
1497 }
1498 Out << "\nType* " << fname << "(Module *mod) {\n";
1499 printType(Ty);
1500 Out << "return " << getCppName(Ty) << ";\n";
1501 Out << "}\n";
1502}
1503
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001504} // end anonymous llvm
1505
1506namespace llvm {
1507
1508void WriteModuleToCppFile(Module* mod, std::ostream& o) {
Reid Spencer12803f52006-05-31 17:31:38 +00001509 // Initialize a CppWriter for us to use
1510 CppWriter W(o, mod);
1511
1512 // Emit a header
Reid Spencer25edc352006-05-31 04:43:19 +00001513 o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
Reid Spencer12803f52006-05-31 17:31:38 +00001514
1515 // Get the name of the function we're supposed to generate
Reid Spencer15f7e012006-05-30 21:18:23 +00001516 std::string fname = FuncName.getValue();
Reid Spencer12803f52006-05-31 17:31:38 +00001517
1518 // Get the name of the thing we are to generate
1519 std::string tgtname = NameToGenerate.getValue();
1520 if (GenerationType == GenModule ||
1521 GenerationType == GenContents ||
1522 GenerationType == GenProgram) {
1523 if (tgtname == "!bad!") {
1524 if (mod->getModuleIdentifier() == "-")
1525 tgtname = "<stdin>";
1526 else
1527 tgtname = mod->getModuleIdentifier();
1528 }
1529 } else if (tgtname == "!bad!") {
1530 W.error("You must use the -for option with -gen-{function,variable,type}");
1531 }
1532
1533 switch (WhatToGenerate(GenerationType)) {
1534 case GenProgram:
1535 if (fname.empty())
1536 fname = "makeLLVMModule";
1537 W.printProgram(fname,tgtname);
1538 break;
1539 case GenModule:
1540 if (fname.empty())
1541 fname = "makeLLVMModule";
1542 W.printModule(fname,tgtname);
1543 break;
1544 case GenContents:
1545 if (fname.empty())
1546 fname = "makeLLVMModuleContents";
1547 W.printContents(fname,tgtname);
1548 break;
1549 case GenFunction:
1550 if (fname.empty())
1551 fname = "makeLLVMFunction";
1552 W.printFunction(fname,tgtname);
1553 break;
1554 case GenVariable:
1555 if (fname.empty())
1556 fname = "makeLLVMVariable";
1557 W.printVariable(fname,tgtname);
1558 break;
1559 case GenType:
1560 if (fname.empty())
1561 fname = "makeLLVMType";
1562 W.printType(fname,tgtname);
1563 break;
1564 default:
1565 W.error("Invalid generation option");
Reid Spencer15f7e012006-05-30 21:18:23 +00001566 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001567}
1568
1569}