blob: 41b9b7eef9222b8d109d7c083e94fcc1790c8d52 [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 Spencer12803f52006-05-31 17:31:38 +0000142inline void
143sanitize(std::string& str) {
144 for (size_t i = 0; i < str.length(); ++i)
145 if (!isalnum(str[i]) && str[i] != '_')
146 str[i] = '_';
147}
148
149inline const char*
150getTypePrefix(const Type* Ty ) {
151 const char* prefix;
152 switch (Ty->getTypeID()) {
153 case Type::VoidTyID: prefix = "void_"; break;
154 case Type::BoolTyID: prefix = "bool_"; break;
155 case Type::UByteTyID: prefix = "ubyte_"; break;
156 case Type::SByteTyID: prefix = "sbyte_"; break;
157 case Type::UShortTyID: prefix = "ushort_"; break;
158 case Type::ShortTyID: prefix = "short_"; break;
159 case Type::UIntTyID: prefix = "uint_"; break;
160 case Type::IntTyID: prefix = "int_"; break;
161 case Type::ULongTyID: prefix = "ulong_"; break;
162 case Type::LongTyID: prefix = "long_"; break;
163 case Type::FloatTyID: prefix = "float_"; break;
164 case Type::DoubleTyID: prefix = "double_"; break;
165 case Type::LabelTyID: prefix = "label_"; break;
166 case Type::FunctionTyID: prefix = "func_"; break;
167 case Type::StructTyID: prefix = "struct_"; break;
168 case Type::ArrayTyID: prefix = "array_"; break;
169 case Type::PointerTyID: prefix = "ptr_"; break;
170 case Type::PackedTyID: prefix = "packed_"; break;
171 case Type::OpaqueTyID: prefix = "opaque_"; break;
172 default: prefix = "other_"; break;
173 }
174 return prefix;
175}
176
177// Looks up the type in the symbol table and returns a pointer to its name or
178// a null pointer if it wasn't found. Note that this isn't the same as the
179// Mode::getTypeName function which will return an empty string, not a null
180// pointer if the name is not found.
181inline const std::string*
182findTypeName(const SymbolTable& ST, const Type* Ty)
183{
184 SymbolTable::type_const_iterator TI = ST.type_begin();
185 SymbolTable::type_const_iterator TE = ST.type_end();
186 for (;TI != TE; ++TI)
187 if (TI->second == Ty)
188 return &(TI->first);
189 return 0;
190}
191
192void
193CppWriter::error(const std::string& msg) {
194 std::cerr << progname << ": " << msg << "\n";
195 exit(2);
196}
197
Reid Spencer15f7e012006-05-30 21:18:23 +0000198// printCFP - Print a floating point constant .. very carefully :)
199// This makes sure that conversion to/from floating yields the same binary
200// result so that we don't lose precision.
201void
202CppWriter::printCFP(const ConstantFP *CFP) {
Reid Spencerf977e7b2006-06-01 23:43:47 +0000203 Out << "ConstantFP::get(";
204 if (CFP->getType() == Type::DoubleTy)
205 Out << "Type::DoubleTy, ";
206 else
207 Out << "Type::FloatTy, ";
Reid Spencer15f7e012006-05-30 21:18:23 +0000208#if HAVE_PRINTF_A
209 char Buffer[100];
210 sprintf(Buffer, "%A", CFP->getValue());
211 if ((!strncmp(Buffer, "0x", 2) ||
212 !strncmp(Buffer, "-0x", 3) ||
213 !strncmp(Buffer, "+0x", 3)) &&
214 (atof(Buffer) == CFP->getValue()))
Reid Spencerf977e7b2006-06-01 23:43:47 +0000215 if (CFP->getType() == Type::DoubleTy)
216 Out << "BitsToDouble(" << Buffer << ")";
217 else
218 Out << "BitsToFloat(" << Buffer << ")";
Reid Spencer15f7e012006-05-30 21:18:23 +0000219 else {
Reid Spencer15f7e012006-05-30 21:18:23 +0000220#endif
Reid Spencerf977e7b2006-06-01 23:43:47 +0000221 std::string StrVal = ftostr(CFP->getValue());
222
223 while (StrVal[0] == ' ')
224 StrVal.erase(StrVal.begin());
225
226 // Check to make sure that the stringized number is not some string like
227 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
228 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
229 ((StrVal[0] == '-' || StrVal[0] == '+') &&
230 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
231 (atof(StrVal.c_str()) == CFP->getValue()))
232 if (CFP->getType() == Type::DoubleTy)
233 Out << StrVal;
234 else
235 Out << StrVal;
236 else if (CFP->getType() == Type::DoubleTy)
237 Out << "BitsToDouble(0x" << std::hex << DoubleToBits(CFP->getValue())
238 << std::dec << "ULL) /* " << StrVal << " */";
239 else
240 Out << "BitsToFloat(0x" << std::hex << FloatToBits(CFP->getValue())
241 << std::dec << "U) /* " << StrVal << " */";
Reid Spencer15f7e012006-05-30 21:18:23 +0000242#if HAVE_PRINTF_A
243 }
244#endif
Reid Spencerf977e7b2006-06-01 23:43:47 +0000245 Out << ")";
Reid Spencer15f7e012006-05-30 21:18:23 +0000246}
247
Reid Spencer12803f52006-05-31 17:31:38 +0000248void
249CppWriter::printCallingConv(unsigned cc){
250 // Print the calling convention.
251 switch (cc) {
252 case CallingConv::C: Out << "CallingConv::C"; break;
253 case CallingConv::CSRet: Out << "CallingConv::CSRet"; break;
254 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
255 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
256 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
257 default: Out << cc; break;
258 }
259}
Reid Spencer15f7e012006-05-30 21:18:23 +0000260
Reid Spencer12803f52006-05-31 17:31:38 +0000261void
262CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
263 switch (LT) {
264 case GlobalValue::InternalLinkage:
265 Out << "GlobalValue::InternalLinkage"; break;
266 case GlobalValue::LinkOnceLinkage:
267 Out << "GlobalValue::LinkOnceLinkage "; break;
268 case GlobalValue::WeakLinkage:
269 Out << "GlobalValue::WeakLinkage"; break;
270 case GlobalValue::AppendingLinkage:
271 Out << "GlobalValue::AppendingLinkage"; break;
272 case GlobalValue::ExternalLinkage:
273 Out << "GlobalValue::ExternalLinkage"; break;
274 case GlobalValue::GhostLinkage:
275 Out << "GlobalValue::GhostLinkage"; break;
276 }
Reid Spencer15f7e012006-05-30 21:18:23 +0000277}
278
Reid Spencere0d133f2006-05-29 18:08:06 +0000279// printEscapedString - Print each character of the specified string, escaping
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000280// it if it is not printable or if it is an escape char.
Reid Spencere0d133f2006-05-29 18:08:06 +0000281void
282CppWriter::printEscapedString(const std::string &Str) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000283 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
284 unsigned char C = Str[i];
285 if (isprint(C) && C != '"' && C != '\\') {
286 Out << C;
287 } else {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000288 Out << "\\x"
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000289 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
290 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
291 }
292 }
293}
294
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000295std::string
296CppWriter::getCppName(const Type* Ty)
297{
298 // First, handle the primitive types .. easy
299 if (Ty->isPrimitiveType()) {
300 switch (Ty->getTypeID()) {
301 case Type::VoidTyID: return "Type::VoidTy";
302 case Type::BoolTyID: return "Type::BoolTy";
303 case Type::UByteTyID: return "Type::UByteTy";
304 case Type::SByteTyID: return "Type::SByteTy";
305 case Type::UShortTyID: return "Type::UShortTy";
306 case Type::ShortTyID: return "Type::ShortTy";
307 case Type::UIntTyID: return "Type::UIntTy";
308 case Type::IntTyID: return "Type::IntTy";
309 case Type::ULongTyID: return "Type::ULongTy";
310 case Type::LongTyID: return "Type::LongTy";
311 case Type::FloatTyID: return "Type::FloatTy";
312 case Type::DoubleTyID: return "Type::DoubleTy";
313 case Type::LabelTyID: return "Type::LabelTy";
314 default:
Reid Spencer12803f52006-05-31 17:31:38 +0000315 error("Invalid primitive type");
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000316 break;
317 }
318 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
319 }
320
321 // Now, see if we've seen the type before and return that
322 TypeMap::iterator I = TypeNames.find(Ty);
323 if (I != TypeNames.end())
324 return I->second;
325
326 // Okay, let's build a new name for this type. Start with a prefix
327 const char* prefix = 0;
328 switch (Ty->getTypeID()) {
329 case Type::FunctionTyID: prefix = "FuncTy_"; break;
330 case Type::StructTyID: prefix = "StructTy_"; break;
331 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
332 case Type::PointerTyID: prefix = "PointerTy_"; break;
333 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
334 case Type::PackedTyID: prefix = "PackedTy_"; break;
335 default: prefix = "OtherTy_"; break; // prevent breakage
336 }
337
338 // See if the type has a name in the symboltable and build accordingly
339 const std::string* tName = findTypeName(TheModule->getSymbolTable(), Ty);
340 std::string name;
341 if (tName)
342 name = std::string(prefix) + *tName;
343 else
344 name = std::string(prefix) + utostr(uniqueNum++);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000345 sanitize(name);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000346
347 // Save the name
348 return TypeNames[Ty] = name;
349}
350
Reid Spencer12803f52006-05-31 17:31:38 +0000351void
352CppWriter::printCppName(const Type* Ty)
353{
354 printEscapedString(getCppName(Ty));
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000355}
356
Reid Spencer12803f52006-05-31 17:31:38 +0000357std::string
358CppWriter::getCppName(const Value* val) {
359 std::string name;
360 ValueMap::iterator I = ValueNames.find(val);
361 if (I != ValueNames.end() && I->first == val)
362 return I->second;
Reid Spencer25edc352006-05-31 04:43:19 +0000363
Reid Spencer12803f52006-05-31 17:31:38 +0000364 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
365 name = std::string("gvar_") +
366 getTypePrefix(GV->getType()->getElementType());
367 } else if (const Function* F = dyn_cast<Function>(val)) {
368 name = std::string("func_");
369 } else if (const Constant* C = dyn_cast<Constant>(val)) {
370 name = std::string("const_") + getTypePrefix(C->getType());
Reid Spencerf977e7b2006-06-01 23:43:47 +0000371 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
372 if (is_inline) {
373 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
374 Function::const_arg_iterator(Arg)) + 1;
375 name = std::string("arg_") + utostr(argNum);
376 NameSet::iterator NI = UsedNames.find(name);
377 if (NI != UsedNames.end())
378 name += std::string("_") + utostr(uniqueNum++);
379 UsedNames.insert(name);
380 return ValueNames[val] = name;
381 } else {
382 name = getTypePrefix(val->getType());
383 }
Reid Spencer12803f52006-05-31 17:31:38 +0000384 } else {
385 name = getTypePrefix(val->getType());
Reid Spencer25edc352006-05-31 04:43:19 +0000386 }
Reid Spencer12803f52006-05-31 17:31:38 +0000387 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
388 sanitize(name);
389 NameSet::iterator NI = UsedNames.find(name);
390 if (NI != UsedNames.end())
391 name += std::string("_") + utostr(uniqueNum++);
392 UsedNames.insert(name);
393 return ValueNames[val] = name;
Reid Spencer25edc352006-05-31 04:43:19 +0000394}
395
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000396void
Reid Spencer12803f52006-05-31 17:31:38 +0000397CppWriter::printCppName(const Value* val) {
398 printEscapedString(getCppName(val));
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000399}
400
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000401bool
Reid Spencer12803f52006-05-31 17:31:38 +0000402CppWriter::printTypeInternal(const Type* Ty) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000403 // We don't print definitions for primitive types
404 if (Ty->isPrimitiveType())
405 return false;
406
Reid Spencer15f7e012006-05-30 21:18:23 +0000407 // If we already defined this type, we don't need to define it again.
408 if (DefinedTypes.find(Ty) != DefinedTypes.end())
409 return false;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000410
Reid Spencer15f7e012006-05-30 21:18:23 +0000411 // Everything below needs the name for the type so get it now.
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000412 std::string typeName(getCppName(Ty));
413
414 // Search the type stack for recursion. If we find it, then generate this
415 // as an OpaqueType, but make sure not to do this multiple times because
416 // the type could appear in multiple places on the stack. Once the opaque
Reid Spencer15f7e012006-05-30 21:18:23 +0000417 // definition is issued, it must not be re-issued. Consequently we have to
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000418 // check the UnresolvedTypes list as well.
Reid Spencer12803f52006-05-31 17:31:38 +0000419 TypeList::const_iterator TI = std::find(TypeStack.begin(),TypeStack.end(),Ty);
420 if (TI != TypeStack.end()) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000421 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
422 if (I == UnresolvedTypes.end()) {
423 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();\n";
424 UnresolvedTypes[Ty] = typeName;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000425 }
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000426 return true;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000427 }
428
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000429 // We're going to print a derived type which, by definition, contains other
430 // types. So, push this one we're printing onto the type stack to assist with
431 // recursive definitions.
Reid Spencer15f7e012006-05-30 21:18:23 +0000432 TypeStack.push_back(Ty);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000433
434 // Print the type definition
435 switch (Ty->getTypeID()) {
436 case Type::FunctionTyID: {
437 const FunctionType* FT = cast<FunctionType>(Ty);
438 Out << "std::vector<const Type*>" << typeName << "_args;\n";
439 FunctionType::param_iterator PI = FT->param_begin();
440 FunctionType::param_iterator PE = FT->param_end();
441 for (; PI != PE; ++PI) {
442 const Type* argTy = static_cast<const Type*>(*PI);
Reid Spencer12803f52006-05-31 17:31:38 +0000443 bool isForward = printTypeInternal(argTy);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000444 std::string argName(getCppName(argTy));
445 Out << typeName << "_args.push_back(" << argName;
446 if (isForward)
447 Out << "_fwd";
448 Out << ");\n";
449 }
Reid Spencer12803f52006-05-31 17:31:38 +0000450 bool isForward = printTypeInternal(FT->getReturnType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000451 std::string retTypeName(getCppName(FT->getReturnType()));
452 Out << "FunctionType* " << typeName << " = FunctionType::get(\n"
453 << " /*Result=*/" << retTypeName;
454 if (isForward)
455 Out << "_fwd";
456 Out << ",\n /*Params=*/" << typeName << "_args,\n /*isVarArg=*/"
457 << (FT->isVarArg() ? "true" : "false") << ");\n";
458 break;
459 }
460 case Type::StructTyID: {
461 const StructType* ST = cast<StructType>(Ty);
462 Out << "std::vector<const Type*>" << typeName << "_fields;\n";
463 StructType::element_iterator EI = ST->element_begin();
464 StructType::element_iterator EE = ST->element_end();
465 for (; EI != EE; ++EI) {
466 const Type* fieldTy = static_cast<const Type*>(*EI);
Reid Spencer12803f52006-05-31 17:31:38 +0000467 bool isForward = printTypeInternal(fieldTy);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000468 std::string fieldName(getCppName(fieldTy));
469 Out << typeName << "_fields.push_back(" << fieldName;
470 if (isForward)
471 Out << "_fwd";
472 Out << ");\n";
473 }
474 Out << "StructType* " << typeName << " = StructType::get("
475 << typeName << "_fields);\n";
476 break;
477 }
478 case Type::ArrayTyID: {
479 const ArrayType* AT = cast<ArrayType>(Ty);
480 const Type* ET = AT->getElementType();
Reid Spencer12803f52006-05-31 17:31:38 +0000481 bool isForward = printTypeInternal(ET);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000482 std::string elemName(getCppName(ET));
483 Out << "ArrayType* " << typeName << " = ArrayType::get("
484 << elemName << (isForward ? "_fwd" : "")
485 << ", " << utostr(AT->getNumElements()) << ");\n";
486 break;
487 }
488 case Type::PointerTyID: {
489 const PointerType* PT = cast<PointerType>(Ty);
490 const Type* ET = PT->getElementType();
Reid Spencer12803f52006-05-31 17:31:38 +0000491 bool isForward = printTypeInternal(ET);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000492 std::string elemName(getCppName(ET));
493 Out << "PointerType* " << typeName << " = PointerType::get("
494 << elemName << (isForward ? "_fwd" : "") << ");\n";
495 break;
496 }
497 case Type::PackedTyID: {
498 const PackedType* PT = cast<PackedType>(Ty);
499 const Type* ET = PT->getElementType();
Reid Spencer12803f52006-05-31 17:31:38 +0000500 bool isForward = printTypeInternal(ET);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000501 std::string elemName(getCppName(ET));
502 Out << "PackedType* " << typeName << " = PackedType::get("
503 << elemName << (isForward ? "_fwd" : "")
504 << ", " << utostr(PT->getNumElements()) << ");\n";
505 break;
506 }
507 case Type::OpaqueTyID: {
508 const OpaqueType* OT = cast<OpaqueType>(Ty);
509 Out << "OpaqueType* " << typeName << " = OpaqueType::get();\n";
510 break;
511 }
512 default:
Reid Spencer12803f52006-05-31 17:31:38 +0000513 error("Invalid TypeID");
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000514 }
515
Reid Spencer74e032a2006-05-29 02:58:15 +0000516 // If the type had a name, make sure we recreate it.
517 const std::string* progTypeName =
518 findTypeName(TheModule->getSymbolTable(),Ty);
519 if (progTypeName)
520 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
521 << typeName << ");\n";
522
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000523 // Pop us off the type stack
524 TypeStack.pop_back();
Reid Spencer15f7e012006-05-30 21:18:23 +0000525
526 // Indicate that this type is now defined.
527 DefinedTypes.insert(Ty);
528
529 // Early resolve as many unresolved types as possible. Search the unresolved
530 // types map for the type we just printed. Now that its definition is complete
531 // we can resolve any previous references to it. This prevents a cascade of
532 // unresolved types.
533 TypeMap::iterator I = UnresolvedTypes.find(Ty);
534 if (I != UnresolvedTypes.end()) {
535 Out << "cast<OpaqueType>(" << I->second
536 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");\n";
537 Out << I->second << " = cast<";
538 switch (Ty->getTypeID()) {
539 case Type::FunctionTyID: Out << "FunctionType"; break;
540 case Type::ArrayTyID: Out << "ArrayType"; break;
541 case Type::StructTyID: Out << "StructType"; break;
542 case Type::PackedTyID: Out << "PackedType"; break;
543 case Type::PointerTyID: Out << "PointerType"; break;
544 case Type::OpaqueTyID: Out << "OpaqueType"; break;
545 default: Out << "NoSuchDerivedType"; break;
546 }
547 Out << ">(" << I->second << "_fwd.get());\n\n";
548 UnresolvedTypes.erase(I);
549 }
550
551 // Finally, separate the type definition from other with a newline.
Reid Spencere0d133f2006-05-29 18:08:06 +0000552 Out << "\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000553
554 // We weren't a recursive type
555 return false;
556}
557
Reid Spencer12803f52006-05-31 17:31:38 +0000558// Prints a type definition. Returns true if it could not resolve all the types
559// in the definition but had to use a forward reference.
560void
561CppWriter::printType(const Type* Ty) {
562 assert(TypeStack.empty());
563 TypeStack.clear();
564 printTypeInternal(Ty);
565 assert(TypeStack.empty());
566}
567
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000568void
569CppWriter::printTypes(const Module* M) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000570
571 // Walk the symbol table and print out all its types
572 const SymbolTable& symtab = M->getSymbolTable();
573 for (SymbolTable::type_const_iterator TI = symtab.type_begin(),
574 TE = symtab.type_end(); TI != TE; ++TI) {
575
576 // For primitive types and types already defined, just add a name
577 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
578 if (TI->second->isPrimitiveType() || TNI != TypeNames.end()) {
579 Out << "mod->addTypeName(\"";
580 printEscapedString(TI->first);
581 Out << "\", " << getCppName(TI->second) << ");\n";
582 // For everything else, define the type
583 } else {
Reid Spencer12803f52006-05-31 17:31:38 +0000584 printType(TI->second);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000585 }
586 }
587
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000588 // Add all of the global variables to the value table...
589 for (Module::const_global_iterator I = TheModule->global_begin(),
590 E = TheModule->global_end(); I != E; ++I) {
591 if (I->hasInitializer())
Reid Spencer12803f52006-05-31 17:31:38 +0000592 printType(I->getInitializer()->getType());
593 printType(I->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000594 }
595
596 // Add all the functions to the table
597 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
598 FI != FE; ++FI) {
Reid Spencer12803f52006-05-31 17:31:38 +0000599 printType(FI->getReturnType());
600 printType(FI->getFunctionType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000601 // Add all the function arguments
602 for(Function::const_arg_iterator AI = FI->arg_begin(),
603 AE = FI->arg_end(); AI != AE; ++AI) {
Reid Spencer12803f52006-05-31 17:31:38 +0000604 printType(AI->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000605 }
606
607 // Add all of the basic blocks and instructions
608 for (Function::const_iterator BB = FI->begin(),
609 E = FI->end(); BB != E; ++BB) {
Reid Spencer12803f52006-05-31 17:31:38 +0000610 printType(BB->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000611 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
612 ++I) {
Reid Spencer12803f52006-05-31 17:31:38 +0000613 printType(I->getType());
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000614 for (unsigned i = 0; i < I->getNumOperands(); ++i)
Reid Spencer12803f52006-05-31 17:31:38 +0000615 printType(I->getOperand(i)->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000616 }
617 }
618 }
619}
620
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000621
Reid Spencere0d133f2006-05-29 18:08:06 +0000622// printConstant - Print out a constant pool entry...
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000623void CppWriter::printConstant(const Constant *CV) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000624 // First, if the constant is actually a GlobalValue (variable or function) or
625 // its already in the constant list then we've printed it already and we can
626 // just return.
627 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
Reid Spencere0d133f2006-05-29 18:08:06 +0000628 return;
629
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000630 const int IndentSize = 2;
631 static std::string Indent = "\n";
632 std::string constName(getCppName(CV));
633 std::string typeName(getCppName(CV->getType()));
634 if (CV->isNullValue()) {
635 Out << "Constant* " << constName << " = Constant::getNullValue("
636 << typeName << ");\n";
637 return;
638 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000639 if (isa<GlobalValue>(CV)) {
640 // Skip variables and functions, we emit them elsewhere
641 return;
642 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000643 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000644 Out << "ConstantBool* " << constName << " = ConstantBool::get("
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000645 << (CB == ConstantBool::True ? "true" : "false")
646 << ");";
647 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000648 Out << "ConstantSInt* " << constName << " = ConstantSInt::get("
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000649 << typeName << ", " << CI->getValue() << ");";
650 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000651 Out << "ConstantUInt* " << constName << " = ConstantUInt::get("
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000652 << typeName << ", " << CI->getValue() << ");";
653 } else if (isa<ConstantAggregateZero>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000654 Out << "ConstantAggregateZero* " << constName
655 << " = ConstantAggregateZero::get(" << typeName << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000656 } else if (isa<ConstantPointerNull>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000657 Out << "ConstantPointerNull* " << constName
658 << " = ConstanPointerNull::get(" << typeName << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000659 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
Reid Spencerf977e7b2006-06-01 23:43:47 +0000660 Out << "ConstantFP* " << constName << " = ";
Reid Spencer12803f52006-05-31 17:31:38 +0000661 printCFP(CFP);
Reid Spencerf977e7b2006-06-01 23:43:47 +0000662 Out << ";";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000663 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000664 if (CA->isString() && CA->getType()->getElementType() == Type::SByteTy) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000665 Out << "Constant* " << constName << " = ConstantArray::get(\"";
Reid Spencere0d133f2006-05-29 18:08:06 +0000666 printEscapedString(CA->getAsString());
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000667 // Determine if we want null termination or not.
668 if (CA->getType()->getNumElements() <= CA->getAsString().length())
Reid Spencer15f7e012006-05-30 21:18:23 +0000669 Out << "\", false";// No null terminator
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000670 else
Reid Spencer15f7e012006-05-30 21:18:23 +0000671 Out << "\", true"; // Indicate that the null terminator should be added.
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000672 Out << ");";
673 } else {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000674 Out << "std::vector<Constant*> " << constName << "_elems;\n";
675 unsigned N = CA->getNumOperands();
676 for (unsigned i = 0; i < N; ++i) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000677 printConstant(CA->getOperand(i)); // recurse to print operands
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000678 Out << constName << "_elems.push_back("
679 << getCppName(CA->getOperand(i)) << ");\n";
680 }
681 Out << "Constant* " << constName << " = ConstantArray::get("
682 << typeName << ", " << constName << "_elems);";
683 }
684 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
685 Out << "std::vector<Constant*> " << constName << "_fields;\n";
686 unsigned N = CS->getNumOperands();
687 for (unsigned i = 0; i < N; i++) {
688 printConstant(CS->getOperand(i));
689 Out << constName << "_fields.push_back("
Reid Spencer66c87342006-05-30 03:43:49 +0000690 << getCppName(CS->getOperand(i)) << ");\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000691 }
692 Out << "Constant* " << constName << " = ConstantStruct::get("
693 << typeName << ", " << constName << "_fields);";
694 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
695 Out << "std::vector<Constant*> " << constName << "_elems;\n";
696 unsigned N = CP->getNumOperands();
697 for (unsigned i = 0; i < N; ++i) {
698 printConstant(CP->getOperand(i));
699 Out << constName << "_elems.push_back("
700 << getCppName(CP->getOperand(i)) << ");\n";
701 }
702 Out << "Constant* " << constName << " = ConstantPacked::get("
703 << typeName << ", " << constName << "_elems);";
704 } else if (isa<UndefValue>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000705 Out << "UndefValue* " << constName << " = UndefValue::get("
Reid Spencere0d133f2006-05-29 18:08:06 +0000706 << typeName << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000707 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000708 if (CE->getOpcode() == Instruction::GetElementPtr) {
709 Out << "std::vector<Constant*> " << constName << "_indices;\n";
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000710 printConstant(CE->getOperand(0));
Reid Spencere0d133f2006-05-29 18:08:06 +0000711 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000712 printConstant(CE->getOperand(i));
Reid Spencere0d133f2006-05-29 18:08:06 +0000713 Out << constName << "_indices.push_back("
714 << getCppName(CE->getOperand(i)) << ");\n";
715 }
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000716 Out << "Constant* " << constName
717 << " = ConstantExpr::getGetElementPtr("
718 << getCppName(CE->getOperand(0)) << ", "
719 << constName << "_indices);";
Reid Spencere0d133f2006-05-29 18:08:06 +0000720 } else if (CE->getOpcode() == Instruction::Cast) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000721 printConstant(CE->getOperand(0));
Reid Spencere0d133f2006-05-29 18:08:06 +0000722 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
723 Out << getCppName(CE->getOperand(0)) << ", " << getCppName(CE->getType())
724 << ");";
725 } else {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000726 unsigned N = CE->getNumOperands();
727 for (unsigned i = 0; i < N; ++i ) {
728 printConstant(CE->getOperand(i));
729 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000730 Out << "Constant* " << constName << " = ConstantExpr::";
731 switch (CE->getOpcode()) {
732 case Instruction::Add: Out << "getAdd"; break;
733 case Instruction::Sub: Out << "getSub"; break;
734 case Instruction::Mul: Out << "getMul"; break;
735 case Instruction::Div: Out << "getDiv"; break;
736 case Instruction::Rem: Out << "getRem"; break;
737 case Instruction::And: Out << "getAnd"; break;
738 case Instruction::Or: Out << "getOr"; break;
739 case Instruction::Xor: Out << "getXor"; break;
740 case Instruction::SetEQ: Out << "getSetEQ"; break;
741 case Instruction::SetNE: Out << "getSetNE"; break;
742 case Instruction::SetLE: Out << "getSetLE"; break;
743 case Instruction::SetGE: Out << "getSetGE"; break;
744 case Instruction::SetLT: Out << "getSetLT"; break;
745 case Instruction::SetGT: Out << "getSetGT"; break;
746 case Instruction::Shl: Out << "getShl"; break;
747 case Instruction::Shr: Out << "getShr"; break;
748 case Instruction::Select: Out << "getSelect"; break;
749 case Instruction::ExtractElement: Out << "getExtractElement"; break;
750 case Instruction::InsertElement: Out << "getInsertElement"; break;
751 case Instruction::ShuffleVector: Out << "getShuffleVector"; break;
752 default:
Reid Spencer12803f52006-05-31 17:31:38 +0000753 error("Invalid constant expression");
Reid Spencere0d133f2006-05-29 18:08:06 +0000754 break;
755 }
756 Out << getCppName(CE->getOperand(0));
757 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
758 Out << ", " << getCppName(CE->getOperand(i));
759 Out << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000760 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000761 } else {
Reid Spencer12803f52006-05-31 17:31:38 +0000762 error("Bad Constant");
Reid Spencere0d133f2006-05-29 18:08:06 +0000763 Out << "Constant* " << constName << " = 0; ";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000764 }
765 Out << "\n";
766}
767
Reid Spencer12803f52006-05-31 17:31:38 +0000768void
769CppWriter::printConstants(const Module* M) {
770 // Traverse all the global variables looking for constant initializers
771 for (Module::const_global_iterator I = TheModule->global_begin(),
772 E = TheModule->global_end(); I != E; ++I)
773 if (I->hasInitializer())
774 printConstant(I->getInitializer());
775
776 // Traverse the LLVM functions looking for constants
777 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
778 FI != FE; ++FI) {
779 // Add all of the basic blocks and instructions
780 for (Function::const_iterator BB = FI->begin(),
781 E = FI->end(); BB != E; ++BB) {
782 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
783 ++I) {
784 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
785 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
786 printConstant(C);
787 }
788 }
789 }
790 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000791 }
Reid Spencer66c87342006-05-30 03:43:49 +0000792}
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000793
Reid Spencer12803f52006-05-31 17:31:38 +0000794void CppWriter::printVariableUses(const GlobalVariable *GV) {
795 Out << "\n// Type Definitions\n";
796 printType(GV->getType());
797 if (GV->hasInitializer()) {
798 Constant* Init = GV->getInitializer();
799 printType(Init->getType());
800 if (Function* F = dyn_cast<Function>(Init)) {
801 Out << "\n// Function Declarations\n";
802 printFunctionHead(F);
803 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
804 Out << "\n// Global Variable Declarations\n";
805 printVariableHead(gv);
806 } else {
807 Out << "\n// Constant Definitions\n";
808 printConstant(gv);
809 }
810 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
811 Out << "\n// Global Variable Definitions\n";
812 printVariableBody(gv);
Reid Spencere0d133f2006-05-29 18:08:06 +0000813 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000814 }
Reid Spencer12803f52006-05-31 17:31:38 +0000815}
Reid Spencer15f7e012006-05-30 21:18:23 +0000816
Reid Spencer12803f52006-05-31 17:31:38 +0000817void CppWriter::printVariableHead(const GlobalVariable *GV) {
Reid Spencerf977e7b2006-06-01 23:43:47 +0000818 Out << "\nGlobalVariable* " << getCppName(GV);
819 if (is_inline) {
820 Out << " = mod->getGlobalVariable(";
821 printEscapedString(GV->getName());
822 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)\n";
823 Out << "if (!" << getCppName(GV) << ") {\n " << getCppName(GV);
824 }
Reid Spencer12803f52006-05-31 17:31:38 +0000825 Out << " = new GlobalVariable(\n";
826 Out << " /*Type=*/";
827 printCppName(GV->getType()->getElementType());
828 Out << ",\n";
829 Out << " /*isConstant=*/" << (GV->isConstant()?"true":"false")
830 << ",\n /*Linkage=*/";
831 printLinkageType(GV->getLinkage());
832 Out << ",\n /*Initializer=*/0, ";
833 if (GV->hasInitializer()) {
834 Out << "// has initializer, specified below";
Reid Spencer15f7e012006-05-30 21:18:23 +0000835 }
Reid Spencer12803f52006-05-31 17:31:38 +0000836 Out << "\n /*Name=*/\"";
837 printEscapedString(GV->getName());
838 Out << "\",\n mod);\n";
839
840 if (GV->hasSection()) {
841 printCppName(GV);
842 Out << "->setSection(\"";
843 printEscapedString(GV->getSection());
844 Out << "\");\n";
845 }
846 if (GV->getAlignment()) {
847 printCppName(GV);
848 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");\n";
849 };
Reid Spencerf977e7b2006-06-01 23:43:47 +0000850 if (is_inline)
851 Out << "}\n";
Reid Spencer12803f52006-05-31 17:31:38 +0000852}
853
854void
855CppWriter::printVariableBody(const GlobalVariable *GV) {
856 if (GV->hasInitializer()) {
857 printCppName(GV);
858 Out << "->setInitializer(";
859 //if (!isa<GlobalValue(GV->getInitializer()))
860 //else
861 Out << getCppName(GV->getInitializer()) << ");\n";
862 }
863}
864
865std::string
866CppWriter::getOpName(Value* V) {
867 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
868 return getCppName(V);
869
870 // See if its alread in the map of forward references, if so just return the
871 // name we already set up for it
872 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
873 if (I != ForwardRefs.end())
874 return I->second;
875
876 // This is a new forward reference. Generate a unique name for it
877 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
878
879 // Yes, this is a hack. An Argument is the smallest instantiable value that
880 // we can make as a placeholder for the real value. We'll replace these
881 // Argument instances later.
882 Out << " Argument* " << result << " = new Argument("
883 << getCppName(V->getType()) << ");\n";
884 ForwardRefs[V] = result;
885 return result;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000886}
887
Reid Spencere0d133f2006-05-29 18:08:06 +0000888// printInstruction - This member is called for each Instruction in a function.
889void
Reid Spencer12803f52006-05-31 17:31:38 +0000890CppWriter::printInstruction(const Instruction *I, const std::string& bbname) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000891 std::string iName(getCppName(I));
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000892
Reid Spencer15f7e012006-05-30 21:18:23 +0000893 // Before we emit this instruction, we need to take care of generating any
894 // forward references. So, we get the names of all the operands in advance
895 std::string* opNames = new std::string[I->getNumOperands()];
896 for (unsigned i = 0; i < I->getNumOperands(); i++) {
897 opNames[i] = getOpName(I->getOperand(i));
898 }
899
Reid Spencere0d133f2006-05-29 18:08:06 +0000900 switch (I->getOpcode()) {
901 case Instruction::Ret: {
902 const ReturnInst* ret = cast<ReturnInst>(I);
Reid Spencer15f7e012006-05-30 21:18:23 +0000903 Out << " ReturnInst* " << iName << " = new ReturnInst("
904 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
Reid Spencere0d133f2006-05-29 18:08:06 +0000905 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000906 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000907 case Instruction::Br: {
908 const BranchInst* br = cast<BranchInst>(I);
Reid Spencer66c87342006-05-30 03:43:49 +0000909 Out << " BranchInst* " << iName << " = new BranchInst(" ;
Reid Spencere0d133f2006-05-29 18:08:06 +0000910 if (br->getNumOperands() == 3 ) {
Reid Spencer15f7e012006-05-30 21:18:23 +0000911 Out << opNames[0] << ", "
912 << opNames[1] << ", "
913 << opNames[2] << ", ";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000914
Reid Spencere0d133f2006-05-29 18:08:06 +0000915 } else if (br->getNumOperands() == 1) {
Reid Spencer15f7e012006-05-30 21:18:23 +0000916 Out << opNames[0] << ", ";
Reid Spencere0d133f2006-05-29 18:08:06 +0000917 } else {
Reid Spencer12803f52006-05-31 17:31:38 +0000918 error("Branch with 2 operands?");
Reid Spencere0d133f2006-05-29 18:08:06 +0000919 }
920 Out << bbname << ");";
921 break;
922 }
Reid Spencer66c87342006-05-30 03:43:49 +0000923 case Instruction::Switch: {
924 const SwitchInst* sw = cast<SwitchInst>(I);
925 Out << " SwitchInst* " << iName << " = new SwitchInst("
Reid Spencer15f7e012006-05-30 21:18:23 +0000926 << opNames[0] << ", "
927 << opNames[1] << ", "
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000928 << sw->getNumCases() << ", " << bbname << ");\n";
Reid Spencer15f7e012006-05-30 21:18:23 +0000929 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
Reid Spencer66c87342006-05-30 03:43:49 +0000930 Out << " " << iName << "->addCase("
Reid Spencer15f7e012006-05-30 21:18:23 +0000931 << opNames[i] << ", "
932 << opNames[i+1] << ");\n";
Reid Spencer66c87342006-05-30 03:43:49 +0000933 }
934 break;
935 }
936 case Instruction::Invoke: {
937 const InvokeInst* inv = cast<InvokeInst>(I);
938 Out << " std::vector<Value*> " << iName << "_params;\n";
939 for (unsigned i = 3; i < inv->getNumOperands(); ++i)
940 Out << " " << iName << "_params.push_back("
Reid Spencer15f7e012006-05-30 21:18:23 +0000941 << opNames[i] << ");\n";
Reid Spencer66c87342006-05-30 03:43:49 +0000942 Out << " InvokeInst* " << iName << " = new InvokeInst("
Reid Spencer15f7e012006-05-30 21:18:23 +0000943 << opNames[0] << ", "
944 << opNames[1] << ", "
945 << opNames[2] << ", "
Reid Spencer66c87342006-05-30 03:43:49 +0000946 << iName << "_params, \"";
947 printEscapedString(inv->getName());
948 Out << "\", " << bbname << ");\n";
949 Out << iName << "->setCallingConv(";
950 printCallingConv(inv->getCallingConv());
951 Out << ");";
952 break;
953 }
954 case Instruction::Unwind: {
955 Out << " UnwindInst* " << iName << " = new UnwindInst("
956 << bbname << ");";
957 break;
958 }
959 case Instruction::Unreachable:{
960 Out << " UnreachableInst* " << iName << " = new UnreachableInst("
961 << bbname << ");";
962 break;
963 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000964 case Instruction::Add:
965 case Instruction::Sub:
966 case Instruction::Mul:
967 case Instruction::Div:
968 case Instruction::Rem:
969 case Instruction::And:
970 case Instruction::Or:
971 case Instruction::Xor:
Reid Spencer66c87342006-05-30 03:43:49 +0000972 case Instruction::Shl:
973 case Instruction::Shr:{
974 Out << " BinaryOperator* " << iName << " = BinaryOperator::create(";
975 switch (I->getOpcode()) {
976 case Instruction::Add: Out << "Instruction::Add"; break;
977 case Instruction::Sub: Out << "Instruction::Sub"; break;
978 case Instruction::Mul: Out << "Instruction::Mul"; break;
979 case Instruction::Div: Out << "Instruction::Div"; break;
980 case Instruction::Rem: Out << "Instruction::Rem"; break;
981 case Instruction::And: Out << "Instruction::And"; break;
982 case Instruction::Or: Out << "Instruction::Or"; break;
983 case Instruction::Xor: Out << "Instruction::Xor"; break;
984 case Instruction::Shl: Out << "Instruction::Shl"; break;
985 case Instruction::Shr: Out << "Instruction::Shr"; break;
986 default: Out << "Instruction::BadOpCode"; break;
987 }
Reid Spencer15f7e012006-05-30 21:18:23 +0000988 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +0000989 printEscapedString(I->getName());
990 Out << "\", " << bbname << ");";
991 break;
992 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000993 case Instruction::SetEQ:
994 case Instruction::SetNE:
995 case Instruction::SetLE:
996 case Instruction::SetGE:
997 case Instruction::SetLT:
Reid Spencer66c87342006-05-30 03:43:49 +0000998 case Instruction::SetGT: {
999 Out << " SetCondInst* " << iName << " = new SetCondInst(";
1000 switch (I->getOpcode()) {
1001 case Instruction::SetEQ: Out << "Instruction::SetEQ"; break;
1002 case Instruction::SetNE: Out << "Instruction::SetNE"; break;
1003 case Instruction::SetLE: Out << "Instruction::SetLE"; break;
1004 case Instruction::SetGE: Out << "Instruction::SetGE"; break;
1005 case Instruction::SetLT: Out << "Instruction::SetLT"; break;
1006 case Instruction::SetGT: Out << "Instruction::SetGT"; break;
1007 default: Out << "Instruction::BadOpCode"; break;
1008 }
Reid Spencer15f7e012006-05-30 21:18:23 +00001009 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001010 printEscapedString(I->getName());
1011 Out << "\", " << bbname << ");";
1012 break;
1013 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001014 case Instruction::Malloc: {
1015 const MallocInst* mallocI = cast<MallocInst>(I);
Reid Spencer66c87342006-05-30 03:43:49 +00001016 Out << " MallocInst* " << iName << " = new MallocInst("
Reid Spencere0d133f2006-05-29 18:08:06 +00001017 << getCppName(mallocI->getAllocatedType()) << ", ";
1018 if (mallocI->isArrayAllocation())
Reid Spencer15f7e012006-05-30 21:18:23 +00001019 Out << opNames[0] << ", " ;
Reid Spencere0d133f2006-05-29 18:08:06 +00001020 Out << "\"";
1021 printEscapedString(mallocI->getName());
1022 Out << "\", " << bbname << ");";
1023 if (mallocI->getAlignment())
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001024 Out << "\n " << iName << "->setAlignment("
Reid Spencere0d133f2006-05-29 18:08:06 +00001025 << mallocI->getAlignment() << ");";
1026 break;
1027 }
Reid Spencer66c87342006-05-30 03:43:49 +00001028 case Instruction::Free: {
1029 Out << " FreeInst* " << iName << " = new FreeInst("
1030 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1031 break;
1032 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001033 case Instruction::Alloca: {
1034 const AllocaInst* allocaI = cast<AllocaInst>(I);
Reid Spencer66c87342006-05-30 03:43:49 +00001035 Out << " AllocaInst* " << iName << " = new AllocaInst("
Reid Spencere0d133f2006-05-29 18:08:06 +00001036 << getCppName(allocaI->getAllocatedType()) << ", ";
1037 if (allocaI->isArrayAllocation())
Reid Spencer15f7e012006-05-30 21:18:23 +00001038 Out << opNames[0] << ", ";
Reid Spencere0d133f2006-05-29 18:08:06 +00001039 Out << "\"";
1040 printEscapedString(allocaI->getName());
1041 Out << "\", " << bbname << ");";
1042 if (allocaI->getAlignment())
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001043 Out << "\n " << iName << "->setAlignment("
Reid Spencere0d133f2006-05-29 18:08:06 +00001044 << allocaI->getAlignment() << ");";
1045 break;
1046 }
Reid Spencer66c87342006-05-30 03:43:49 +00001047 case Instruction::Load:{
1048 const LoadInst* load = cast<LoadInst>(I);
1049 Out << " LoadInst* " << iName << " = new LoadInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001050 << opNames[0] << ", \"";
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001051 printEscapedString(load->getName());
1052 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1053 << ", " << bbname << ");\n";
Reid Spencer66c87342006-05-30 03:43:49 +00001054 break;
1055 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001056 case Instruction::Store: {
1057 const StoreInst* store = cast<StoreInst>(I);
Reid Spencer66c87342006-05-30 03:43:49 +00001058 Out << " StoreInst* " << iName << " = new StoreInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001059 << opNames[0] << ", "
1060 << opNames[1] << ", "
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001061 << (store->isVolatile() ? "true" : "false")
1062 << ", " << bbname << ");\n";
Reid Spencere0d133f2006-05-29 18:08:06 +00001063 break;
1064 }
1065 case Instruction::GetElementPtr: {
1066 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1067 if (gep->getNumOperands() <= 2) {
Reid Spencer66c87342006-05-30 03:43:49 +00001068 Out << " GetElementPtrInst* " << iName << " = new GetElementPtrInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001069 << opNames[0];
Reid Spencere0d133f2006-05-29 18:08:06 +00001070 if (gep->getNumOperands() == 2)
Reid Spencer15f7e012006-05-30 21:18:23 +00001071 Out << ", " << opNames[1];
Reid Spencere0d133f2006-05-29 18:08:06 +00001072 } else {
Reid Spencer66c87342006-05-30 03:43:49 +00001073 Out << " std::vector<Value*> " << iName << "_indices;\n";
Reid Spencere0d133f2006-05-29 18:08:06 +00001074 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
Reid Spencer66c87342006-05-30 03:43:49 +00001075 Out << " " << iName << "_indices.push_back("
Reid Spencer15f7e012006-05-30 21:18:23 +00001076 << opNames[i] << ");\n";
Reid Spencere0d133f2006-05-29 18:08:06 +00001077 }
Reid Spencer66c87342006-05-30 03:43:49 +00001078 Out << " Instruction* " << iName << " = new GetElementPtrInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001079 << opNames[0] << ", " << iName << "_indices";
Reid Spencere0d133f2006-05-29 18:08:06 +00001080 }
1081 Out << ", \"";
1082 printEscapedString(gep->getName());
1083 Out << "\", " << bbname << ");";
1084 break;
1085 }
Reid Spencer66c87342006-05-30 03:43:49 +00001086 case Instruction::PHI: {
1087 const PHINode* phi = cast<PHINode>(I);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001088
Reid Spencer66c87342006-05-30 03:43:49 +00001089 Out << " PHINode* " << iName << " = new PHINode("
1090 << getCppName(phi->getType()) << ", \"";
1091 printEscapedString(phi->getName());
1092 Out << "\", " << bbname << ");\n";
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001093 Out << " " << iName << "->reserveOperandSpace("
1094 << phi->getNumIncomingValues()
Reid Spencer66c87342006-05-30 03:43:49 +00001095 << ");\n";
Reid Spencer15f7e012006-05-30 21:18:23 +00001096 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001097 Out << " " << iName << "->addIncoming("
Reid Spencer15f7e012006-05-30 21:18:23 +00001098 << opNames[i] << ", " << opNames[i+1] << ");\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001099 }
Reid Spencer66c87342006-05-30 03:43:49 +00001100 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001101 }
Reid Spencer66c87342006-05-30 03:43:49 +00001102 case Instruction::Cast: {
1103 const CastInst* cst = cast<CastInst>(I);
1104 Out << " CastInst* " << iName << " = new CastInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001105 << opNames[0] << ", "
Reid Spencer66c87342006-05-30 03:43:49 +00001106 << getCppName(cst->getType()) << ", \"";
1107 printEscapedString(cst->getName());
1108 Out << "\", " << bbname << ");\n";
1109 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001110 }
Reid Spencer66c87342006-05-30 03:43:49 +00001111 case Instruction::Call:{
1112 const CallInst* call = cast<CallInst>(I);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001113 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1114 Out << " InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1115 << getCppName(ila->getFunctionType()) << ", \""
1116 << ila->getAsmString() << "\", \""
1117 << ila->getConstraintString() << "\","
1118 << (ila->hasSideEffects() ? "true" : "false") << ");\n";
1119 }
Reid Spencer66c87342006-05-30 03:43:49 +00001120 if (call->getNumOperands() > 3) {
1121 Out << " std::vector<Value*> " << iName << "_params;\n";
Reid Spencer15f7e012006-05-30 21:18:23 +00001122 for (unsigned i = 1; i < call->getNumOperands(); ++i)
1123 Out << " " << iName << "_params.push_back(" << opNames[i] << ");\n";
Reid Spencer66c87342006-05-30 03:43:49 +00001124 Out << " CallInst* " << iName << " = new CallInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001125 << opNames[0] << ", " << iName << "_params, \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001126 } else if (call->getNumOperands() == 3) {
1127 Out << " CallInst* " << iName << " = new CallInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001128 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001129 } else if (call->getNumOperands() == 2) {
1130 Out << " CallInst* " << iName << " = new CallInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001131 << opNames[0] << ", " << opNames[1] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001132 } else {
Reid Spencer15f7e012006-05-30 21:18:23 +00001133 Out << " CallInst* " << iName << " = new CallInst(" << opNames[0]
1134 << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001135 }
1136 printEscapedString(call->getName());
1137 Out << "\", " << bbname << ");\n";
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001138 Out << " " << iName << "->setCallingConv(";
Reid Spencer66c87342006-05-30 03:43:49 +00001139 printCallingConv(call->getCallingConv());
1140 Out << ");\n";
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001141 Out << " " << iName << "->setTailCall("
1142 << (call->isTailCall() ? "true":"false");
Reid Spencer66c87342006-05-30 03:43:49 +00001143 Out << ");";
1144 break;
1145 }
1146 case Instruction::Select: {
1147 const SelectInst* sel = cast<SelectInst>(I);
1148 Out << " SelectInst* " << getCppName(sel) << " = new SelectInst(";
Reid Spencer15f7e012006-05-30 21:18:23 +00001149 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001150 printEscapedString(sel->getName());
1151 Out << "\", " << bbname << ");\n";
1152 break;
1153 }
1154 case Instruction::UserOp1:
1155 /// FALL THROUGH
1156 case Instruction::UserOp2: {
1157 /// FIXME: What should be done here?
1158 break;
1159 }
1160 case Instruction::VAArg: {
1161 const VAArgInst* va = cast<VAArgInst>(I);
1162 Out << " VAArgInst* " << getCppName(va) << " = new VAArgInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001163 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001164 printEscapedString(va->getName());
1165 Out << "\", " << bbname << ");\n";
1166 break;
1167 }
1168 case Instruction::ExtractElement: {
1169 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1170 Out << " ExtractElementInst* " << getCppName(eei)
Reid Spencer15f7e012006-05-30 21:18:23 +00001171 << " = new ExtractElementInst(" << opNames[0]
1172 << ", " << opNames[1] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001173 printEscapedString(eei->getName());
1174 Out << "\", " << bbname << ");\n";
1175 break;
1176 }
1177 case Instruction::InsertElement: {
1178 const InsertElementInst* iei = cast<InsertElementInst>(I);
1179 Out << " InsertElementInst* " << getCppName(iei)
Reid Spencer15f7e012006-05-30 21:18:23 +00001180 << " = new InsertElementInst(" << opNames[0]
1181 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001182 printEscapedString(iei->getName());
1183 Out << "\", " << bbname << ");\n";
1184 break;
1185 }
1186 case Instruction::ShuffleVector: {
1187 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1188 Out << " ShuffleVectorInst* " << getCppName(svi)
Reid Spencer15f7e012006-05-30 21:18:23 +00001189 << " = new ShuffleVectorInst(" << opNames[0]
1190 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001191 printEscapedString(svi->getName());
1192 Out << "\", " << bbname << ");\n";
1193 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001194 }
1195 }
Reid Spencer68464b72006-06-15 16:09:59 +00001196 DefinedValues.insert(I);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001197 Out << "\n";
Reid Spencer15f7e012006-05-30 21:18:23 +00001198 delete [] opNames;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001199}
1200
Reid Spencer12803f52006-05-31 17:31:38 +00001201// Print out the types, constants and declarations needed by one function
1202void CppWriter::printFunctionUses(const Function* F) {
1203
1204 Out << "\n// Type Definitions\n";
Reid Spencerf977e7b2006-06-01 23:43:47 +00001205 if (!is_inline) {
1206 // Print the function's return type
1207 printType(F->getReturnType());
Reid Spencer12803f52006-05-31 17:31:38 +00001208
Reid Spencerf977e7b2006-06-01 23:43:47 +00001209 // Print the function's function type
1210 printType(F->getFunctionType());
Reid Spencer12803f52006-05-31 17:31:38 +00001211
Reid Spencerf977e7b2006-06-01 23:43:47 +00001212 // Print the types of each of the function's arguments
1213 for(Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1214 AI != AE; ++AI) {
1215 printType(AI->getType());
1216 }
Reid Spencer12803f52006-05-31 17:31:38 +00001217 }
1218
1219 // Print type definitions for every type referenced by an instruction and
1220 // make a note of any global values or constants that are referenced
1221 std::vector<GlobalValue*> gvs;
1222 std::vector<Constant*> consts;
1223 for (Function::const_iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB){
1224 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1225 I != E; ++I) {
1226 // Print the type of the instruction itself
1227 printType(I->getType());
1228
1229 // Print the type of each of the instruction's operands
1230 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1231 Value* operand = I->getOperand(i);
1232 printType(operand->getType());
1233 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand))
1234 gvs.push_back(GV);
1235 else if (Constant* C = dyn_cast<Constant>(operand))
1236 consts.push_back(C);
1237 }
1238 }
1239 }
1240
1241 // Print the function declarations for any functions encountered
1242 Out << "\n// Function Declarations\n";
1243 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1244 I != E; ++I) {
Reid Spencerf977e7b2006-06-01 23:43:47 +00001245 if (Function* Fun = dyn_cast<Function>(*I)) {
1246 if (!is_inline || Fun != F)
1247 printFunctionHead(Fun);
1248 }
Reid Spencer12803f52006-05-31 17:31:38 +00001249 }
1250
1251 // Print the global variable declarations for any variables encountered
1252 Out << "\n// Global Variable Declarations\n";
1253 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1254 I != E; ++I) {
1255 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1256 printVariableHead(F);
1257 }
1258
1259 // Print the constants found
1260 Out << "\n// Constant Definitions\n";
1261 for (std::vector<Constant*>::iterator I = consts.begin(), E = consts.end();
1262 I != E; ++I) {
Reid Spencerf977e7b2006-06-01 23:43:47 +00001263 printConstant(*I);
Reid Spencer12803f52006-05-31 17:31:38 +00001264 }
1265
1266 // Process the global variables definitions now that all the constants have
1267 // been emitted. These definitions just couple the gvars with their constant
1268 // initializers.
1269 Out << "\n// Global Variable Definitions\n";
1270 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1271 I != E; ++I) {
1272 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1273 printVariableBody(GV);
1274 }
1275}
1276
1277void CppWriter::printFunctionHead(const Function* F) {
Reid Spencerf977e7b2006-06-01 23:43:47 +00001278 Out << "\nFunction* " << getCppName(F);
1279 if (is_inline) {
1280 Out << " = mod->getFunction(\"";
1281 printEscapedString(F->getName());
1282 Out << "\", " << getCppName(F->getFunctionType()) << ");\n";
1283 Out << "if (!" << getCppName(F) << ") {\n";
1284 Out << getCppName(F);
1285 }
1286 Out<< " = new Function(\n"
Reid Spencer12803f52006-05-31 17:31:38 +00001287 << " /*Type=*/" << getCppName(F->getFunctionType()) << ",\n"
1288 << " /*Linkage=*/";
1289 printLinkageType(F->getLinkage());
1290 Out << ",\n /*Name=*/\"";
1291 printEscapedString(F->getName());
1292 Out << "\", mod); "
1293 << (F->isExternal()? "// (external, no body)" : "") << "\n";
1294 printCppName(F);
1295 Out << "->setCallingConv(";
1296 printCallingConv(F->getCallingConv());
1297 Out << ");\n";
1298 if (F->hasSection()) {
1299 printCppName(F);
1300 Out << "->setSection(\"" << F->getSection() << "\");\n";
1301 }
1302 if (F->getAlignment()) {
1303 printCppName(F);
1304 Out << "->setAlignment(" << F->getAlignment() << ");\n";
1305 }
Reid Spencerf977e7b2006-06-01 23:43:47 +00001306 if (is_inline) {
1307 Out << "}\n";
1308 }
Reid Spencer12803f52006-05-31 17:31:38 +00001309}
1310
1311void CppWriter::printFunctionBody(const Function *F) {
1312 if (F->isExternal())
1313 return; // external functions have no bodies.
1314
1315 // Clear the DefinedValues and ForwardRefs maps because we can't have
1316 // cross-function forward refs
1317 ForwardRefs.clear();
1318 DefinedValues.clear();
1319
1320 // Create all the argument values
Reid Spencerf977e7b2006-06-01 23:43:47 +00001321 if (!is_inline) {
1322 if (!F->arg_empty()) {
1323 Out << " Function::arg_iterator args = " << getCppName(F)
1324 << "->arg_begin();\n";
1325 }
1326 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1327 AI != AE; ++AI) {
1328 Out << " Value* " << getCppName(AI) << " = args++;\n";
1329 if (AI->hasName())
1330 Out << " " << getCppName(AI) << "->setName(\"" << AI->getName()
1331 << "\");\n";
1332 }
Reid Spencer12803f52006-05-31 17:31:38 +00001333 }
1334
1335 // Create all the basic blocks
1336 Out << "\n";
1337 for (Function::const_iterator BI = F->begin(), BE = F->end();
1338 BI != BE; ++BI) {
1339 std::string bbname(getCppName(BI));
1340 Out << " BasicBlock* " << bbname << " = new BasicBlock(\"";
1341 if (BI->hasName())
1342 printEscapedString(BI->getName());
1343 Out << "\"," << getCppName(BI->getParent()) << ",0);\n";
1344 }
1345
1346 // Output all of its basic blocks... for the function
1347 for (Function::const_iterator BI = F->begin(), BE = F->end();
1348 BI != BE; ++BI) {
1349 std::string bbname(getCppName(BI));
1350 Out << "\n // Block " << BI->getName() << " (" << bbname << ")\n";
1351
1352 // Output all of the instructions in the basic block...
1353 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1354 I != E; ++I) {
1355 printInstruction(I,bbname);
1356 }
1357 }
1358
1359 // Loop over the ForwardRefs and resolve them now that all instructions
1360 // are generated.
1361 if (!ForwardRefs.empty())
1362 Out << "\n // Resolve Forward References\n";
1363 while (!ForwardRefs.empty()) {
1364 ForwardRefMap::iterator I = ForwardRefs.begin();
1365 Out << " " << I->second << "->replaceAllUsesWith("
1366 << getCppName(I->first) << "); delete " << I->second << ";\n";
1367 ForwardRefs.erase(I);
1368 }
1369}
1370
Reid Spencerf977e7b2006-06-01 23:43:47 +00001371void CppWriter::printInline(const std::string& fname, const std::string& func) {
1372 const Function* F = TheModule->getNamedFunction(func);
1373 if (!F) {
1374 error(std::string("Function '") + func + "' not found in input module");
1375 return;
1376 }
1377 if (F->isExternal()) {
1378 error(std::string("Function '") + func + "' is external!");
1379 return;
1380 }
1381 Out << "\nBasicBlock* " << fname << "(Module* mod, Function *"
1382 << getCppName(F);
1383 unsigned arg_count = 1;
1384 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1385 AI != AE; ++AI) {
1386 Out << ", Value* arg_" << arg_count;
1387 }
1388 Out << ") {\n";
1389 is_inline = true;
1390 printFunctionUses(F);
1391 printFunctionBody(F);
1392 is_inline = false;
1393 Out << "return " << getCppName(F->begin()) << ";\n";
1394 Out << "}\n";
1395}
1396
Reid Spencer12803f52006-05-31 17:31:38 +00001397void CppWriter::printModuleBody() {
1398 // Print out all the type definitions
1399 Out << "\n// Type Definitions\n";
1400 printTypes(TheModule);
1401
1402 // Functions can call each other and global variables can reference them so
1403 // define all the functions first before emitting their function bodies.
1404 Out << "\n// Function Declarations\n";
1405 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1406 I != E; ++I)
1407 printFunctionHead(I);
1408
1409 // Process the global variables declarations. We can't initialze them until
1410 // after the constants are printed so just print a header for each global
1411 Out << "\n// Global Variable Declarations\n";
1412 for (Module::const_global_iterator I = TheModule->global_begin(),
1413 E = TheModule->global_end(); I != E; ++I) {
1414 printVariableHead(I);
1415 }
1416
1417 // Print out all the constants definitions. Constants don't recurse except
1418 // through GlobalValues. All GlobalValues have been declared at this point
1419 // so we can proceed to generate the constants.
1420 Out << "\n// Constant Definitions\n";
1421 printConstants(TheModule);
1422
1423 // Process the global variables definitions now that all the constants have
1424 // been emitted. These definitions just couple the gvars with their constant
1425 // initializers.
1426 Out << "\n// Global Variable Definitions\n";
1427 for (Module::const_global_iterator I = TheModule->global_begin(),
1428 E = TheModule->global_end(); I != E; ++I) {
1429 printVariableBody(I);
1430 }
1431
1432 // Finally, we can safely put out all of the function bodies.
1433 Out << "\n// Function Definitions\n";
1434 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1435 I != E; ++I) {
1436 if (!I->isExternal()) {
1437 Out << "\n// Function: " << I->getName() << " (" << getCppName(I)
1438 << ")\n{\n";
1439 printFunctionBody(I);
1440 Out << "}\n";
1441 }
1442 }
1443}
1444
1445void CppWriter::printProgram(
1446 const std::string& fname,
1447 const std::string& mName
1448) {
1449 Out << "#include <llvm/Module.h>\n";
1450 Out << "#include <llvm/DerivedTypes.h>\n";
1451 Out << "#include <llvm/Constants.h>\n";
1452 Out << "#include <llvm/GlobalVariable.h>\n";
1453 Out << "#include <llvm/Function.h>\n";
1454 Out << "#include <llvm/CallingConv.h>\n";
1455 Out << "#include <llvm/BasicBlock.h>\n";
1456 Out << "#include <llvm/Instructions.h>\n";
1457 Out << "#include <llvm/InlineAsm.h>\n";
Reid Spencerf977e7b2006-06-01 23:43:47 +00001458 Out << "#include <llvm/Support/MathExtras.h>\n";
Reid Spencer12803f52006-05-31 17:31:38 +00001459 Out << "#include <llvm/Pass.h>\n";
1460 Out << "#include <llvm/PassManager.h>\n";
1461 Out << "#include <llvm/Analysis/Verifier.h>\n";
1462 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1463 Out << "#include <algorithm>\n";
1464 Out << "#include <iostream>\n\n";
1465 Out << "using namespace llvm;\n\n";
1466 Out << "Module* " << fname << "();\n\n";
1467 Out << "int main(int argc, char**argv) {\n";
1468 Out << " Module* Mod = makeLLVMModule();\n";
1469 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1470 Out << " std::cerr.flush();\n";
1471 Out << " std::cout.flush();\n";
1472 Out << " PassManager PM;\n";
1473 Out << " PM.add(new PrintModulePass(&std::cout));\n";
1474 Out << " PM.run(*Mod);\n";
1475 Out << " return 0;\n";
1476 Out << "}\n\n";
1477 printModule(fname,mName);
1478}
1479
1480void CppWriter::printModule(
1481 const std::string& fname,
1482 const std::string& mName
1483) {
1484 Out << "\nModule* " << fname << "() {\n";
1485 Out << "\n// Module Construction\n";
Reid Spencerad67a042006-06-01 07:24:29 +00001486 Out << "\nModule* mod = new Module(\"" << mName << "\");\n";
Reid Spencer12803f52006-05-31 17:31:38 +00001487 Out << "mod->setEndianness(";
1488 switch (TheModule->getEndianness()) {
1489 case Module::LittleEndian: Out << "Module::LittleEndian);\n"; break;
1490 case Module::BigEndian: Out << "Module::BigEndian);\n"; break;
1491 case Module::AnyEndianness:Out << "Module::AnyEndianness);\n"; break;
1492 }
1493 Out << "mod->setPointerSize(";
1494 switch (TheModule->getPointerSize()) {
1495 case Module::Pointer32: Out << "Module::Pointer32);\n"; break;
1496 case Module::Pointer64: Out << "Module::Pointer64);\n"; break;
1497 case Module::AnyPointerSize: Out << "Module::AnyPointerSize);\n"; break;
1498 }
1499 if (!TheModule->getTargetTriple().empty())
1500 Out << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1501 << "\");\n";
1502
1503 if (!TheModule->getModuleInlineAsm().empty()) {
1504 Out << "mod->setModuleInlineAsm(\"";
1505 printEscapedString(TheModule->getModuleInlineAsm());
1506 Out << "\");\n";
1507 }
1508
1509 // Loop over the dependent libraries and emit them.
1510 Module::lib_iterator LI = TheModule->lib_begin();
1511 Module::lib_iterator LE = TheModule->lib_end();
1512 while (LI != LE) {
1513 Out << "mod->addLibrary(\"" << *LI << "\");\n";
1514 ++LI;
1515 }
1516 printModuleBody();
1517 Out << "\nreturn mod;\n";
1518 Out << "}\n";
1519}
1520
1521void CppWriter::printContents(
1522 const std::string& fname, // Name of generated function
1523 const std::string& mName // Name of module generated module
1524) {
1525 Out << "\nModule* " << fname << "(Module *mod) {\n";
1526 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
Reid Spencer12803f52006-05-31 17:31:38 +00001527 printModuleBody();
1528 Out << "\nreturn mod;\n";
1529 Out << "\n}\n";
1530}
1531
1532void CppWriter::printFunction(
1533 const std::string& fname, // Name of generated function
1534 const std::string& funcName // Name of function to generate
1535) {
1536 const Function* F = TheModule->getNamedFunction(funcName);
1537 if (!F) {
1538 error(std::string("Function '") + funcName + "' not found in input module");
1539 return;
1540 }
1541 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1542 printFunctionUses(F);
1543 printFunctionHead(F);
1544 printFunctionBody(F);
1545 Out << "return " << getCppName(F) << ";\n";
1546 Out << "}\n";
1547}
1548
1549void CppWriter::printVariable(
1550 const std::string& fname, /// Name of generated function
1551 const std::string& varName // Name of variable to generate
1552) {
1553 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1554
1555 if (!GV) {
1556 error(std::string("Variable '") + varName + "' not found in input module");
1557 return;
1558 }
1559 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1560 printVariableUses(GV);
1561 printVariableHead(GV);
1562 printVariableBody(GV);
1563 Out << "return " << getCppName(GV) << ";\n";
1564 Out << "}\n";
1565}
1566
1567void CppWriter::printType(
1568 const std::string& fname, /// Name of generated function
1569 const std::string& typeName // Name of type to generate
1570) {
1571 const Type* Ty = TheModule->getTypeByName(typeName);
1572 if (!Ty) {
1573 error(std::string("Type '") + typeName + "' not found in input module");
1574 return;
1575 }
1576 Out << "\nType* " << fname << "(Module *mod) {\n";
1577 printType(Ty);
1578 Out << "return " << getCppName(Ty) << ";\n";
1579 Out << "}\n";
1580}
1581
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001582} // end anonymous llvm
1583
1584namespace llvm {
1585
1586void WriteModuleToCppFile(Module* mod, std::ostream& o) {
Reid Spencer12803f52006-05-31 17:31:38 +00001587 // Initialize a CppWriter for us to use
1588 CppWriter W(o, mod);
1589
1590 // Emit a header
Reid Spencer25edc352006-05-31 04:43:19 +00001591 o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
Reid Spencer12803f52006-05-31 17:31:38 +00001592
1593 // Get the name of the function we're supposed to generate
Reid Spencer15f7e012006-05-30 21:18:23 +00001594 std::string fname = FuncName.getValue();
Reid Spencer12803f52006-05-31 17:31:38 +00001595
1596 // Get the name of the thing we are to generate
1597 std::string tgtname = NameToGenerate.getValue();
1598 if (GenerationType == GenModule ||
1599 GenerationType == GenContents ||
1600 GenerationType == GenProgram) {
1601 if (tgtname == "!bad!") {
1602 if (mod->getModuleIdentifier() == "-")
1603 tgtname = "<stdin>";
1604 else
1605 tgtname = mod->getModuleIdentifier();
1606 }
1607 } else if (tgtname == "!bad!") {
1608 W.error("You must use the -for option with -gen-{function,variable,type}");
1609 }
1610
1611 switch (WhatToGenerate(GenerationType)) {
1612 case GenProgram:
1613 if (fname.empty())
1614 fname = "makeLLVMModule";
1615 W.printProgram(fname,tgtname);
1616 break;
1617 case GenModule:
1618 if (fname.empty())
1619 fname = "makeLLVMModule";
1620 W.printModule(fname,tgtname);
1621 break;
1622 case GenContents:
1623 if (fname.empty())
1624 fname = "makeLLVMModuleContents";
1625 W.printContents(fname,tgtname);
1626 break;
1627 case GenFunction:
1628 if (fname.empty())
1629 fname = "makeLLVMFunction";
1630 W.printFunction(fname,tgtname);
1631 break;
Reid Spencerf977e7b2006-06-01 23:43:47 +00001632 case GenInline:
1633 if (fname.empty())
1634 fname = "makeLLVMInline";
1635 W.printInline(fname,tgtname);
1636 break;
Reid Spencer12803f52006-05-31 17:31:38 +00001637 case GenVariable:
1638 if (fname.empty())
1639 fname = "makeLLVMVariable";
1640 W.printVariable(fname,tgtname);
1641 break;
1642 case GenType:
1643 if (fname.empty())
1644 fname = "makeLLVMType";
1645 W.printType(fname,tgtname);
1646 break;
1647 default:
1648 W.error("Invalid generation option");
Reid Spencer15f7e012006-05-30 21:18:23 +00001649 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001650}
1651
1652}