blob: b1f717d0bf526ce031f94066c1fefda6d4f50523 [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 Spencerf977e7b2006-06-01 23:43:47 +000028#include "llvm/Config/config.h"
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000029#include <algorithm>
30#include <iostream>
Reid Spencer66c87342006-05-30 03:43:49 +000031#include <set>
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000032
33using namespace llvm;
34
Reid Spencer15f7e012006-05-30 21:18:23 +000035static cl::opt<std::string>
Reid Spencer15f7e012006-05-30 21:18:23 +000036FuncName("funcname", cl::desc("Specify the name of the generated function"),
37 cl::value_desc("function name"));
38
Reid Spencer12803f52006-05-31 17:31:38 +000039enum WhatToGenerate {
40 GenProgram,
41 GenModule,
42 GenContents,
43 GenFunction,
Reid Spencerf977e7b2006-06-01 23:43:47 +000044 GenInline,
Reid Spencer12803f52006-05-31 17:31:38 +000045 GenVariable,
46 GenType
47};
48
49static cl::opt<WhatToGenerate> GenerationType(cl::Optional,
50 cl::desc("Choose what kind of output to generate"),
51 cl::init(GenProgram),
52 cl::values(
53 clEnumValN(GenProgram, "gen-program", "Generate a complete program"),
54 clEnumValN(GenModule, "gen-module", "Generate a module definition"),
55 clEnumValN(GenContents,"gen-contents", "Generate contents of a module"),
56 clEnumValN(GenFunction,"gen-function", "Generate a function definition"),
Reid Spencerf977e7b2006-06-01 23:43:47 +000057 clEnumValN(GenInline, "gen-inline", "Generate an inline function"),
Reid Spencer12803f52006-05-31 17:31:38 +000058 clEnumValN(GenVariable,"gen-variable", "Generate a variable definition"),
59 clEnumValN(GenType, "gen-type", "Generate a type definition"),
60 clEnumValEnd
61 )
62);
63
64static cl::opt<std::string> NameToGenerate("for", cl::Optional,
65 cl::desc("Specify the name of the thing to generate"),
66 cl::init("!bad!"));
Reid Spencer15f7e012006-05-30 21:18:23 +000067
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000068namespace {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000069typedef std::vector<const Type*> TypeList;
70typedef std::map<const Type*,std::string> TypeMap;
71typedef std::map<const Value*,std::string> ValueMap;
Reid Spencer66c87342006-05-30 03:43:49 +000072typedef std::set<std::string> NameSet;
Reid Spencer15f7e012006-05-30 21:18:23 +000073typedef std::set<const Type*> TypeSet;
74typedef std::set<const Value*> ValueSet;
75typedef std::map<const Value*,std::string> ForwardRefMap;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000076
Reid Spencere0d133f2006-05-29 18:08:06 +000077class CppWriter {
Reid Spencer12803f52006-05-31 17:31:38 +000078 const char* progname;
Reid Spencere0d133f2006-05-29 18:08:06 +000079 std::ostream &Out;
80 const Module *TheModule;
Andrew Lenharth539d8712006-05-31 20:18:56 +000081 uint64_t uniqueNum;
Reid Spencere0d133f2006-05-29 18:08:06 +000082 TypeMap TypeNames;
83 ValueMap ValueNames;
84 TypeMap UnresolvedTypes;
85 TypeList TypeStack;
Reid Spencer66c87342006-05-30 03:43:49 +000086 NameSet UsedNames;
Reid Spencer15f7e012006-05-30 21:18:23 +000087 TypeSet DefinedTypes;
88 ValueSet DefinedValues;
89 ForwardRefMap ForwardRefs;
Reid Spencerf977e7b2006-06-01 23:43:47 +000090 bool is_inline;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000091
Reid Spencere0d133f2006-05-29 18:08:06 +000092public:
Reid Spencer12803f52006-05-31 17:31:38 +000093 inline CppWriter(std::ostream &o, const Module *M, const char* pn="llvm2cpp")
94 : progname(pn), Out(o), TheModule(M), uniqueNum(0), TypeNames(),
Reid Spencerf977e7b2006-06-01 23:43:47 +000095 ValueNames(), UnresolvedTypes(), TypeStack(), is_inline(false) { }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000096
Reid Spencere0d133f2006-05-29 18:08:06 +000097 const Module* getModule() { return TheModule; }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000098
Reid Spencer12803f52006-05-31 17:31:38 +000099 void printProgram(const std::string& fname, const std::string& modName );
100 void printModule(const std::string& fname, const std::string& modName );
101 void printContents(const std::string& fname, const std::string& modName );
102 void printFunction(const std::string& fname, const std::string& funcName );
Reid Spencerf977e7b2006-06-01 23:43:47 +0000103 void printInline(const std::string& fname, const std::string& funcName );
Reid Spencer12803f52006-05-31 17:31:38 +0000104 void printVariable(const std::string& fname, const std::string& varName );
105 void printType(const std::string& fname, const std::string& typeName );
106
107 void error(const std::string& msg);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000108
Reid Spencere0d133f2006-05-29 18:08:06 +0000109private:
Reid Spencer12803f52006-05-31 17:31:38 +0000110 void printLinkageType(GlobalValue::LinkageTypes LT);
111 void printCallingConv(unsigned cc);
112 void printEscapedString(const std::string& str);
113 void printCFP(const ConstantFP* CFP);
114
115 std::string getCppName(const Type* val);
116 inline void printCppName(const Type* val);
117
118 std::string getCppName(const Value* val);
119 inline void printCppName(const Value* val);
120
121 bool printTypeInternal(const Type* Ty);
122 inline void printType(const Type* Ty);
Reid Spencere0d133f2006-05-29 18:08:06 +0000123 void printTypes(const Module* M);
Reid Spencer12803f52006-05-31 17:31:38 +0000124
Reid Spencere0d133f2006-05-29 18:08:06 +0000125 void printConstant(const Constant *CPV);
Reid Spencer12803f52006-05-31 17:31:38 +0000126 void printConstants(const Module* M);
127
128 void printVariableUses(const GlobalVariable *GV);
129 void printVariableHead(const GlobalVariable *GV);
130 void printVariableBody(const GlobalVariable *GV);
131
132 void printFunctionUses(const Function *F);
Reid Spencer66c87342006-05-30 03:43:49 +0000133 void printFunctionHead(const Function *F);
134 void printFunctionBody(const Function *F);
Reid Spencere0d133f2006-05-29 18:08:06 +0000135 void printInstruction(const Instruction *I, const std::string& bbname);
Reid Spencer15f7e012006-05-30 21:18:23 +0000136 std::string getOpName(Value*);
137
Reid Spencer12803f52006-05-31 17:31:38 +0000138 void printModuleBody();
139
Reid Spencere0d133f2006-05-29 18:08:06 +0000140};
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000141
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000142static unsigned indent_level = 0;
143inline std::ostream& nl(std::ostream& Out, int delta = 0) {
144 Out << "\n";
145 if (delta >= 0 || indent_level >= unsigned(-delta))
146 indent_level += delta;
147 for (unsigned i = 0; i < indent_level; ++i)
148 Out << " ";
149 return Out;
150}
151
152inline void in() { indent_level++; }
153inline void out() { if (indent_level >0) indent_level--; }
154
Reid Spencer12803f52006-05-31 17:31:38 +0000155inline void
156sanitize(std::string& str) {
157 for (size_t i = 0; i < str.length(); ++i)
158 if (!isalnum(str[i]) && str[i] != '_')
159 str[i] = '_';
160}
161
162inline const char*
163getTypePrefix(const Type* Ty ) {
164 const char* prefix;
165 switch (Ty->getTypeID()) {
166 case Type::VoidTyID: prefix = "void_"; break;
167 case Type::BoolTyID: prefix = "bool_"; break;
168 case Type::UByteTyID: prefix = "ubyte_"; break;
169 case Type::SByteTyID: prefix = "sbyte_"; break;
170 case Type::UShortTyID: prefix = "ushort_"; break;
171 case Type::ShortTyID: prefix = "short_"; break;
172 case Type::UIntTyID: prefix = "uint_"; break;
173 case Type::IntTyID: prefix = "int_"; break;
174 case Type::ULongTyID: prefix = "ulong_"; break;
175 case Type::LongTyID: prefix = "long_"; break;
176 case Type::FloatTyID: prefix = "float_"; break;
177 case Type::DoubleTyID: prefix = "double_"; break;
178 case Type::LabelTyID: prefix = "label_"; break;
179 case Type::FunctionTyID: prefix = "func_"; break;
180 case Type::StructTyID: prefix = "struct_"; break;
181 case Type::ArrayTyID: prefix = "array_"; break;
182 case Type::PointerTyID: prefix = "ptr_"; break;
183 case Type::PackedTyID: prefix = "packed_"; break;
184 case Type::OpaqueTyID: prefix = "opaque_"; break;
185 default: prefix = "other_"; break;
186 }
187 return prefix;
188}
189
190// Looks up the type in the symbol table and returns a pointer to its name or
191// a null pointer if it wasn't found. Note that this isn't the same as the
192// Mode::getTypeName function which will return an empty string, not a null
193// pointer if the name is not found.
194inline const std::string*
195findTypeName(const SymbolTable& ST, const Type* Ty)
196{
197 SymbolTable::type_const_iterator TI = ST.type_begin();
198 SymbolTable::type_const_iterator TE = ST.type_end();
199 for (;TI != TE; ++TI)
200 if (TI->second == Ty)
201 return &(TI->first);
202 return 0;
203}
204
205void
206CppWriter::error(const std::string& msg) {
207 std::cerr << progname << ": " << msg << "\n";
208 exit(2);
209}
210
Reid Spencer15f7e012006-05-30 21:18:23 +0000211// printCFP - Print a floating point constant .. very carefully :)
212// This makes sure that conversion to/from floating yields the same binary
213// result so that we don't lose precision.
214void
215CppWriter::printCFP(const ConstantFP *CFP) {
Reid Spencerf977e7b2006-06-01 23:43:47 +0000216 Out << "ConstantFP::get(";
217 if (CFP->getType() == Type::DoubleTy)
218 Out << "Type::DoubleTy, ";
219 else
220 Out << "Type::FloatTy, ";
Reid Spencer15f7e012006-05-30 21:18:23 +0000221#if HAVE_PRINTF_A
222 char Buffer[100];
223 sprintf(Buffer, "%A", CFP->getValue());
224 if ((!strncmp(Buffer, "0x", 2) ||
225 !strncmp(Buffer, "-0x", 3) ||
226 !strncmp(Buffer, "+0x", 3)) &&
227 (atof(Buffer) == CFP->getValue()))
Reid Spencerf977e7b2006-06-01 23:43:47 +0000228 if (CFP->getType() == Type::DoubleTy)
229 Out << "BitsToDouble(" << Buffer << ")";
230 else
231 Out << "BitsToFloat(" << Buffer << ")";
Reid Spencer15f7e012006-05-30 21:18:23 +0000232 else {
Reid Spencer15f7e012006-05-30 21:18:23 +0000233#endif
Reid Spencerf977e7b2006-06-01 23:43:47 +0000234 std::string StrVal = ftostr(CFP->getValue());
235
236 while (StrVal[0] == ' ')
237 StrVal.erase(StrVal.begin());
238
239 // Check to make sure that the stringized number is not some string like
240 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
241 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
242 ((StrVal[0] == '-' || StrVal[0] == '+') &&
243 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
244 (atof(StrVal.c_str()) == CFP->getValue()))
245 if (CFP->getType() == Type::DoubleTy)
246 Out << StrVal;
247 else
248 Out << StrVal;
249 else if (CFP->getType() == Type::DoubleTy)
250 Out << "BitsToDouble(0x" << std::hex << DoubleToBits(CFP->getValue())
251 << std::dec << "ULL) /* " << StrVal << " */";
252 else
253 Out << "BitsToFloat(0x" << std::hex << FloatToBits(CFP->getValue())
254 << std::dec << "U) /* " << StrVal << " */";
Reid Spencer15f7e012006-05-30 21:18:23 +0000255#if HAVE_PRINTF_A
256 }
257#endif
Reid Spencerf977e7b2006-06-01 23:43:47 +0000258 Out << ")";
Reid Spencer15f7e012006-05-30 21:18:23 +0000259}
260
Reid Spencer12803f52006-05-31 17:31:38 +0000261void
262CppWriter::printCallingConv(unsigned cc){
263 // Print the calling convention.
264 switch (cc) {
265 case CallingConv::C: Out << "CallingConv::C"; break;
266 case CallingConv::CSRet: Out << "CallingConv::CSRet"; break;
267 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
268 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
269 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
270 default: Out << cc; break;
271 }
272}
Reid Spencer15f7e012006-05-30 21:18:23 +0000273
Reid Spencer12803f52006-05-31 17:31:38 +0000274void
275CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
276 switch (LT) {
277 case GlobalValue::InternalLinkage:
278 Out << "GlobalValue::InternalLinkage"; break;
279 case GlobalValue::LinkOnceLinkage:
280 Out << "GlobalValue::LinkOnceLinkage "; break;
281 case GlobalValue::WeakLinkage:
282 Out << "GlobalValue::WeakLinkage"; break;
283 case GlobalValue::AppendingLinkage:
284 Out << "GlobalValue::AppendingLinkage"; break;
285 case GlobalValue::ExternalLinkage:
286 Out << "GlobalValue::ExternalLinkage"; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000287 case GlobalValue::DLLImportLinkage:
288 Out << "GlobalValue::DllImportLinkage"; break;
289 case GlobalValue::DLLExportLinkage:
290 Out << "GlobalValue::DllExportLinkage"; break;
291 case GlobalValue::ExternalWeakLinkage:
292 Out << "GlobalValue::ExternalWeakLinkage"; break;
Reid Spencer12803f52006-05-31 17:31:38 +0000293 case GlobalValue::GhostLinkage:
294 Out << "GlobalValue::GhostLinkage"; break;
295 }
Reid Spencer15f7e012006-05-30 21:18:23 +0000296}
297
Reid Spencere0d133f2006-05-29 18:08:06 +0000298// printEscapedString - Print each character of the specified string, escaping
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000299// it if it is not printable or if it is an escape char.
Reid Spencere0d133f2006-05-29 18:08:06 +0000300void
301CppWriter::printEscapedString(const std::string &Str) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000302 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
303 unsigned char C = Str[i];
304 if (isprint(C) && C != '"' && C != '\\') {
305 Out << C;
306 } else {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000307 Out << "\\x"
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000308 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
309 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
310 }
311 }
312}
313
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000314std::string
315CppWriter::getCppName(const Type* Ty)
316{
317 // First, handle the primitive types .. easy
318 if (Ty->isPrimitiveType()) {
319 switch (Ty->getTypeID()) {
320 case Type::VoidTyID: return "Type::VoidTy";
321 case Type::BoolTyID: return "Type::BoolTy";
322 case Type::UByteTyID: return "Type::UByteTy";
323 case Type::SByteTyID: return "Type::SByteTy";
324 case Type::UShortTyID: return "Type::UShortTy";
325 case Type::ShortTyID: return "Type::ShortTy";
326 case Type::UIntTyID: return "Type::UIntTy";
327 case Type::IntTyID: return "Type::IntTy";
328 case Type::ULongTyID: return "Type::ULongTy";
329 case Type::LongTyID: return "Type::LongTy";
330 case Type::FloatTyID: return "Type::FloatTy";
331 case Type::DoubleTyID: return "Type::DoubleTy";
332 case Type::LabelTyID: return "Type::LabelTy";
333 default:
Reid Spencer12803f52006-05-31 17:31:38 +0000334 error("Invalid primitive type");
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000335 break;
336 }
337 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
338 }
339
340 // Now, see if we've seen the type before and return that
341 TypeMap::iterator I = TypeNames.find(Ty);
342 if (I != TypeNames.end())
343 return I->second;
344
345 // Okay, let's build a new name for this type. Start with a prefix
346 const char* prefix = 0;
347 switch (Ty->getTypeID()) {
348 case Type::FunctionTyID: prefix = "FuncTy_"; break;
349 case Type::StructTyID: prefix = "StructTy_"; break;
350 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
351 case Type::PointerTyID: prefix = "PointerTy_"; break;
352 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
353 case Type::PackedTyID: prefix = "PackedTy_"; break;
354 default: prefix = "OtherTy_"; break; // prevent breakage
355 }
356
357 // See if the type has a name in the symboltable and build accordingly
358 const std::string* tName = findTypeName(TheModule->getSymbolTable(), Ty);
359 std::string name;
360 if (tName)
361 name = std::string(prefix) + *tName;
362 else
363 name = std::string(prefix) + utostr(uniqueNum++);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000364 sanitize(name);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000365
366 // Save the name
367 return TypeNames[Ty] = name;
368}
369
Reid Spencer12803f52006-05-31 17:31:38 +0000370void
371CppWriter::printCppName(const Type* Ty)
372{
373 printEscapedString(getCppName(Ty));
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000374}
375
Reid Spencer12803f52006-05-31 17:31:38 +0000376std::string
377CppWriter::getCppName(const Value* val) {
378 std::string name;
379 ValueMap::iterator I = ValueNames.find(val);
380 if (I != ValueNames.end() && I->first == val)
381 return I->second;
Reid Spencer25edc352006-05-31 04:43:19 +0000382
Reid Spencer12803f52006-05-31 17:31:38 +0000383 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
384 name = std::string("gvar_") +
385 getTypePrefix(GV->getType()->getElementType());
Reid Spencer3ed469c2006-11-02 20:25:50 +0000386 } else if (isa<Function>(val)) {
Reid Spencer12803f52006-05-31 17:31:38 +0000387 name = std::string("func_");
388 } else if (const Constant* C = dyn_cast<Constant>(val)) {
389 name = std::string("const_") + getTypePrefix(C->getType());
Reid Spencerf977e7b2006-06-01 23:43:47 +0000390 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
391 if (is_inline) {
392 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
393 Function::const_arg_iterator(Arg)) + 1;
394 name = std::string("arg_") + utostr(argNum);
395 NameSet::iterator NI = UsedNames.find(name);
396 if (NI != UsedNames.end())
397 name += std::string("_") + utostr(uniqueNum++);
398 UsedNames.insert(name);
399 return ValueNames[val] = name;
400 } else {
401 name = getTypePrefix(val->getType());
402 }
Reid Spencer12803f52006-05-31 17:31:38 +0000403 } else {
404 name = getTypePrefix(val->getType());
Reid Spencer25edc352006-05-31 04:43:19 +0000405 }
Reid Spencer12803f52006-05-31 17:31:38 +0000406 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
407 sanitize(name);
408 NameSet::iterator NI = UsedNames.find(name);
409 if (NI != UsedNames.end())
410 name += std::string("_") + utostr(uniqueNum++);
411 UsedNames.insert(name);
412 return ValueNames[val] = name;
Reid Spencer25edc352006-05-31 04:43:19 +0000413}
414
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000415void
Reid Spencer12803f52006-05-31 17:31:38 +0000416CppWriter::printCppName(const Value* val) {
417 printEscapedString(getCppName(val));
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000418}
419
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000420bool
Reid Spencer12803f52006-05-31 17:31:38 +0000421CppWriter::printTypeInternal(const Type* Ty) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000422 // We don't print definitions for primitive types
423 if (Ty->isPrimitiveType())
424 return false;
425
Reid Spencer15f7e012006-05-30 21:18:23 +0000426 // If we already defined this type, we don't need to define it again.
427 if (DefinedTypes.find(Ty) != DefinedTypes.end())
428 return false;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000429
Reid Spencer15f7e012006-05-30 21:18:23 +0000430 // Everything below needs the name for the type so get it now.
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000431 std::string typeName(getCppName(Ty));
432
433 // Search the type stack for recursion. If we find it, then generate this
434 // as an OpaqueType, but make sure not to do this multiple times because
435 // the type could appear in multiple places on the stack. Once the opaque
Reid Spencer15f7e012006-05-30 21:18:23 +0000436 // definition is issued, it must not be re-issued. Consequently we have to
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000437 // check the UnresolvedTypes list as well.
Reid Spencer12803f52006-05-31 17:31:38 +0000438 TypeList::const_iterator TI = std::find(TypeStack.begin(),TypeStack.end(),Ty);
439 if (TI != TypeStack.end()) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000440 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
441 if (I == UnresolvedTypes.end()) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000442 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
443 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000444 UnresolvedTypes[Ty] = typeName;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000445 }
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000446 return true;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000447 }
448
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000449 // We're going to print a derived type which, by definition, contains other
450 // types. So, push this one we're printing onto the type stack to assist with
451 // recursive definitions.
Reid Spencer15f7e012006-05-30 21:18:23 +0000452 TypeStack.push_back(Ty);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000453
454 // Print the type definition
455 switch (Ty->getTypeID()) {
456 case Type::FunctionTyID: {
457 const FunctionType* FT = cast<FunctionType>(Ty);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000458 Out << "std::vector<const Type*>" << typeName << "_args;";
459 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000460 FunctionType::param_iterator PI = FT->param_begin();
461 FunctionType::param_iterator PE = FT->param_end();
462 for (; PI != PE; ++PI) {
463 const Type* argTy = static_cast<const Type*>(*PI);
Reid Spencer12803f52006-05-31 17:31:38 +0000464 bool isForward = printTypeInternal(argTy);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000465 std::string argName(getCppName(argTy));
466 Out << typeName << "_args.push_back(" << argName;
467 if (isForward)
468 Out << "_fwd";
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000469 Out << ");";
470 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000471 }
Reid Spencer12803f52006-05-31 17:31:38 +0000472 bool isForward = printTypeInternal(FT->getReturnType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000473 std::string retTypeName(getCppName(FT->getReturnType()));
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000474 Out << "FunctionType* " << typeName << " = FunctionType::get(";
475 in(); nl(Out) << "/*Result=*/" << retTypeName;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000476 if (isForward)
477 Out << "_fwd";
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000478 Out << ",";
479 nl(Out) << "/*Params=*/" << typeName << "_args,";
480 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
481 out();
482 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000483 break;
484 }
485 case Type::StructTyID: {
486 const StructType* ST = cast<StructType>(Ty);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000487 Out << "std::vector<const Type*>" << typeName << "_fields;";
488 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000489 StructType::element_iterator EI = ST->element_begin();
490 StructType::element_iterator EE = ST->element_end();
491 for (; EI != EE; ++EI) {
492 const Type* fieldTy = static_cast<const Type*>(*EI);
Reid Spencer12803f52006-05-31 17:31:38 +0000493 bool isForward = printTypeInternal(fieldTy);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000494 std::string fieldName(getCppName(fieldTy));
495 Out << typeName << "_fields.push_back(" << fieldName;
496 if (isForward)
497 Out << "_fwd";
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000498 Out << ");";
499 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000500 }
501 Out << "StructType* " << typeName << " = StructType::get("
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000502 << typeName << "_fields);";
503 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000504 break;
505 }
506 case Type::ArrayTyID: {
507 const ArrayType* AT = cast<ArrayType>(Ty);
508 const Type* ET = AT->getElementType();
Reid Spencer12803f52006-05-31 17:31:38 +0000509 bool isForward = printTypeInternal(ET);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000510 std::string elemName(getCppName(ET));
511 Out << "ArrayType* " << typeName << " = ArrayType::get("
512 << elemName << (isForward ? "_fwd" : "")
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000513 << ", " << utostr(AT->getNumElements()) << ");";
514 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000515 break;
516 }
517 case Type::PointerTyID: {
518 const PointerType* PT = cast<PointerType>(Ty);
519 const Type* ET = PT->getElementType();
Reid Spencer12803f52006-05-31 17:31:38 +0000520 bool isForward = printTypeInternal(ET);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000521 std::string elemName(getCppName(ET));
522 Out << "PointerType* " << typeName << " = PointerType::get("
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000523 << elemName << (isForward ? "_fwd" : "") << ");";
524 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000525 break;
526 }
527 case Type::PackedTyID: {
528 const PackedType* PT = cast<PackedType>(Ty);
529 const Type* ET = PT->getElementType();
Reid Spencer12803f52006-05-31 17:31:38 +0000530 bool isForward = printTypeInternal(ET);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000531 std::string elemName(getCppName(ET));
532 Out << "PackedType* " << typeName << " = PackedType::get("
533 << elemName << (isForward ? "_fwd" : "")
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000534 << ", " << utostr(PT->getNumElements()) << ");";
535 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000536 break;
537 }
538 case Type::OpaqueTyID: {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000539 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
540 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000541 break;
542 }
543 default:
Reid Spencer12803f52006-05-31 17:31:38 +0000544 error("Invalid TypeID");
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000545 }
546
Reid Spencer74e032a2006-05-29 02:58:15 +0000547 // If the type had a name, make sure we recreate it.
548 const std::string* progTypeName =
549 findTypeName(TheModule->getSymbolTable(),Ty);
550 if (progTypeName)
551 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000552 << typeName << ");";
553 nl(Out);
Reid Spencer74e032a2006-05-29 02:58:15 +0000554
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000555 // Pop us off the type stack
556 TypeStack.pop_back();
Reid Spencer15f7e012006-05-30 21:18:23 +0000557
558 // Indicate that this type is now defined.
559 DefinedTypes.insert(Ty);
560
561 // Early resolve as many unresolved types as possible. Search the unresolved
562 // types map for the type we just printed. Now that its definition is complete
563 // we can resolve any previous references to it. This prevents a cascade of
564 // unresolved types.
565 TypeMap::iterator I = UnresolvedTypes.find(Ty);
566 if (I != UnresolvedTypes.end()) {
567 Out << "cast<OpaqueType>(" << I->second
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000568 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
569 nl(Out);
Reid Spencer15f7e012006-05-30 21:18:23 +0000570 Out << I->second << " = cast<";
571 switch (Ty->getTypeID()) {
572 case Type::FunctionTyID: Out << "FunctionType"; break;
573 case Type::ArrayTyID: Out << "ArrayType"; break;
574 case Type::StructTyID: Out << "StructType"; break;
575 case Type::PackedTyID: Out << "PackedType"; break;
576 case Type::PointerTyID: Out << "PointerType"; break;
577 case Type::OpaqueTyID: Out << "OpaqueType"; break;
578 default: Out << "NoSuchDerivedType"; break;
579 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000580 Out << ">(" << I->second << "_fwd.get());";
581 nl(Out); nl(Out);
Reid Spencer15f7e012006-05-30 21:18:23 +0000582 UnresolvedTypes.erase(I);
583 }
584
585 // Finally, separate the type definition from other with a newline.
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000586 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000587
588 // We weren't a recursive type
589 return false;
590}
591
Reid Spencer12803f52006-05-31 17:31:38 +0000592// Prints a type definition. Returns true if it could not resolve all the types
593// in the definition but had to use a forward reference.
594void
595CppWriter::printType(const Type* Ty) {
596 assert(TypeStack.empty());
597 TypeStack.clear();
598 printTypeInternal(Ty);
599 assert(TypeStack.empty());
600}
601
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000602void
603CppWriter::printTypes(const Module* M) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000604
605 // Walk the symbol table and print out all its types
606 const SymbolTable& symtab = M->getSymbolTable();
607 for (SymbolTable::type_const_iterator TI = symtab.type_begin(),
608 TE = symtab.type_end(); TI != TE; ++TI) {
609
610 // For primitive types and types already defined, just add a name
611 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
612 if (TI->second->isPrimitiveType() || TNI != TypeNames.end()) {
613 Out << "mod->addTypeName(\"";
614 printEscapedString(TI->first);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000615 Out << "\", " << getCppName(TI->second) << ");";
616 nl(Out);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000617 // For everything else, define the type
618 } else {
Reid Spencer12803f52006-05-31 17:31:38 +0000619 printType(TI->second);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000620 }
621 }
622
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000623 // Add all of the global variables to the value table...
624 for (Module::const_global_iterator I = TheModule->global_begin(),
625 E = TheModule->global_end(); I != E; ++I) {
626 if (I->hasInitializer())
Reid Spencer12803f52006-05-31 17:31:38 +0000627 printType(I->getInitializer()->getType());
628 printType(I->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000629 }
630
631 // Add all the functions to the table
632 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
633 FI != FE; ++FI) {
Reid Spencer12803f52006-05-31 17:31:38 +0000634 printType(FI->getReturnType());
635 printType(FI->getFunctionType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000636 // Add all the function arguments
637 for(Function::const_arg_iterator AI = FI->arg_begin(),
638 AE = FI->arg_end(); AI != AE; ++AI) {
Reid Spencer12803f52006-05-31 17:31:38 +0000639 printType(AI->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000640 }
641
642 // Add all of the basic blocks and instructions
643 for (Function::const_iterator BB = FI->begin(),
644 E = FI->end(); BB != E; ++BB) {
Reid Spencer12803f52006-05-31 17:31:38 +0000645 printType(BB->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000646 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
647 ++I) {
Reid Spencer12803f52006-05-31 17:31:38 +0000648 printType(I->getType());
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000649 for (unsigned i = 0; i < I->getNumOperands(); ++i)
Reid Spencer12803f52006-05-31 17:31:38 +0000650 printType(I->getOperand(i)->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000651 }
652 }
653 }
654}
655
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000656
Reid Spencere0d133f2006-05-29 18:08:06 +0000657// printConstant - Print out a constant pool entry...
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000658void CppWriter::printConstant(const Constant *CV) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000659 // First, if the constant is actually a GlobalValue (variable or function) or
660 // its already in the constant list then we've printed it already and we can
661 // just return.
662 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
Reid Spencere0d133f2006-05-29 18:08:06 +0000663 return;
664
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000665 std::string constName(getCppName(CV));
666 std::string typeName(getCppName(CV->getType()));
667 if (CV->isNullValue()) {
668 Out << "Constant* " << constName << " = Constant::getNullValue("
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000669 << typeName << ");";
670 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000671 return;
672 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000673 if (isa<GlobalValue>(CV)) {
674 // Skip variables and functions, we emit them elsewhere
675 return;
676 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000677 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000678 Out << "ConstantBool* " << constName << " = ConstantBool::get("
Chris Lattnere354df92006-09-28 23:24:48 +0000679 << (CB->getValue() ? "true" : "false") << ");";
Reid Spencerb83eb642006-10-20 07:07:24 +0000680 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
681 Out << "ConstantInt* " << constName << " = ConstantInt::get("
682 << typeName << ", "
683 << (CV->getType()->isSigned() ? CI->getSExtValue() : CI->getZExtValue())
684 << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000685 } else if (isa<ConstantAggregateZero>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000686 Out << "ConstantAggregateZero* " << constName
687 << " = ConstantAggregateZero::get(" << typeName << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000688 } else if (isa<ConstantPointerNull>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000689 Out << "ConstantPointerNull* " << constName
690 << " = ConstanPointerNull::get(" << typeName << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000691 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
Reid Spencerf977e7b2006-06-01 23:43:47 +0000692 Out << "ConstantFP* " << constName << " = ";
Reid Spencer12803f52006-05-31 17:31:38 +0000693 printCFP(CFP);
Reid Spencerf977e7b2006-06-01 23:43:47 +0000694 Out << ";";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000695 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000696 if (CA->isString() && CA->getType()->getElementType() == Type::SByteTy) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000697 Out << "Constant* " << constName << " = ConstantArray::get(\"";
Reid Spencere0d133f2006-05-29 18:08:06 +0000698 printEscapedString(CA->getAsString());
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000699 // Determine if we want null termination or not.
700 if (CA->getType()->getNumElements() <= CA->getAsString().length())
Reid Spencer15f7e012006-05-30 21:18:23 +0000701 Out << "\", false";// No null terminator
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000702 else
Reid Spencer15f7e012006-05-30 21:18:23 +0000703 Out << "\", true"; // Indicate that the null terminator should be added.
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000704 Out << ");";
705 } else {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000706 Out << "std::vector<Constant*> " << constName << "_elems;";
707 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000708 unsigned N = CA->getNumOperands();
709 for (unsigned i = 0; i < N; ++i) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000710 printConstant(CA->getOperand(i)); // recurse to print operands
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000711 Out << constName << "_elems.push_back("
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000712 << getCppName(CA->getOperand(i)) << ");";
713 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000714 }
715 Out << "Constant* " << constName << " = ConstantArray::get("
716 << typeName << ", " << constName << "_elems);";
717 }
718 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000719 Out << "std::vector<Constant*> " << constName << "_fields;";
720 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000721 unsigned N = CS->getNumOperands();
722 for (unsigned i = 0; i < N; i++) {
723 printConstant(CS->getOperand(i));
724 Out << constName << "_fields.push_back("
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000725 << getCppName(CS->getOperand(i)) << ");";
726 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000727 }
728 Out << "Constant* " << constName << " = ConstantStruct::get("
729 << typeName << ", " << constName << "_fields);";
730 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000731 Out << "std::vector<Constant*> " << constName << "_elems;";
732 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000733 unsigned N = CP->getNumOperands();
734 for (unsigned i = 0; i < N; ++i) {
735 printConstant(CP->getOperand(i));
736 Out << constName << "_elems.push_back("
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000737 << getCppName(CP->getOperand(i)) << ");";
738 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000739 }
740 Out << "Constant* " << constName << " = ConstantPacked::get("
741 << typeName << ", " << constName << "_elems);";
742 } else if (isa<UndefValue>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000743 Out << "UndefValue* " << constName << " = UndefValue::get("
Reid Spencere0d133f2006-05-29 18:08:06 +0000744 << typeName << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000745 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000746 if (CE->getOpcode() == Instruction::GetElementPtr) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000747 Out << "std::vector<Constant*> " << constName << "_indices;";
748 nl(Out);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000749 printConstant(CE->getOperand(0));
Reid Spencere0d133f2006-05-29 18:08:06 +0000750 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000751 printConstant(CE->getOperand(i));
Reid Spencere0d133f2006-05-29 18:08:06 +0000752 Out << constName << "_indices.push_back("
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000753 << getCppName(CE->getOperand(i)) << ");";
754 nl(Out);
Reid Spencere0d133f2006-05-29 18:08:06 +0000755 }
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000756 Out << "Constant* " << constName
757 << " = ConstantExpr::getGetElementPtr("
758 << getCppName(CE->getOperand(0)) << ", "
759 << constName << "_indices);";
Reid Spencer3da59db2006-11-27 01:05:10 +0000760 } else if (CE->isCast()) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000761 printConstant(CE->getOperand(0));
Reid Spencere0d133f2006-05-29 18:08:06 +0000762 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
763 Out << getCppName(CE->getOperand(0)) << ", " << getCppName(CE->getType())
764 << ");";
765 } else {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000766 unsigned N = CE->getNumOperands();
767 for (unsigned i = 0; i < N; ++i ) {
768 printConstant(CE->getOperand(i));
769 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000770 Out << "Constant* " << constName << " = ConstantExpr::";
771 switch (CE->getOpcode()) {
772 case Instruction::Add: Out << "getAdd"; break;
773 case Instruction::Sub: Out << "getSub"; break;
774 case Instruction::Mul: Out << "getMul"; break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000775 case Instruction::UDiv: Out << "getUDiv"; break;
776 case Instruction::SDiv: Out << "getSDiv"; break;
777 case Instruction::FDiv: Out << "getFDiv"; break;
Reid Spencer0a783f72006-11-02 01:53:59 +0000778 case Instruction::URem: Out << "getURem"; break;
779 case Instruction::SRem: Out << "getSRem"; break;
780 case Instruction::FRem: Out << "getFRem"; break;
Reid Spencere0d133f2006-05-29 18:08:06 +0000781 case Instruction::And: Out << "getAnd"; break;
782 case Instruction::Or: Out << "getOr"; break;
783 case Instruction::Xor: Out << "getXor"; break;
784 case Instruction::SetEQ: Out << "getSetEQ"; break;
785 case Instruction::SetNE: Out << "getSetNE"; break;
786 case Instruction::SetLE: Out << "getSetLE"; break;
787 case Instruction::SetGE: Out << "getSetGE"; break;
788 case Instruction::SetLT: Out << "getSetLT"; break;
789 case Instruction::SetGT: Out << "getSetGT"; break;
790 case Instruction::Shl: Out << "getShl"; break;
Reid Spencer3822ff52006-11-08 06:47:33 +0000791 case Instruction::LShr: Out << "getLShr"; break;
792 case Instruction::AShr: Out << "getAShr"; break;
Reid Spencere0d133f2006-05-29 18:08:06 +0000793 case Instruction::Select: Out << "getSelect"; break;
794 case Instruction::ExtractElement: Out << "getExtractElement"; break;
795 case Instruction::InsertElement: Out << "getInsertElement"; break;
796 case Instruction::ShuffleVector: Out << "getShuffleVector"; break;
797 default:
Reid Spencer12803f52006-05-31 17:31:38 +0000798 error("Invalid constant expression");
Reid Spencere0d133f2006-05-29 18:08:06 +0000799 break;
800 }
801 Out << getCppName(CE->getOperand(0));
802 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
803 Out << ", " << getCppName(CE->getOperand(i));
804 Out << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000805 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000806 } else {
Reid Spencer12803f52006-05-31 17:31:38 +0000807 error("Bad Constant");
Reid Spencere0d133f2006-05-29 18:08:06 +0000808 Out << "Constant* " << constName << " = 0; ";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000809 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000810 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000811}
812
Reid Spencer12803f52006-05-31 17:31:38 +0000813void
814CppWriter::printConstants(const Module* M) {
815 // Traverse all the global variables looking for constant initializers
816 for (Module::const_global_iterator I = TheModule->global_begin(),
817 E = TheModule->global_end(); I != E; ++I)
818 if (I->hasInitializer())
819 printConstant(I->getInitializer());
820
821 // Traverse the LLVM functions looking for constants
822 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
823 FI != FE; ++FI) {
824 // Add all of the basic blocks and instructions
825 for (Function::const_iterator BB = FI->begin(),
826 E = FI->end(); BB != E; ++BB) {
827 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
828 ++I) {
829 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
830 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
831 printConstant(C);
832 }
833 }
834 }
835 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000836 }
Reid Spencer66c87342006-05-30 03:43:49 +0000837}
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000838
Reid Spencer12803f52006-05-31 17:31:38 +0000839void CppWriter::printVariableUses(const GlobalVariable *GV) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000840 nl(Out) << "// Type Definitions";
841 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000842 printType(GV->getType());
843 if (GV->hasInitializer()) {
844 Constant* Init = GV->getInitializer();
845 printType(Init->getType());
846 if (Function* F = dyn_cast<Function>(Init)) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000847 nl(Out)<< "/ Function Declarations"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000848 printFunctionHead(F);
849 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000850 nl(Out) << "// Global Variable Declarations"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000851 printVariableHead(gv);
852 } else {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000853 nl(Out) << "// Constant Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000854 printConstant(gv);
855 }
856 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000857 nl(Out) << "// Global Variable Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000858 printVariableBody(gv);
Reid Spencere0d133f2006-05-29 18:08:06 +0000859 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000860 }
Reid Spencer12803f52006-05-31 17:31:38 +0000861}
Reid Spencer15f7e012006-05-30 21:18:23 +0000862
Reid Spencer12803f52006-05-31 17:31:38 +0000863void CppWriter::printVariableHead(const GlobalVariable *GV) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000864 nl(Out) << "GlobalVariable* " << getCppName(GV);
Reid Spencerf977e7b2006-06-01 23:43:47 +0000865 if (is_inline) {
866 Out << " = mod->getGlobalVariable(";
867 printEscapedString(GV->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000868 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
869 nl(Out) << "if (!" << getCppName(GV) << ") {";
870 in(); nl(Out) << getCppName(GV);
Reid Spencerf977e7b2006-06-01 23:43:47 +0000871 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000872 Out << " = new GlobalVariable(";
873 nl(Out) << "/*Type=*/";
Reid Spencer12803f52006-05-31 17:31:38 +0000874 printCppName(GV->getType()->getElementType());
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000875 Out << ",";
876 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
877 Out << ",";
878 nl(Out) << "/*Linkage=*/";
Reid Spencer12803f52006-05-31 17:31:38 +0000879 printLinkageType(GV->getLinkage());
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000880 Out << ",";
881 nl(Out) << "/*Initializer=*/0, ";
Reid Spencer12803f52006-05-31 17:31:38 +0000882 if (GV->hasInitializer()) {
883 Out << "// has initializer, specified below";
Reid Spencer15f7e012006-05-30 21:18:23 +0000884 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000885 nl(Out) << "/*Name=*/\"";
Reid Spencer12803f52006-05-31 17:31:38 +0000886 printEscapedString(GV->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000887 Out << "\",";
888 nl(Out) << "mod);";
889 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000890
891 if (GV->hasSection()) {
892 printCppName(GV);
893 Out << "->setSection(\"";
894 printEscapedString(GV->getSection());
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000895 Out << "\");";
896 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000897 }
898 if (GV->getAlignment()) {
899 printCppName(GV);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000900 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
901 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000902 };
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000903 if (is_inline) {
904 out(); Out << "}"; nl(Out);
905 }
Reid Spencer12803f52006-05-31 17:31:38 +0000906}
907
908void
909CppWriter::printVariableBody(const GlobalVariable *GV) {
910 if (GV->hasInitializer()) {
911 printCppName(GV);
912 Out << "->setInitializer(";
913 //if (!isa<GlobalValue(GV->getInitializer()))
914 //else
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000915 Out << getCppName(GV->getInitializer()) << ");";
916 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000917 }
918}
919
920std::string
921CppWriter::getOpName(Value* V) {
922 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
923 return getCppName(V);
924
925 // See if its alread in the map of forward references, if so just return the
926 // name we already set up for it
927 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
928 if (I != ForwardRefs.end())
929 return I->second;
930
931 // This is a new forward reference. Generate a unique name for it
932 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
933
934 // Yes, this is a hack. An Argument is the smallest instantiable value that
935 // we can make as a placeholder for the real value. We'll replace these
936 // Argument instances later.
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000937 Out << "Argument* " << result << " = new Argument("
938 << getCppName(V->getType()) << ");";
939 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000940 ForwardRefs[V] = result;
941 return result;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000942}
943
Reid Spencere0d133f2006-05-29 18:08:06 +0000944// printInstruction - This member is called for each Instruction in a function.
945void
Reid Spencer12803f52006-05-31 17:31:38 +0000946CppWriter::printInstruction(const Instruction *I, const std::string& bbname) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000947 std::string iName(getCppName(I));
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000948
Reid Spencer15f7e012006-05-30 21:18:23 +0000949 // Before we emit this instruction, we need to take care of generating any
950 // forward references. So, we get the names of all the operands in advance
951 std::string* opNames = new std::string[I->getNumOperands()];
952 for (unsigned i = 0; i < I->getNumOperands(); i++) {
953 opNames[i] = getOpName(I->getOperand(i));
954 }
955
Reid Spencere0d133f2006-05-29 18:08:06 +0000956 switch (I->getOpcode()) {
957 case Instruction::Ret: {
958 const ReturnInst* ret = cast<ReturnInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000959 Out << "ReturnInst* " << iName << " = new ReturnInst("
Reid Spencer15f7e012006-05-30 21:18:23 +0000960 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
Reid Spencere0d133f2006-05-29 18:08:06 +0000961 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000962 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000963 case Instruction::Br: {
964 const BranchInst* br = cast<BranchInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000965 Out << "BranchInst* " << iName << " = new BranchInst(" ;
Reid Spencere0d133f2006-05-29 18:08:06 +0000966 if (br->getNumOperands() == 3 ) {
Reid Spencer15f7e012006-05-30 21:18:23 +0000967 Out << opNames[0] << ", "
968 << opNames[1] << ", "
969 << opNames[2] << ", ";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000970
Reid Spencere0d133f2006-05-29 18:08:06 +0000971 } else if (br->getNumOperands() == 1) {
Reid Spencer15f7e012006-05-30 21:18:23 +0000972 Out << opNames[0] << ", ";
Reid Spencere0d133f2006-05-29 18:08:06 +0000973 } else {
Reid Spencer12803f52006-05-31 17:31:38 +0000974 error("Branch with 2 operands?");
Reid Spencere0d133f2006-05-29 18:08:06 +0000975 }
976 Out << bbname << ");";
977 break;
978 }
Reid Spencer66c87342006-05-30 03:43:49 +0000979 case Instruction::Switch: {
980 const SwitchInst* sw = cast<SwitchInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000981 Out << "SwitchInst* " << iName << " = new SwitchInst("
Reid Spencer15f7e012006-05-30 21:18:23 +0000982 << opNames[0] << ", "
983 << opNames[1] << ", "
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000984 << sw->getNumCases() << ", " << bbname << ");";
985 nl(Out);
Reid Spencer15f7e012006-05-30 21:18:23 +0000986 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000987 Out << iName << "->addCase("
Reid Spencer15f7e012006-05-30 21:18:23 +0000988 << opNames[i] << ", "
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000989 << opNames[i+1] << ");";
990 nl(Out);
Reid Spencer66c87342006-05-30 03:43:49 +0000991 }
992 break;
993 }
994 case Instruction::Invoke: {
995 const InvokeInst* inv = cast<InvokeInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000996 Out << "std::vector<Value*> " << iName << "_params;";
997 nl(Out);
998 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
999 Out << iName << "_params.push_back("
1000 << opNames[i] << ");";
1001 nl(Out);
1002 }
1003 Out << "InvokeInst* " << iName << " = new InvokeInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001004 << opNames[0] << ", "
1005 << opNames[1] << ", "
1006 << opNames[2] << ", "
Reid Spencer66c87342006-05-30 03:43:49 +00001007 << iName << "_params, \"";
1008 printEscapedString(inv->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001009 Out << "\", " << bbname << ");";
1010 nl(Out) << iName << "->setCallingConv(";
Reid Spencer66c87342006-05-30 03:43:49 +00001011 printCallingConv(inv->getCallingConv());
1012 Out << ");";
1013 break;
1014 }
1015 case Instruction::Unwind: {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001016 Out << "UnwindInst* " << iName << " = new UnwindInst("
Reid Spencer66c87342006-05-30 03:43:49 +00001017 << bbname << ");";
1018 break;
1019 }
1020 case Instruction::Unreachable:{
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001021 Out << "UnreachableInst* " << iName << " = new UnreachableInst("
Reid Spencer66c87342006-05-30 03:43:49 +00001022 << bbname << ");";
1023 break;
1024 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001025 case Instruction::Add:
1026 case Instruction::Sub:
1027 case Instruction::Mul:
Reid Spencer1628cec2006-10-26 06:15:43 +00001028 case Instruction::UDiv:
1029 case Instruction::SDiv:
1030 case Instruction::FDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001031 case Instruction::URem:
1032 case Instruction::SRem:
1033 case Instruction::FRem:
Reid Spencere0d133f2006-05-29 18:08:06 +00001034 case Instruction::And:
1035 case Instruction::Or:
1036 case Instruction::Xor:
Reid Spencer66c87342006-05-30 03:43:49 +00001037 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00001038 case Instruction::LShr:
1039 case Instruction::AShr:{
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001040 Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
Reid Spencer66c87342006-05-30 03:43:49 +00001041 switch (I->getOpcode()) {
1042 case Instruction::Add: Out << "Instruction::Add"; break;
1043 case Instruction::Sub: Out << "Instruction::Sub"; break;
1044 case Instruction::Mul: Out << "Instruction::Mul"; break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001045 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1046 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1047 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
Reid Spencer0a783f72006-11-02 01:53:59 +00001048 case Instruction::URem:Out << "Instruction::URem"; break;
1049 case Instruction::SRem:Out << "Instruction::SRem"; break;
1050 case Instruction::FRem:Out << "Instruction::FRem"; break;
Reid Spencer66c87342006-05-30 03:43:49 +00001051 case Instruction::And: Out << "Instruction::And"; break;
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001052 case Instruction::Or: Out << "Instruction::Or"; break;
Reid Spencer66c87342006-05-30 03:43:49 +00001053 case Instruction::Xor: Out << "Instruction::Xor"; break;
1054 case Instruction::Shl: Out << "Instruction::Shl"; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001055 case Instruction::LShr:Out << "Instruction::LShr"; break;
1056 case Instruction::AShr:Out << "Instruction::AShr"; break;
Reid Spencer66c87342006-05-30 03:43:49 +00001057 default: Out << "Instruction::BadOpCode"; break;
1058 }
Reid Spencer15f7e012006-05-30 21:18:23 +00001059 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001060 printEscapedString(I->getName());
1061 Out << "\", " << bbname << ");";
1062 break;
1063 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001064 case Instruction::SetEQ:
1065 case Instruction::SetNE:
1066 case Instruction::SetLE:
1067 case Instruction::SetGE:
1068 case Instruction::SetLT:
Reid Spencer66c87342006-05-30 03:43:49 +00001069 case Instruction::SetGT: {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001070 Out << "SetCondInst* " << iName << " = new SetCondInst(";
Reid Spencer66c87342006-05-30 03:43:49 +00001071 switch (I->getOpcode()) {
1072 case Instruction::SetEQ: Out << "Instruction::SetEQ"; break;
1073 case Instruction::SetNE: Out << "Instruction::SetNE"; break;
1074 case Instruction::SetLE: Out << "Instruction::SetLE"; break;
1075 case Instruction::SetGE: Out << "Instruction::SetGE"; break;
1076 case Instruction::SetLT: Out << "Instruction::SetLT"; break;
1077 case Instruction::SetGT: Out << "Instruction::SetGT"; break;
1078 default: Out << "Instruction::BadOpCode"; break;
1079 }
Reid Spencer15f7e012006-05-30 21:18:23 +00001080 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001081 printEscapedString(I->getName());
1082 Out << "\", " << bbname << ");";
1083 break;
1084 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001085 case Instruction::Malloc: {
1086 const MallocInst* mallocI = cast<MallocInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001087 Out << "MallocInst* " << iName << " = new MallocInst("
Reid Spencere0d133f2006-05-29 18:08:06 +00001088 << getCppName(mallocI->getAllocatedType()) << ", ";
1089 if (mallocI->isArrayAllocation())
Reid Spencer15f7e012006-05-30 21:18:23 +00001090 Out << opNames[0] << ", " ;
Reid Spencere0d133f2006-05-29 18:08:06 +00001091 Out << "\"";
1092 printEscapedString(mallocI->getName());
1093 Out << "\", " << bbname << ");";
1094 if (mallocI->getAlignment())
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001095 nl(Out) << iName << "->setAlignment("
Reid Spencere0d133f2006-05-29 18:08:06 +00001096 << mallocI->getAlignment() << ");";
1097 break;
1098 }
Reid Spencer66c87342006-05-30 03:43:49 +00001099 case Instruction::Free: {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001100 Out << "FreeInst* " << iName << " = new FreeInst("
Reid Spencer66c87342006-05-30 03:43:49 +00001101 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1102 break;
1103 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001104 case Instruction::Alloca: {
1105 const AllocaInst* allocaI = cast<AllocaInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001106 Out << "AllocaInst* " << iName << " = new AllocaInst("
Reid Spencere0d133f2006-05-29 18:08:06 +00001107 << getCppName(allocaI->getAllocatedType()) << ", ";
1108 if (allocaI->isArrayAllocation())
Reid Spencer15f7e012006-05-30 21:18:23 +00001109 Out << opNames[0] << ", ";
Reid Spencere0d133f2006-05-29 18:08:06 +00001110 Out << "\"";
1111 printEscapedString(allocaI->getName());
1112 Out << "\", " << bbname << ");";
1113 if (allocaI->getAlignment())
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001114 nl(Out) << iName << "->setAlignment("
Reid Spencere0d133f2006-05-29 18:08:06 +00001115 << allocaI->getAlignment() << ");";
1116 break;
1117 }
Reid Spencer66c87342006-05-30 03:43:49 +00001118 case Instruction::Load:{
1119 const LoadInst* load = cast<LoadInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001120 Out << "LoadInst* " << iName << " = new LoadInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001121 << opNames[0] << ", \"";
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001122 printEscapedString(load->getName());
1123 Out << "\", " << (load->isVolatile() ? "true" : "false" )
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001124 << ", " << bbname << ");";
Reid Spencer66c87342006-05-30 03:43:49 +00001125 break;
1126 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001127 case Instruction::Store: {
1128 const StoreInst* store = cast<StoreInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001129 Out << "StoreInst* " << iName << " = new StoreInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001130 << opNames[0] << ", "
1131 << opNames[1] << ", "
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001132 << (store->isVolatile() ? "true" : "false")
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001133 << ", " << bbname << ");";
Reid Spencere0d133f2006-05-29 18:08:06 +00001134 break;
1135 }
1136 case Instruction::GetElementPtr: {
1137 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1138 if (gep->getNumOperands() <= 2) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001139 Out << "GetElementPtrInst* " << iName << " = new GetElementPtrInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001140 << opNames[0];
Reid Spencere0d133f2006-05-29 18:08:06 +00001141 if (gep->getNumOperands() == 2)
Reid Spencer15f7e012006-05-30 21:18:23 +00001142 Out << ", " << opNames[1];
Reid Spencere0d133f2006-05-29 18:08:06 +00001143 } else {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001144 Out << "std::vector<Value*> " << iName << "_indices;";
1145 nl(Out);
Reid Spencere0d133f2006-05-29 18:08:06 +00001146 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001147 Out << iName << "_indices.push_back("
1148 << opNames[i] << ");";
1149 nl(Out);
Reid Spencere0d133f2006-05-29 18:08:06 +00001150 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001151 Out << "Instruction* " << iName << " = new GetElementPtrInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001152 << opNames[0] << ", " << iName << "_indices";
Reid Spencere0d133f2006-05-29 18:08:06 +00001153 }
1154 Out << ", \"";
1155 printEscapedString(gep->getName());
1156 Out << "\", " << bbname << ");";
1157 break;
1158 }
Reid Spencer66c87342006-05-30 03:43:49 +00001159 case Instruction::PHI: {
1160 const PHINode* phi = cast<PHINode>(I);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001161
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001162 Out << "PHINode* " << iName << " = new PHINode("
Reid Spencer66c87342006-05-30 03:43:49 +00001163 << getCppName(phi->getType()) << ", \"";
1164 printEscapedString(phi->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001165 Out << "\", " << bbname << ");";
1166 nl(Out) << iName << "->reserveOperandSpace("
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001167 << phi->getNumIncomingValues()
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001168 << ");";
1169 nl(Out);
Reid Spencer15f7e012006-05-30 21:18:23 +00001170 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001171 Out << iName << "->addIncoming("
1172 << opNames[i] << ", " << opNames[i+1] << ");";
1173 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001174 }
Reid Spencer66c87342006-05-30 03:43:49 +00001175 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001176 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001177 case Instruction::Trunc:
1178 case Instruction::ZExt:
1179 case Instruction::SExt:
1180 case Instruction::FPTrunc:
1181 case Instruction::FPExt:
1182 case Instruction::FPToUI:
1183 case Instruction::FPToSI:
1184 case Instruction::UIToFP:
1185 case Instruction::SIToFP:
1186 case Instruction::PtrToInt:
1187 case Instruction::IntToPtr:
1188 case Instruction::BitCast: {
Reid Spencer66c87342006-05-30 03:43:49 +00001189 const CastInst* cst = cast<CastInst>(I);
Reid Spencer3da59db2006-11-27 01:05:10 +00001190 Out << "CastInst* " << iName << " = new ";
1191 switch (I->getOpcode()) {
1192 case Instruction::Trunc: Out << "TruncInst";
1193 case Instruction::ZExt: Out << "ZExtInst";
1194 case Instruction::SExt: Out << "SExtInst";
1195 case Instruction::FPTrunc: Out << "FPTruncInst";
1196 case Instruction::FPExt: Out << "FPExtInst";
1197 case Instruction::FPToUI: Out << "FPToUIInst";
1198 case Instruction::FPToSI: Out << "FPToSIInst";
1199 case Instruction::UIToFP: Out << "UIToFPInst";
1200 case Instruction::SIToFP: Out << "SIToFPInst";
1201 case Instruction::PtrToInt: Out << "PtrToInst";
1202 case Instruction::IntToPtr: Out << "IntToPtrInst";
1203 case Instruction::BitCast: Out << "BitCastInst";
1204 default: assert(!"Unreachable"); break;
1205 }
1206 Out << "(" << opNames[0] << ", "
Reid Spencer66c87342006-05-30 03:43:49 +00001207 << getCppName(cst->getType()) << ", \"";
1208 printEscapedString(cst->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001209 Out << "\", " << bbname << ");";
Reid Spencer66c87342006-05-30 03:43:49 +00001210 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001211 }
Reid Spencer66c87342006-05-30 03:43:49 +00001212 case Instruction::Call:{
1213 const CallInst* call = cast<CallInst>(I);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001214 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001215 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001216 << getCppName(ila->getFunctionType()) << ", \""
1217 << ila->getAsmString() << "\", \""
1218 << ila->getConstraintString() << "\","
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001219 << (ila->hasSideEffects() ? "true" : "false") << ");";
1220 nl(Out);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001221 }
Reid Spencer66c87342006-05-30 03:43:49 +00001222 if (call->getNumOperands() > 3) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001223 Out << "std::vector<Value*> " << iName << "_params;";
1224 nl(Out);
1225 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1226 Out << iName << "_params.push_back(" << opNames[i] << ");";
1227 nl(Out);
1228 }
1229 Out << "CallInst* " << iName << " = new CallInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001230 << opNames[0] << ", " << iName << "_params, \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001231 } else if (call->getNumOperands() == 3) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001232 Out << "CallInst* " << iName << " = new CallInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001233 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001234 } else if (call->getNumOperands() == 2) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001235 Out << "CallInst* " << iName << " = new CallInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001236 << opNames[0] << ", " << opNames[1] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001237 } else {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001238 Out << "CallInst* " << iName << " = new CallInst(" << opNames[0]
Reid Spencer15f7e012006-05-30 21:18:23 +00001239 << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001240 }
1241 printEscapedString(call->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001242 Out << "\", " << bbname << ");";
1243 nl(Out) << iName << "->setCallingConv(";
Reid Spencer66c87342006-05-30 03:43:49 +00001244 printCallingConv(call->getCallingConv());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001245 Out << ");";
1246 nl(Out) << iName << "->setTailCall("
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001247 << (call->isTailCall() ? "true":"false");
Reid Spencer66c87342006-05-30 03:43:49 +00001248 Out << ");";
1249 break;
1250 }
1251 case Instruction::Select: {
1252 const SelectInst* sel = cast<SelectInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001253 Out << "SelectInst* " << getCppName(sel) << " = new SelectInst(";
Reid Spencer15f7e012006-05-30 21:18:23 +00001254 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001255 printEscapedString(sel->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001256 Out << "\", " << bbname << ");";
Reid Spencer66c87342006-05-30 03:43:49 +00001257 break;
1258 }
1259 case Instruction::UserOp1:
1260 /// FALL THROUGH
1261 case Instruction::UserOp2: {
1262 /// FIXME: What should be done here?
1263 break;
1264 }
1265 case Instruction::VAArg: {
1266 const VAArgInst* va = cast<VAArgInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001267 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001268 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001269 printEscapedString(va->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001270 Out << "\", " << bbname << ");";
Reid Spencer66c87342006-05-30 03:43:49 +00001271 break;
1272 }
1273 case Instruction::ExtractElement: {
1274 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001275 Out << "ExtractElementInst* " << getCppName(eei)
Reid Spencer15f7e012006-05-30 21:18:23 +00001276 << " = new ExtractElementInst(" << opNames[0]
1277 << ", " << opNames[1] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001278 printEscapedString(eei->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001279 Out << "\", " << bbname << ");";
Reid Spencer66c87342006-05-30 03:43:49 +00001280 break;
1281 }
1282 case Instruction::InsertElement: {
1283 const InsertElementInst* iei = cast<InsertElementInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001284 Out << "InsertElementInst* " << getCppName(iei)
Reid Spencer15f7e012006-05-30 21:18:23 +00001285 << " = new InsertElementInst(" << opNames[0]
1286 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001287 printEscapedString(iei->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001288 Out << "\", " << bbname << ");";
Reid Spencer66c87342006-05-30 03:43:49 +00001289 break;
1290 }
1291 case Instruction::ShuffleVector: {
1292 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001293 Out << "ShuffleVectorInst* " << getCppName(svi)
Reid Spencer15f7e012006-05-30 21:18:23 +00001294 << " = new ShuffleVectorInst(" << opNames[0]
1295 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001296 printEscapedString(svi->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001297 Out << "\", " << bbname << ");";
Reid Spencer66c87342006-05-30 03:43:49 +00001298 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001299 }
1300 }
Reid Spencer68464b72006-06-15 16:09:59 +00001301 DefinedValues.insert(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001302 nl(Out);
Reid Spencer15f7e012006-05-30 21:18:23 +00001303 delete [] opNames;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001304}
1305
Reid Spencer12803f52006-05-31 17:31:38 +00001306// Print out the types, constants and declarations needed by one function
1307void CppWriter::printFunctionUses(const Function* F) {
1308
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001309 nl(Out) << "// Type Definitions"; nl(Out);
Reid Spencerf977e7b2006-06-01 23:43:47 +00001310 if (!is_inline) {
1311 // Print the function's return type
1312 printType(F->getReturnType());
Reid Spencer12803f52006-05-31 17:31:38 +00001313
Reid Spencerf977e7b2006-06-01 23:43:47 +00001314 // Print the function's function type
1315 printType(F->getFunctionType());
Reid Spencer12803f52006-05-31 17:31:38 +00001316
Reid Spencerf977e7b2006-06-01 23:43:47 +00001317 // Print the types of each of the function's arguments
1318 for(Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1319 AI != AE; ++AI) {
1320 printType(AI->getType());
1321 }
Reid Spencer12803f52006-05-31 17:31:38 +00001322 }
1323
1324 // Print type definitions for every type referenced by an instruction and
1325 // make a note of any global values or constants that are referenced
1326 std::vector<GlobalValue*> gvs;
1327 std::vector<Constant*> consts;
1328 for (Function::const_iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB){
1329 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1330 I != E; ++I) {
1331 // Print the type of the instruction itself
1332 printType(I->getType());
1333
1334 // Print the type of each of the instruction's operands
1335 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1336 Value* operand = I->getOperand(i);
1337 printType(operand->getType());
1338 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand))
1339 gvs.push_back(GV);
1340 else if (Constant* C = dyn_cast<Constant>(operand))
1341 consts.push_back(C);
1342 }
1343 }
1344 }
1345
1346 // Print the function declarations for any functions encountered
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001347 nl(Out) << "// Function Declarations"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001348 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1349 I != E; ++I) {
Reid Spencerf977e7b2006-06-01 23:43:47 +00001350 if (Function* Fun = dyn_cast<Function>(*I)) {
1351 if (!is_inline || Fun != F)
1352 printFunctionHead(Fun);
1353 }
Reid Spencer12803f52006-05-31 17:31:38 +00001354 }
1355
1356 // Print the global variable declarations for any variables encountered
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001357 nl(Out) << "// Global Variable Declarations"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001358 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1359 I != E; ++I) {
1360 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1361 printVariableHead(F);
1362 }
1363
1364 // Print the constants found
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001365 nl(Out) << "// Constant Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001366 for (std::vector<Constant*>::iterator I = consts.begin(), E = consts.end();
1367 I != E; ++I) {
Reid Spencerf977e7b2006-06-01 23:43:47 +00001368 printConstant(*I);
Reid Spencer12803f52006-05-31 17:31:38 +00001369 }
1370
1371 // Process the global variables definitions now that all the constants have
1372 // been emitted. These definitions just couple the gvars with their constant
1373 // initializers.
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001374 nl(Out) << "// Global Variable Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001375 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1376 I != E; ++I) {
1377 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1378 printVariableBody(GV);
1379 }
1380}
1381
1382void CppWriter::printFunctionHead(const Function* F) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001383 nl(Out) << "Function* " << getCppName(F);
Reid Spencerf977e7b2006-06-01 23:43:47 +00001384 if (is_inline) {
1385 Out << " = mod->getFunction(\"";
1386 printEscapedString(F->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001387 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1388 nl(Out) << "if (!" << getCppName(F) << ") {";
1389 nl(Out) << getCppName(F);
Reid Spencerf977e7b2006-06-01 23:43:47 +00001390 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001391 Out<< " = new Function(";
1392 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1393 nl(Out) << "/*Linkage=*/";
Reid Spencer12803f52006-05-31 17:31:38 +00001394 printLinkageType(F->getLinkage());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001395 Out << ",";
1396 nl(Out) << "/*Name=*/\"";
Reid Spencer12803f52006-05-31 17:31:38 +00001397 printEscapedString(F->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001398 Out << "\", mod); " << (F->isExternal()? "// (external, no body)" : "");
1399 nl(Out,-1);
Reid Spencer12803f52006-05-31 17:31:38 +00001400 printCppName(F);
1401 Out << "->setCallingConv(";
1402 printCallingConv(F->getCallingConv());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001403 Out << ");";
1404 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001405 if (F->hasSection()) {
1406 printCppName(F);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001407 Out << "->setSection(\"" << F->getSection() << "\");";
1408 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001409 }
1410 if (F->getAlignment()) {
1411 printCppName(F);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001412 Out << "->setAlignment(" << F->getAlignment() << ");";
1413 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001414 }
Reid Spencerf977e7b2006-06-01 23:43:47 +00001415 if (is_inline) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001416 Out << "}";
1417 nl(Out);
Reid Spencerf977e7b2006-06-01 23:43:47 +00001418 }
Reid Spencer12803f52006-05-31 17:31:38 +00001419}
1420
1421void CppWriter::printFunctionBody(const Function *F) {
1422 if (F->isExternal())
1423 return; // external functions have no bodies.
1424
1425 // Clear the DefinedValues and ForwardRefs maps because we can't have
1426 // cross-function forward refs
1427 ForwardRefs.clear();
1428 DefinedValues.clear();
1429
1430 // Create all the argument values
Reid Spencerf977e7b2006-06-01 23:43:47 +00001431 if (!is_inline) {
1432 if (!F->arg_empty()) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001433 Out << "Function::arg_iterator args = " << getCppName(F)
1434 << "->arg_begin();";
1435 nl(Out);
Reid Spencerf977e7b2006-06-01 23:43:47 +00001436 }
1437 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1438 AI != AE; ++AI) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001439 Out << "Value* " << getCppName(AI) << " = args++;";
1440 nl(Out);
1441 if (AI->hasName()) {
1442 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1443 nl(Out);
1444 }
Reid Spencerf977e7b2006-06-01 23:43:47 +00001445 }
Reid Spencer12803f52006-05-31 17:31:38 +00001446 }
1447
1448 // Create all the basic blocks
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001449 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001450 for (Function::const_iterator BI = F->begin(), BE = F->end();
1451 BI != BE; ++BI) {
1452 std::string bbname(getCppName(BI));
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001453 Out << "BasicBlock* " << bbname << " = new BasicBlock(\"";
Reid Spencer12803f52006-05-31 17:31:38 +00001454 if (BI->hasName())
1455 printEscapedString(BI->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001456 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1457 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001458 }
1459
1460 // Output all of its basic blocks... for the function
1461 for (Function::const_iterator BI = F->begin(), BE = F->end();
1462 BI != BE; ++BI) {
1463 std::string bbname(getCppName(BI));
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001464 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1465 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001466
1467 // Output all of the instructions in the basic block...
1468 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1469 I != E; ++I) {
1470 printInstruction(I,bbname);
1471 }
1472 }
1473
1474 // Loop over the ForwardRefs and resolve them now that all instructions
1475 // are generated.
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001476 if (!ForwardRefs.empty()) {
1477 nl(Out) << "// Resolve Forward References";
1478 nl(Out);
1479 }
1480
Reid Spencer12803f52006-05-31 17:31:38 +00001481 while (!ForwardRefs.empty()) {
1482 ForwardRefMap::iterator I = ForwardRefs.begin();
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001483 Out << I->second << "->replaceAllUsesWith("
1484 << getCppName(I->first) << "); delete " << I->second << ";";
1485 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001486 ForwardRefs.erase(I);
1487 }
1488}
1489
Reid Spencerf977e7b2006-06-01 23:43:47 +00001490void CppWriter::printInline(const std::string& fname, const std::string& func) {
1491 const Function* F = TheModule->getNamedFunction(func);
1492 if (!F) {
1493 error(std::string("Function '") + func + "' not found in input module");
1494 return;
1495 }
1496 if (F->isExternal()) {
1497 error(std::string("Function '") + func + "' is external!");
1498 return;
1499 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001500 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
Reid Spencerf977e7b2006-06-01 23:43:47 +00001501 << getCppName(F);
1502 unsigned arg_count = 1;
1503 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1504 AI != AE; ++AI) {
1505 Out << ", Value* arg_" << arg_count;
1506 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001507 Out << ") {";
1508 nl(Out);
Reid Spencerf977e7b2006-06-01 23:43:47 +00001509 is_inline = true;
1510 printFunctionUses(F);
1511 printFunctionBody(F);
1512 is_inline = false;
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001513 Out << "return " << getCppName(F->begin()) << ";";
1514 nl(Out) << "}";
1515 nl(Out);
Reid Spencerf977e7b2006-06-01 23:43:47 +00001516}
1517
Reid Spencer12803f52006-05-31 17:31:38 +00001518void CppWriter::printModuleBody() {
1519 // Print out all the type definitions
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001520 nl(Out) << "// Type Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001521 printTypes(TheModule);
1522
1523 // Functions can call each other and global variables can reference them so
1524 // define all the functions first before emitting their function bodies.
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001525 nl(Out) << "// Function Declarations"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001526 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1527 I != E; ++I)
1528 printFunctionHead(I);
1529
1530 // Process the global variables declarations. We can't initialze them until
1531 // after the constants are printed so just print a header for each global
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001532 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001533 for (Module::const_global_iterator I = TheModule->global_begin(),
1534 E = TheModule->global_end(); I != E; ++I) {
1535 printVariableHead(I);
1536 }
1537
1538 // Print out all the constants definitions. Constants don't recurse except
1539 // through GlobalValues. All GlobalValues have been declared at this point
1540 // so we can proceed to generate the constants.
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001541 nl(Out) << "// Constant Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001542 printConstants(TheModule);
1543
1544 // Process the global variables definitions now that all the constants have
1545 // been emitted. These definitions just couple the gvars with their constant
1546 // initializers.
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001547 nl(Out) << "// Global Variable Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001548 for (Module::const_global_iterator I = TheModule->global_begin(),
1549 E = TheModule->global_end(); I != E; ++I) {
1550 printVariableBody(I);
1551 }
1552
1553 // Finally, we can safely put out all of the function bodies.
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001554 nl(Out) << "// Function Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001555 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1556 I != E; ++I) {
1557 if (!I->isExternal()) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001558 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1559 << ")";
1560 nl(Out) << "{";
1561 nl(Out,1);
Reid Spencer12803f52006-05-31 17:31:38 +00001562 printFunctionBody(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001563 nl(Out,-1) << "}";
1564 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001565 }
1566 }
1567}
1568
1569void CppWriter::printProgram(
1570 const std::string& fname,
1571 const std::string& mName
1572) {
1573 Out << "#include <llvm/Module.h>\n";
1574 Out << "#include <llvm/DerivedTypes.h>\n";
1575 Out << "#include <llvm/Constants.h>\n";
1576 Out << "#include <llvm/GlobalVariable.h>\n";
1577 Out << "#include <llvm/Function.h>\n";
1578 Out << "#include <llvm/CallingConv.h>\n";
1579 Out << "#include <llvm/BasicBlock.h>\n";
1580 Out << "#include <llvm/Instructions.h>\n";
1581 Out << "#include <llvm/InlineAsm.h>\n";
Reid Spencerf977e7b2006-06-01 23:43:47 +00001582 Out << "#include <llvm/Support/MathExtras.h>\n";
Reid Spencer12803f52006-05-31 17:31:38 +00001583 Out << "#include <llvm/Pass.h>\n";
1584 Out << "#include <llvm/PassManager.h>\n";
1585 Out << "#include <llvm/Analysis/Verifier.h>\n";
1586 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1587 Out << "#include <algorithm>\n";
1588 Out << "#include <iostream>\n\n";
1589 Out << "using namespace llvm;\n\n";
1590 Out << "Module* " << fname << "();\n\n";
1591 Out << "int main(int argc, char**argv) {\n";
1592 Out << " Module* Mod = makeLLVMModule();\n";
1593 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1594 Out << " std::cerr.flush();\n";
1595 Out << " std::cout.flush();\n";
1596 Out << " PassManager PM;\n";
1597 Out << " PM.add(new PrintModulePass(&std::cout));\n";
1598 Out << " PM.run(*Mod);\n";
1599 Out << " return 0;\n";
1600 Out << "}\n\n";
1601 printModule(fname,mName);
1602}
1603
1604void CppWriter::printModule(
1605 const std::string& fname,
1606 const std::string& mName
1607) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001608 nl(Out) << "Module* " << fname << "() {";
1609 nl(Out,1) << "// Module Construction";
1610 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1611 nl(Out) << "mod->setEndianness(";
Reid Spencer12803f52006-05-31 17:31:38 +00001612 switch (TheModule->getEndianness()) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001613 case Module::LittleEndian: Out << "Module::LittleEndian);"; break;
1614 case Module::BigEndian: Out << "Module::BigEndian);"; break;
1615 case Module::AnyEndianness:Out << "Module::AnyEndianness);"; break;
Reid Spencer12803f52006-05-31 17:31:38 +00001616 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001617 nl(Out) << "mod->setPointerSize(";
Reid Spencer12803f52006-05-31 17:31:38 +00001618 switch (TheModule->getPointerSize()) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001619 case Module::Pointer32: Out << "Module::Pointer32);"; break;
1620 case Module::Pointer64: Out << "Module::Pointer64);"; break;
1621 case Module::AnyPointerSize: Out << "Module::AnyPointerSize);"; break;
Reid Spencer12803f52006-05-31 17:31:38 +00001622 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001623 nl(Out);
1624 if (!TheModule->getTargetTriple().empty()) {
Reid Spencer12803f52006-05-31 17:31:38 +00001625 Out << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001626 << "\");";
1627 nl(Out);
1628 }
Reid Spencer12803f52006-05-31 17:31:38 +00001629
1630 if (!TheModule->getModuleInlineAsm().empty()) {
1631 Out << "mod->setModuleInlineAsm(\"";
1632 printEscapedString(TheModule->getModuleInlineAsm());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001633 Out << "\");";
1634 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001635 }
1636
1637 // Loop over the dependent libraries and emit them.
1638 Module::lib_iterator LI = TheModule->lib_begin();
1639 Module::lib_iterator LE = TheModule->lib_end();
1640 while (LI != LE) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001641 Out << "mod->addLibrary(\"" << *LI << "\");";
1642 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001643 ++LI;
1644 }
1645 printModuleBody();
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001646 nl(Out) << "return mod;";
1647 nl(Out,-1) << "}";
1648 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001649}
1650
1651void CppWriter::printContents(
1652 const std::string& fname, // Name of generated function
1653 const std::string& mName // Name of module generated module
1654) {
1655 Out << "\nModule* " << fname << "(Module *mod) {\n";
1656 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
Reid Spencer12803f52006-05-31 17:31:38 +00001657 printModuleBody();
1658 Out << "\nreturn mod;\n";
1659 Out << "\n}\n";
1660}
1661
1662void CppWriter::printFunction(
1663 const std::string& fname, // Name of generated function
1664 const std::string& funcName // Name of function to generate
1665) {
1666 const Function* F = TheModule->getNamedFunction(funcName);
1667 if (!F) {
1668 error(std::string("Function '") + funcName + "' not found in input module");
1669 return;
1670 }
1671 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1672 printFunctionUses(F);
1673 printFunctionHead(F);
1674 printFunctionBody(F);
1675 Out << "return " << getCppName(F) << ";\n";
1676 Out << "}\n";
1677}
1678
1679void CppWriter::printVariable(
1680 const std::string& fname, /// Name of generated function
1681 const std::string& varName // Name of variable to generate
1682) {
1683 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1684
1685 if (!GV) {
1686 error(std::string("Variable '") + varName + "' not found in input module");
1687 return;
1688 }
1689 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1690 printVariableUses(GV);
1691 printVariableHead(GV);
1692 printVariableBody(GV);
1693 Out << "return " << getCppName(GV) << ";\n";
1694 Out << "}\n";
1695}
1696
1697void CppWriter::printType(
1698 const std::string& fname, /// Name of generated function
1699 const std::string& typeName // Name of type to generate
1700) {
1701 const Type* Ty = TheModule->getTypeByName(typeName);
1702 if (!Ty) {
1703 error(std::string("Type '") + typeName + "' not found in input module");
1704 return;
1705 }
1706 Out << "\nType* " << fname << "(Module *mod) {\n";
1707 printType(Ty);
1708 Out << "return " << getCppName(Ty) << ";\n";
1709 Out << "}\n";
1710}
1711
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001712} // end anonymous llvm
1713
1714namespace llvm {
1715
1716void WriteModuleToCppFile(Module* mod, std::ostream& o) {
Reid Spencer12803f52006-05-31 17:31:38 +00001717 // Initialize a CppWriter for us to use
1718 CppWriter W(o, mod);
1719
1720 // Emit a header
Reid Spencer25edc352006-05-31 04:43:19 +00001721 o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
Reid Spencer12803f52006-05-31 17:31:38 +00001722
1723 // Get the name of the function we're supposed to generate
Reid Spencer15f7e012006-05-30 21:18:23 +00001724 std::string fname = FuncName.getValue();
Reid Spencer12803f52006-05-31 17:31:38 +00001725
1726 // Get the name of the thing we are to generate
1727 std::string tgtname = NameToGenerate.getValue();
1728 if (GenerationType == GenModule ||
1729 GenerationType == GenContents ||
1730 GenerationType == GenProgram) {
1731 if (tgtname == "!bad!") {
1732 if (mod->getModuleIdentifier() == "-")
1733 tgtname = "<stdin>";
1734 else
1735 tgtname = mod->getModuleIdentifier();
1736 }
1737 } else if (tgtname == "!bad!") {
1738 W.error("You must use the -for option with -gen-{function,variable,type}");
1739 }
1740
1741 switch (WhatToGenerate(GenerationType)) {
1742 case GenProgram:
1743 if (fname.empty())
1744 fname = "makeLLVMModule";
1745 W.printProgram(fname,tgtname);
1746 break;
1747 case GenModule:
1748 if (fname.empty())
1749 fname = "makeLLVMModule";
1750 W.printModule(fname,tgtname);
1751 break;
1752 case GenContents:
1753 if (fname.empty())
1754 fname = "makeLLVMModuleContents";
1755 W.printContents(fname,tgtname);
1756 break;
1757 case GenFunction:
1758 if (fname.empty())
1759 fname = "makeLLVMFunction";
1760 W.printFunction(fname,tgtname);
1761 break;
Reid Spencerf977e7b2006-06-01 23:43:47 +00001762 case GenInline:
1763 if (fname.empty())
1764 fname = "makeLLVMInline";
1765 W.printInline(fname,tgtname);
1766 break;
Reid Spencer12803f52006-05-31 17:31:38 +00001767 case GenVariable:
1768 if (fname.empty())
1769 fname = "makeLLVMVariable";
1770 W.printVariable(fname,tgtname);
1771 break;
1772 case GenType:
1773 if (fname.empty())
1774 fname = "makeLLVMType";
1775 W.printType(fname,tgtname);
1776 break;
1777 default:
1778 W.error("Invalid generation option");
Reid Spencer15f7e012006-05-30 21:18:23 +00001779 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001780}
1781
1782}