blob: a30635eb2fcbaf30c07b3d5617438aaf6e504a6b [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"
27#include <algorithm>
28#include <iostream>
Reid Spencer66c87342006-05-30 03:43:49 +000029#include <set>
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000030
31using namespace llvm;
32
33namespace {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000034typedef std::vector<const Type*> TypeList;
35typedef std::map<const Type*,std::string> TypeMap;
36typedef std::map<const Value*,std::string> ValueMap;
Reid Spencer66c87342006-05-30 03:43:49 +000037typedef std::set<std::string> NameSet;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000038
Reid Spencere0d133f2006-05-29 18:08:06 +000039class CppWriter {
40 std::ostream &Out;
41 const Module *TheModule;
42 unsigned long uniqueNum;
43 TypeMap TypeNames;
44 ValueMap ValueNames;
45 TypeMap UnresolvedTypes;
46 TypeList TypeStack;
Reid Spencer66c87342006-05-30 03:43:49 +000047 NameSet UsedNames;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000048
Reid Spencere0d133f2006-05-29 18:08:06 +000049public:
50 inline CppWriter(std::ostream &o, const Module *M)
51 : Out(o), TheModule(M), uniqueNum(0), TypeNames(),
52 ValueNames(), UnresolvedTypes(), TypeStack() { }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000053
Reid Spencere0d133f2006-05-29 18:08:06 +000054 const Module* getModule() { return TheModule; }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000055
Reid Spencere0d133f2006-05-29 18:08:06 +000056 void printModule(const Module *M);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000057
Reid Spencere0d133f2006-05-29 18:08:06 +000058private:
59 void printTypes(const Module* M);
60 void printConstants(const Module* M);
61 void printConstant(const Constant *CPV);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +000062 void printGlobalHead(const GlobalVariable *GV);
63 void printGlobalBody(const GlobalVariable *GV);
Reid Spencer66c87342006-05-30 03:43:49 +000064 void printFunctionHead(const Function *F);
65 void printFunctionBody(const Function *F);
Reid Spencere0d133f2006-05-29 18:08:06 +000066 void printInstruction(const Instruction *I, const std::string& bbname);
67 void printSymbolTable(const SymbolTable &ST);
68 void printLinkageType(GlobalValue::LinkageTypes LT);
69 void printCallingConv(unsigned cc);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000070
Reid Spencere0d133f2006-05-29 18:08:06 +000071 std::string getCppName(const Type* val);
72 std::string getCppName(const Value* val);
73 inline void printCppName(const Value* val);
74 inline void printCppName(const Type* val);
75 bool isOnStack(const Type*) const;
76 inline void printTypeDef(const Type* Ty);
77 bool printTypeDefInternal(const Type* Ty);
78 void printEscapedString(const std::string& str);
79};
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000080
Reid Spencere0d133f2006-05-29 18:08:06 +000081// printEscapedString - Print each character of the specified string, escaping
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000082// it if it is not printable or if it is an escape char.
Reid Spencere0d133f2006-05-29 18:08:06 +000083void
84CppWriter::printEscapedString(const std::string &Str) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000085 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
86 unsigned char C = Str[i];
87 if (isprint(C) && C != '"' && C != '\\') {
88 Out << C;
89 } else {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +000090 Out << "\\x"
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000091 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
92 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
93 }
94 }
95}
96
Reid Spencer1a2a0cc2006-05-30 10:21:41 +000097inline void
98sanitize(std::string& str) {
99 for (size_t i = 0; i < str.length(); ++i)
100 if (!isalnum(str[i]) && str[i] != '_')
101 str[i] = '_';
102}
103
Reid Spencer66c87342006-05-30 03:43:49 +0000104inline const char*
105getTypePrefix(const Type* Ty ) {
106 const char* prefix;
107 switch (Ty->getTypeID()) {
108 case Type::VoidTyID: prefix = "void_"; break;
109 case Type::BoolTyID: prefix = "bool_"; break;
110 case Type::UByteTyID: prefix = "ubyte_"; break;
111 case Type::SByteTyID: prefix = "sbyte_"; break;
112 case Type::UShortTyID: prefix = "ushort_"; break;
113 case Type::ShortTyID: prefix = "short_"; break;
114 case Type::UIntTyID: prefix = "uint_"; break;
115 case Type::IntTyID: prefix = "int_"; break;
116 case Type::ULongTyID: prefix = "ulong_"; break;
117 case Type::LongTyID: prefix = "long_"; break;
118 case Type::FloatTyID: prefix = "float_"; break;
119 case Type::DoubleTyID: prefix = "double_"; break;
120 case Type::LabelTyID: prefix = "label_"; break;
121 case Type::FunctionTyID: prefix = "func_"; break;
122 case Type::StructTyID: prefix = "struct_"; break;
123 case Type::ArrayTyID: prefix = "array_"; break;
124 case Type::PointerTyID: prefix = "ptr_"; break;
125 case Type::PackedTyID: prefix = "packed_"; break;
126 case Type::OpaqueTyID: prefix = "opaque_"; break;
127 default: prefix = "other_"; break;
128 }
129 return prefix;
130}
131
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000132std::string
133CppWriter::getCppName(const Value* val) {
134 std::string name;
135 ValueMap::iterator I = ValueNames.find(val);
Reid Spencer66c87342006-05-30 03:43:49 +0000136 if (I != ValueNames.end() && I->first == val)
137 return I->second;
138
139 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
140 name = std::string("gvar_") +
141 getTypePrefix(GV->getType()->getElementType());
142 } else if (const Function* F = dyn_cast<Function>(val)) {
143 name = std::string("func_");
144 } else if (const Constant* C = dyn_cast<Constant>(val)) {
145 name = std::string("const_") + getTypePrefix(C->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000146 } else {
Reid Spencer66c87342006-05-30 03:43:49 +0000147 name = getTypePrefix(val->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000148 }
Reid Spencer66c87342006-05-30 03:43:49 +0000149 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000150 sanitize(name);
Reid Spencer66c87342006-05-30 03:43:49 +0000151 NameSet::iterator NI = UsedNames.find(name);
152 if (NI != UsedNames.end())
153 name += std::string("_") + utostr(uniqueNum++);
154 UsedNames.insert(name);
155 return ValueNames[val] = name;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000156}
157
158void
159CppWriter::printCppName(const Value* val) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000160 printEscapedString(getCppName(val));
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000161}
162
163void
164CppWriter::printCppName(const Type* Ty)
165{
Reid Spencere0d133f2006-05-29 18:08:06 +0000166 printEscapedString(getCppName(Ty));
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000167}
168
169// Gets the C++ name for a type. Returns true if we already saw the type,
170// false otherwise.
171//
172inline const std::string*
173findTypeName(const SymbolTable& ST, const Type* Ty)
174{
175 SymbolTable::type_const_iterator TI = ST.type_begin();
176 SymbolTable::type_const_iterator TE = ST.type_end();
177 for (;TI != TE; ++TI)
178 if (TI->second == Ty)
179 return &(TI->first);
180 return 0;
181}
182
183std::string
184CppWriter::getCppName(const Type* Ty)
185{
186 // First, handle the primitive types .. easy
187 if (Ty->isPrimitiveType()) {
188 switch (Ty->getTypeID()) {
189 case Type::VoidTyID: return "Type::VoidTy";
190 case Type::BoolTyID: return "Type::BoolTy";
191 case Type::UByteTyID: return "Type::UByteTy";
192 case Type::SByteTyID: return "Type::SByteTy";
193 case Type::UShortTyID: return "Type::UShortTy";
194 case Type::ShortTyID: return "Type::ShortTy";
195 case Type::UIntTyID: return "Type::UIntTy";
196 case Type::IntTyID: return "Type::IntTy";
197 case Type::ULongTyID: return "Type::ULongTy";
198 case Type::LongTyID: return "Type::LongTy";
199 case Type::FloatTyID: return "Type::FloatTy";
200 case Type::DoubleTyID: return "Type::DoubleTy";
201 case Type::LabelTyID: return "Type::LabelTy";
202 default:
203 assert(!"Can't get here");
204 break;
205 }
206 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
207 }
208
209 // Now, see if we've seen the type before and return that
210 TypeMap::iterator I = TypeNames.find(Ty);
211 if (I != TypeNames.end())
212 return I->second;
213
214 // Okay, let's build a new name for this type. Start with a prefix
215 const char* prefix = 0;
216 switch (Ty->getTypeID()) {
217 case Type::FunctionTyID: prefix = "FuncTy_"; break;
218 case Type::StructTyID: prefix = "StructTy_"; break;
219 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
220 case Type::PointerTyID: prefix = "PointerTy_"; break;
221 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
222 case Type::PackedTyID: prefix = "PackedTy_"; break;
223 default: prefix = "OtherTy_"; break; // prevent breakage
224 }
225
226 // See if the type has a name in the symboltable and build accordingly
227 const std::string* tName = findTypeName(TheModule->getSymbolTable(), Ty);
228 std::string name;
229 if (tName)
230 name = std::string(prefix) + *tName;
231 else
232 name = std::string(prefix) + utostr(uniqueNum++);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000233 sanitize(name);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000234
235 // Save the name
236 return TypeNames[Ty] = name;
237}
238
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000239void CppWriter::printModule(const Module *M) {
240 Out << "\n// Module Construction\n";
241 Out << "Module* mod = new Module(\"";
Reid Spencere0d133f2006-05-29 18:08:06 +0000242 if (M->getModuleIdentifier() == "-")
243 printEscapedString("<stdin>");
244 else
245 printEscapedString(M->getModuleIdentifier());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000246 Out << "\");\n";
247 Out << "mod->setEndianness(";
248 switch (M->getEndianness()) {
249 case Module::LittleEndian: Out << "Module::LittleEndian);\n"; break;
250 case Module::BigEndian: Out << "Module::BigEndian);\n"; break;
251 case Module::AnyEndianness:Out << "Module::AnyEndianness);\n"; break;
252 }
253 Out << "mod->setPointerSize(";
254 switch (M->getPointerSize()) {
255 case Module::Pointer32: Out << "Module::Pointer32);\n"; break;
256 case Module::Pointer64: Out << "Module::Pointer64);\n"; break;
257 case Module::AnyPointerSize: Out << "Module::AnyPointerSize);\n"; break;
258 }
259 if (!M->getTargetTriple().empty())
260 Out << "mod->setTargetTriple(\"" << M->getTargetTriple() << "\");\n";
261
262 if (!M->getModuleInlineAsm().empty()) {
263 Out << "mod->setModuleInlineAsm(\"";
Reid Spencere0d133f2006-05-29 18:08:06 +0000264 printEscapedString(M->getModuleInlineAsm());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000265 Out << "\");\n";
266 }
267
268 // Loop over the dependent libraries and emit them.
269 Module::lib_iterator LI = M->lib_begin();
270 Module::lib_iterator LE = M->lib_end();
271 while (LI != LE) {
272 Out << "mod->addLibrary(\"" << *LI << "\");\n";
273 ++LI;
274 }
275
276 // Print out all the type definitions
277 Out << "\n// Type Definitions\n";
278 printTypes(M);
279
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000280 // Functions can call each other and global variables can reference them so
281 // define all the functions first before emitting their function bodies.
Reid Spencer66c87342006-05-30 03:43:49 +0000282 Out << "\n// Function Declarations\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000283 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Reid Spencer66c87342006-05-30 03:43:49 +0000284 printFunctionHead(I);
285
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000286 // Process the global variables declarations. We can't initialze them until
287 // after the constants are printed so just print a header for each global
288 Out << "\n// Global Variable Declarations\n";
289 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
290 I != E; ++I) {
291 printGlobalHead(I);
292 }
293
294 // Print out all the constants definitions. Constants don't recurse except
295 // through GlobalValues. All GlobalValues have been declared at this point
296 // so we can proceed to generate the constants.
297 Out << "\n// Constant Definitions\n";
298 printConstants(M);
299
300 // Process the global variables definitions now that all the constants have
301 // been emitted. These definitions just couple the gvars with their constant
302 // initializers.
303 Out << "\n// Global Variable Definitions\n";
304 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
305 I != E; ++I) {
306 printGlobalBody(I);
307 }
308
309 // Finally, we can safely put out all of the function bodies.
Reid Spencer66c87342006-05-30 03:43:49 +0000310 Out << "\n// Function Definitions\n";
311 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000312 if (!I->isExternal()) {
313 Out << "\n// Function: " << I->getName() << " (" << getCppName(I)
314 << ")\n{\n";
315 printFunctionBody(I);
316 Out << "}\n";
317 }
Reid Spencer66c87342006-05-30 03:43:49 +0000318 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000319}
320
321void
322CppWriter::printCallingConv(unsigned cc){
323 // Print the calling convention.
324 switch (cc) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000325 case CallingConv::C: Out << "CallingConv::C"; break;
326 case CallingConv::CSRet: Out << "CallingConv::CSRet"; break;
327 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
328 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
329 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
Reid Spencer66c87342006-05-30 03:43:49 +0000330 default: Out << cc; break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000331 }
332}
333
334void
335CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
336 switch (LT) {
337 case GlobalValue::InternalLinkage:
338 Out << "GlobalValue::InternalLinkage"; break;
339 case GlobalValue::LinkOnceLinkage:
340 Out << "GlobalValue::LinkOnceLinkage "; break;
341 case GlobalValue::WeakLinkage:
342 Out << "GlobalValue::WeakLinkage"; break;
343 case GlobalValue::AppendingLinkage:
344 Out << "GlobalValue::AppendingLinkage"; break;
345 case GlobalValue::ExternalLinkage:
346 Out << "GlobalValue::ExternalLinkage"; break;
347 case GlobalValue::GhostLinkage:
348 Out << "GlobalValue::GhostLinkage"; break;
349 }
350}
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000351
352void CppWriter::printGlobalHead(const GlobalVariable *GV) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000353 Out << "\n";
354 Out << "GlobalVariable* ";
355 printCppName(GV);
356 Out << " = new GlobalVariable(\n";
357 Out << " /*Type=*/";
358 printCppName(GV->getType()->getElementType());
359 Out << ",\n";
360 Out << " /*isConstant=*/" << (GV->isConstant()?"true":"false")
361 << ",\n /*Linkage=*/";
362 printLinkageType(GV->getLinkage());
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000363 Out << ",\n /*Initializer=*/0, ";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000364 if (GV->hasInitializer()) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000365 Out << "// has initializer, specified below";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000366 }
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000367 Out << "\n /*Name=*/\"";
Reid Spencere0d133f2006-05-29 18:08:06 +0000368 printEscapedString(GV->getName());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000369 Out << "\",\n mod);\n";
370
371 if (GV->hasSection()) {
372 printCppName(GV);
373 Out << "->setSection(\"";
Reid Spencere0d133f2006-05-29 18:08:06 +0000374 printEscapedString(GV->getSection());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000375 Out << "\");\n";
376 }
377 if (GV->getAlignment()) {
378 printCppName(GV);
379 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");\n";
380 };
381}
382
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000383void
384CppWriter::printGlobalBody(const GlobalVariable *GV) {
385 if (GV->hasInitializer()) {
386 printCppName(GV);
387 Out << "->setInitializer(";
388 //if (!isa<GlobalValue(GV->getInitializer()))
389 //else
390 Out << getCppName(GV->getInitializer()) << ");\n";
391 }
392}
393
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000394bool
395CppWriter::isOnStack(const Type* Ty) const {
396 TypeList::const_iterator TI =
397 std::find(TypeStack.begin(),TypeStack.end(),Ty);
398 return TI != TypeStack.end();
399}
400
401// Prints a type definition. Returns true if it could not resolve all the types
402// in the definition but had to use a forward reference.
403void
404CppWriter::printTypeDef(const Type* Ty) {
405 assert(TypeStack.empty());
406 TypeStack.clear();
407 printTypeDefInternal(Ty);
408 assert(TypeStack.empty());
409 // early resolve as many unresolved types as possible. Search the unresolved
410 // types map for the type we just printed. Now that its definition is complete
411 // we can resolve any preview references to it. This prevents a cascade of
412 // unresolved types.
413 TypeMap::iterator I = UnresolvedTypes.find(Ty);
414 if (I != UnresolvedTypes.end()) {
415 Out << "cast<OpaqueType>(" << I->second
416 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");\n";
417 Out << I->second << " = cast<";
418 switch (Ty->getTypeID()) {
419 case Type::FunctionTyID: Out << "FunctionType"; break;
420 case Type::ArrayTyID: Out << "ArrayType"; break;
421 case Type::StructTyID: Out << "StructType"; break;
422 case Type::PackedTyID: Out << "PackedType"; break;
423 case Type::PointerTyID: Out << "PointerType"; break;
424 case Type::OpaqueTyID: Out << "OpaqueType"; break;
425 default: Out << "NoSuchDerivedType"; break;
426 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000427 Out << ">(" << I->second << "_fwd.get());\n\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000428 UnresolvedTypes.erase(I);
429 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000430}
431
432bool
433CppWriter::printTypeDefInternal(const Type* Ty) {
434 // We don't print definitions for primitive types
435 if (Ty->isPrimitiveType())
436 return false;
437
438 // Determine if the name is in the name list before we modify that list.
439 TypeMap::const_iterator TNI = TypeNames.find(Ty);
440
441 // Everything below needs the name for the type so get it now
442 std::string typeName(getCppName(Ty));
443
444 // Search the type stack for recursion. If we find it, then generate this
445 // as an OpaqueType, but make sure not to do this multiple times because
446 // the type could appear in multiple places on the stack. Once the opaque
447 // definition is issues, it must not be re-issued. Consequently we have to
448 // check the UnresolvedTypes list as well.
449 if (isOnStack(Ty)) {
450 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
451 if (I == UnresolvedTypes.end()) {
452 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();\n";
453 UnresolvedTypes[Ty] = typeName;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000454 }
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000455 return true;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000456 }
457
458 // Avoid printing things we have already printed. Since TNI was obtained
459 // before the name was inserted with getCppName and because we know the name
460 // is not on the stack (currently being defined), we can surmise here that if
461 // we got the name we've also already emitted its definition.
462 if (TNI != TypeNames.end())
463 return false;
464
465 // We're going to print a derived type which, by definition, contains other
466 // types. So, push this one we're printing onto the type stack to assist with
467 // recursive definitions.
468 TypeStack.push_back(Ty); // push on type stack
469 bool didRecurse = false;
470
471 // Print the type definition
472 switch (Ty->getTypeID()) {
473 case Type::FunctionTyID: {
474 const FunctionType* FT = cast<FunctionType>(Ty);
475 Out << "std::vector<const Type*>" << typeName << "_args;\n";
476 FunctionType::param_iterator PI = FT->param_begin();
477 FunctionType::param_iterator PE = FT->param_end();
478 for (; PI != PE; ++PI) {
479 const Type* argTy = static_cast<const Type*>(*PI);
480 bool isForward = printTypeDefInternal(argTy);
481 std::string argName(getCppName(argTy));
482 Out << typeName << "_args.push_back(" << argName;
483 if (isForward)
484 Out << "_fwd";
485 Out << ");\n";
486 }
487 bool isForward = printTypeDefInternal(FT->getReturnType());
488 std::string retTypeName(getCppName(FT->getReturnType()));
489 Out << "FunctionType* " << typeName << " = FunctionType::get(\n"
490 << " /*Result=*/" << retTypeName;
491 if (isForward)
492 Out << "_fwd";
493 Out << ",\n /*Params=*/" << typeName << "_args,\n /*isVarArg=*/"
494 << (FT->isVarArg() ? "true" : "false") << ");\n";
495 break;
496 }
497 case Type::StructTyID: {
498 const StructType* ST = cast<StructType>(Ty);
499 Out << "std::vector<const Type*>" << typeName << "_fields;\n";
500 StructType::element_iterator EI = ST->element_begin();
501 StructType::element_iterator EE = ST->element_end();
502 for (; EI != EE; ++EI) {
503 const Type* fieldTy = static_cast<const Type*>(*EI);
504 bool isForward = printTypeDefInternal(fieldTy);
505 std::string fieldName(getCppName(fieldTy));
506 Out << typeName << "_fields.push_back(" << fieldName;
507 if (isForward)
508 Out << "_fwd";
509 Out << ");\n";
510 }
511 Out << "StructType* " << typeName << " = StructType::get("
512 << typeName << "_fields);\n";
513 break;
514 }
515 case Type::ArrayTyID: {
516 const ArrayType* AT = cast<ArrayType>(Ty);
517 const Type* ET = AT->getElementType();
518 bool isForward = printTypeDefInternal(ET);
519 std::string elemName(getCppName(ET));
520 Out << "ArrayType* " << typeName << " = ArrayType::get("
521 << elemName << (isForward ? "_fwd" : "")
522 << ", " << utostr(AT->getNumElements()) << ");\n";
523 break;
524 }
525 case Type::PointerTyID: {
526 const PointerType* PT = cast<PointerType>(Ty);
527 const Type* ET = PT->getElementType();
528 bool isForward = printTypeDefInternal(ET);
529 std::string elemName(getCppName(ET));
530 Out << "PointerType* " << typeName << " = PointerType::get("
531 << elemName << (isForward ? "_fwd" : "") << ");\n";
532 break;
533 }
534 case Type::PackedTyID: {
535 const PackedType* PT = cast<PackedType>(Ty);
536 const Type* ET = PT->getElementType();
537 bool isForward = printTypeDefInternal(ET);
538 std::string elemName(getCppName(ET));
539 Out << "PackedType* " << typeName << " = PackedType::get("
540 << elemName << (isForward ? "_fwd" : "")
541 << ", " << utostr(PT->getNumElements()) << ");\n";
542 break;
543 }
544 case Type::OpaqueTyID: {
545 const OpaqueType* OT = cast<OpaqueType>(Ty);
546 Out << "OpaqueType* " << typeName << " = OpaqueType::get();\n";
547 break;
548 }
549 default:
550 assert(!"Invalid TypeID");
551 }
552
Reid Spencer74e032a2006-05-29 02:58:15 +0000553 // If the type had a name, make sure we recreate it.
554 const std::string* progTypeName =
555 findTypeName(TheModule->getSymbolTable(),Ty);
556 if (progTypeName)
557 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
558 << typeName << ");\n";
559
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000560 // Pop us off the type stack
561 TypeStack.pop_back();
Reid Spencere0d133f2006-05-29 18:08:06 +0000562 Out << "\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000563
564 // We weren't a recursive type
565 return false;
566}
567
568void
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 {
584 printTypeDef(TI->second);
585 }
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())
592 printTypeDef(I->getInitializer()->getType());
593 printTypeDef(I->getType());
594 }
595
596 // Add all the functions to the table
597 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
598 FI != FE; ++FI) {
599 printTypeDef(FI->getReturnType());
600 printTypeDef(FI->getFunctionType());
601 // Add all the function arguments
602 for(Function::const_arg_iterator AI = FI->arg_begin(),
603 AE = FI->arg_end(); AI != AE; ++AI) {
604 printTypeDef(AI->getType());
605 }
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) {
610 printTypeDef(BB->getType());
611 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
612 ++I) {
613 printTypeDef(I->getType());
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000614 for (unsigned i = 0; i < I->getNumOperands(); ++i)
615 printTypeDef(I->getOperand(i)->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000616 }
617 }
618 }
619}
620
621void
622CppWriter::printConstants(const Module* M) {
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())
627 printConstant(I->getInitializer());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000628
Reid Spencere0d133f2006-05-29 18:08:06 +0000629 // Traverse the LLVM functions looking for constants
630 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
631 FI != FE; ++FI) {
632 // Add all of the basic blocks and instructions
633 for (Function::const_iterator BB = FI->begin(),
634 E = FI->end(); BB != E; ++BB) {
635 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
636 ++I) {
637 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
638 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
639 printConstant(C);
640 }
641 }
642 }
643 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000644 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000645}
646
Reid Spencere0d133f2006-05-29 18:08:06 +0000647// printConstant - Print out a constant pool entry...
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000648void CppWriter::printConstant(const Constant *CV) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000649 // First, if the constant is actually a GlobalValue (variable or function) or
650 // its already in the constant list then we've printed it already and we can
651 // just return.
652 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
Reid Spencere0d133f2006-05-29 18:08:06 +0000653 return;
654
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000655 const int IndentSize = 2;
656 static std::string Indent = "\n";
657 std::string constName(getCppName(CV));
658 std::string typeName(getCppName(CV->getType()));
659 if (CV->isNullValue()) {
660 Out << "Constant* " << constName << " = Constant::getNullValue("
661 << typeName << ");\n";
662 return;
663 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000664 if (isa<GlobalValue>(CV)) {
665 // Skip variables and functions, we emit them elsewhere
666 return;
667 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000668 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000669 Out << "ConstantBool* " << constName << " = ConstantBool::get("
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000670 << (CB == ConstantBool::True ? "true" : "false")
671 << ");";
672 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000673 Out << "ConstantSInt* " << constName << " = ConstantSInt::get("
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000674 << typeName << ", " << CI->getValue() << ");";
675 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000676 Out << "ConstantUInt* " << constName << " = ConstantUInt::get("
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000677 << typeName << ", " << CI->getValue() << ");";
678 } else if (isa<ConstantAggregateZero>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000679 Out << "ConstantAggregateZero* " << constName
680 << " = ConstantAggregateZero::get(" << typeName << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000681 } else if (isa<ConstantPointerNull>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000682 Out << "ConstantPointerNull* " << constName
683 << " = ConstanPointerNull::get(" << typeName << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000684 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000685 Out << "ConstantFP* " << constName << " = ConstantFP::get(" << typeName
686 << ", ";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000687 // We would like to output the FP constant value in exponential notation,
688 // but we cannot do this if doing so will lose precision. Check here to
689 // make sure that we only output it in exponential format if we can parse
690 // the value back and get the same value.
691 //
692 std::string StrVal = ftostr(CFP->getValue());
693
694 // Check to make sure that the stringized number is not some string like
695 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
696 // the string matches the "[-+]?[0-9]" regex.
697 //
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000698 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000699 ((StrVal[0] == '-' || StrVal[0] == '+') &&
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000700 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
701 (atof(StrVal.c_str()) == CFP->getValue()))
702 {
703 Out << StrVal << ");";
704 } else {
705 // Otherwise we could not reparse it to exactly the same value, so we must
706 // output the string in hexadecimal format!
707 assert(sizeof(double) == sizeof(uint64_t) &&
708 "assuming double is 64 bits!");
709 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue())) << ");";
710 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000711 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000712 if (CA->isString() && CA->getType()->getElementType() == Type::SByteTy) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000713 Out << "Constant* " << constName << " = ConstantArray::get(\"";
Reid Spencere0d133f2006-05-29 18:08:06 +0000714 printEscapedString(CA->getAsString());
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000715 // Determine if we want null termination or not.
716 if (CA->getType()->getNumElements() <= CA->getAsString().length())
717 Out << "\", " << CA->getType()->getNumElements();
718 else
719 Out << "\", 0"; // Indicate that the null terminator should be added.
720 Out << ");";
721 } else {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000722 Out << "std::vector<Constant*> " << constName << "_elems;\n";
723 unsigned N = CA->getNumOperands();
724 for (unsigned i = 0; i < N; ++i) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000725 printConstant(CA->getOperand(i)); // recurse to print operands
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000726 Out << constName << "_elems.push_back("
727 << getCppName(CA->getOperand(i)) << ");\n";
728 }
729 Out << "Constant* " << constName << " = ConstantArray::get("
730 << typeName << ", " << constName << "_elems);";
731 }
732 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
733 Out << "std::vector<Constant*> " << constName << "_fields;\n";
734 unsigned N = CS->getNumOperands();
735 for (unsigned i = 0; i < N; i++) {
736 printConstant(CS->getOperand(i));
737 Out << constName << "_fields.push_back("
Reid Spencer66c87342006-05-30 03:43:49 +0000738 << getCppName(CS->getOperand(i)) << ");\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000739 }
740 Out << "Constant* " << constName << " = ConstantStruct::get("
741 << typeName << ", " << constName << "_fields);";
742 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
743 Out << "std::vector<Constant*> " << constName << "_elems;\n";
744 unsigned N = CP->getNumOperands();
745 for (unsigned i = 0; i < N; ++i) {
746 printConstant(CP->getOperand(i));
747 Out << constName << "_elems.push_back("
748 << getCppName(CP->getOperand(i)) << ");\n";
749 }
750 Out << "Constant* " << constName << " = ConstantPacked::get("
751 << typeName << ", " << constName << "_elems);";
752 } else if (isa<UndefValue>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000753 Out << "UndefValue* " << constName << " = UndefValue::get("
Reid Spencere0d133f2006-05-29 18:08:06 +0000754 << typeName << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000755 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000756 if (CE->getOpcode() == Instruction::GetElementPtr) {
757 Out << "std::vector<Constant*> " << constName << "_indices;\n";
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000758 printConstant(CE->getOperand(0));
Reid Spencere0d133f2006-05-29 18:08:06 +0000759 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000760 printConstant(CE->getOperand(i));
Reid Spencere0d133f2006-05-29 18:08:06 +0000761 Out << constName << "_indices.push_back("
762 << getCppName(CE->getOperand(i)) << ");\n";
763 }
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000764 Out << "Constant* " << constName
765 << " = ConstantExpr::getGetElementPtr("
766 << getCppName(CE->getOperand(0)) << ", "
767 << constName << "_indices);";
Reid Spencere0d133f2006-05-29 18:08:06 +0000768 } else if (CE->getOpcode() == Instruction::Cast) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000769 printConstant(CE->getOperand(0));
Reid Spencere0d133f2006-05-29 18:08:06 +0000770 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
771 Out << getCppName(CE->getOperand(0)) << ", " << getCppName(CE->getType())
772 << ");";
773 } else {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000774 unsigned N = CE->getNumOperands();
775 for (unsigned i = 0; i < N; ++i ) {
776 printConstant(CE->getOperand(i));
777 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000778 Out << "Constant* " << constName << " = ConstantExpr::";
779 switch (CE->getOpcode()) {
780 case Instruction::Add: Out << "getAdd"; break;
781 case Instruction::Sub: Out << "getSub"; break;
782 case Instruction::Mul: Out << "getMul"; break;
783 case Instruction::Div: Out << "getDiv"; break;
784 case Instruction::Rem: Out << "getRem"; break;
785 case Instruction::And: Out << "getAnd"; break;
786 case Instruction::Or: Out << "getOr"; break;
787 case Instruction::Xor: Out << "getXor"; break;
788 case Instruction::SetEQ: Out << "getSetEQ"; break;
789 case Instruction::SetNE: Out << "getSetNE"; break;
790 case Instruction::SetLE: Out << "getSetLE"; break;
791 case Instruction::SetGE: Out << "getSetGE"; break;
792 case Instruction::SetLT: Out << "getSetLT"; break;
793 case Instruction::SetGT: Out << "getSetGT"; break;
794 case Instruction::Shl: Out << "getShl"; break;
795 case Instruction::Shr: Out << "getShr"; break;
796 case Instruction::Select: Out << "getSelect"; break;
797 case Instruction::ExtractElement: Out << "getExtractElement"; break;
798 case Instruction::InsertElement: Out << "getInsertElement"; break;
799 case Instruction::ShuffleVector: Out << "getShuffleVector"; break;
800 default:
801 assert(!"Invalid constant expression");
802 break;
803 }
804 Out << getCppName(CE->getOperand(0));
805 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
806 Out << ", " << getCppName(CE->getOperand(i));
807 Out << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000808 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000809 } else {
Reid Spencere0d133f2006-05-29 18:08:06 +0000810 assert(!"Bad Constant");
811 Out << "Constant* " << constName << " = 0; ";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000812 }
813 Out << "\n";
814}
815
Reid Spencer66c87342006-05-30 03:43:49 +0000816void CppWriter::printFunctionHead(const Function* F) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000817 Out << "\nFunction* " << getCppName(F) << " = new Function(\n"
818 << " /*Type=*/" << getCppName(F->getFunctionType()) << ",\n"
819 << " /*Linkage=*/";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000820 printLinkageType(F->getLinkage());
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000821 Out << ",\n /*Name=*/\"";
822 printEscapedString(F->getName());
823 Out << "\", mod); "
824 << (F->isExternal()? "// (external, no body)" : "") << "\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000825 printCppName(F);
826 Out << "->setCallingConv(";
827 printCallingConv(F->getCallingConv());
828 Out << ");\n";
829 if (F->hasSection()) {
830 printCppName(F);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000831 Out << "->setSection(\"" << F->getSection() << "\");\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000832 }
833 if (F->getAlignment()) {
834 printCppName(F);
835 Out << "->setAlignment(" << F->getAlignment() << ");\n";
836 }
Reid Spencer66c87342006-05-30 03:43:49 +0000837}
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000838
Reid Spencer66c87342006-05-30 03:43:49 +0000839void CppWriter::printFunctionBody(const Function *F) {
840 if (F->isExternal())
841 return; // external functions have no bodies.
842
843 // Create all the argument values
844 if (!F->arg_empty()) {
845 Out << " Function::arg_iterator args = " << getCppName(F)
846 << "->arg_begin();\n";
847 }
848 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
849 AI != AE; ++AI) {
850 Out << " Value* " << getCppName(AI) << " = args++;\n";
851 if (AI->hasName())
852 Out << " " << getCppName(AI) << "->setName(\"" << AI->getName()
853 << "\");\n";
854 }
855
856 // Create all the basic blocks
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000857 Out << "\n";
Reid Spencer66c87342006-05-30 03:43:49 +0000858 for (Function::const_iterator BI = F->begin(), BE = F->end();
859 BI != BE; ++BI) {
860 std::string bbname(getCppName(BI));
861 Out << " BasicBlock* " << bbname << " = new BasicBlock(\"";
862 if (BI->hasName())
863 printEscapedString(BI->getName());
864 Out << "\"," << getCppName(BI->getParent()) << ",0);\n";
865 }
866
867 // Output all of its basic blocks... for the function
868 for (Function::const_iterator BI = F->begin(), BE = F->end();
869 BI != BE; ++BI) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000870 std::string bbname(getCppName(BI));
871 Out << "\n // Block " << BI->getName() << " (" << bbname << ")\n";
872
Reid Spencer66c87342006-05-30 03:43:49 +0000873 // Output all of the instructions in the basic block...
874 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
875 I != E; ++I) {
Reid Spencer66c87342006-05-30 03:43:49 +0000876 printInstruction(I,bbname);
Reid Spencere0d133f2006-05-29 18:08:06 +0000877 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000878 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000879}
880
Reid Spencere0d133f2006-05-29 18:08:06 +0000881// printInstruction - This member is called for each Instruction in a function.
882void
883CppWriter::printInstruction(const Instruction *I, const std::string& bbname)
884{
885 std::string iName(getCppName(I));
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000886
Reid Spencere0d133f2006-05-29 18:08:06 +0000887 switch (I->getOpcode()) {
888 case Instruction::Ret: {
889 const ReturnInst* ret = cast<ReturnInst>(I);
Reid Spencer66c87342006-05-30 03:43:49 +0000890 Out << " ReturnInst* " << iName << " = new ReturnInst(";
Reid Spencere0d133f2006-05-29 18:08:06 +0000891 if (ret->getReturnValue())
892 Out << getCppName(ret->getReturnValue()) << ", ";
893 Out << bbname << ");";
894 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000895 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000896 case Instruction::Br: {
897 const BranchInst* br = cast<BranchInst>(I);
Reid Spencer66c87342006-05-30 03:43:49 +0000898 Out << " BranchInst* " << iName << " = new BranchInst(" ;
Reid Spencere0d133f2006-05-29 18:08:06 +0000899 if (br->getNumOperands() == 3 ) {
900 Out << getCppName(br->getOperand(0)) << ", "
901 << getCppName(br->getOperand(1)) << ", "
902 << getCppName(br->getOperand(2)) << ", ";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000903
Reid Spencere0d133f2006-05-29 18:08:06 +0000904 } else if (br->getNumOperands() == 1) {
905 Out << getCppName(br->getOperand(0)) << ", ";
906 } else {
907 assert(!"branch with 2 operands?");
908 }
909 Out << bbname << ");";
910 break;
911 }
Reid Spencer66c87342006-05-30 03:43:49 +0000912 case Instruction::Switch: {
913 const SwitchInst* sw = cast<SwitchInst>(I);
914 Out << " SwitchInst* " << iName << " = new SwitchInst("
915 << getCppName(sw->getOperand(0)) << ", "
916 << getCppName(sw->getOperand(1)) << ", "
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000917 << sw->getNumCases() << ", " << bbname << ");\n";
Reid Spencer66c87342006-05-30 03:43:49 +0000918 for (unsigned i = 1; i < sw->getNumCases(); i++ ) {
919 Out << " " << iName << "->addCase("
920 << getCppName(sw->getCaseValue(i)) << ", "
921 << getCppName(sw->getSuccessor(i)) << ");\n";
922 }
923 break;
924 }
925 case Instruction::Invoke: {
926 const InvokeInst* inv = cast<InvokeInst>(I);
927 Out << " std::vector<Value*> " << iName << "_params;\n";
928 for (unsigned i = 3; i < inv->getNumOperands(); ++i)
929 Out << " " << iName << "_params.push_back("
930 << getCppName(inv->getOperand(i)) << ");\n";
931 Out << " InvokeInst* " << iName << " = new InvokeInst("
932 << getCppName(inv->getCalledFunction()) << ", "
933 << getCppName(inv->getNormalDest()) << ", "
934 << getCppName(inv->getUnwindDest()) << ", "
935 << iName << "_params, \"";
936 printEscapedString(inv->getName());
937 Out << "\", " << bbname << ");\n";
938 Out << iName << "->setCallingConv(";
939 printCallingConv(inv->getCallingConv());
940 Out << ");";
941 break;
942 }
943 case Instruction::Unwind: {
944 Out << " UnwindInst* " << iName << " = new UnwindInst("
945 << bbname << ");";
946 break;
947 }
948 case Instruction::Unreachable:{
949 Out << " UnreachableInst* " << iName << " = new UnreachableInst("
950 << bbname << ");";
951 break;
952 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000953 case Instruction::Add:
954 case Instruction::Sub:
955 case Instruction::Mul:
956 case Instruction::Div:
957 case Instruction::Rem:
958 case Instruction::And:
959 case Instruction::Or:
960 case Instruction::Xor:
Reid Spencer66c87342006-05-30 03:43:49 +0000961 case Instruction::Shl:
962 case Instruction::Shr:{
963 Out << " BinaryOperator* " << iName << " = BinaryOperator::create(";
964 switch (I->getOpcode()) {
965 case Instruction::Add: Out << "Instruction::Add"; break;
966 case Instruction::Sub: Out << "Instruction::Sub"; break;
967 case Instruction::Mul: Out << "Instruction::Mul"; break;
968 case Instruction::Div: Out << "Instruction::Div"; break;
969 case Instruction::Rem: Out << "Instruction::Rem"; break;
970 case Instruction::And: Out << "Instruction::And"; break;
971 case Instruction::Or: Out << "Instruction::Or"; break;
972 case Instruction::Xor: Out << "Instruction::Xor"; break;
973 case Instruction::Shl: Out << "Instruction::Shl"; break;
974 case Instruction::Shr: Out << "Instruction::Shr"; break;
975 default: Out << "Instruction::BadOpCode"; break;
976 }
977 Out << ", " << getCppName(I->getOperand(0));
978 Out << ", " << getCppName(I->getOperand(1)) << ", \"";
979 printEscapedString(I->getName());
980 Out << "\", " << bbname << ");";
981 break;
982 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000983 case Instruction::SetEQ:
984 case Instruction::SetNE:
985 case Instruction::SetLE:
986 case Instruction::SetGE:
987 case Instruction::SetLT:
Reid Spencer66c87342006-05-30 03:43:49 +0000988 case Instruction::SetGT: {
989 Out << " SetCondInst* " << iName << " = new SetCondInst(";
990 switch (I->getOpcode()) {
991 case Instruction::SetEQ: Out << "Instruction::SetEQ"; break;
992 case Instruction::SetNE: Out << "Instruction::SetNE"; break;
993 case Instruction::SetLE: Out << "Instruction::SetLE"; break;
994 case Instruction::SetGE: Out << "Instruction::SetGE"; break;
995 case Instruction::SetLT: Out << "Instruction::SetLT"; break;
996 case Instruction::SetGT: Out << "Instruction::SetGT"; break;
997 default: Out << "Instruction::BadOpCode"; break;
998 }
999 Out << ", " << getCppName(I->getOperand(0));
1000 Out << ", " << getCppName(I->getOperand(1)) << ", \"";
1001 printEscapedString(I->getName());
1002 Out << "\", " << bbname << ");";
1003 break;
1004 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001005 case Instruction::Malloc: {
1006 const MallocInst* mallocI = cast<MallocInst>(I);
Reid Spencer66c87342006-05-30 03:43:49 +00001007 Out << " MallocInst* " << iName << " = new MallocInst("
Reid Spencere0d133f2006-05-29 18:08:06 +00001008 << getCppName(mallocI->getAllocatedType()) << ", ";
1009 if (mallocI->isArrayAllocation())
1010 Out << getCppName(mallocI->getArraySize()) << ", ";
1011 Out << "\"";
1012 printEscapedString(mallocI->getName());
1013 Out << "\", " << bbname << ");";
1014 if (mallocI->getAlignment())
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001015 Out << "\n " << iName << "->setAlignment("
Reid Spencere0d133f2006-05-29 18:08:06 +00001016 << mallocI->getAlignment() << ");";
1017 break;
1018 }
Reid Spencer66c87342006-05-30 03:43:49 +00001019 case Instruction::Free: {
1020 Out << " FreeInst* " << iName << " = new FreeInst("
1021 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1022 break;
1023 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001024 case Instruction::Alloca: {
1025 const AllocaInst* allocaI = cast<AllocaInst>(I);
Reid Spencer66c87342006-05-30 03:43:49 +00001026 Out << " AllocaInst* " << iName << " = new AllocaInst("
Reid Spencere0d133f2006-05-29 18:08:06 +00001027 << getCppName(allocaI->getAllocatedType()) << ", ";
1028 if (allocaI->isArrayAllocation())
1029 Out << getCppName(allocaI->getArraySize()) << ", ";
1030 Out << "\"";
1031 printEscapedString(allocaI->getName());
1032 Out << "\", " << bbname << ");";
1033 if (allocaI->getAlignment())
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001034 Out << "\n " << iName << "->setAlignment("
Reid Spencere0d133f2006-05-29 18:08:06 +00001035 << allocaI->getAlignment() << ");";
1036 break;
1037 }
Reid Spencer66c87342006-05-30 03:43:49 +00001038 case Instruction::Load:{
1039 const LoadInst* load = cast<LoadInst>(I);
1040 Out << " LoadInst* " << iName << " = new LoadInst("
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001041 << getCppName(load->getOperand(0)) << ", \"";
1042 printEscapedString(load->getName());
1043 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1044 << ", " << bbname << ");\n";
Reid Spencer66c87342006-05-30 03:43:49 +00001045 break;
1046 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001047 case Instruction::Store: {
1048 const StoreInst* store = cast<StoreInst>(I);
Reid Spencer66c87342006-05-30 03:43:49 +00001049 Out << " StoreInst* " << iName << " = new StoreInst("
Reid Spencere0d133f2006-05-29 18:08:06 +00001050 << getCppName(store->getOperand(0)) << ", "
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001051 << getCppName(store->getOperand(1)) << ", "
1052 << (store->isVolatile() ? "true" : "false")
1053 << ", " << bbname << ");\n";
Reid Spencere0d133f2006-05-29 18:08:06 +00001054 break;
1055 }
1056 case Instruction::GetElementPtr: {
1057 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1058 if (gep->getNumOperands() <= 2) {
Reid Spencer66c87342006-05-30 03:43:49 +00001059 Out << " GetElementPtrInst* " << iName << " = new GetElementPtrInst("
Reid Spencere0d133f2006-05-29 18:08:06 +00001060 << getCppName(gep->getOperand(0));
1061 if (gep->getNumOperands() == 2)
1062 Out << ", " << getCppName(gep->getOperand(1));
1063 Out << ", " << bbname;
1064 } else {
Reid Spencer66c87342006-05-30 03:43:49 +00001065 Out << " std::vector<Value*> " << iName << "_indices;\n";
Reid Spencere0d133f2006-05-29 18:08:06 +00001066 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
Reid Spencer66c87342006-05-30 03:43:49 +00001067 Out << " " << iName << "_indices.push_back("
Reid Spencere0d133f2006-05-29 18:08:06 +00001068 << getCppName(gep->getOperand(i)) << ");\n";
1069 }
Reid Spencer66c87342006-05-30 03:43:49 +00001070 Out << " Instruction* " << iName << " = new GetElementPtrInst("
Reid Spencere0d133f2006-05-29 18:08:06 +00001071 << getCppName(gep->getOperand(0)) << ", " << iName << "_indices";
1072 }
1073 Out << ", \"";
1074 printEscapedString(gep->getName());
1075 Out << "\", " << bbname << ");";
1076 break;
1077 }
Reid Spencer66c87342006-05-30 03:43:49 +00001078 case Instruction::PHI: {
1079 const PHINode* phi = cast<PHINode>(I);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001080
Reid Spencer66c87342006-05-30 03:43:49 +00001081 Out << " PHINode* " << iName << " = new PHINode("
1082 << getCppName(phi->getType()) << ", \"";
1083 printEscapedString(phi->getName());
1084 Out << "\", " << bbname << ");\n";
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001085 Out << " " << iName << "->reserveOperandSpace("
1086 << phi->getNumIncomingValues()
Reid Spencer66c87342006-05-30 03:43:49 +00001087 << ");\n";
1088 for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001089 Out << " " << iName << "->addIncoming("
Reid Spencer66c87342006-05-30 03:43:49 +00001090 << getCppName(phi->getIncomingValue(i)) << ", "
1091 << getCppName(phi->getIncomingBlock(i)) << ");\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001092 }
Reid Spencer66c87342006-05-30 03:43:49 +00001093 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001094 }
Reid Spencer66c87342006-05-30 03:43:49 +00001095 case Instruction::Cast: {
1096 const CastInst* cst = cast<CastInst>(I);
1097 Out << " CastInst* " << iName << " = new CastInst("
1098 << getCppName(cst->getOperand(0)) << ", "
1099 << getCppName(cst->getType()) << ", \"";
1100 printEscapedString(cst->getName());
1101 Out << "\", " << bbname << ");\n";
1102 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001103 }
Reid Spencer66c87342006-05-30 03:43:49 +00001104 case Instruction::Call:{
1105 const CallInst* call = cast<CallInst>(I);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001106 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1107 Out << " InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1108 << getCppName(ila->getFunctionType()) << ", \""
1109 << ila->getAsmString() << "\", \""
1110 << ila->getConstraintString() << "\","
1111 << (ila->hasSideEffects() ? "true" : "false") << ");\n";
1112 }
Reid Spencer66c87342006-05-30 03:43:49 +00001113 if (call->getNumOperands() > 3) {
1114 Out << " std::vector<Value*> " << iName << "_params;\n";
1115 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1116 Out << " " << iName << "_params.push_back("
1117 << getCppName(call->getOperand(i)) << ");\n";
1118 }
1119 Out << " CallInst* " << iName << " = new CallInst("
1120 << getCppName(call->getOperand(0)) << ", "
1121 << iName << "_params, \"";
1122 } else if (call->getNumOperands() == 3) {
1123 Out << " CallInst* " << iName << " = new CallInst("
1124 << getCppName(call->getOperand(0)) << ", "
1125 << getCppName(call->getOperand(1)) << ", "
1126 << getCppName(call->getOperand(2)) << ", \"";
1127 } else if (call->getNumOperands() == 2) {
1128 Out << " CallInst* " << iName << " = new CallInst("
1129 << getCppName(call->getOperand(0)) << ", "
1130 << getCppName(call->getOperand(1)) << ", \"";
1131 } else {
1132 Out << " CallInst* " << iName << " = new CallInst("
1133 << getCppName(call->getOperand(0)) << ", \"";
1134 }
1135 printEscapedString(call->getName());
1136 Out << "\", " << bbname << ");\n";
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001137 Out << " " << iName << "->setCallingConv(";
Reid Spencer66c87342006-05-30 03:43:49 +00001138 printCallingConv(call->getCallingConv());
1139 Out << ");\n";
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001140 Out << " " << iName << "->setTailCall("
1141 << (call->isTailCall() ? "true":"false");
Reid Spencer66c87342006-05-30 03:43:49 +00001142 Out << ");";
1143 break;
1144 }
1145 case Instruction::Select: {
1146 const SelectInst* sel = cast<SelectInst>(I);
1147 Out << " SelectInst* " << getCppName(sel) << " = new SelectInst(";
1148 Out << getCppName(sel->getCondition()) << ", ";
1149 Out << getCppName(sel->getTrueValue()) << ", ";
1150 Out << getCppName(sel->getFalseValue()) << ", \"";
1151 printEscapedString(sel->getName());
1152 Out << "\", " << bbname << ");\n";
1153 break;
1154 }
1155 case Instruction::UserOp1:
1156 /// FALL THROUGH
1157 case Instruction::UserOp2: {
1158 /// FIXME: What should be done here?
1159 break;
1160 }
1161 case Instruction::VAArg: {
1162 const VAArgInst* va = cast<VAArgInst>(I);
1163 Out << " VAArgInst* " << getCppName(va) << " = new VAArgInst("
1164 << getCppName(va->getOperand(0)) << ", "
1165 << getCppName(va->getType()) << ", \"";
1166 printEscapedString(va->getName());
1167 Out << "\", " << bbname << ");\n";
1168 break;
1169 }
1170 case Instruction::ExtractElement: {
1171 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1172 Out << " ExtractElementInst* " << getCppName(eei)
1173 << " = new ExtractElementInst(" << getCppName(eei->getOperand(0))
1174 << ", " << getCppName(eei->getOperand(1)) << ", \"";
1175 printEscapedString(eei->getName());
1176 Out << "\", " << bbname << ");\n";
1177 break;
1178 }
1179 case Instruction::InsertElement: {
1180 const InsertElementInst* iei = cast<InsertElementInst>(I);
1181 Out << " InsertElementInst* " << getCppName(iei)
1182 << " = new InsertElementInst(" << getCppName(iei->getOperand(0))
1183 << ", " << getCppName(iei->getOperand(1)) << ", "
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001184 << getCppName(iei->getOperand(2)) << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001185 printEscapedString(iei->getName());
1186 Out << "\", " << bbname << ");\n";
1187 break;
1188 }
1189 case Instruction::ShuffleVector: {
1190 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1191 Out << " ShuffleVectorInst* " << getCppName(svi)
1192 << " = new ShuffleVectorInst(" << getCppName(svi->getOperand(0))
1193 << ", " << getCppName(svi->getOperand(1)) << ", "
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001194 << getCppName(svi->getOperand(2)) << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001195 printEscapedString(svi->getName());
1196 Out << "\", " << bbname << ");\n";
1197 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001198 }
1199 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001200 Out << "\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001201}
1202
1203} // end anonymous llvm
1204
1205namespace llvm {
1206
1207void WriteModuleToCppFile(Module* mod, std::ostream& o) {
1208 o << "#include <llvm/Module.h>\n";
1209 o << "#include <llvm/DerivedTypes.h>\n";
1210 o << "#include <llvm/Constants.h>\n";
1211 o << "#include <llvm/GlobalVariable.h>\n";
1212 o << "#include <llvm/Function.h>\n";
1213 o << "#include <llvm/CallingConv.h>\n";
1214 o << "#include <llvm/BasicBlock.h>\n";
1215 o << "#include <llvm/Instructions.h>\n";
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001216 o << "#include <llvm/InlineAsm.h>\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001217 o << "#include <llvm/Pass.h>\n";
1218 o << "#include <llvm/PassManager.h>\n";
1219 o << "#include <llvm/Analysis/Verifier.h>\n";
1220 o << "#include <llvm/Assembly/PrintModulePass.h>\n";
1221 o << "#include <algorithm>\n";
1222 o << "#include <iostream>\n\n";
1223 o << "using namespace llvm;\n\n";
1224 o << "Module* makeLLVMModule();\n\n";
1225 o << "int main(int argc, char**argv) {\n";
1226 o << " Module* Mod = makeLLVMModule();\n";
1227 o << " verifyModule(*Mod, PrintMessageAction);\n";
Reid Spencere0d133f2006-05-29 18:08:06 +00001228 o << " std::cerr.flush();\n";
1229 o << " std::cout.flush();\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001230 o << " PassManager PM;\n";
1231 o << " PM.add(new PrintModulePass(&std::cout));\n";
1232 o << " PM.run(*Mod);\n";
1233 o << " return 0;\n";
1234 o << "}\n\n";
1235 o << "Module* makeLLVMModule() {\n";
Reid Spencere0d133f2006-05-29 18:08:06 +00001236 CppWriter W(o, mod);
1237 W.printModule(mod);
Reid Spencer74e032a2006-05-29 02:58:15 +00001238 o << "return mod;\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001239 o << "}\n";
1240}
1241
1242}