blob: 2d0a3be0df2c32d78015af079a913a0db8a5ba20 [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"
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000023#include "llvm/ADT/StringExtras.h"
24#include "llvm/ADT/STLExtras.h"
Reid Spencer15f7e012006-05-30 21:18:23 +000025#include "llvm/Support/CommandLine.h"
Chris Lattnerc30598b2006-12-06 01:18:01 +000026#include "llvm/Support/CFG.h"
27#include "llvm/Support/ManagedStatic.h"
28#include "llvm/Support/MathExtras.h"
Reid Spencerf977e7b2006-06-01 23:43:47 +000029#include "llvm/Config/config.h"
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000030#include <algorithm>
31#include <iostream>
Reid Spencer66c87342006-05-30 03:43:49 +000032#include <set>
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000033
34using namespace llvm;
35
Reid Spencer15f7e012006-05-30 21:18:23 +000036static cl::opt<std::string>
Reid Spencer15f7e012006-05-30 21:18:23 +000037FuncName("funcname", cl::desc("Specify the name of the generated function"),
38 cl::value_desc("function name"));
39
Reid Spencer12803f52006-05-31 17:31:38 +000040enum WhatToGenerate {
41 GenProgram,
42 GenModule,
43 GenContents,
44 GenFunction,
Reid Spencerf977e7b2006-06-01 23:43:47 +000045 GenInline,
Reid Spencer12803f52006-05-31 17:31:38 +000046 GenVariable,
47 GenType
48};
49
50static cl::opt<WhatToGenerate> GenerationType(cl::Optional,
51 cl::desc("Choose what kind of output to generate"),
52 cl::init(GenProgram),
53 cl::values(
54 clEnumValN(GenProgram, "gen-program", "Generate a complete program"),
55 clEnumValN(GenModule, "gen-module", "Generate a module definition"),
56 clEnumValN(GenContents,"gen-contents", "Generate contents of a module"),
57 clEnumValN(GenFunction,"gen-function", "Generate a function definition"),
Reid Spencerf977e7b2006-06-01 23:43:47 +000058 clEnumValN(GenInline, "gen-inline", "Generate an inline function"),
Reid Spencer12803f52006-05-31 17:31:38 +000059 clEnumValN(GenVariable,"gen-variable", "Generate a variable definition"),
60 clEnumValN(GenType, "gen-type", "Generate a type definition"),
61 clEnumValEnd
62 )
63);
64
65static cl::opt<std::string> NameToGenerate("for", cl::Optional,
66 cl::desc("Specify the name of the thing to generate"),
67 cl::init("!bad!"));
Reid Spencer15f7e012006-05-30 21:18:23 +000068
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000069namespace {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000070typedef std::vector<const Type*> TypeList;
71typedef std::map<const Type*,std::string> TypeMap;
72typedef std::map<const Value*,std::string> ValueMap;
Reid Spencer66c87342006-05-30 03:43:49 +000073typedef std::set<std::string> NameSet;
Reid Spencer15f7e012006-05-30 21:18:23 +000074typedef std::set<const Type*> TypeSet;
75typedef std::set<const Value*> ValueSet;
76typedef std::map<const Value*,std::string> ForwardRefMap;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000077
Reid Spencere0d133f2006-05-29 18:08:06 +000078class CppWriter {
Reid Spencer12803f52006-05-31 17:31:38 +000079 const char* progname;
Reid Spencere0d133f2006-05-29 18:08:06 +000080 std::ostream &Out;
81 const Module *TheModule;
Andrew Lenharth539d8712006-05-31 20:18:56 +000082 uint64_t uniqueNum;
Reid Spencere0d133f2006-05-29 18:08:06 +000083 TypeMap TypeNames;
84 ValueMap ValueNames;
85 TypeMap UnresolvedTypes;
86 TypeList TypeStack;
Reid Spencer66c87342006-05-30 03:43:49 +000087 NameSet UsedNames;
Reid Spencer15f7e012006-05-30 21:18:23 +000088 TypeSet DefinedTypes;
89 ValueSet DefinedValues;
90 ForwardRefMap ForwardRefs;
Reid Spencerf977e7b2006-06-01 23:43:47 +000091 bool is_inline;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000092
Reid Spencere0d133f2006-05-29 18:08:06 +000093public:
Reid Spencer12803f52006-05-31 17:31:38 +000094 inline CppWriter(std::ostream &o, const Module *M, const char* pn="llvm2cpp")
95 : progname(pn), Out(o), TheModule(M), uniqueNum(0), TypeNames(),
Reid Spencerf977e7b2006-06-01 23:43:47 +000096 ValueNames(), UnresolvedTypes(), TypeStack(), is_inline(false) { }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000097
Reid Spencere0d133f2006-05-29 18:08:06 +000098 const Module* getModule() { return TheModule; }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000099
Reid Spencer12803f52006-05-31 17:31:38 +0000100 void printProgram(const std::string& fname, const std::string& modName );
101 void printModule(const std::string& fname, const std::string& modName );
102 void printContents(const std::string& fname, const std::string& modName );
103 void printFunction(const std::string& fname, const std::string& funcName );
Reid Spencerf977e7b2006-06-01 23:43:47 +0000104 void printInline(const std::string& fname, const std::string& funcName );
Reid Spencer12803f52006-05-31 17:31:38 +0000105 void printVariable(const std::string& fname, const std::string& varName );
106 void printType(const std::string& fname, const std::string& typeName );
107
108 void error(const std::string& msg);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000109
Reid Spencere0d133f2006-05-29 18:08:06 +0000110private:
Reid Spencer12803f52006-05-31 17:31:38 +0000111 void printLinkageType(GlobalValue::LinkageTypes LT);
112 void printCallingConv(unsigned cc);
113 void printEscapedString(const std::string& str);
114 void printCFP(const ConstantFP* CFP);
115
116 std::string getCppName(const Type* val);
117 inline void printCppName(const Type* val);
118
119 std::string getCppName(const Value* val);
120 inline void printCppName(const Value* val);
121
122 bool printTypeInternal(const Type* Ty);
123 inline void printType(const Type* Ty);
Reid Spencere0d133f2006-05-29 18:08:06 +0000124 void printTypes(const Module* M);
Reid Spencer12803f52006-05-31 17:31:38 +0000125
Reid Spencere0d133f2006-05-29 18:08:06 +0000126 void printConstant(const Constant *CPV);
Reid Spencer12803f52006-05-31 17:31:38 +0000127 void printConstants(const Module* M);
128
129 void printVariableUses(const GlobalVariable *GV);
130 void printVariableHead(const GlobalVariable *GV);
131 void printVariableBody(const GlobalVariable *GV);
132
133 void printFunctionUses(const Function *F);
Reid Spencer66c87342006-05-30 03:43:49 +0000134 void printFunctionHead(const Function *F);
135 void printFunctionBody(const Function *F);
Reid Spencere0d133f2006-05-29 18:08:06 +0000136 void printInstruction(const Instruction *I, const std::string& bbname);
Reid Spencer15f7e012006-05-30 21:18:23 +0000137 std::string getOpName(Value*);
138
Reid Spencer12803f52006-05-31 17:31:38 +0000139 void printModuleBody();
140
Reid Spencere0d133f2006-05-29 18:08:06 +0000141};
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000142
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000143static unsigned indent_level = 0;
144inline std::ostream& nl(std::ostream& Out, int delta = 0) {
145 Out << "\n";
146 if (delta >= 0 || indent_level >= unsigned(-delta))
147 indent_level += delta;
148 for (unsigned i = 0; i < indent_level; ++i)
149 Out << " ";
150 return Out;
151}
152
153inline void in() { indent_level++; }
154inline void out() { if (indent_level >0) indent_level--; }
155
Reid Spencer12803f52006-05-31 17:31:38 +0000156inline void
157sanitize(std::string& str) {
158 for (size_t i = 0; i < str.length(); ++i)
159 if (!isalnum(str[i]) && str[i] != '_')
160 str[i] = '_';
161}
162
163inline const char*
164getTypePrefix(const Type* Ty ) {
165 const char* prefix;
166 switch (Ty->getTypeID()) {
167 case Type::VoidTyID: prefix = "void_"; break;
168 case Type::BoolTyID: prefix = "bool_"; break;
169 case Type::UByteTyID: prefix = "ubyte_"; break;
170 case Type::SByteTyID: prefix = "sbyte_"; break;
171 case Type::UShortTyID: prefix = "ushort_"; break;
172 case Type::ShortTyID: prefix = "short_"; break;
173 case Type::UIntTyID: prefix = "uint_"; break;
174 case Type::IntTyID: prefix = "int_"; break;
175 case Type::ULongTyID: prefix = "ulong_"; break;
176 case Type::LongTyID: prefix = "long_"; break;
177 case Type::FloatTyID: prefix = "float_"; break;
178 case Type::DoubleTyID: prefix = "double_"; break;
179 case Type::LabelTyID: prefix = "label_"; break;
180 case Type::FunctionTyID: prefix = "func_"; break;
181 case Type::StructTyID: prefix = "struct_"; break;
182 case Type::ArrayTyID: prefix = "array_"; break;
183 case Type::PointerTyID: prefix = "ptr_"; break;
184 case Type::PackedTyID: prefix = "packed_"; break;
185 case Type::OpaqueTyID: prefix = "opaque_"; break;
186 default: prefix = "other_"; break;
187 }
188 return prefix;
189}
190
191// Looks up the type in the symbol table and returns a pointer to its name or
192// a null pointer if it wasn't found. Note that this isn't the same as the
193// Mode::getTypeName function which will return an empty string, not a null
194// pointer if the name is not found.
195inline const std::string*
196findTypeName(const SymbolTable& ST, const Type* Ty)
197{
198 SymbolTable::type_const_iterator TI = ST.type_begin();
199 SymbolTable::type_const_iterator TE = ST.type_end();
200 for (;TI != TE; ++TI)
201 if (TI->second == Ty)
202 return &(TI->first);
203 return 0;
204}
205
206void
207CppWriter::error(const std::string& msg) {
208 std::cerr << progname << ": " << msg << "\n";
209 exit(2);
210}
211
Reid Spencer15f7e012006-05-30 21:18:23 +0000212// printCFP - Print a floating point constant .. very carefully :)
213// This makes sure that conversion to/from floating yields the same binary
214// result so that we don't lose precision.
215void
216CppWriter::printCFP(const ConstantFP *CFP) {
Reid Spencerf977e7b2006-06-01 23:43:47 +0000217 Out << "ConstantFP::get(";
218 if (CFP->getType() == Type::DoubleTy)
219 Out << "Type::DoubleTy, ";
220 else
221 Out << "Type::FloatTy, ";
Reid Spencer15f7e012006-05-30 21:18:23 +0000222#if HAVE_PRINTF_A
223 char Buffer[100];
224 sprintf(Buffer, "%A", CFP->getValue());
225 if ((!strncmp(Buffer, "0x", 2) ||
226 !strncmp(Buffer, "-0x", 3) ||
227 !strncmp(Buffer, "+0x", 3)) &&
228 (atof(Buffer) == CFP->getValue()))
Reid Spencerf977e7b2006-06-01 23:43:47 +0000229 if (CFP->getType() == Type::DoubleTy)
230 Out << "BitsToDouble(" << Buffer << ")";
231 else
232 Out << "BitsToFloat(" << Buffer << ")";
Reid Spencer15f7e012006-05-30 21:18:23 +0000233 else {
Reid Spencer15f7e012006-05-30 21:18:23 +0000234#endif
Reid Spencerf977e7b2006-06-01 23:43:47 +0000235 std::string StrVal = ftostr(CFP->getValue());
236
237 while (StrVal[0] == ' ')
238 StrVal.erase(StrVal.begin());
239
240 // Check to make sure that the stringized number is not some string like
241 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
242 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
243 ((StrVal[0] == '-' || StrVal[0] == '+') &&
244 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
245 (atof(StrVal.c_str()) == CFP->getValue()))
246 if (CFP->getType() == Type::DoubleTy)
247 Out << StrVal;
248 else
249 Out << StrVal;
250 else if (CFP->getType() == Type::DoubleTy)
251 Out << "BitsToDouble(0x" << std::hex << DoubleToBits(CFP->getValue())
252 << std::dec << "ULL) /* " << StrVal << " */";
253 else
254 Out << "BitsToFloat(0x" << std::hex << FloatToBits(CFP->getValue())
255 << std::dec << "U) /* " << StrVal << " */";
Reid Spencer15f7e012006-05-30 21:18:23 +0000256#if HAVE_PRINTF_A
257 }
258#endif
Reid Spencerf977e7b2006-06-01 23:43:47 +0000259 Out << ")";
Reid Spencer15f7e012006-05-30 21:18:23 +0000260}
261
Reid Spencer12803f52006-05-31 17:31:38 +0000262void
263CppWriter::printCallingConv(unsigned cc){
264 // Print the calling convention.
265 switch (cc) {
266 case CallingConv::C: Out << "CallingConv::C"; break;
267 case CallingConv::CSRet: Out << "CallingConv::CSRet"; break;
268 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
269 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
270 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
271 default: Out << cc; break;
272 }
273}
Reid Spencer15f7e012006-05-30 21:18:23 +0000274
Reid Spencer12803f52006-05-31 17:31:38 +0000275void
276CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
277 switch (LT) {
278 case GlobalValue::InternalLinkage:
279 Out << "GlobalValue::InternalLinkage"; break;
280 case GlobalValue::LinkOnceLinkage:
281 Out << "GlobalValue::LinkOnceLinkage "; break;
282 case GlobalValue::WeakLinkage:
283 Out << "GlobalValue::WeakLinkage"; break;
284 case GlobalValue::AppendingLinkage:
285 Out << "GlobalValue::AppendingLinkage"; break;
286 case GlobalValue::ExternalLinkage:
287 Out << "GlobalValue::ExternalLinkage"; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000288 case GlobalValue::DLLImportLinkage:
289 Out << "GlobalValue::DllImportLinkage"; break;
290 case GlobalValue::DLLExportLinkage:
291 Out << "GlobalValue::DllExportLinkage"; break;
292 case GlobalValue::ExternalWeakLinkage:
293 Out << "GlobalValue::ExternalWeakLinkage"; break;
Reid Spencer12803f52006-05-31 17:31:38 +0000294 case GlobalValue::GhostLinkage:
295 Out << "GlobalValue::GhostLinkage"; break;
296 }
Reid Spencer15f7e012006-05-30 21:18:23 +0000297}
298
Reid Spencere0d133f2006-05-29 18:08:06 +0000299// printEscapedString - Print each character of the specified string, escaping
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000300// it if it is not printable or if it is an escape char.
Reid Spencere0d133f2006-05-29 18:08:06 +0000301void
302CppWriter::printEscapedString(const std::string &Str) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000303 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
304 unsigned char C = Str[i];
305 if (isprint(C) && C != '"' && C != '\\') {
306 Out << C;
307 } else {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000308 Out << "\\x"
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000309 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
310 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
311 }
312 }
313}
314
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000315std::string
316CppWriter::getCppName(const Type* Ty)
317{
318 // First, handle the primitive types .. easy
319 if (Ty->isPrimitiveType()) {
320 switch (Ty->getTypeID()) {
321 case Type::VoidTyID: return "Type::VoidTy";
322 case Type::BoolTyID: return "Type::BoolTy";
323 case Type::UByteTyID: return "Type::UByteTy";
324 case Type::SByteTyID: return "Type::SByteTy";
325 case Type::UShortTyID: return "Type::UShortTy";
326 case Type::ShortTyID: return "Type::ShortTy";
327 case Type::UIntTyID: return "Type::UIntTy";
328 case Type::IntTyID: return "Type::IntTy";
329 case Type::ULongTyID: return "Type::ULongTy";
330 case Type::LongTyID: return "Type::LongTy";
331 case Type::FloatTyID: return "Type::FloatTy";
332 case Type::DoubleTyID: return "Type::DoubleTy";
333 case Type::LabelTyID: return "Type::LabelTy";
334 default:
Reid Spencer12803f52006-05-31 17:31:38 +0000335 error("Invalid primitive type");
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000336 break;
337 }
338 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
339 }
340
341 // Now, see if we've seen the type before and return that
342 TypeMap::iterator I = TypeNames.find(Ty);
343 if (I != TypeNames.end())
344 return I->second;
345
346 // Okay, let's build a new name for this type. Start with a prefix
347 const char* prefix = 0;
348 switch (Ty->getTypeID()) {
349 case Type::FunctionTyID: prefix = "FuncTy_"; break;
350 case Type::StructTyID: prefix = "StructTy_"; break;
351 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
352 case Type::PointerTyID: prefix = "PointerTy_"; break;
353 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
354 case Type::PackedTyID: prefix = "PackedTy_"; break;
355 default: prefix = "OtherTy_"; break; // prevent breakage
356 }
357
358 // See if the type has a name in the symboltable and build accordingly
359 const std::string* tName = findTypeName(TheModule->getSymbolTable(), Ty);
360 std::string name;
361 if (tName)
362 name = std::string(prefix) + *tName;
363 else
364 name = std::string(prefix) + utostr(uniqueNum++);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000365 sanitize(name);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000366
367 // Save the name
368 return TypeNames[Ty] = name;
369}
370
Reid Spencer12803f52006-05-31 17:31:38 +0000371void
372CppWriter::printCppName(const Type* Ty)
373{
374 printEscapedString(getCppName(Ty));
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000375}
376
Reid Spencer12803f52006-05-31 17:31:38 +0000377std::string
378CppWriter::getCppName(const Value* val) {
379 std::string name;
380 ValueMap::iterator I = ValueNames.find(val);
381 if (I != ValueNames.end() && I->first == val)
382 return I->second;
Reid Spencer25edc352006-05-31 04:43:19 +0000383
Reid Spencer12803f52006-05-31 17:31:38 +0000384 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
385 name = std::string("gvar_") +
386 getTypePrefix(GV->getType()->getElementType());
Reid Spencer3ed469c2006-11-02 20:25:50 +0000387 } else if (isa<Function>(val)) {
Reid Spencer12803f52006-05-31 17:31:38 +0000388 name = std::string("func_");
389 } else if (const Constant* C = dyn_cast<Constant>(val)) {
390 name = std::string("const_") + getTypePrefix(C->getType());
Reid Spencerf977e7b2006-06-01 23:43:47 +0000391 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
392 if (is_inline) {
393 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
394 Function::const_arg_iterator(Arg)) + 1;
395 name = std::string("arg_") + utostr(argNum);
396 NameSet::iterator NI = UsedNames.find(name);
397 if (NI != UsedNames.end())
398 name += std::string("_") + utostr(uniqueNum++);
399 UsedNames.insert(name);
400 return ValueNames[val] = name;
401 } else {
402 name = getTypePrefix(val->getType());
403 }
Reid Spencer12803f52006-05-31 17:31:38 +0000404 } else {
405 name = getTypePrefix(val->getType());
Reid Spencer25edc352006-05-31 04:43:19 +0000406 }
Reid Spencer12803f52006-05-31 17:31:38 +0000407 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
408 sanitize(name);
409 NameSet::iterator NI = UsedNames.find(name);
410 if (NI != UsedNames.end())
411 name += std::string("_") + utostr(uniqueNum++);
412 UsedNames.insert(name);
413 return ValueNames[val] = name;
Reid Spencer25edc352006-05-31 04:43:19 +0000414}
415
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000416void
Reid Spencer12803f52006-05-31 17:31:38 +0000417CppWriter::printCppName(const Value* val) {
418 printEscapedString(getCppName(val));
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000419}
420
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000421bool
Reid Spencer12803f52006-05-31 17:31:38 +0000422CppWriter::printTypeInternal(const Type* Ty) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000423 // We don't print definitions for primitive types
424 if (Ty->isPrimitiveType())
425 return false;
426
Reid Spencer15f7e012006-05-30 21:18:23 +0000427 // If we already defined this type, we don't need to define it again.
428 if (DefinedTypes.find(Ty) != DefinedTypes.end())
429 return false;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000430
Reid Spencer15f7e012006-05-30 21:18:23 +0000431 // Everything below needs the name for the type so get it now.
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000432 std::string typeName(getCppName(Ty));
433
434 // Search the type stack for recursion. If we find it, then generate this
435 // as an OpaqueType, but make sure not to do this multiple times because
436 // the type could appear in multiple places on the stack. Once the opaque
Reid Spencer15f7e012006-05-30 21:18:23 +0000437 // definition is issued, it must not be re-issued. Consequently we have to
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000438 // check the UnresolvedTypes list as well.
Reid Spencer12803f52006-05-31 17:31:38 +0000439 TypeList::const_iterator TI = std::find(TypeStack.begin(),TypeStack.end(),Ty);
440 if (TI != TypeStack.end()) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000441 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
442 if (I == UnresolvedTypes.end()) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000443 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
444 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000445 UnresolvedTypes[Ty] = typeName;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000446 }
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000447 return true;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000448 }
449
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000450 // We're going to print a derived type which, by definition, contains other
451 // types. So, push this one we're printing onto the type stack to assist with
452 // recursive definitions.
Reid Spencer15f7e012006-05-30 21:18:23 +0000453 TypeStack.push_back(Ty);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000454
455 // Print the type definition
456 switch (Ty->getTypeID()) {
457 case Type::FunctionTyID: {
458 const FunctionType* FT = cast<FunctionType>(Ty);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000459 Out << "std::vector<const Type*>" << typeName << "_args;";
460 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000461 FunctionType::param_iterator PI = FT->param_begin();
462 FunctionType::param_iterator PE = FT->param_end();
463 for (; PI != PE; ++PI) {
464 const Type* argTy = static_cast<const Type*>(*PI);
Reid Spencer12803f52006-05-31 17:31:38 +0000465 bool isForward = printTypeInternal(argTy);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000466 std::string argName(getCppName(argTy));
467 Out << typeName << "_args.push_back(" << argName;
468 if (isForward)
469 Out << "_fwd";
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000470 Out << ");";
471 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000472 }
Reid Spencer12803f52006-05-31 17:31:38 +0000473 bool isForward = printTypeInternal(FT->getReturnType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000474 std::string retTypeName(getCppName(FT->getReturnType()));
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000475 Out << "FunctionType* " << typeName << " = FunctionType::get(";
476 in(); nl(Out) << "/*Result=*/" << retTypeName;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000477 if (isForward)
478 Out << "_fwd";
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000479 Out << ",";
480 nl(Out) << "/*Params=*/" << typeName << "_args,";
481 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
482 out();
483 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000484 break;
485 }
486 case Type::StructTyID: {
487 const StructType* ST = cast<StructType>(Ty);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000488 Out << "std::vector<const Type*>" << typeName << "_fields;";
489 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000490 StructType::element_iterator EI = ST->element_begin();
491 StructType::element_iterator EE = ST->element_end();
492 for (; EI != EE; ++EI) {
493 const Type* fieldTy = static_cast<const Type*>(*EI);
Reid Spencer12803f52006-05-31 17:31:38 +0000494 bool isForward = printTypeInternal(fieldTy);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000495 std::string fieldName(getCppName(fieldTy));
496 Out << typeName << "_fields.push_back(" << fieldName;
497 if (isForward)
498 Out << "_fwd";
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000499 Out << ");";
500 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000501 }
502 Out << "StructType* " << typeName << " = StructType::get("
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000503 << typeName << "_fields);";
504 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000505 break;
506 }
507 case Type::ArrayTyID: {
508 const ArrayType* AT = cast<ArrayType>(Ty);
509 const Type* ET = AT->getElementType();
Reid Spencer12803f52006-05-31 17:31:38 +0000510 bool isForward = printTypeInternal(ET);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000511 std::string elemName(getCppName(ET));
512 Out << "ArrayType* " << typeName << " = ArrayType::get("
513 << elemName << (isForward ? "_fwd" : "")
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000514 << ", " << utostr(AT->getNumElements()) << ");";
515 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000516 break;
517 }
518 case Type::PointerTyID: {
519 const PointerType* PT = cast<PointerType>(Ty);
520 const Type* ET = PT->getElementType();
Reid Spencer12803f52006-05-31 17:31:38 +0000521 bool isForward = printTypeInternal(ET);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000522 std::string elemName(getCppName(ET));
523 Out << "PointerType* " << typeName << " = PointerType::get("
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000524 << elemName << (isForward ? "_fwd" : "") << ");";
525 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000526 break;
527 }
528 case Type::PackedTyID: {
529 const PackedType* PT = cast<PackedType>(Ty);
530 const Type* ET = PT->getElementType();
Reid Spencer12803f52006-05-31 17:31:38 +0000531 bool isForward = printTypeInternal(ET);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000532 std::string elemName(getCppName(ET));
533 Out << "PackedType* " << typeName << " = PackedType::get("
534 << elemName << (isForward ? "_fwd" : "")
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000535 << ", " << utostr(PT->getNumElements()) << ");";
536 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000537 break;
538 }
539 case Type::OpaqueTyID: {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000540 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
541 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000542 break;
543 }
544 default:
Reid Spencer12803f52006-05-31 17:31:38 +0000545 error("Invalid TypeID");
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000546 }
547
Reid Spencer74e032a2006-05-29 02:58:15 +0000548 // If the type had a name, make sure we recreate it.
549 const std::string* progTypeName =
550 findTypeName(TheModule->getSymbolTable(),Ty);
551 if (progTypeName)
552 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000553 << typeName << ");";
554 nl(Out);
Reid Spencer74e032a2006-05-29 02:58:15 +0000555
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000556 // Pop us off the type stack
557 TypeStack.pop_back();
Reid Spencer15f7e012006-05-30 21:18:23 +0000558
559 // Indicate that this type is now defined.
560 DefinedTypes.insert(Ty);
561
562 // Early resolve as many unresolved types as possible. Search the unresolved
563 // types map for the type we just printed. Now that its definition is complete
564 // we can resolve any previous references to it. This prevents a cascade of
565 // unresolved types.
566 TypeMap::iterator I = UnresolvedTypes.find(Ty);
567 if (I != UnresolvedTypes.end()) {
568 Out << "cast<OpaqueType>(" << I->second
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000569 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
570 nl(Out);
Reid Spencer15f7e012006-05-30 21:18:23 +0000571 Out << I->second << " = cast<";
572 switch (Ty->getTypeID()) {
573 case Type::FunctionTyID: Out << "FunctionType"; break;
574 case Type::ArrayTyID: Out << "ArrayType"; break;
575 case Type::StructTyID: Out << "StructType"; break;
576 case Type::PackedTyID: Out << "PackedType"; break;
577 case Type::PointerTyID: Out << "PointerType"; break;
578 case Type::OpaqueTyID: Out << "OpaqueType"; break;
579 default: Out << "NoSuchDerivedType"; break;
580 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000581 Out << ">(" << I->second << "_fwd.get());";
582 nl(Out); nl(Out);
Reid Spencer15f7e012006-05-30 21:18:23 +0000583 UnresolvedTypes.erase(I);
584 }
585
586 // Finally, separate the type definition from other with a newline.
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000587 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000588
589 // We weren't a recursive type
590 return false;
591}
592
Reid Spencer12803f52006-05-31 17:31:38 +0000593// Prints a type definition. Returns true if it could not resolve all the types
594// in the definition but had to use a forward reference.
595void
596CppWriter::printType(const Type* Ty) {
597 assert(TypeStack.empty());
598 TypeStack.clear();
599 printTypeInternal(Ty);
600 assert(TypeStack.empty());
601}
602
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000603void
604CppWriter::printTypes(const Module* M) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000605
606 // Walk the symbol table and print out all its types
607 const SymbolTable& symtab = M->getSymbolTable();
608 for (SymbolTable::type_const_iterator TI = symtab.type_begin(),
609 TE = symtab.type_end(); TI != TE; ++TI) {
610
611 // For primitive types and types already defined, just add a name
612 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
613 if (TI->second->isPrimitiveType() || TNI != TypeNames.end()) {
614 Out << "mod->addTypeName(\"";
615 printEscapedString(TI->first);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000616 Out << "\", " << getCppName(TI->second) << ");";
617 nl(Out);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000618 // For everything else, define the type
619 } else {
Reid Spencer12803f52006-05-31 17:31:38 +0000620 printType(TI->second);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000621 }
622 }
623
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000624 // Add all of the global variables to the value table...
625 for (Module::const_global_iterator I = TheModule->global_begin(),
626 E = TheModule->global_end(); I != E; ++I) {
627 if (I->hasInitializer())
Reid Spencer12803f52006-05-31 17:31:38 +0000628 printType(I->getInitializer()->getType());
629 printType(I->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000630 }
631
632 // Add all the functions to the table
633 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
634 FI != FE; ++FI) {
Reid Spencer12803f52006-05-31 17:31:38 +0000635 printType(FI->getReturnType());
636 printType(FI->getFunctionType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000637 // Add all the function arguments
638 for(Function::const_arg_iterator AI = FI->arg_begin(),
639 AE = FI->arg_end(); AI != AE; ++AI) {
Reid Spencer12803f52006-05-31 17:31:38 +0000640 printType(AI->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000641 }
642
643 // Add all of the basic blocks and instructions
644 for (Function::const_iterator BB = FI->begin(),
645 E = FI->end(); BB != E; ++BB) {
Reid Spencer12803f52006-05-31 17:31:38 +0000646 printType(BB->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000647 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
648 ++I) {
Reid Spencer12803f52006-05-31 17:31:38 +0000649 printType(I->getType());
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000650 for (unsigned i = 0; i < I->getNumOperands(); ++i)
Reid Spencer12803f52006-05-31 17:31:38 +0000651 printType(I->getOperand(i)->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000652 }
653 }
654 }
655}
656
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000657
Reid Spencere0d133f2006-05-29 18:08:06 +0000658// printConstant - Print out a constant pool entry...
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000659void CppWriter::printConstant(const Constant *CV) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000660 // First, if the constant is actually a GlobalValue (variable or function) or
661 // its already in the constant list then we've printed it already and we can
662 // just return.
663 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
Reid Spencere0d133f2006-05-29 18:08:06 +0000664 return;
665
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000666 std::string constName(getCppName(CV));
667 std::string typeName(getCppName(CV->getType()));
668 if (CV->isNullValue()) {
669 Out << "Constant* " << constName << " = Constant::getNullValue("
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000670 << typeName << ");";
671 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000672 return;
673 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000674 if (isa<GlobalValue>(CV)) {
675 // Skip variables and functions, we emit them elsewhere
676 return;
677 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000678 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000679 Out << "ConstantBool* " << constName << " = ConstantBool::get("
Chris Lattnere354df92006-09-28 23:24:48 +0000680 << (CB->getValue() ? "true" : "false") << ");";
Reid Spencerb83eb642006-10-20 07:07:24 +0000681 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
682 Out << "ConstantInt* " << constName << " = ConstantInt::get("
683 << typeName << ", "
684 << (CV->getType()->isSigned() ? CI->getSExtValue() : CI->getZExtValue())
685 << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000686 } else if (isa<ConstantAggregateZero>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000687 Out << "ConstantAggregateZero* " << constName
688 << " = ConstantAggregateZero::get(" << typeName << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000689 } else if (isa<ConstantPointerNull>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000690 Out << "ConstantPointerNull* " << constName
691 << " = ConstanPointerNull::get(" << typeName << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000692 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
Reid Spencerf977e7b2006-06-01 23:43:47 +0000693 Out << "ConstantFP* " << constName << " = ";
Reid Spencer12803f52006-05-31 17:31:38 +0000694 printCFP(CFP);
Reid Spencerf977e7b2006-06-01 23:43:47 +0000695 Out << ";";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000696 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000697 if (CA->isString() && CA->getType()->getElementType() == Type::SByteTy) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000698 Out << "Constant* " << constName << " = ConstantArray::get(\"";
Reid Spencere0d133f2006-05-29 18:08:06 +0000699 printEscapedString(CA->getAsString());
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000700 // Determine if we want null termination or not.
701 if (CA->getType()->getNumElements() <= CA->getAsString().length())
Reid Spencer15f7e012006-05-30 21:18:23 +0000702 Out << "\", false";// No null terminator
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000703 else
Reid Spencer15f7e012006-05-30 21:18:23 +0000704 Out << "\", true"; // Indicate that the null terminator should be added.
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000705 Out << ");";
706 } else {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000707 Out << "std::vector<Constant*> " << constName << "_elems;";
708 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000709 unsigned N = CA->getNumOperands();
710 for (unsigned i = 0; i < N; ++i) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000711 printConstant(CA->getOperand(i)); // recurse to print operands
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000712 Out << constName << "_elems.push_back("
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000713 << getCppName(CA->getOperand(i)) << ");";
714 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000715 }
716 Out << "Constant* " << constName << " = ConstantArray::get("
717 << typeName << ", " << constName << "_elems);";
718 }
719 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000720 Out << "std::vector<Constant*> " << constName << "_fields;";
721 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000722 unsigned N = CS->getNumOperands();
723 for (unsigned i = 0; i < N; i++) {
724 printConstant(CS->getOperand(i));
725 Out << constName << "_fields.push_back("
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000726 << getCppName(CS->getOperand(i)) << ");";
727 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000728 }
729 Out << "Constant* " << constName << " = ConstantStruct::get("
730 << typeName << ", " << constName << "_fields);";
731 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000732 Out << "std::vector<Constant*> " << constName << "_elems;";
733 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000734 unsigned N = CP->getNumOperands();
735 for (unsigned i = 0; i < N; ++i) {
736 printConstant(CP->getOperand(i));
737 Out << constName << "_elems.push_back("
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000738 << getCppName(CP->getOperand(i)) << ");";
739 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000740 }
741 Out << "Constant* " << constName << " = ConstantPacked::get("
742 << typeName << ", " << constName << "_elems);";
743 } else if (isa<UndefValue>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000744 Out << "UndefValue* " << constName << " = UndefValue::get("
Reid Spencere0d133f2006-05-29 18:08:06 +0000745 << typeName << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000746 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000747 if (CE->getOpcode() == Instruction::GetElementPtr) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000748 Out << "std::vector<Constant*> " << constName << "_indices;";
749 nl(Out);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000750 printConstant(CE->getOperand(0));
Reid Spencere0d133f2006-05-29 18:08:06 +0000751 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000752 printConstant(CE->getOperand(i));
Reid Spencere0d133f2006-05-29 18:08:06 +0000753 Out << constName << "_indices.push_back("
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000754 << getCppName(CE->getOperand(i)) << ");";
755 nl(Out);
Reid Spencere0d133f2006-05-29 18:08:06 +0000756 }
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000757 Out << "Constant* " << constName
758 << " = ConstantExpr::getGetElementPtr("
759 << getCppName(CE->getOperand(0)) << ", "
760 << constName << "_indices);";
Reid Spencer3da59db2006-11-27 01:05:10 +0000761 } else if (CE->isCast()) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000762 printConstant(CE->getOperand(0));
Reid Spencere0d133f2006-05-29 18:08:06 +0000763 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
Reid Spencerb0e9f722006-12-12 01:31:37 +0000764 switch (CE->getOpcode()) {
765 default: assert(0 && "Invalid cast opcode");
766 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
767 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
768 case Instruction::SExt: Out << "Instruction::SExt"; break;
769 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
770 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
771 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
772 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
773 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
774 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
775 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
776 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
777 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
778 }
779 Out << ", " << getCppName(CE->getOperand(0)) << ", "
780 << getCppName(CE->getType()) << ");";
Reid Spencere0d133f2006-05-29 18:08:06 +0000781 } else {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000782 unsigned N = CE->getNumOperands();
783 for (unsigned i = 0; i < N; ++i ) {
784 printConstant(CE->getOperand(i));
785 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000786 Out << "Constant* " << constName << " = ConstantExpr::";
787 switch (CE->getOpcode()) {
788 case Instruction::Add: Out << "getAdd"; break;
789 case Instruction::Sub: Out << "getSub"; break;
790 case Instruction::Mul: Out << "getMul"; break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000791 case Instruction::UDiv: Out << "getUDiv"; break;
792 case Instruction::SDiv: Out << "getSDiv"; break;
793 case Instruction::FDiv: Out << "getFDiv"; break;
Reid Spencer0a783f72006-11-02 01:53:59 +0000794 case Instruction::URem: Out << "getURem"; break;
795 case Instruction::SRem: Out << "getSRem"; break;
796 case Instruction::FRem: Out << "getFRem"; break;
Reid Spencere0d133f2006-05-29 18:08:06 +0000797 case Instruction::And: Out << "getAnd"; break;
798 case Instruction::Or: Out << "getOr"; break;
799 case Instruction::Xor: Out << "getXor"; break;
800 case Instruction::SetEQ: Out << "getSetEQ"; break;
801 case Instruction::SetNE: Out << "getSetNE"; break;
802 case Instruction::SetLE: Out << "getSetLE"; break;
803 case Instruction::SetGE: Out << "getSetGE"; break;
804 case Instruction::SetLT: Out << "getSetLT"; break;
805 case Instruction::SetGT: Out << "getSetGT"; break;
806 case Instruction::Shl: Out << "getShl"; break;
Reid Spencer3822ff52006-11-08 06:47:33 +0000807 case Instruction::LShr: Out << "getLShr"; break;
808 case Instruction::AShr: Out << "getAShr"; break;
Reid Spencere0d133f2006-05-29 18:08:06 +0000809 case Instruction::Select: Out << "getSelect"; break;
810 case Instruction::ExtractElement: Out << "getExtractElement"; break;
811 case Instruction::InsertElement: Out << "getInsertElement"; break;
812 case Instruction::ShuffleVector: Out << "getShuffleVector"; break;
813 default:
Reid Spencer12803f52006-05-31 17:31:38 +0000814 error("Invalid constant expression");
Reid Spencere0d133f2006-05-29 18:08:06 +0000815 break;
816 }
817 Out << getCppName(CE->getOperand(0));
818 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
819 Out << ", " << getCppName(CE->getOperand(i));
820 Out << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000821 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000822 } else {
Reid Spencer12803f52006-05-31 17:31:38 +0000823 error("Bad Constant");
Reid Spencere0d133f2006-05-29 18:08:06 +0000824 Out << "Constant* " << constName << " = 0; ";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000825 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000826 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000827}
828
Reid Spencer12803f52006-05-31 17:31:38 +0000829void
830CppWriter::printConstants(const Module* M) {
831 // Traverse all the global variables looking for constant initializers
832 for (Module::const_global_iterator I = TheModule->global_begin(),
833 E = TheModule->global_end(); I != E; ++I)
834 if (I->hasInitializer())
835 printConstant(I->getInitializer());
836
837 // Traverse the LLVM functions looking for constants
838 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
839 FI != FE; ++FI) {
840 // Add all of the basic blocks and instructions
841 for (Function::const_iterator BB = FI->begin(),
842 E = FI->end(); BB != E; ++BB) {
843 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
844 ++I) {
845 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
846 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
847 printConstant(C);
848 }
849 }
850 }
851 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000852 }
Reid Spencer66c87342006-05-30 03:43:49 +0000853}
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000854
Reid Spencer12803f52006-05-31 17:31:38 +0000855void CppWriter::printVariableUses(const GlobalVariable *GV) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000856 nl(Out) << "// Type Definitions";
857 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000858 printType(GV->getType());
859 if (GV->hasInitializer()) {
860 Constant* Init = GV->getInitializer();
861 printType(Init->getType());
862 if (Function* F = dyn_cast<Function>(Init)) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000863 nl(Out)<< "/ Function Declarations"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000864 printFunctionHead(F);
865 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000866 nl(Out) << "// Global Variable Declarations"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000867 printVariableHead(gv);
868 } else {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000869 nl(Out) << "// Constant Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000870 printConstant(gv);
871 }
872 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000873 nl(Out) << "// Global Variable Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000874 printVariableBody(gv);
Reid Spencere0d133f2006-05-29 18:08:06 +0000875 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000876 }
Reid Spencer12803f52006-05-31 17:31:38 +0000877}
Reid Spencer15f7e012006-05-30 21:18:23 +0000878
Reid Spencer12803f52006-05-31 17:31:38 +0000879void CppWriter::printVariableHead(const GlobalVariable *GV) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000880 nl(Out) << "GlobalVariable* " << getCppName(GV);
Reid Spencerf977e7b2006-06-01 23:43:47 +0000881 if (is_inline) {
882 Out << " = mod->getGlobalVariable(";
883 printEscapedString(GV->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000884 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
885 nl(Out) << "if (!" << getCppName(GV) << ") {";
886 in(); nl(Out) << getCppName(GV);
Reid Spencerf977e7b2006-06-01 23:43:47 +0000887 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000888 Out << " = new GlobalVariable(";
889 nl(Out) << "/*Type=*/";
Reid Spencer12803f52006-05-31 17:31:38 +0000890 printCppName(GV->getType()->getElementType());
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000891 Out << ",";
892 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
893 Out << ",";
894 nl(Out) << "/*Linkage=*/";
Reid Spencer12803f52006-05-31 17:31:38 +0000895 printLinkageType(GV->getLinkage());
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000896 Out << ",";
897 nl(Out) << "/*Initializer=*/0, ";
Reid Spencer12803f52006-05-31 17:31:38 +0000898 if (GV->hasInitializer()) {
899 Out << "// has initializer, specified below";
Reid Spencer15f7e012006-05-30 21:18:23 +0000900 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000901 nl(Out) << "/*Name=*/\"";
Reid Spencer12803f52006-05-31 17:31:38 +0000902 printEscapedString(GV->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000903 Out << "\",";
904 nl(Out) << "mod);";
905 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000906
907 if (GV->hasSection()) {
908 printCppName(GV);
909 Out << "->setSection(\"";
910 printEscapedString(GV->getSection());
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000911 Out << "\");";
912 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000913 }
914 if (GV->getAlignment()) {
915 printCppName(GV);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000916 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
917 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000918 };
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000919 if (is_inline) {
920 out(); Out << "}"; nl(Out);
921 }
Reid Spencer12803f52006-05-31 17:31:38 +0000922}
923
924void
925CppWriter::printVariableBody(const GlobalVariable *GV) {
926 if (GV->hasInitializer()) {
927 printCppName(GV);
928 Out << "->setInitializer(";
929 //if (!isa<GlobalValue(GV->getInitializer()))
930 //else
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000931 Out << getCppName(GV->getInitializer()) << ");";
932 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000933 }
934}
935
936std::string
937CppWriter::getOpName(Value* V) {
938 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
939 return getCppName(V);
940
941 // See if its alread in the map of forward references, if so just return the
942 // name we already set up for it
943 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
944 if (I != ForwardRefs.end())
945 return I->second;
946
947 // This is a new forward reference. Generate a unique name for it
948 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
949
950 // Yes, this is a hack. An Argument is the smallest instantiable value that
951 // we can make as a placeholder for the real value. We'll replace these
952 // Argument instances later.
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000953 Out << "Argument* " << result << " = new Argument("
954 << getCppName(V->getType()) << ");";
955 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000956 ForwardRefs[V] = result;
957 return result;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000958}
959
Reid Spencere0d133f2006-05-29 18:08:06 +0000960// printInstruction - This member is called for each Instruction in a function.
961void
Reid Spencer12803f52006-05-31 17:31:38 +0000962CppWriter::printInstruction(const Instruction *I, const std::string& bbname) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000963 std::string iName(getCppName(I));
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000964
Reid Spencer15f7e012006-05-30 21:18:23 +0000965 // Before we emit this instruction, we need to take care of generating any
966 // forward references. So, we get the names of all the operands in advance
967 std::string* opNames = new std::string[I->getNumOperands()];
968 for (unsigned i = 0; i < I->getNumOperands(); i++) {
969 opNames[i] = getOpName(I->getOperand(i));
970 }
971
Reid Spencere0d133f2006-05-29 18:08:06 +0000972 switch (I->getOpcode()) {
973 case Instruction::Ret: {
974 const ReturnInst* ret = cast<ReturnInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000975 Out << "ReturnInst* " << iName << " = new ReturnInst("
Reid Spencer15f7e012006-05-30 21:18:23 +0000976 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
Reid Spencere0d133f2006-05-29 18:08:06 +0000977 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000978 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000979 case Instruction::Br: {
980 const BranchInst* br = cast<BranchInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000981 Out << "BranchInst* " << iName << " = new BranchInst(" ;
Reid Spencere0d133f2006-05-29 18:08:06 +0000982 if (br->getNumOperands() == 3 ) {
Reid Spencer15f7e012006-05-30 21:18:23 +0000983 Out << opNames[0] << ", "
984 << opNames[1] << ", "
985 << opNames[2] << ", ";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000986
Reid Spencere0d133f2006-05-29 18:08:06 +0000987 } else if (br->getNumOperands() == 1) {
Reid Spencer15f7e012006-05-30 21:18:23 +0000988 Out << opNames[0] << ", ";
Reid Spencere0d133f2006-05-29 18:08:06 +0000989 } else {
Reid Spencer12803f52006-05-31 17:31:38 +0000990 error("Branch with 2 operands?");
Reid Spencere0d133f2006-05-29 18:08:06 +0000991 }
992 Out << bbname << ");";
993 break;
994 }
Reid Spencer66c87342006-05-30 03:43:49 +0000995 case Instruction::Switch: {
996 const SwitchInst* sw = cast<SwitchInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000997 Out << "SwitchInst* " << iName << " = new SwitchInst("
Reid Spencer15f7e012006-05-30 21:18:23 +0000998 << opNames[0] << ", "
999 << opNames[1] << ", "
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001000 << sw->getNumCases() << ", " << bbname << ");";
1001 nl(Out);
Reid Spencer15f7e012006-05-30 21:18:23 +00001002 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001003 Out << iName << "->addCase("
Reid Spencer15f7e012006-05-30 21:18:23 +00001004 << opNames[i] << ", "
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001005 << opNames[i+1] << ");";
1006 nl(Out);
Reid Spencer66c87342006-05-30 03:43:49 +00001007 }
1008 break;
1009 }
1010 case Instruction::Invoke: {
1011 const InvokeInst* inv = cast<InvokeInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001012 Out << "std::vector<Value*> " << iName << "_params;";
1013 nl(Out);
1014 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1015 Out << iName << "_params.push_back("
1016 << opNames[i] << ");";
1017 nl(Out);
1018 }
1019 Out << "InvokeInst* " << iName << " = new InvokeInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001020 << opNames[0] << ", "
1021 << opNames[1] << ", "
1022 << opNames[2] << ", "
Reid Spencer66c87342006-05-30 03:43:49 +00001023 << iName << "_params, \"";
1024 printEscapedString(inv->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001025 Out << "\", " << bbname << ");";
1026 nl(Out) << iName << "->setCallingConv(";
Reid Spencer66c87342006-05-30 03:43:49 +00001027 printCallingConv(inv->getCallingConv());
1028 Out << ");";
1029 break;
1030 }
1031 case Instruction::Unwind: {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001032 Out << "UnwindInst* " << iName << " = new UnwindInst("
Reid Spencer66c87342006-05-30 03:43:49 +00001033 << bbname << ");";
1034 break;
1035 }
1036 case Instruction::Unreachable:{
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001037 Out << "UnreachableInst* " << iName << " = new UnreachableInst("
Reid Spencer66c87342006-05-30 03:43:49 +00001038 << bbname << ");";
1039 break;
1040 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001041 case Instruction::Add:
1042 case Instruction::Sub:
1043 case Instruction::Mul:
Reid Spencer1628cec2006-10-26 06:15:43 +00001044 case Instruction::UDiv:
1045 case Instruction::SDiv:
1046 case Instruction::FDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001047 case Instruction::URem:
1048 case Instruction::SRem:
1049 case Instruction::FRem:
Reid Spencere0d133f2006-05-29 18:08:06 +00001050 case Instruction::And:
1051 case Instruction::Or:
1052 case Instruction::Xor:
Reid Spencer66c87342006-05-30 03:43:49 +00001053 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00001054 case Instruction::LShr:
1055 case Instruction::AShr:{
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001056 Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
Reid Spencer66c87342006-05-30 03:43:49 +00001057 switch (I->getOpcode()) {
1058 case Instruction::Add: Out << "Instruction::Add"; break;
1059 case Instruction::Sub: Out << "Instruction::Sub"; break;
1060 case Instruction::Mul: Out << "Instruction::Mul"; break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001061 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1062 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1063 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
Reid Spencer0a783f72006-11-02 01:53:59 +00001064 case Instruction::URem:Out << "Instruction::URem"; break;
1065 case Instruction::SRem:Out << "Instruction::SRem"; break;
1066 case Instruction::FRem:Out << "Instruction::FRem"; break;
Reid Spencer66c87342006-05-30 03:43:49 +00001067 case Instruction::And: Out << "Instruction::And"; break;
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001068 case Instruction::Or: Out << "Instruction::Or"; break;
Reid Spencer66c87342006-05-30 03:43:49 +00001069 case Instruction::Xor: Out << "Instruction::Xor"; break;
1070 case Instruction::Shl: Out << "Instruction::Shl"; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001071 case Instruction::LShr:Out << "Instruction::LShr"; break;
1072 case Instruction::AShr:Out << "Instruction::AShr"; break;
Reid Spencer66c87342006-05-30 03:43:49 +00001073 default: Out << "Instruction::BadOpCode"; break;
1074 }
Reid Spencer15f7e012006-05-30 21:18:23 +00001075 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001076 printEscapedString(I->getName());
1077 Out << "\", " << bbname << ");";
1078 break;
1079 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001080 case Instruction::SetEQ:
1081 case Instruction::SetNE:
1082 case Instruction::SetLE:
1083 case Instruction::SetGE:
1084 case Instruction::SetLT:
Reid Spencer66c87342006-05-30 03:43:49 +00001085 case Instruction::SetGT: {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001086 Out << "SetCondInst* " << iName << " = new SetCondInst(";
Reid Spencer66c87342006-05-30 03:43:49 +00001087 switch (I->getOpcode()) {
1088 case Instruction::SetEQ: Out << "Instruction::SetEQ"; break;
1089 case Instruction::SetNE: Out << "Instruction::SetNE"; break;
1090 case Instruction::SetLE: Out << "Instruction::SetLE"; break;
1091 case Instruction::SetGE: Out << "Instruction::SetGE"; break;
1092 case Instruction::SetLT: Out << "Instruction::SetLT"; break;
1093 case Instruction::SetGT: Out << "Instruction::SetGT"; break;
1094 default: Out << "Instruction::BadOpCode"; break;
1095 }
Reid Spencer15f7e012006-05-30 21:18:23 +00001096 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001097 printEscapedString(I->getName());
1098 Out << "\", " << bbname << ");";
1099 break;
1100 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001101 case Instruction::Malloc: {
1102 const MallocInst* mallocI = cast<MallocInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001103 Out << "MallocInst* " << iName << " = new MallocInst("
Reid Spencere0d133f2006-05-29 18:08:06 +00001104 << getCppName(mallocI->getAllocatedType()) << ", ";
1105 if (mallocI->isArrayAllocation())
Reid Spencer15f7e012006-05-30 21:18:23 +00001106 Out << opNames[0] << ", " ;
Reid Spencere0d133f2006-05-29 18:08:06 +00001107 Out << "\"";
1108 printEscapedString(mallocI->getName());
1109 Out << "\", " << bbname << ");";
1110 if (mallocI->getAlignment())
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001111 nl(Out) << iName << "->setAlignment("
Reid Spencere0d133f2006-05-29 18:08:06 +00001112 << mallocI->getAlignment() << ");";
1113 break;
1114 }
Reid Spencer66c87342006-05-30 03:43:49 +00001115 case Instruction::Free: {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001116 Out << "FreeInst* " << iName << " = new FreeInst("
Reid Spencer66c87342006-05-30 03:43:49 +00001117 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1118 break;
1119 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001120 case Instruction::Alloca: {
1121 const AllocaInst* allocaI = cast<AllocaInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001122 Out << "AllocaInst* " << iName << " = new AllocaInst("
Reid Spencere0d133f2006-05-29 18:08:06 +00001123 << getCppName(allocaI->getAllocatedType()) << ", ";
1124 if (allocaI->isArrayAllocation())
Reid Spencer15f7e012006-05-30 21:18:23 +00001125 Out << opNames[0] << ", ";
Reid Spencere0d133f2006-05-29 18:08:06 +00001126 Out << "\"";
1127 printEscapedString(allocaI->getName());
1128 Out << "\", " << bbname << ");";
1129 if (allocaI->getAlignment())
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001130 nl(Out) << iName << "->setAlignment("
Reid Spencere0d133f2006-05-29 18:08:06 +00001131 << allocaI->getAlignment() << ");";
1132 break;
1133 }
Reid Spencer66c87342006-05-30 03:43:49 +00001134 case Instruction::Load:{
1135 const LoadInst* load = cast<LoadInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001136 Out << "LoadInst* " << iName << " = new LoadInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001137 << opNames[0] << ", \"";
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001138 printEscapedString(load->getName());
1139 Out << "\", " << (load->isVolatile() ? "true" : "false" )
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001140 << ", " << bbname << ");";
Reid Spencer66c87342006-05-30 03:43:49 +00001141 break;
1142 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001143 case Instruction::Store: {
1144 const StoreInst* store = cast<StoreInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001145 Out << "StoreInst* " << iName << " = new StoreInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001146 << opNames[0] << ", "
1147 << opNames[1] << ", "
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001148 << (store->isVolatile() ? "true" : "false")
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001149 << ", " << bbname << ");";
Reid Spencere0d133f2006-05-29 18:08:06 +00001150 break;
1151 }
1152 case Instruction::GetElementPtr: {
1153 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1154 if (gep->getNumOperands() <= 2) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001155 Out << "GetElementPtrInst* " << iName << " = new GetElementPtrInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001156 << opNames[0];
Reid Spencere0d133f2006-05-29 18:08:06 +00001157 if (gep->getNumOperands() == 2)
Reid Spencer15f7e012006-05-30 21:18:23 +00001158 Out << ", " << opNames[1];
Reid Spencere0d133f2006-05-29 18:08:06 +00001159 } else {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001160 Out << "std::vector<Value*> " << iName << "_indices;";
1161 nl(Out);
Reid Spencere0d133f2006-05-29 18:08:06 +00001162 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001163 Out << iName << "_indices.push_back("
1164 << opNames[i] << ");";
1165 nl(Out);
Reid Spencere0d133f2006-05-29 18:08:06 +00001166 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001167 Out << "Instruction* " << iName << " = new GetElementPtrInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001168 << opNames[0] << ", " << iName << "_indices";
Reid Spencere0d133f2006-05-29 18:08:06 +00001169 }
1170 Out << ", \"";
1171 printEscapedString(gep->getName());
1172 Out << "\", " << bbname << ");";
1173 break;
1174 }
Reid Spencer66c87342006-05-30 03:43:49 +00001175 case Instruction::PHI: {
1176 const PHINode* phi = cast<PHINode>(I);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001177
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001178 Out << "PHINode* " << iName << " = new PHINode("
Reid Spencer66c87342006-05-30 03:43:49 +00001179 << getCppName(phi->getType()) << ", \"";
1180 printEscapedString(phi->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001181 Out << "\", " << bbname << ");";
1182 nl(Out) << iName << "->reserveOperandSpace("
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001183 << phi->getNumIncomingValues()
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001184 << ");";
1185 nl(Out);
Reid Spencer15f7e012006-05-30 21:18:23 +00001186 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001187 Out << iName << "->addIncoming("
1188 << opNames[i] << ", " << opNames[i+1] << ");";
1189 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001190 }
Reid Spencer66c87342006-05-30 03:43:49 +00001191 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001192 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001193 case Instruction::Trunc:
1194 case Instruction::ZExt:
1195 case Instruction::SExt:
1196 case Instruction::FPTrunc:
1197 case Instruction::FPExt:
1198 case Instruction::FPToUI:
1199 case Instruction::FPToSI:
1200 case Instruction::UIToFP:
1201 case Instruction::SIToFP:
1202 case Instruction::PtrToInt:
1203 case Instruction::IntToPtr:
1204 case Instruction::BitCast: {
Reid Spencer66c87342006-05-30 03:43:49 +00001205 const CastInst* cst = cast<CastInst>(I);
Reid Spencer3da59db2006-11-27 01:05:10 +00001206 Out << "CastInst* " << iName << " = new ";
1207 switch (I->getOpcode()) {
1208 case Instruction::Trunc: Out << "TruncInst";
1209 case Instruction::ZExt: Out << "ZExtInst";
1210 case Instruction::SExt: Out << "SExtInst";
1211 case Instruction::FPTrunc: Out << "FPTruncInst";
1212 case Instruction::FPExt: Out << "FPExtInst";
1213 case Instruction::FPToUI: Out << "FPToUIInst";
1214 case Instruction::FPToSI: Out << "FPToSIInst";
1215 case Instruction::UIToFP: Out << "UIToFPInst";
1216 case Instruction::SIToFP: Out << "SIToFPInst";
1217 case Instruction::PtrToInt: Out << "PtrToInst";
1218 case Instruction::IntToPtr: Out << "IntToPtrInst";
1219 case Instruction::BitCast: Out << "BitCastInst";
1220 default: assert(!"Unreachable"); break;
1221 }
1222 Out << "(" << opNames[0] << ", "
Reid Spencer66c87342006-05-30 03:43:49 +00001223 << getCppName(cst->getType()) << ", \"";
1224 printEscapedString(cst->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001225 Out << "\", " << bbname << ");";
Reid Spencer66c87342006-05-30 03:43:49 +00001226 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001227 }
Reid Spencer66c87342006-05-30 03:43:49 +00001228 case Instruction::Call:{
1229 const CallInst* call = cast<CallInst>(I);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001230 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001231 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001232 << getCppName(ila->getFunctionType()) << ", \""
1233 << ila->getAsmString() << "\", \""
1234 << ila->getConstraintString() << "\","
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001235 << (ila->hasSideEffects() ? "true" : "false") << ");";
1236 nl(Out);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001237 }
Reid Spencer66c87342006-05-30 03:43:49 +00001238 if (call->getNumOperands() > 3) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001239 Out << "std::vector<Value*> " << iName << "_params;";
1240 nl(Out);
1241 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1242 Out << iName << "_params.push_back(" << opNames[i] << ");";
1243 nl(Out);
1244 }
1245 Out << "CallInst* " << iName << " = new CallInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001246 << opNames[0] << ", " << iName << "_params, \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001247 } else if (call->getNumOperands() == 3) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001248 Out << "CallInst* " << iName << " = new CallInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001249 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001250 } else if (call->getNumOperands() == 2) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001251 Out << "CallInst* " << iName << " = new CallInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001252 << opNames[0] << ", " << opNames[1] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001253 } else {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001254 Out << "CallInst* " << iName << " = new CallInst(" << opNames[0]
Reid Spencer15f7e012006-05-30 21:18:23 +00001255 << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001256 }
1257 printEscapedString(call->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001258 Out << "\", " << bbname << ");";
1259 nl(Out) << iName << "->setCallingConv(";
Reid Spencer66c87342006-05-30 03:43:49 +00001260 printCallingConv(call->getCallingConv());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001261 Out << ");";
1262 nl(Out) << iName << "->setTailCall("
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001263 << (call->isTailCall() ? "true":"false");
Reid Spencer66c87342006-05-30 03:43:49 +00001264 Out << ");";
1265 break;
1266 }
1267 case Instruction::Select: {
1268 const SelectInst* sel = cast<SelectInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001269 Out << "SelectInst* " << getCppName(sel) << " = new SelectInst(";
Reid Spencer15f7e012006-05-30 21:18:23 +00001270 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001271 printEscapedString(sel->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001272 Out << "\", " << bbname << ");";
Reid Spencer66c87342006-05-30 03:43:49 +00001273 break;
1274 }
1275 case Instruction::UserOp1:
1276 /// FALL THROUGH
1277 case Instruction::UserOp2: {
1278 /// FIXME: What should be done here?
1279 break;
1280 }
1281 case Instruction::VAArg: {
1282 const VAArgInst* va = cast<VAArgInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001283 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001284 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001285 printEscapedString(va->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001286 Out << "\", " << bbname << ");";
Reid Spencer66c87342006-05-30 03:43:49 +00001287 break;
1288 }
1289 case Instruction::ExtractElement: {
1290 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001291 Out << "ExtractElementInst* " << getCppName(eei)
Reid Spencer15f7e012006-05-30 21:18:23 +00001292 << " = new ExtractElementInst(" << opNames[0]
1293 << ", " << opNames[1] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001294 printEscapedString(eei->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001295 Out << "\", " << bbname << ");";
Reid Spencer66c87342006-05-30 03:43:49 +00001296 break;
1297 }
1298 case Instruction::InsertElement: {
1299 const InsertElementInst* iei = cast<InsertElementInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001300 Out << "InsertElementInst* " << getCppName(iei)
Reid Spencer15f7e012006-05-30 21:18:23 +00001301 << " = new InsertElementInst(" << opNames[0]
1302 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001303 printEscapedString(iei->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001304 Out << "\", " << bbname << ");";
Reid Spencer66c87342006-05-30 03:43:49 +00001305 break;
1306 }
1307 case Instruction::ShuffleVector: {
1308 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001309 Out << "ShuffleVectorInst* " << getCppName(svi)
Reid Spencer15f7e012006-05-30 21:18:23 +00001310 << " = new ShuffleVectorInst(" << opNames[0]
1311 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001312 printEscapedString(svi->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001313 Out << "\", " << bbname << ");";
Reid Spencer66c87342006-05-30 03:43:49 +00001314 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001315 }
1316 }
Reid Spencer68464b72006-06-15 16:09:59 +00001317 DefinedValues.insert(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001318 nl(Out);
Reid Spencer15f7e012006-05-30 21:18:23 +00001319 delete [] opNames;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001320}
1321
Reid Spencer12803f52006-05-31 17:31:38 +00001322// Print out the types, constants and declarations needed by one function
1323void CppWriter::printFunctionUses(const Function* F) {
1324
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001325 nl(Out) << "// Type Definitions"; nl(Out);
Reid Spencerf977e7b2006-06-01 23:43:47 +00001326 if (!is_inline) {
1327 // Print the function's return type
1328 printType(F->getReturnType());
Reid Spencer12803f52006-05-31 17:31:38 +00001329
Reid Spencerf977e7b2006-06-01 23:43:47 +00001330 // Print the function's function type
1331 printType(F->getFunctionType());
Reid Spencer12803f52006-05-31 17:31:38 +00001332
Reid Spencerf977e7b2006-06-01 23:43:47 +00001333 // Print the types of each of the function's arguments
1334 for(Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1335 AI != AE; ++AI) {
1336 printType(AI->getType());
1337 }
Reid Spencer12803f52006-05-31 17:31:38 +00001338 }
1339
1340 // Print type definitions for every type referenced by an instruction and
1341 // make a note of any global values or constants that are referenced
1342 std::vector<GlobalValue*> gvs;
1343 std::vector<Constant*> consts;
1344 for (Function::const_iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB){
1345 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1346 I != E; ++I) {
1347 // Print the type of the instruction itself
1348 printType(I->getType());
1349
1350 // Print the type of each of the instruction's operands
1351 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1352 Value* operand = I->getOperand(i);
1353 printType(operand->getType());
1354 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand))
1355 gvs.push_back(GV);
1356 else if (Constant* C = dyn_cast<Constant>(operand))
1357 consts.push_back(C);
1358 }
1359 }
1360 }
1361
1362 // Print the function declarations for any functions encountered
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001363 nl(Out) << "// Function Declarations"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001364 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1365 I != E; ++I) {
Reid Spencerf977e7b2006-06-01 23:43:47 +00001366 if (Function* Fun = dyn_cast<Function>(*I)) {
1367 if (!is_inline || Fun != F)
1368 printFunctionHead(Fun);
1369 }
Reid Spencer12803f52006-05-31 17:31:38 +00001370 }
1371
1372 // Print the global variable declarations for any variables encountered
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001373 nl(Out) << "// Global Variable Declarations"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001374 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1375 I != E; ++I) {
1376 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1377 printVariableHead(F);
1378 }
1379
1380 // Print the constants found
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001381 nl(Out) << "// Constant Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001382 for (std::vector<Constant*>::iterator I = consts.begin(), E = consts.end();
1383 I != E; ++I) {
Reid Spencerf977e7b2006-06-01 23:43:47 +00001384 printConstant(*I);
Reid Spencer12803f52006-05-31 17:31:38 +00001385 }
1386
1387 // Process the global variables definitions now that all the constants have
1388 // been emitted. These definitions just couple the gvars with their constant
1389 // initializers.
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001390 nl(Out) << "// Global Variable Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001391 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1392 I != E; ++I) {
1393 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1394 printVariableBody(GV);
1395 }
1396}
1397
1398void CppWriter::printFunctionHead(const Function* F) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001399 nl(Out) << "Function* " << getCppName(F);
Reid Spencerf977e7b2006-06-01 23:43:47 +00001400 if (is_inline) {
1401 Out << " = mod->getFunction(\"";
1402 printEscapedString(F->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001403 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1404 nl(Out) << "if (!" << getCppName(F) << ") {";
1405 nl(Out) << getCppName(F);
Reid Spencerf977e7b2006-06-01 23:43:47 +00001406 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001407 Out<< " = new Function(";
1408 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1409 nl(Out) << "/*Linkage=*/";
Reid Spencer12803f52006-05-31 17:31:38 +00001410 printLinkageType(F->getLinkage());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001411 Out << ",";
1412 nl(Out) << "/*Name=*/\"";
Reid Spencer12803f52006-05-31 17:31:38 +00001413 printEscapedString(F->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001414 Out << "\", mod); " << (F->isExternal()? "// (external, no body)" : "");
1415 nl(Out,-1);
Reid Spencer12803f52006-05-31 17:31:38 +00001416 printCppName(F);
1417 Out << "->setCallingConv(";
1418 printCallingConv(F->getCallingConv());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001419 Out << ");";
1420 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001421 if (F->hasSection()) {
1422 printCppName(F);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001423 Out << "->setSection(\"" << F->getSection() << "\");";
1424 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001425 }
1426 if (F->getAlignment()) {
1427 printCppName(F);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001428 Out << "->setAlignment(" << F->getAlignment() << ");";
1429 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001430 }
Reid Spencerf977e7b2006-06-01 23:43:47 +00001431 if (is_inline) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001432 Out << "}";
1433 nl(Out);
Reid Spencerf977e7b2006-06-01 23:43:47 +00001434 }
Reid Spencer12803f52006-05-31 17:31:38 +00001435}
1436
1437void CppWriter::printFunctionBody(const Function *F) {
1438 if (F->isExternal())
1439 return; // external functions have no bodies.
1440
1441 // Clear the DefinedValues and ForwardRefs maps because we can't have
1442 // cross-function forward refs
1443 ForwardRefs.clear();
1444 DefinedValues.clear();
1445
1446 // Create all the argument values
Reid Spencerf977e7b2006-06-01 23:43:47 +00001447 if (!is_inline) {
1448 if (!F->arg_empty()) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001449 Out << "Function::arg_iterator args = " << getCppName(F)
1450 << "->arg_begin();";
1451 nl(Out);
Reid Spencerf977e7b2006-06-01 23:43:47 +00001452 }
1453 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1454 AI != AE; ++AI) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001455 Out << "Value* " << getCppName(AI) << " = args++;";
1456 nl(Out);
1457 if (AI->hasName()) {
1458 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1459 nl(Out);
1460 }
Reid Spencerf977e7b2006-06-01 23:43:47 +00001461 }
Reid Spencer12803f52006-05-31 17:31:38 +00001462 }
1463
1464 // Create all the basic blocks
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001465 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001466 for (Function::const_iterator BI = F->begin(), BE = F->end();
1467 BI != BE; ++BI) {
1468 std::string bbname(getCppName(BI));
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001469 Out << "BasicBlock* " << bbname << " = new BasicBlock(\"";
Reid Spencer12803f52006-05-31 17:31:38 +00001470 if (BI->hasName())
1471 printEscapedString(BI->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001472 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1473 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001474 }
1475
1476 // Output all of its basic blocks... for the function
1477 for (Function::const_iterator BI = F->begin(), BE = F->end();
1478 BI != BE; ++BI) {
1479 std::string bbname(getCppName(BI));
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001480 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1481 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001482
1483 // Output all of the instructions in the basic block...
1484 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1485 I != E; ++I) {
1486 printInstruction(I,bbname);
1487 }
1488 }
1489
1490 // Loop over the ForwardRefs and resolve them now that all instructions
1491 // are generated.
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001492 if (!ForwardRefs.empty()) {
1493 nl(Out) << "// Resolve Forward References";
1494 nl(Out);
1495 }
1496
Reid Spencer12803f52006-05-31 17:31:38 +00001497 while (!ForwardRefs.empty()) {
1498 ForwardRefMap::iterator I = ForwardRefs.begin();
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001499 Out << I->second << "->replaceAllUsesWith("
1500 << getCppName(I->first) << "); delete " << I->second << ";";
1501 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001502 ForwardRefs.erase(I);
1503 }
1504}
1505
Reid Spencerf977e7b2006-06-01 23:43:47 +00001506void CppWriter::printInline(const std::string& fname, const std::string& func) {
1507 const Function* F = TheModule->getNamedFunction(func);
1508 if (!F) {
1509 error(std::string("Function '") + func + "' not found in input module");
1510 return;
1511 }
1512 if (F->isExternal()) {
1513 error(std::string("Function '") + func + "' is external!");
1514 return;
1515 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001516 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
Reid Spencerf977e7b2006-06-01 23:43:47 +00001517 << getCppName(F);
1518 unsigned arg_count = 1;
1519 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1520 AI != AE; ++AI) {
1521 Out << ", Value* arg_" << arg_count;
1522 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001523 Out << ") {";
1524 nl(Out);
Reid Spencerf977e7b2006-06-01 23:43:47 +00001525 is_inline = true;
1526 printFunctionUses(F);
1527 printFunctionBody(F);
1528 is_inline = false;
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001529 Out << "return " << getCppName(F->begin()) << ";";
1530 nl(Out) << "}";
1531 nl(Out);
Reid Spencerf977e7b2006-06-01 23:43:47 +00001532}
1533
Reid Spencer12803f52006-05-31 17:31:38 +00001534void CppWriter::printModuleBody() {
1535 // Print out all the type definitions
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001536 nl(Out) << "// Type Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001537 printTypes(TheModule);
1538
1539 // Functions can call each other and global variables can reference them so
1540 // define all the functions first before emitting their function bodies.
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001541 nl(Out) << "// Function Declarations"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001542 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1543 I != E; ++I)
1544 printFunctionHead(I);
1545
1546 // Process the global variables declarations. We can't initialze them until
1547 // after the constants are printed so just print a header for each global
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001548 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001549 for (Module::const_global_iterator I = TheModule->global_begin(),
1550 E = TheModule->global_end(); I != E; ++I) {
1551 printVariableHead(I);
1552 }
1553
1554 // Print out all the constants definitions. Constants don't recurse except
1555 // through GlobalValues. All GlobalValues have been declared at this point
1556 // so we can proceed to generate the constants.
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001557 nl(Out) << "// Constant Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001558 printConstants(TheModule);
1559
1560 // Process the global variables definitions now that all the constants have
1561 // been emitted. These definitions just couple the gvars with their constant
1562 // initializers.
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001563 nl(Out) << "// Global Variable Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001564 for (Module::const_global_iterator I = TheModule->global_begin(),
1565 E = TheModule->global_end(); I != E; ++I) {
1566 printVariableBody(I);
1567 }
1568
1569 // Finally, we can safely put out all of the function bodies.
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001570 nl(Out) << "// Function Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001571 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1572 I != E; ++I) {
1573 if (!I->isExternal()) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001574 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1575 << ")";
1576 nl(Out) << "{";
1577 nl(Out,1);
Reid Spencer12803f52006-05-31 17:31:38 +00001578 printFunctionBody(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001579 nl(Out,-1) << "}";
1580 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001581 }
1582 }
1583}
1584
1585void CppWriter::printProgram(
1586 const std::string& fname,
1587 const std::string& mName
1588) {
1589 Out << "#include <llvm/Module.h>\n";
1590 Out << "#include <llvm/DerivedTypes.h>\n";
1591 Out << "#include <llvm/Constants.h>\n";
1592 Out << "#include <llvm/GlobalVariable.h>\n";
1593 Out << "#include <llvm/Function.h>\n";
1594 Out << "#include <llvm/CallingConv.h>\n";
1595 Out << "#include <llvm/BasicBlock.h>\n";
1596 Out << "#include <llvm/Instructions.h>\n";
1597 Out << "#include <llvm/InlineAsm.h>\n";
Reid Spencerf977e7b2006-06-01 23:43:47 +00001598 Out << "#include <llvm/Support/MathExtras.h>\n";
Reid Spencer12803f52006-05-31 17:31:38 +00001599 Out << "#include <llvm/Pass.h>\n";
1600 Out << "#include <llvm/PassManager.h>\n";
1601 Out << "#include <llvm/Analysis/Verifier.h>\n";
1602 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1603 Out << "#include <algorithm>\n";
1604 Out << "#include <iostream>\n\n";
1605 Out << "using namespace llvm;\n\n";
1606 Out << "Module* " << fname << "();\n\n";
1607 Out << "int main(int argc, char**argv) {\n";
1608 Out << " Module* Mod = makeLLVMModule();\n";
1609 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1610 Out << " std::cerr.flush();\n";
1611 Out << " std::cout.flush();\n";
1612 Out << " PassManager PM;\n";
1613 Out << " PM.add(new PrintModulePass(&std::cout));\n";
1614 Out << " PM.run(*Mod);\n";
1615 Out << " return 0;\n";
1616 Out << "}\n\n";
1617 printModule(fname,mName);
1618}
1619
1620void CppWriter::printModule(
1621 const std::string& fname,
1622 const std::string& mName
1623) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001624 nl(Out) << "Module* " << fname << "() {";
1625 nl(Out,1) << "// Module Construction";
1626 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1627 nl(Out) << "mod->setEndianness(";
Reid Spencer12803f52006-05-31 17:31:38 +00001628 switch (TheModule->getEndianness()) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001629 case Module::LittleEndian: Out << "Module::LittleEndian);"; break;
1630 case Module::BigEndian: Out << "Module::BigEndian);"; break;
1631 case Module::AnyEndianness:Out << "Module::AnyEndianness);"; break;
Reid Spencer12803f52006-05-31 17:31:38 +00001632 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001633 nl(Out) << "mod->setPointerSize(";
Reid Spencer12803f52006-05-31 17:31:38 +00001634 switch (TheModule->getPointerSize()) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001635 case Module::Pointer32: Out << "Module::Pointer32);"; break;
1636 case Module::Pointer64: Out << "Module::Pointer64);"; break;
1637 case Module::AnyPointerSize: Out << "Module::AnyPointerSize);"; break;
Reid Spencer12803f52006-05-31 17:31:38 +00001638 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001639 nl(Out);
1640 if (!TheModule->getTargetTriple().empty()) {
Reid Spencer12803f52006-05-31 17:31:38 +00001641 Out << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001642 << "\");";
1643 nl(Out);
1644 }
Reid Spencer12803f52006-05-31 17:31:38 +00001645
1646 if (!TheModule->getModuleInlineAsm().empty()) {
1647 Out << "mod->setModuleInlineAsm(\"";
1648 printEscapedString(TheModule->getModuleInlineAsm());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001649 Out << "\");";
1650 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001651 }
1652
1653 // Loop over the dependent libraries and emit them.
1654 Module::lib_iterator LI = TheModule->lib_begin();
1655 Module::lib_iterator LE = TheModule->lib_end();
1656 while (LI != LE) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001657 Out << "mod->addLibrary(\"" << *LI << "\");";
1658 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001659 ++LI;
1660 }
1661 printModuleBody();
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001662 nl(Out) << "return mod;";
1663 nl(Out,-1) << "}";
1664 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001665}
1666
1667void CppWriter::printContents(
1668 const std::string& fname, // Name of generated function
1669 const std::string& mName // Name of module generated module
1670) {
1671 Out << "\nModule* " << fname << "(Module *mod) {\n";
1672 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
Reid Spencer12803f52006-05-31 17:31:38 +00001673 printModuleBody();
1674 Out << "\nreturn mod;\n";
1675 Out << "\n}\n";
1676}
1677
1678void CppWriter::printFunction(
1679 const std::string& fname, // Name of generated function
1680 const std::string& funcName // Name of function to generate
1681) {
1682 const Function* F = TheModule->getNamedFunction(funcName);
1683 if (!F) {
1684 error(std::string("Function '") + funcName + "' not found in input module");
1685 return;
1686 }
1687 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1688 printFunctionUses(F);
1689 printFunctionHead(F);
1690 printFunctionBody(F);
1691 Out << "return " << getCppName(F) << ";\n";
1692 Out << "}\n";
1693}
1694
1695void CppWriter::printVariable(
1696 const std::string& fname, /// Name of generated function
1697 const std::string& varName // Name of variable to generate
1698) {
1699 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1700
1701 if (!GV) {
1702 error(std::string("Variable '") + varName + "' not found in input module");
1703 return;
1704 }
1705 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1706 printVariableUses(GV);
1707 printVariableHead(GV);
1708 printVariableBody(GV);
1709 Out << "return " << getCppName(GV) << ";\n";
1710 Out << "}\n";
1711}
1712
1713void CppWriter::printType(
1714 const std::string& fname, /// Name of generated function
1715 const std::string& typeName // Name of type to generate
1716) {
1717 const Type* Ty = TheModule->getTypeByName(typeName);
1718 if (!Ty) {
1719 error(std::string("Type '") + typeName + "' not found in input module");
1720 return;
1721 }
1722 Out << "\nType* " << fname << "(Module *mod) {\n";
1723 printType(Ty);
1724 Out << "return " << getCppName(Ty) << ";\n";
1725 Out << "}\n";
1726}
1727
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001728} // end anonymous llvm
1729
1730namespace llvm {
1731
1732void WriteModuleToCppFile(Module* mod, std::ostream& o) {
Reid Spencer12803f52006-05-31 17:31:38 +00001733 // Initialize a CppWriter for us to use
1734 CppWriter W(o, mod);
1735
1736 // Emit a header
Reid Spencer25edc352006-05-31 04:43:19 +00001737 o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
Reid Spencer12803f52006-05-31 17:31:38 +00001738
1739 // Get the name of the function we're supposed to generate
Reid Spencer15f7e012006-05-30 21:18:23 +00001740 std::string fname = FuncName.getValue();
Reid Spencer12803f52006-05-31 17:31:38 +00001741
1742 // Get the name of the thing we are to generate
1743 std::string tgtname = NameToGenerate.getValue();
1744 if (GenerationType == GenModule ||
1745 GenerationType == GenContents ||
1746 GenerationType == GenProgram) {
1747 if (tgtname == "!bad!") {
1748 if (mod->getModuleIdentifier() == "-")
1749 tgtname = "<stdin>";
1750 else
1751 tgtname = mod->getModuleIdentifier();
1752 }
1753 } else if (tgtname == "!bad!") {
1754 W.error("You must use the -for option with -gen-{function,variable,type}");
1755 }
1756
1757 switch (WhatToGenerate(GenerationType)) {
1758 case GenProgram:
1759 if (fname.empty())
1760 fname = "makeLLVMModule";
1761 W.printProgram(fname,tgtname);
1762 break;
1763 case GenModule:
1764 if (fname.empty())
1765 fname = "makeLLVMModule";
1766 W.printModule(fname,tgtname);
1767 break;
1768 case GenContents:
1769 if (fname.empty())
1770 fname = "makeLLVMModuleContents";
1771 W.printContents(fname,tgtname);
1772 break;
1773 case GenFunction:
1774 if (fname.empty())
1775 fname = "makeLLVMFunction";
1776 W.printFunction(fname,tgtname);
1777 break;
Reid Spencerf977e7b2006-06-01 23:43:47 +00001778 case GenInline:
1779 if (fname.empty())
1780 fname = "makeLLVMInline";
1781 W.printInline(fname,tgtname);
1782 break;
Reid Spencer12803f52006-05-31 17:31:38 +00001783 case GenVariable:
1784 if (fname.empty())
1785 fname = "makeLLVMVariable";
1786 W.printVariable(fname,tgtname);
1787 break;
1788 case GenType:
1789 if (fname.empty())
1790 fname = "makeLLVMType";
1791 W.printType(fname,tgtname);
1792 break;
1793 default:
1794 W.error("Invalid generation option");
Reid Spencer15f7e012006-05-30 21:18:23 +00001795 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001796}
1797
1798}