blob: 2b66b065ae8ef1cdbbb265a13ce40566f0196091 [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);
62 void printGlobal(const GlobalVariable *GV);
Reid Spencer66c87342006-05-30 03:43:49 +000063 void printFunctionHead(const Function *F);
64 void printFunctionBody(const Function *F);
Reid Spencere0d133f2006-05-29 18:08:06 +000065 void printInstruction(const Instruction *I, const std::string& bbname);
66 void printSymbolTable(const SymbolTable &ST);
67 void printLinkageType(GlobalValue::LinkageTypes LT);
68 void printCallingConv(unsigned cc);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000069
Reid Spencere0d133f2006-05-29 18:08:06 +000070 std::string getCppName(const Type* val);
71 std::string getCppName(const Value* val);
72 inline void printCppName(const Value* val);
73 inline void printCppName(const Type* val);
74 bool isOnStack(const Type*) const;
75 inline void printTypeDef(const Type* Ty);
76 bool printTypeDefInternal(const Type* Ty);
77 void printEscapedString(const std::string& str);
78};
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000079
Reid Spencere0d133f2006-05-29 18:08:06 +000080// printEscapedString - Print each character of the specified string, escaping
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000081// it if it is not printable or if it is an escape char.
Reid Spencere0d133f2006-05-29 18:08:06 +000082void
83CppWriter::printEscapedString(const std::string &Str) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000084 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
85 unsigned char C = Str[i];
86 if (isprint(C) && C != '"' && C != '\\') {
87 Out << C;
88 } else {
89 Out << '\\'
90 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
91 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
92 }
93 }
94}
95
Reid Spencer66c87342006-05-30 03:43:49 +000096inline const char*
97getTypePrefix(const Type* Ty ) {
98 const char* prefix;
99 switch (Ty->getTypeID()) {
100 case Type::VoidTyID: prefix = "void_"; break;
101 case Type::BoolTyID: prefix = "bool_"; break;
102 case Type::UByteTyID: prefix = "ubyte_"; break;
103 case Type::SByteTyID: prefix = "sbyte_"; break;
104 case Type::UShortTyID: prefix = "ushort_"; break;
105 case Type::ShortTyID: prefix = "short_"; break;
106 case Type::UIntTyID: prefix = "uint_"; break;
107 case Type::IntTyID: prefix = "int_"; break;
108 case Type::ULongTyID: prefix = "ulong_"; break;
109 case Type::LongTyID: prefix = "long_"; break;
110 case Type::FloatTyID: prefix = "float_"; break;
111 case Type::DoubleTyID: prefix = "double_"; break;
112 case Type::LabelTyID: prefix = "label_"; break;
113 case Type::FunctionTyID: prefix = "func_"; break;
114 case Type::StructTyID: prefix = "struct_"; break;
115 case Type::ArrayTyID: prefix = "array_"; break;
116 case Type::PointerTyID: prefix = "ptr_"; break;
117 case Type::PackedTyID: prefix = "packed_"; break;
118 case Type::OpaqueTyID: prefix = "opaque_"; break;
119 default: prefix = "other_"; break;
120 }
121 return prefix;
122}
123
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000124std::string
125CppWriter::getCppName(const Value* val) {
126 std::string name;
127 ValueMap::iterator I = ValueNames.find(val);
Reid Spencer66c87342006-05-30 03:43:49 +0000128 if (I != ValueNames.end() && I->first == val)
129 return I->second;
130
131 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
132 name = std::string("gvar_") +
133 getTypePrefix(GV->getType()->getElementType());
134 } else if (const Function* F = dyn_cast<Function>(val)) {
135 name = std::string("func_");
136 } else if (const Constant* C = dyn_cast<Constant>(val)) {
137 name = std::string("const_") + getTypePrefix(C->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000138 } else {
Reid Spencer66c87342006-05-30 03:43:49 +0000139 name = getTypePrefix(val->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000140 }
Reid Spencer66c87342006-05-30 03:43:49 +0000141 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
142 NameSet::iterator NI = UsedNames.find(name);
143 if (NI != UsedNames.end())
144 name += std::string("_") + utostr(uniqueNum++);
145 UsedNames.insert(name);
146 return ValueNames[val] = name;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000147}
148
149void
150CppWriter::printCppName(const Value* val) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000151 printEscapedString(getCppName(val));
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000152}
153
154void
155CppWriter::printCppName(const Type* Ty)
156{
Reid Spencere0d133f2006-05-29 18:08:06 +0000157 printEscapedString(getCppName(Ty));
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000158}
159
160// Gets the C++ name for a type. Returns true if we already saw the type,
161// false otherwise.
162//
163inline const std::string*
164findTypeName(const SymbolTable& ST, const Type* Ty)
165{
166 SymbolTable::type_const_iterator TI = ST.type_begin();
167 SymbolTable::type_const_iterator TE = ST.type_end();
168 for (;TI != TE; ++TI)
169 if (TI->second == Ty)
170 return &(TI->first);
171 return 0;
172}
173
174std::string
175CppWriter::getCppName(const Type* Ty)
176{
177 // First, handle the primitive types .. easy
178 if (Ty->isPrimitiveType()) {
179 switch (Ty->getTypeID()) {
180 case Type::VoidTyID: return "Type::VoidTy";
181 case Type::BoolTyID: return "Type::BoolTy";
182 case Type::UByteTyID: return "Type::UByteTy";
183 case Type::SByteTyID: return "Type::SByteTy";
184 case Type::UShortTyID: return "Type::UShortTy";
185 case Type::ShortTyID: return "Type::ShortTy";
186 case Type::UIntTyID: return "Type::UIntTy";
187 case Type::IntTyID: return "Type::IntTy";
188 case Type::ULongTyID: return "Type::ULongTy";
189 case Type::LongTyID: return "Type::LongTy";
190 case Type::FloatTyID: return "Type::FloatTy";
191 case Type::DoubleTyID: return "Type::DoubleTy";
192 case Type::LabelTyID: return "Type::LabelTy";
193 default:
194 assert(!"Can't get here");
195 break;
196 }
197 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
198 }
199
200 // Now, see if we've seen the type before and return that
201 TypeMap::iterator I = TypeNames.find(Ty);
202 if (I != TypeNames.end())
203 return I->second;
204
205 // Okay, let's build a new name for this type. Start with a prefix
206 const char* prefix = 0;
207 switch (Ty->getTypeID()) {
208 case Type::FunctionTyID: prefix = "FuncTy_"; break;
209 case Type::StructTyID: prefix = "StructTy_"; break;
210 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
211 case Type::PointerTyID: prefix = "PointerTy_"; break;
212 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
213 case Type::PackedTyID: prefix = "PackedTy_"; break;
214 default: prefix = "OtherTy_"; break; // prevent breakage
215 }
216
217 // See if the type has a name in the symboltable and build accordingly
218 const std::string* tName = findTypeName(TheModule->getSymbolTable(), Ty);
219 std::string name;
220 if (tName)
221 name = std::string(prefix) + *tName;
222 else
223 name = std::string(prefix) + utostr(uniqueNum++);
224
225 // Save the name
226 return TypeNames[Ty] = name;
227}
228
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000229void CppWriter::printModule(const Module *M) {
230 Out << "\n// Module Construction\n";
231 Out << "Module* mod = new Module(\"";
Reid Spencere0d133f2006-05-29 18:08:06 +0000232 if (M->getModuleIdentifier() == "-")
233 printEscapedString("<stdin>");
234 else
235 printEscapedString(M->getModuleIdentifier());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000236 Out << "\");\n";
237 Out << "mod->setEndianness(";
238 switch (M->getEndianness()) {
239 case Module::LittleEndian: Out << "Module::LittleEndian);\n"; break;
240 case Module::BigEndian: Out << "Module::BigEndian);\n"; break;
241 case Module::AnyEndianness:Out << "Module::AnyEndianness);\n"; break;
242 }
243 Out << "mod->setPointerSize(";
244 switch (M->getPointerSize()) {
245 case Module::Pointer32: Out << "Module::Pointer32);\n"; break;
246 case Module::Pointer64: Out << "Module::Pointer64);\n"; break;
247 case Module::AnyPointerSize: Out << "Module::AnyPointerSize);\n"; break;
248 }
249 if (!M->getTargetTriple().empty())
250 Out << "mod->setTargetTriple(\"" << M->getTargetTriple() << "\");\n";
251
252 if (!M->getModuleInlineAsm().empty()) {
253 Out << "mod->setModuleInlineAsm(\"";
Reid Spencere0d133f2006-05-29 18:08:06 +0000254 printEscapedString(M->getModuleInlineAsm());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000255 Out << "\");\n";
256 }
257
258 // Loop over the dependent libraries and emit them.
259 Module::lib_iterator LI = M->lib_begin();
260 Module::lib_iterator LE = M->lib_end();
261 while (LI != LE) {
262 Out << "mod->addLibrary(\"" << *LI << "\");\n";
263 ++LI;
264 }
265
266 // Print out all the type definitions
267 Out << "\n// Type Definitions\n";
268 printTypes(M);
269
270 // Print out all the constants declarations
Reid Spencer66c87342006-05-30 03:43:49 +0000271 Out << "\n// Constant Definitions\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000272 printConstants(M);
273
274 // Process the global variables
Reid Spencer66c87342006-05-30 03:43:49 +0000275 Out << "\n// Global Variable Definitions\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000276 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
277 I != E; ++I) {
278 printGlobal(I);
279 }
280
Reid Spencer66c87342006-05-30 03:43:49 +0000281 // Functions can call each other so define all the functions first before
282 // emitting their function bodies.
283 Out << "\n// Function Declarations\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000284 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Reid Spencer66c87342006-05-30 03:43:49 +0000285 printFunctionHead(I);
286
287 // Output all of the function bodies.
288 Out << "\n// Function Definitions\n";
289 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
290 Out << "\n// Function: " << I->getName() << "(" << getCppName(I) << ")\n";
291 Out << "{\n";
292 printFunctionBody(I);
293 Out << "}\n";
294 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000295}
296
297void
298CppWriter::printCallingConv(unsigned cc){
299 // Print the calling convention.
300 switch (cc) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000301 case CallingConv::C: Out << "CallingConv::C"; break;
302 case CallingConv::CSRet: Out << "CallingConv::CSRet"; break;
303 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
304 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
305 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
Reid Spencer66c87342006-05-30 03:43:49 +0000306 default: Out << cc; break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000307 }
308}
309
310void
311CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
312 switch (LT) {
313 case GlobalValue::InternalLinkage:
314 Out << "GlobalValue::InternalLinkage"; break;
315 case GlobalValue::LinkOnceLinkage:
316 Out << "GlobalValue::LinkOnceLinkage "; break;
317 case GlobalValue::WeakLinkage:
318 Out << "GlobalValue::WeakLinkage"; break;
319 case GlobalValue::AppendingLinkage:
320 Out << "GlobalValue::AppendingLinkage"; break;
321 case GlobalValue::ExternalLinkage:
322 Out << "GlobalValue::ExternalLinkage"; break;
323 case GlobalValue::GhostLinkage:
324 Out << "GlobalValue::GhostLinkage"; break;
325 }
326}
327void CppWriter::printGlobal(const GlobalVariable *GV) {
328 Out << "\n";
329 Out << "GlobalVariable* ";
330 printCppName(GV);
331 Out << " = new GlobalVariable(\n";
332 Out << " /*Type=*/";
333 printCppName(GV->getType()->getElementType());
334 Out << ",\n";
335 Out << " /*isConstant=*/" << (GV->isConstant()?"true":"false")
336 << ",\n /*Linkage=*/";
337 printLinkageType(GV->getLinkage());
338 Out << ",\n /*Initializer=*/";
339 if (GV->hasInitializer()) {
340 printCppName(GV->getInitializer());
341 } else {
342 Out << "0";
343 }
344 Out << ",\n /*Name=*/\"";
Reid Spencere0d133f2006-05-29 18:08:06 +0000345 printEscapedString(GV->getName());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000346 Out << "\",\n mod);\n";
347
348 if (GV->hasSection()) {
349 printCppName(GV);
350 Out << "->setSection(\"";
Reid Spencere0d133f2006-05-29 18:08:06 +0000351 printEscapedString(GV->getSection());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000352 Out << "\");\n";
353 }
354 if (GV->getAlignment()) {
355 printCppName(GV);
356 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");\n";
357 };
358}
359
360bool
361CppWriter::isOnStack(const Type* Ty) const {
362 TypeList::const_iterator TI =
363 std::find(TypeStack.begin(),TypeStack.end(),Ty);
364 return TI != TypeStack.end();
365}
366
367// Prints a type definition. Returns true if it could not resolve all the types
368// in the definition but had to use a forward reference.
369void
370CppWriter::printTypeDef(const Type* Ty) {
371 assert(TypeStack.empty());
372 TypeStack.clear();
373 printTypeDefInternal(Ty);
374 assert(TypeStack.empty());
375 // early resolve as many unresolved types as possible. Search the unresolved
376 // types map for the type we just printed. Now that its definition is complete
377 // we can resolve any preview references to it. This prevents a cascade of
378 // unresolved types.
379 TypeMap::iterator I = UnresolvedTypes.find(Ty);
380 if (I != UnresolvedTypes.end()) {
381 Out << "cast<OpaqueType>(" << I->second
382 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");\n";
383 Out << I->second << " = cast<";
384 switch (Ty->getTypeID()) {
385 case Type::FunctionTyID: Out << "FunctionType"; break;
386 case Type::ArrayTyID: Out << "ArrayType"; break;
387 case Type::StructTyID: Out << "StructType"; break;
388 case Type::PackedTyID: Out << "PackedType"; break;
389 case Type::PointerTyID: Out << "PointerType"; break;
390 case Type::OpaqueTyID: Out << "OpaqueType"; break;
391 default: Out << "NoSuchDerivedType"; break;
392 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000393 Out << ">(" << I->second << "_fwd.get());\n\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000394 UnresolvedTypes.erase(I);
395 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000396}
397
398bool
399CppWriter::printTypeDefInternal(const Type* Ty) {
400 // We don't print definitions for primitive types
401 if (Ty->isPrimitiveType())
402 return false;
403
404 // Determine if the name is in the name list before we modify that list.
405 TypeMap::const_iterator TNI = TypeNames.find(Ty);
406
407 // Everything below needs the name for the type so get it now
408 std::string typeName(getCppName(Ty));
409
410 // Search the type stack for recursion. If we find it, then generate this
411 // as an OpaqueType, but make sure not to do this multiple times because
412 // the type could appear in multiple places on the stack. Once the opaque
413 // definition is issues, it must not be re-issued. Consequently we have to
414 // check the UnresolvedTypes list as well.
415 if (isOnStack(Ty)) {
416 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
417 if (I == UnresolvedTypes.end()) {
418 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();\n";
419 UnresolvedTypes[Ty] = typeName;
420 return true;
421 }
422 }
423
424 // Avoid printing things we have already printed. Since TNI was obtained
425 // before the name was inserted with getCppName and because we know the name
426 // is not on the stack (currently being defined), we can surmise here that if
427 // we got the name we've also already emitted its definition.
428 if (TNI != TypeNames.end())
429 return false;
430
431 // We're going to print a derived type which, by definition, contains other
432 // types. So, push this one we're printing onto the type stack to assist with
433 // recursive definitions.
434 TypeStack.push_back(Ty); // push on type stack
435 bool didRecurse = false;
436
437 // Print the type definition
438 switch (Ty->getTypeID()) {
439 case Type::FunctionTyID: {
440 const FunctionType* FT = cast<FunctionType>(Ty);
441 Out << "std::vector<const Type*>" << typeName << "_args;\n";
442 FunctionType::param_iterator PI = FT->param_begin();
443 FunctionType::param_iterator PE = FT->param_end();
444 for (; PI != PE; ++PI) {
445 const Type* argTy = static_cast<const Type*>(*PI);
446 bool isForward = printTypeDefInternal(argTy);
447 std::string argName(getCppName(argTy));
448 Out << typeName << "_args.push_back(" << argName;
449 if (isForward)
450 Out << "_fwd";
451 Out << ");\n";
452 }
453 bool isForward = printTypeDefInternal(FT->getReturnType());
454 std::string retTypeName(getCppName(FT->getReturnType()));
455 Out << "FunctionType* " << typeName << " = FunctionType::get(\n"
456 << " /*Result=*/" << retTypeName;
457 if (isForward)
458 Out << "_fwd";
459 Out << ",\n /*Params=*/" << typeName << "_args,\n /*isVarArg=*/"
460 << (FT->isVarArg() ? "true" : "false") << ");\n";
461 break;
462 }
463 case Type::StructTyID: {
464 const StructType* ST = cast<StructType>(Ty);
465 Out << "std::vector<const Type*>" << typeName << "_fields;\n";
466 StructType::element_iterator EI = ST->element_begin();
467 StructType::element_iterator EE = ST->element_end();
468 for (; EI != EE; ++EI) {
469 const Type* fieldTy = static_cast<const Type*>(*EI);
470 bool isForward = printTypeDefInternal(fieldTy);
471 std::string fieldName(getCppName(fieldTy));
472 Out << typeName << "_fields.push_back(" << fieldName;
473 if (isForward)
474 Out << "_fwd";
475 Out << ");\n";
476 }
477 Out << "StructType* " << typeName << " = StructType::get("
478 << typeName << "_fields);\n";
479 break;
480 }
481 case Type::ArrayTyID: {
482 const ArrayType* AT = cast<ArrayType>(Ty);
483 const Type* ET = AT->getElementType();
484 bool isForward = printTypeDefInternal(ET);
485 std::string elemName(getCppName(ET));
486 Out << "ArrayType* " << typeName << " = ArrayType::get("
487 << elemName << (isForward ? "_fwd" : "")
488 << ", " << utostr(AT->getNumElements()) << ");\n";
489 break;
490 }
491 case Type::PointerTyID: {
492 const PointerType* PT = cast<PointerType>(Ty);
493 const Type* ET = PT->getElementType();
494 bool isForward = printTypeDefInternal(ET);
495 std::string elemName(getCppName(ET));
496 Out << "PointerType* " << typeName << " = PointerType::get("
497 << elemName << (isForward ? "_fwd" : "") << ");\n";
498 break;
499 }
500 case Type::PackedTyID: {
501 const PackedType* PT = cast<PackedType>(Ty);
502 const Type* ET = PT->getElementType();
503 bool isForward = printTypeDefInternal(ET);
504 std::string elemName(getCppName(ET));
505 Out << "PackedType* " << typeName << " = PackedType::get("
506 << elemName << (isForward ? "_fwd" : "")
507 << ", " << utostr(PT->getNumElements()) << ");\n";
508 break;
509 }
510 case Type::OpaqueTyID: {
511 const OpaqueType* OT = cast<OpaqueType>(Ty);
512 Out << "OpaqueType* " << typeName << " = OpaqueType::get();\n";
513 break;
514 }
515 default:
516 assert(!"Invalid TypeID");
517 }
518
Reid Spencer74e032a2006-05-29 02:58:15 +0000519 // If the type had a name, make sure we recreate it.
520 const std::string* progTypeName =
521 findTypeName(TheModule->getSymbolTable(),Ty);
522 if (progTypeName)
523 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
524 << typeName << ");\n";
525
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000526 // Pop us off the type stack
527 TypeStack.pop_back();
Reid Spencere0d133f2006-05-29 18:08:06 +0000528 Out << "\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000529
530 // We weren't a recursive type
531 return false;
532}
533
534void
535CppWriter::printTypes(const Module* M) {
536 // Add all of the global variables to the value table...
537 for (Module::const_global_iterator I = TheModule->global_begin(),
538 E = TheModule->global_end(); I != E; ++I) {
539 if (I->hasInitializer())
540 printTypeDef(I->getInitializer()->getType());
541 printTypeDef(I->getType());
542 }
543
544 // Add all the functions to the table
545 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
546 FI != FE; ++FI) {
547 printTypeDef(FI->getReturnType());
548 printTypeDef(FI->getFunctionType());
549 // Add all the function arguments
550 for(Function::const_arg_iterator AI = FI->arg_begin(),
551 AE = FI->arg_end(); AI != AE; ++AI) {
552 printTypeDef(AI->getType());
553 }
554
555 // Add all of the basic blocks and instructions
556 for (Function::const_iterator BB = FI->begin(),
557 E = FI->end(); BB != E; ++BB) {
558 printTypeDef(BB->getType());
559 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
560 ++I) {
561 printTypeDef(I->getType());
562 }
563 }
564 }
565}
566
567void
568CppWriter::printConstants(const Module* M) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000569 // Add all of the global variables to the value table...
570 for (Module::const_global_iterator I = TheModule->global_begin(),
571 E = TheModule->global_end(); I != E; ++I)
572 if (I->hasInitializer())
573 printConstant(I->getInitializer());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000574
Reid Spencere0d133f2006-05-29 18:08:06 +0000575 // Traverse the LLVM functions looking for constants
576 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
577 FI != FE; ++FI) {
578 // Add all of the basic blocks and instructions
579 for (Function::const_iterator BB = FI->begin(),
580 E = FI->end(); BB != E; ++BB) {
581 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
582 ++I) {
583 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
584 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
585 printConstant(C);
586 }
587 }
588 }
589 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000590 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000591}
592
Reid Spencere0d133f2006-05-29 18:08:06 +0000593// printConstant - Print out a constant pool entry...
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000594void CppWriter::printConstant(const Constant *CV) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000595 // First, if the constant is in the constant list then we've printed it
596 // already and we shouldn't reprint it.
597 if (ValueNames.find(CV) != ValueNames.end())
598 return;
599
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000600 const int IndentSize = 2;
601 static std::string Indent = "\n";
602 std::string constName(getCppName(CV));
603 std::string typeName(getCppName(CV->getType()));
604 if (CV->isNullValue()) {
605 Out << "Constant* " << constName << " = Constant::getNullValue("
606 << typeName << ");\n";
607 return;
608 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000609 if (isa<GlobalValue>(CV)) {
610 // Skip variables and functions, we emit them elsewhere
611 return;
612 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000613 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
614 Out << "Constant* " << constName << " = ConstantBool::get("
615 << (CB == ConstantBool::True ? "true" : "false")
616 << ");";
617 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
618 Out << "Constant* " << constName << " = ConstantSInt::get("
619 << typeName << ", " << CI->getValue() << ");";
620 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
621 Out << "Constant* " << constName << " = ConstantUInt::get("
622 << typeName << ", " << CI->getValue() << ");";
623 } else if (isa<ConstantAggregateZero>(CV)) {
624 Out << "Constant* " << constName << " = ConstantAggregateZero::get("
625 << typeName << ");";
626 } else if (isa<ConstantPointerNull>(CV)) {
627 Out << "Constant* " << constName << " = ConstanPointerNull::get("
628 << typeName << ");";
629 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
630 Out << "ConstantFP::get(" << typeName << ", ";
631 // We would like to output the FP constant value in exponential notation,
632 // but we cannot do this if doing so will lose precision. Check here to
633 // make sure that we only output it in exponential format if we can parse
634 // the value back and get the same value.
635 //
636 std::string StrVal = ftostr(CFP->getValue());
637
638 // Check to make sure that the stringized number is not some string like
639 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
640 // the string matches the "[-+]?[0-9]" regex.
641 //
642 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
643 ((StrVal[0] == '-' || StrVal[0] == '+') &&
644 (StrVal[1] >= '0' && StrVal[1] <= '9')))
645 // Reparse stringized version!
646 if (atof(StrVal.c_str()) == CFP->getValue()) {
647 Out << StrVal;
648 return;
649 }
650
651 // Otherwise we could not reparse it to exactly the same value, so we must
652 // output the string in hexadecimal format!
653 assert(sizeof(double) == sizeof(uint64_t) &&
654 "assuming that double is 64 bits!");
655 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue())) << ");";
656 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000657 if (CA->isString() && CA->getType()->getElementType() == Type::SByteTy) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000658 Out << "Constant* " << constName << " = ConstantArray::get(\"";
Reid Spencere0d133f2006-05-29 18:08:06 +0000659 printEscapedString(CA->getAsString());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000660 Out << "\");";
661 } else {
662 Out << "std::vector<Constant*> " << constName << "_elems;\n";
663 unsigned N = CA->getNumOperands();
664 for (unsigned i = 0; i < N; ++i) {
665 printConstant(CA->getOperand(i));
666 Out << constName << "_elems.push_back("
667 << getCppName(CA->getOperand(i)) << ");\n";
668 }
669 Out << "Constant* " << constName << " = ConstantArray::get("
670 << typeName << ", " << constName << "_elems);";
671 }
672 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
673 Out << "std::vector<Constant*> " << constName << "_fields;\n";
674 unsigned N = CS->getNumOperands();
675 for (unsigned i = 0; i < N; i++) {
676 printConstant(CS->getOperand(i));
677 Out << constName << "_fields.push_back("
Reid Spencer66c87342006-05-30 03:43:49 +0000678 << getCppName(CS->getOperand(i)) << ");\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000679 }
680 Out << "Constant* " << constName << " = ConstantStruct::get("
681 << typeName << ", " << constName << "_fields);";
682 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
683 Out << "std::vector<Constant*> " << constName << "_elems;\n";
684 unsigned N = CP->getNumOperands();
685 for (unsigned i = 0; i < N; ++i) {
686 printConstant(CP->getOperand(i));
687 Out << constName << "_elems.push_back("
688 << getCppName(CP->getOperand(i)) << ");\n";
689 }
690 Out << "Constant* " << constName << " = ConstantPacked::get("
691 << typeName << ", " << constName << "_elems);";
692 } else if (isa<UndefValue>(CV)) {
693 Out << "Constant* " << constName << " = UndefValue::get("
Reid Spencere0d133f2006-05-29 18:08:06 +0000694 << typeName << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000695 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000696 if (CE->getOpcode() == Instruction::GetElementPtr) {
697 Out << "std::vector<Constant*> " << constName << "_indices;\n";
698 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
699 Out << constName << "_indices.push_back("
700 << getCppName(CE->getOperand(i)) << ");\n";
701 }
702 Out << "Constant* " << constName << " = new GetElementPtrInst("
703 << getCppName(CE->getOperand(0)) << ", " << constName << "_indices";
704 } else if (CE->getOpcode() == Instruction::Cast) {
705 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
706 Out << getCppName(CE->getOperand(0)) << ", " << getCppName(CE->getType())
707 << ");";
708 } else {
709 Out << "Constant* " << constName << " = ConstantExpr::";
710 switch (CE->getOpcode()) {
711 case Instruction::Add: Out << "getAdd"; break;
712 case Instruction::Sub: Out << "getSub"; break;
713 case Instruction::Mul: Out << "getMul"; break;
714 case Instruction::Div: Out << "getDiv"; break;
715 case Instruction::Rem: Out << "getRem"; break;
716 case Instruction::And: Out << "getAnd"; break;
717 case Instruction::Or: Out << "getOr"; break;
718 case Instruction::Xor: Out << "getXor"; break;
719 case Instruction::SetEQ: Out << "getSetEQ"; break;
720 case Instruction::SetNE: Out << "getSetNE"; break;
721 case Instruction::SetLE: Out << "getSetLE"; break;
722 case Instruction::SetGE: Out << "getSetGE"; break;
723 case Instruction::SetLT: Out << "getSetLT"; break;
724 case Instruction::SetGT: Out << "getSetGT"; break;
725 case Instruction::Shl: Out << "getShl"; break;
726 case Instruction::Shr: Out << "getShr"; break;
727 case Instruction::Select: Out << "getSelect"; break;
728 case Instruction::ExtractElement: Out << "getExtractElement"; break;
729 case Instruction::InsertElement: Out << "getInsertElement"; break;
730 case Instruction::ShuffleVector: Out << "getShuffleVector"; break;
731 default:
732 assert(!"Invalid constant expression");
733 break;
734 }
735 Out << getCppName(CE->getOperand(0));
736 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
737 Out << ", " << getCppName(CE->getOperand(i));
738 Out << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000739 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000740 } else {
Reid Spencere0d133f2006-05-29 18:08:06 +0000741 assert(!"Bad Constant");
742 Out << "Constant* " << constName << " = 0; ";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000743 }
744 Out << "\n";
745}
746
Reid Spencer66c87342006-05-30 03:43:49 +0000747void CppWriter::printFunctionHead(const Function* F) {
748 Out << "Function* " << getCppName(F) << " = new Function("
749 << getCppName(F->getFunctionType()) << ", " ;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000750 printLinkageType(F->getLinkage());
Reid Spencere0d133f2006-05-29 18:08:06 +0000751 Out << ",\n \"" << F->getName() << "\", mod);\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000752 printCppName(F);
753 Out << "->setCallingConv(";
754 printCallingConv(F->getCallingConv());
755 Out << ");\n";
756 if (F->hasSection()) {
757 printCppName(F);
758 Out << "->setSection(" << F->getSection() << ");\n";
759 }
760 if (F->getAlignment()) {
761 printCppName(F);
762 Out << "->setAlignment(" << F->getAlignment() << ");\n";
763 }
Reid Spencer66c87342006-05-30 03:43:49 +0000764}
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000765
Reid Spencer66c87342006-05-30 03:43:49 +0000766void CppWriter::printFunctionBody(const Function *F) {
767 if (F->isExternal())
768 return; // external functions have no bodies.
769
770 // Create all the argument values
771 if (!F->arg_empty()) {
772 Out << " Function::arg_iterator args = " << getCppName(F)
773 << "->arg_begin();\n";
774 }
775 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
776 AI != AE; ++AI) {
777 Out << " Value* " << getCppName(AI) << " = args++;\n";
778 if (AI->hasName())
779 Out << " " << getCppName(AI) << "->setName(\"" << AI->getName()
780 << "\");\n";
781 }
782
783 // Create all the basic blocks
784 for (Function::const_iterator BI = F->begin(), BE = F->end();
785 BI != BE; ++BI) {
786 std::string bbname(getCppName(BI));
787 Out << " BasicBlock* " << bbname << " = new BasicBlock(\"";
788 if (BI->hasName())
789 printEscapedString(BI->getName());
790 Out << "\"," << getCppName(BI->getParent()) << ",0);\n";
791 }
792
793 // Output all of its basic blocks... for the function
794 for (Function::const_iterator BI = F->begin(), BE = F->end();
795 BI != BE; ++BI) {
796 // Output all of the instructions in the basic block...
797 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
798 I != E; ++I) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000799 std::string bbname(getCppName(BI));
Reid Spencer66c87342006-05-30 03:43:49 +0000800 printInstruction(I,bbname);
Reid Spencere0d133f2006-05-29 18:08:06 +0000801 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000802 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000803}
804
Reid Spencere0d133f2006-05-29 18:08:06 +0000805// printInstruction - This member is called for each Instruction in a function.
806void
807CppWriter::printInstruction(const Instruction *I, const std::string& bbname)
808{
809 std::string iName(getCppName(I));
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000810
Reid Spencere0d133f2006-05-29 18:08:06 +0000811 switch (I->getOpcode()) {
812 case Instruction::Ret: {
813 const ReturnInst* ret = cast<ReturnInst>(I);
Reid Spencer66c87342006-05-30 03:43:49 +0000814 Out << " ReturnInst* " << iName << " = new ReturnInst(";
Reid Spencere0d133f2006-05-29 18:08:06 +0000815 if (ret->getReturnValue())
816 Out << getCppName(ret->getReturnValue()) << ", ";
817 Out << bbname << ");";
818 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000819 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000820 case Instruction::Br: {
821 const BranchInst* br = cast<BranchInst>(I);
Reid Spencer66c87342006-05-30 03:43:49 +0000822 Out << " BranchInst* " << iName << " = new BranchInst(" ;
Reid Spencere0d133f2006-05-29 18:08:06 +0000823 if (br->getNumOperands() == 3 ) {
824 Out << getCppName(br->getOperand(0)) << ", "
825 << getCppName(br->getOperand(1)) << ", "
826 << getCppName(br->getOperand(2)) << ", ";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000827
Reid Spencere0d133f2006-05-29 18:08:06 +0000828 } else if (br->getNumOperands() == 1) {
829 Out << getCppName(br->getOperand(0)) << ", ";
830 } else {
831 assert(!"branch with 2 operands?");
832 }
833 Out << bbname << ");";
834 break;
835 }
Reid Spencer66c87342006-05-30 03:43:49 +0000836 case Instruction::Switch: {
837 const SwitchInst* sw = cast<SwitchInst>(I);
838 Out << " SwitchInst* " << iName << " = new SwitchInst("
839 << getCppName(sw->getOperand(0)) << ", "
840 << getCppName(sw->getOperand(1)) << ", "
841 << sw->getNumCases() << ", " << bbname << ");";
842 for (unsigned i = 1; i < sw->getNumCases(); i++ ) {
843 Out << " " << iName << "->addCase("
844 << getCppName(sw->getCaseValue(i)) << ", "
845 << getCppName(sw->getSuccessor(i)) << ");\n";
846 }
847 break;
848 }
849 case Instruction::Invoke: {
850 const InvokeInst* inv = cast<InvokeInst>(I);
851 Out << " std::vector<Value*> " << iName << "_params;\n";
852 for (unsigned i = 3; i < inv->getNumOperands(); ++i)
853 Out << " " << iName << "_params.push_back("
854 << getCppName(inv->getOperand(i)) << ");\n";
855 Out << " InvokeInst* " << iName << " = new InvokeInst("
856 << getCppName(inv->getCalledFunction()) << ", "
857 << getCppName(inv->getNormalDest()) << ", "
858 << getCppName(inv->getUnwindDest()) << ", "
859 << iName << "_params, \"";
860 printEscapedString(inv->getName());
861 Out << "\", " << bbname << ");\n";
862 Out << iName << "->setCallingConv(";
863 printCallingConv(inv->getCallingConv());
864 Out << ");";
865 break;
866 }
867 case Instruction::Unwind: {
868 Out << " UnwindInst* " << iName << " = new UnwindInst("
869 << bbname << ");";
870 break;
871 }
872 case Instruction::Unreachable:{
873 Out << " UnreachableInst* " << iName << " = new UnreachableInst("
874 << bbname << ");";
875 break;
876 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000877 case Instruction::Add:
878 case Instruction::Sub:
879 case Instruction::Mul:
880 case Instruction::Div:
881 case Instruction::Rem:
882 case Instruction::And:
883 case Instruction::Or:
884 case Instruction::Xor:
Reid Spencer66c87342006-05-30 03:43:49 +0000885 case Instruction::Shl:
886 case Instruction::Shr:{
887 Out << " BinaryOperator* " << iName << " = BinaryOperator::create(";
888 switch (I->getOpcode()) {
889 case Instruction::Add: Out << "Instruction::Add"; break;
890 case Instruction::Sub: Out << "Instruction::Sub"; break;
891 case Instruction::Mul: Out << "Instruction::Mul"; break;
892 case Instruction::Div: Out << "Instruction::Div"; break;
893 case Instruction::Rem: Out << "Instruction::Rem"; break;
894 case Instruction::And: Out << "Instruction::And"; break;
895 case Instruction::Or: Out << "Instruction::Or"; break;
896 case Instruction::Xor: Out << "Instruction::Xor"; break;
897 case Instruction::Shl: Out << "Instruction::Shl"; break;
898 case Instruction::Shr: Out << "Instruction::Shr"; break;
899 default: Out << "Instruction::BadOpCode"; break;
900 }
901 Out << ", " << getCppName(I->getOperand(0));
902 Out << ", " << getCppName(I->getOperand(1)) << ", \"";
903 printEscapedString(I->getName());
904 Out << "\", " << bbname << ");";
905 break;
906 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000907 case Instruction::SetEQ:
908 case Instruction::SetNE:
909 case Instruction::SetLE:
910 case Instruction::SetGE:
911 case Instruction::SetLT:
Reid Spencer66c87342006-05-30 03:43:49 +0000912 case Instruction::SetGT: {
913 Out << " SetCondInst* " << iName << " = new SetCondInst(";
914 switch (I->getOpcode()) {
915 case Instruction::SetEQ: Out << "Instruction::SetEQ"; break;
916 case Instruction::SetNE: Out << "Instruction::SetNE"; break;
917 case Instruction::SetLE: Out << "Instruction::SetLE"; break;
918 case Instruction::SetGE: Out << "Instruction::SetGE"; break;
919 case Instruction::SetLT: Out << "Instruction::SetLT"; break;
920 case Instruction::SetGT: Out << "Instruction::SetGT"; break;
921 default: Out << "Instruction::BadOpCode"; break;
922 }
923 Out << ", " << getCppName(I->getOperand(0));
924 Out << ", " << getCppName(I->getOperand(1)) << ", \"";
925 printEscapedString(I->getName());
926 Out << "\", " << bbname << ");";
927 break;
928 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000929 case Instruction::Malloc: {
930 const MallocInst* mallocI = cast<MallocInst>(I);
Reid Spencer66c87342006-05-30 03:43:49 +0000931 Out << " MallocInst* " << iName << " = new MallocInst("
Reid Spencere0d133f2006-05-29 18:08:06 +0000932 << getCppName(mallocI->getAllocatedType()) << ", ";
933 if (mallocI->isArrayAllocation())
934 Out << getCppName(mallocI->getArraySize()) << ", ";
935 Out << "\"";
936 printEscapedString(mallocI->getName());
937 Out << "\", " << bbname << ");";
938 if (mallocI->getAlignment())
939 Out << "\n " << iName << "->setAlignment("
940 << mallocI->getAlignment() << ");";
941 break;
942 }
Reid Spencer66c87342006-05-30 03:43:49 +0000943 case Instruction::Free: {
944 Out << " FreeInst* " << iName << " = new FreeInst("
945 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
946 break;
947 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000948 case Instruction::Alloca: {
949 const AllocaInst* allocaI = cast<AllocaInst>(I);
Reid Spencer66c87342006-05-30 03:43:49 +0000950 Out << " AllocaInst* " << iName << " = new AllocaInst("
Reid Spencere0d133f2006-05-29 18:08:06 +0000951 << getCppName(allocaI->getAllocatedType()) << ", ";
952 if (allocaI->isArrayAllocation())
953 Out << getCppName(allocaI->getArraySize()) << ", ";
954 Out << "\"";
955 printEscapedString(allocaI->getName());
956 Out << "\", " << bbname << ");";
957 if (allocaI->getAlignment())
958 Out << "\n " << iName << "->setAlignment("
959 << allocaI->getAlignment() << ");";
960 break;
961 }
Reid Spencer66c87342006-05-30 03:43:49 +0000962 case Instruction::Load:{
963 const LoadInst* load = cast<LoadInst>(I);
964 Out << " LoadInst* " << iName << " = new LoadInst("
965 << getCppName(load->getOperand(0)) << ", " << bbname << ");\n";
966 if (load->isVolatile())
967 Out << "iName->setVolatile(true);";
968 break;
969 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000970 case Instruction::Store: {
971 const StoreInst* store = cast<StoreInst>(I);
Reid Spencer66c87342006-05-30 03:43:49 +0000972 Out << " StoreInst* " << iName << " = new StoreInst("
Reid Spencere0d133f2006-05-29 18:08:06 +0000973 << getCppName(store->getOperand(0)) << ", "
974 << getCppName(store->getOperand(1)) << ", " << bbname << ");\n";
975 if (store->isVolatile())
976 Out << "iName->setVolatile(true);";
977 break;
978 }
979 case Instruction::GetElementPtr: {
980 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
981 if (gep->getNumOperands() <= 2) {
Reid Spencer66c87342006-05-30 03:43:49 +0000982 Out << " GetElementPtrInst* " << iName << " = new GetElementPtrInst("
Reid Spencere0d133f2006-05-29 18:08:06 +0000983 << getCppName(gep->getOperand(0));
984 if (gep->getNumOperands() == 2)
985 Out << ", " << getCppName(gep->getOperand(1));
986 Out << ", " << bbname;
987 } else {
Reid Spencer66c87342006-05-30 03:43:49 +0000988 Out << " std::vector<Value*> " << iName << "_indices;\n";
Reid Spencere0d133f2006-05-29 18:08:06 +0000989 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
Reid Spencer66c87342006-05-30 03:43:49 +0000990 Out << " " << iName << "_indices.push_back("
Reid Spencere0d133f2006-05-29 18:08:06 +0000991 << getCppName(gep->getOperand(i)) << ");\n";
992 }
Reid Spencer66c87342006-05-30 03:43:49 +0000993 Out << " Instruction* " << iName << " = new GetElementPtrInst("
Reid Spencere0d133f2006-05-29 18:08:06 +0000994 << getCppName(gep->getOperand(0)) << ", " << iName << "_indices";
995 }
996 Out << ", \"";
997 printEscapedString(gep->getName());
998 Out << "\", " << bbname << ");";
999 break;
1000 }
Reid Spencer66c87342006-05-30 03:43:49 +00001001 case Instruction::PHI: {
1002 const PHINode* phi = cast<PHINode>(I);
1003 Out << " PHINode* " << iName << " = new PHINode("
1004 << getCppName(phi->getType()) << ", \"";
1005 printEscapedString(phi->getName());
1006 Out << "\", " << bbname << ");\n";
1007 Out << iName << "->reserveOperandSpace(" << phi->getNumIncomingValues()
1008 << ");\n";
1009 for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
1010 Out << iName << "->addIncomingValue("
1011 << getCppName(phi->getIncomingValue(i)) << ", "
1012 << getCppName(phi->getIncomingBlock(i)) << ");\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001013 }
Reid Spencer66c87342006-05-30 03:43:49 +00001014 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001015 }
Reid Spencer66c87342006-05-30 03:43:49 +00001016 case Instruction::Cast: {
1017 const CastInst* cst = cast<CastInst>(I);
1018 Out << " CastInst* " << iName << " = new CastInst("
1019 << getCppName(cst->getOperand(0)) << ", "
1020 << getCppName(cst->getType()) << ", \"";
1021 printEscapedString(cst->getName());
1022 Out << "\", " << bbname << ");\n";
1023 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001024 }
Reid Spencer66c87342006-05-30 03:43:49 +00001025 case Instruction::Call:{
1026 const CallInst* call = cast<CallInst>(I);
1027 if (call->getNumOperands() > 3) {
1028 Out << " std::vector<Value*> " << iName << "_params;\n";
1029 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1030 Out << " " << iName << "_params.push_back("
1031 << getCppName(call->getOperand(i)) << ");\n";
1032 }
1033 Out << " CallInst* " << iName << " = new CallInst("
1034 << getCppName(call->getOperand(0)) << ", "
1035 << iName << "_params, \"";
1036 } else if (call->getNumOperands() == 3) {
1037 Out << " CallInst* " << iName << " = new CallInst("
1038 << getCppName(call->getOperand(0)) << ", "
1039 << getCppName(call->getOperand(1)) << ", "
1040 << getCppName(call->getOperand(2)) << ", \"";
1041 } else if (call->getNumOperands() == 2) {
1042 Out << " CallInst* " << iName << " = new CallInst("
1043 << getCppName(call->getOperand(0)) << ", "
1044 << getCppName(call->getOperand(1)) << ", \"";
1045 } else {
1046 Out << " CallInst* " << iName << " = new CallInst("
1047 << getCppName(call->getOperand(0)) << ", \"";
1048 }
1049 printEscapedString(call->getName());
1050 Out << "\", " << bbname << ");\n";
1051 Out << iName << "->setCallingConv(";
1052 printCallingConv(call->getCallingConv());
1053 Out << ");\n";
1054 Out << iName << "->setTailCall(" << (call->isTailCall() ? "true":"false");
1055 Out << ");";
1056 break;
1057 }
1058 case Instruction::Select: {
1059 const SelectInst* sel = cast<SelectInst>(I);
1060 Out << " SelectInst* " << getCppName(sel) << " = new SelectInst(";
1061 Out << getCppName(sel->getCondition()) << ", ";
1062 Out << getCppName(sel->getTrueValue()) << ", ";
1063 Out << getCppName(sel->getFalseValue()) << ", \"";
1064 printEscapedString(sel->getName());
1065 Out << "\", " << bbname << ");\n";
1066 break;
1067 }
1068 case Instruction::UserOp1:
1069 /// FALL THROUGH
1070 case Instruction::UserOp2: {
1071 /// FIXME: What should be done here?
1072 break;
1073 }
1074 case Instruction::VAArg: {
1075 const VAArgInst* va = cast<VAArgInst>(I);
1076 Out << " VAArgInst* " << getCppName(va) << " = new VAArgInst("
1077 << getCppName(va->getOperand(0)) << ", "
1078 << getCppName(va->getType()) << ", \"";
1079 printEscapedString(va->getName());
1080 Out << "\", " << bbname << ");\n";
1081 break;
1082 }
1083 case Instruction::ExtractElement: {
1084 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1085 Out << " ExtractElementInst* " << getCppName(eei)
1086 << " = new ExtractElementInst(" << getCppName(eei->getOperand(0))
1087 << ", " << getCppName(eei->getOperand(1)) << ", \"";
1088 printEscapedString(eei->getName());
1089 Out << "\", " << bbname << ");\n";
1090 break;
1091 }
1092 case Instruction::InsertElement: {
1093 const InsertElementInst* iei = cast<InsertElementInst>(I);
1094 Out << " InsertElementInst* " << getCppName(iei)
1095 << " = new InsertElementInst(" << getCppName(iei->getOperand(0))
1096 << ", " << getCppName(iei->getOperand(1)) << ", "
1097 << ", " << getCppName(iei->getOperand(2)) << ", \"";
1098 printEscapedString(iei->getName());
1099 Out << "\", " << bbname << ");\n";
1100 break;
1101 }
1102 case Instruction::ShuffleVector: {
1103 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1104 Out << " ShuffleVectorInst* " << getCppName(svi)
1105 << " = new ShuffleVectorInst(" << getCppName(svi->getOperand(0))
1106 << ", " << getCppName(svi->getOperand(1)) << ", "
1107 << ", " << getCppName(svi->getOperand(2)) << ", \"";
1108 printEscapedString(svi->getName());
1109 Out << "\", " << bbname << ");\n";
1110 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001111 }
1112 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001113 Out << "\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001114}
1115
1116} // end anonymous llvm
1117
1118namespace llvm {
1119
1120void WriteModuleToCppFile(Module* mod, std::ostream& o) {
1121 o << "#include <llvm/Module.h>\n";
1122 o << "#include <llvm/DerivedTypes.h>\n";
1123 o << "#include <llvm/Constants.h>\n";
1124 o << "#include <llvm/GlobalVariable.h>\n";
1125 o << "#include <llvm/Function.h>\n";
1126 o << "#include <llvm/CallingConv.h>\n";
1127 o << "#include <llvm/BasicBlock.h>\n";
1128 o << "#include <llvm/Instructions.h>\n";
1129 o << "#include <llvm/Pass.h>\n";
1130 o << "#include <llvm/PassManager.h>\n";
1131 o << "#include <llvm/Analysis/Verifier.h>\n";
1132 o << "#include <llvm/Assembly/PrintModulePass.h>\n";
1133 o << "#include <algorithm>\n";
1134 o << "#include <iostream>\n\n";
1135 o << "using namespace llvm;\n\n";
1136 o << "Module* makeLLVMModule();\n\n";
1137 o << "int main(int argc, char**argv) {\n";
1138 o << " Module* Mod = makeLLVMModule();\n";
1139 o << " verifyModule(*Mod, PrintMessageAction);\n";
Reid Spencere0d133f2006-05-29 18:08:06 +00001140 o << " std::cerr.flush();\n";
1141 o << " std::cout.flush();\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001142 o << " PassManager PM;\n";
1143 o << " PM.add(new PrintModulePass(&std::cout));\n";
1144 o << " PM.run(*Mod);\n";
1145 o << " return 0;\n";
1146 o << "}\n\n";
1147 o << "Module* makeLLVMModule() {\n";
Reid Spencere0d133f2006-05-29 18:08:06 +00001148 CppWriter W(o, mod);
1149 W.printModule(mod);
Reid Spencer74e032a2006-05-29 02:58:15 +00001150 o << "return mod;\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001151 o << "}\n";
1152}
1153
1154}