blob: b7338cb409df61ac6caf7ae6b4c7dd67d9559925 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- CppWriter.cpp - Printing LLVM IR as a C++ Source File -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Reid Spencer and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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/ParameterAttributes.h"
22#include "llvm/Module.h"
23#include "llvm/TypeSymbolTable.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/CFG.h"
29#include "llvm/Support/ManagedStatic.h"
30#include "llvm/Support/MathExtras.h"
31#include "llvm/Config/config.h"
32#include <algorithm>
33#include <iostream>
34#include <set>
35
36using namespace llvm;
37
38static cl::opt<std::string>
39FuncName("funcname", cl::desc("Specify the name of the generated function"),
40 cl::value_desc("function name"));
41
42enum WhatToGenerate {
43 GenProgram,
44 GenModule,
45 GenContents,
46 GenFunction,
Chris Lattner0366a6d2007-11-13 18:22:33 +000047 GenFunctions,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048 GenInline,
49 GenVariable,
50 GenType
51};
52
53static cl::opt<WhatToGenerate> GenerationType(cl::Optional,
54 cl::desc("Choose what kind of output to generate"),
55 cl::init(GenProgram),
56 cl::values(
Chris Lattner0366a6d2007-11-13 18:22:33 +000057 clEnumValN(GenProgram, "gen-program", "Generate a complete program"),
58 clEnumValN(GenModule, "gen-module", "Generate a module definition"),
59 clEnumValN(GenContents, "gen-contents", "Generate contents of a module"),
60 clEnumValN(GenFunction, "gen-function", "Generate a function definition"),
61 clEnumValN(GenFunctions,"gen-functions", "Generate all function definitions"),
62 clEnumValN(GenInline, "gen-inline", "Generate an inline function"),
63 clEnumValN(GenVariable, "gen-variable", "Generate a variable definition"),
64 clEnumValN(GenType, "gen-type", "Generate a type definition"),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000065 clEnumValEnd
66 )
67);
68
69static cl::opt<std::string> NameToGenerate("for", cl::Optional,
70 cl::desc("Specify the name of the thing to generate"),
71 cl::init("!bad!"));
72
73namespace {
74typedef std::vector<const Type*> TypeList;
75typedef std::map<const Type*,std::string> TypeMap;
76typedef std::map<const Value*,std::string> ValueMap;
77typedef std::set<std::string> NameSet;
78typedef std::set<const Type*> TypeSet;
79typedef std::set<const Value*> ValueSet;
80typedef std::map<const Value*,std::string> ForwardRefMap;
81
82class CppWriter {
83 const char* progname;
84 std::ostream &Out;
85 const Module *TheModule;
86 uint64_t uniqueNum;
87 TypeMap TypeNames;
88 ValueMap ValueNames;
89 TypeMap UnresolvedTypes;
90 TypeList TypeStack;
91 NameSet UsedNames;
92 TypeSet DefinedTypes;
93 ValueSet DefinedValues;
94 ForwardRefMap ForwardRefs;
95 bool is_inline;
96
97public:
98 inline CppWriter(std::ostream &o, const Module *M, const char* pn="llvm2cpp")
99 : progname(pn), Out(o), TheModule(M), uniqueNum(0), TypeNames(),
100 ValueNames(), UnresolvedTypes(), TypeStack(), is_inline(false) { }
101
102 const Module* getModule() { return TheModule; }
103
104 void printProgram(const std::string& fname, const std::string& modName );
105 void printModule(const std::string& fname, const std::string& modName );
106 void printContents(const std::string& fname, const std::string& modName );
107 void printFunction(const std::string& fname, const std::string& funcName );
Chris Lattner0366a6d2007-11-13 18:22:33 +0000108 void printFunctions();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000109 void printInline(const std::string& fname, const std::string& funcName );
110 void printVariable(const std::string& fname, const std::string& varName );
111 void printType(const std::string& fname, const std::string& typeName );
112
113 void error(const std::string& msg);
114
115private:
116 void printLinkageType(GlobalValue::LinkageTypes LT);
117 void printCallingConv(unsigned cc);
118 void printEscapedString(const std::string& str);
119 void printCFP(const ConstantFP* CFP);
120
121 std::string getCppName(const Type* val);
122 inline void printCppName(const Type* val);
123
124 std::string getCppName(const Value* val);
125 inline void printCppName(const Value* val);
126
127 bool printTypeInternal(const Type* Ty);
128 inline void printType(const Type* Ty);
129 void printTypes(const Module* M);
130
131 void printConstant(const Constant *CPV);
132 void printConstants(const Module* M);
133
134 void printVariableUses(const GlobalVariable *GV);
135 void printVariableHead(const GlobalVariable *GV);
136 void printVariableBody(const GlobalVariable *GV);
137
138 void printFunctionUses(const Function *F);
139 void printFunctionHead(const Function *F);
140 void printFunctionBody(const Function *F);
141 void printInstruction(const Instruction *I, const std::string& bbname);
142 std::string getOpName(Value*);
143
144 void printModuleBody();
145
146};
147
148static unsigned indent_level = 0;
149inline std::ostream& nl(std::ostream& Out, int delta = 0) {
150 Out << "\n";
151 if (delta >= 0 || indent_level >= unsigned(-delta))
152 indent_level += delta;
153 for (unsigned i = 0; i < indent_level; ++i)
154 Out << " ";
155 return Out;
156}
157
158inline void in() { indent_level++; }
159inline void out() { if (indent_level >0) indent_level--; }
160
161inline void
162sanitize(std::string& str) {
163 for (size_t i = 0; i < str.length(); ++i)
164 if (!isalnum(str[i]) && str[i] != '_')
165 str[i] = '_';
166}
167
168inline std::string
169getTypePrefix(const Type* Ty ) {
170 switch (Ty->getTypeID()) {
171 case Type::VoidTyID: return "void_";
172 case Type::IntegerTyID:
173 return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
174 "_";
175 case Type::FloatTyID: return "float_";
176 case Type::DoubleTyID: return "double_";
177 case Type::LabelTyID: return "label_";
178 case Type::FunctionTyID: return "func_";
179 case Type::StructTyID: return "struct_";
180 case Type::ArrayTyID: return "array_";
181 case Type::PointerTyID: return "ptr_";
182 case Type::VectorTyID: return "packed_";
183 case Type::OpaqueTyID: return "opaque_";
184 default: return "other_";
185 }
186 return "unknown_";
187}
188
189// Looks up the type in the symbol table and returns a pointer to its name or
190// a null pointer if it wasn't found. Note that this isn't the same as the
191// Mode::getTypeName function which will return an empty string, not a null
192// pointer if the name is not found.
193inline const std::string*
194findTypeName(const TypeSymbolTable& ST, const Type* Ty)
195{
196 TypeSymbolTable::const_iterator TI = ST.begin();
197 TypeSymbolTable::const_iterator TE = ST.end();
198 for (;TI != TE; ++TI)
199 if (TI->second == Ty)
200 return &(TI->first);
201 return 0;
202}
203
204void
205CppWriter::error(const std::string& msg) {
206 std::cerr << progname << ": " << msg << "\n";
207 exit(2);
208}
209
210// printCFP - Print a floating point constant .. very carefully :)
211// This makes sure that conversion to/from floating yields the same binary
212// result so that we don't lose precision.
213void
214CppWriter::printCFP(const ConstantFP *CFP) {
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000215 APFloat APF = APFloat(CFP->getValueAPF()); // copy
216 if (CFP->getType() == Type::FloatTy)
217 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000218 Out << "ConstantFP::get(";
219 if (CFP->getType() == Type::DoubleTy)
220 Out << "Type::DoubleTy, ";
221 else
222 Out << "Type::FloatTy, ";
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000223 Out << "APFloat(";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224#if HAVE_PRINTF_A
225 char Buffer[100];
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000226 sprintf(Buffer, "%A", APF.convertToDouble());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000227 if ((!strncmp(Buffer, "0x", 2) ||
228 !strncmp(Buffer, "-0x", 3) ||
229 !strncmp(Buffer, "+0x", 3)) &&
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000230 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231 if (CFP->getType() == Type::DoubleTy)
232 Out << "BitsToDouble(" << Buffer << ")";
233 else
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000234 Out << "BitsToFloat((float)" << Buffer << ")";
235 Out << ")";
236 } else {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000237#endif
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000238 std::string StrVal = ftostr(CFP->getValueAPF());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239
240 while (StrVal[0] == ' ')
241 StrVal.erase(StrVal.begin());
242
243 // Check to make sure that the stringized number is not some string like
244 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
245 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
246 ((StrVal[0] == '-' || StrVal[0] == '+') &&
247 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000248 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000249 if (CFP->getType() == Type::DoubleTy)
250 Out << StrVal;
251 else
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000252 Out << StrVal << "f";
253 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254 else if (CFP->getType() == Type::DoubleTy)
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000255 Out << "BitsToDouble(0x" << std::hex
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000256 << CFP->getValueAPF().convertToAPInt().getZExtValue()
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 << std::dec << "ULL) /* " << StrVal << " */";
258 else
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000259 Out << "BitsToFloat(0x" << std::hex
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000260 << (uint32_t)CFP->getValueAPF().convertToAPInt().getZExtValue()
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000261 << std::dec << "U) /* " << StrVal << " */";
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000262 Out << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000263#if HAVE_PRINTF_A
264 }
265#endif
266 Out << ")";
267}
268
269void
270CppWriter::printCallingConv(unsigned cc){
271 // Print the calling convention.
272 switch (cc) {
273 case CallingConv::C: Out << "CallingConv::C"; break;
274 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
275 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
276 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
277 default: Out << cc; break;
278 }
279}
280
281void
282CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
283 switch (LT) {
284 case GlobalValue::InternalLinkage:
285 Out << "GlobalValue::InternalLinkage"; break;
286 case GlobalValue::LinkOnceLinkage:
287 Out << "GlobalValue::LinkOnceLinkage "; break;
288 case GlobalValue::WeakLinkage:
289 Out << "GlobalValue::WeakLinkage"; break;
290 case GlobalValue::AppendingLinkage:
291 Out << "GlobalValue::AppendingLinkage"; break;
292 case GlobalValue::ExternalLinkage:
293 Out << "GlobalValue::ExternalLinkage"; break;
294 case GlobalValue::DLLImportLinkage:
295 Out << "GlobalValue::DLLImportLinkage"; break;
296 case GlobalValue::DLLExportLinkage:
297 Out << "GlobalValue::DLLExportLinkage"; break;
298 case GlobalValue::ExternalWeakLinkage:
299 Out << "GlobalValue::ExternalWeakLinkage"; break;
300 case GlobalValue::GhostLinkage:
301 Out << "GlobalValue::GhostLinkage"; break;
302 }
303}
304
305// printEscapedString - Print each character of the specified string, escaping
306// it if it is not printable or if it is an escape char.
307void
308CppWriter::printEscapedString(const std::string &Str) {
309 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
310 unsigned char C = Str[i];
311 if (isprint(C) && C != '"' && C != '\\') {
312 Out << C;
313 } else {
314 Out << "\\x"
315 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
316 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
317 }
318 }
319}
320
321std::string
322CppWriter::getCppName(const Type* Ty)
323{
324 // First, handle the primitive types .. easy
325 if (Ty->isPrimitiveType() || Ty->isInteger()) {
326 switch (Ty->getTypeID()) {
327 case Type::VoidTyID: return "Type::VoidTy";
328 case Type::IntegerTyID: {
329 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
330 return "IntegerType::get(" + utostr(BitWidth) + ")";
331 }
332 case Type::FloatTyID: return "Type::FloatTy";
333 case Type::DoubleTyID: return "Type::DoubleTy";
334 case Type::LabelTyID: return "Type::LabelTy";
335 default:
336 error("Invalid primitive type");
337 break;
338 }
339 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
340 }
341
342 // Now, see if we've seen the type before and return that
343 TypeMap::iterator I = TypeNames.find(Ty);
344 if (I != TypeNames.end())
345 return I->second;
346
347 // Okay, let's build a new name for this type. Start with a prefix
348 const char* prefix = 0;
349 switch (Ty->getTypeID()) {
350 case Type::FunctionTyID: prefix = "FuncTy_"; break;
351 case Type::StructTyID: prefix = "StructTy_"; break;
352 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
353 case Type::PointerTyID: prefix = "PointerTy_"; break;
354 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
355 case Type::VectorTyID: prefix = "VectorTy_"; break;
356 default: prefix = "OtherTy_"; break; // prevent breakage
357 }
358
359 // See if the type has a name in the symboltable and build accordingly
360 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
361 std::string name;
362 if (tName)
363 name = std::string(prefix) + *tName;
364 else
365 name = std::string(prefix) + utostr(uniqueNum++);
366 sanitize(name);
367
368 // Save the name
369 return TypeNames[Ty] = name;
370}
371
372void
373CppWriter::printCppName(const Type* Ty)
374{
375 printEscapedString(getCppName(Ty));
376}
377
378std::string
379CppWriter::getCppName(const Value* val) {
380 std::string name;
381 ValueMap::iterator I = ValueNames.find(val);
382 if (I != ValueNames.end() && I->first == val)
383 return I->second;
384
385 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
386 name = std::string("gvar_") +
387 getTypePrefix(GV->getType()->getElementType());
388 } else if (isa<Function>(val)) {
389 name = std::string("func_");
390 } else if (const Constant* C = dyn_cast<Constant>(val)) {
391 name = std::string("const_") + getTypePrefix(C->getType());
392 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
393 if (is_inline) {
394 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
395 Function::const_arg_iterator(Arg)) + 1;
396 name = std::string("arg_") + utostr(argNum);
397 NameSet::iterator NI = UsedNames.find(name);
398 if (NI != UsedNames.end())
399 name += std::string("_") + utostr(uniqueNum++);
400 UsedNames.insert(name);
401 return ValueNames[val] = name;
402 } else {
403 name = getTypePrefix(val->getType());
404 }
405 } else {
406 name = getTypePrefix(val->getType());
407 }
408 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
409 sanitize(name);
410 NameSet::iterator NI = UsedNames.find(name);
411 if (NI != UsedNames.end())
412 name += std::string("_") + utostr(uniqueNum++);
413 UsedNames.insert(name);
414 return ValueNames[val] = name;
415}
416
417void
418CppWriter::printCppName(const Value* val) {
419 printEscapedString(getCppName(val));
420}
421
422bool
423CppWriter::printTypeInternal(const Type* Ty) {
424 // We don't print definitions for primitive types
425 if (Ty->isPrimitiveType() || Ty->isInteger())
426 return false;
427
428 // If we already defined this type, we don't need to define it again.
429 if (DefinedTypes.find(Ty) != DefinedTypes.end())
430 return false;
431
432 // Everything below needs the name for the type so get it now.
433 std::string typeName(getCppName(Ty));
434
435 // Search the type stack for recursion. If we find it, then generate this
436 // as an OpaqueType, but make sure not to do this multiple times because
437 // the type could appear in multiple places on the stack. Once the opaque
438 // definition is issued, it must not be re-issued. Consequently we have to
439 // check the UnresolvedTypes list as well.
440 TypeList::const_iterator TI = std::find(TypeStack.begin(),TypeStack.end(),Ty);
441 if (TI != TypeStack.end()) {
442 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
443 if (I == UnresolvedTypes.end()) {
444 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
445 nl(Out);
446 UnresolvedTypes[Ty] = typeName;
447 }
448 return true;
449 }
450
451 // We're going to print a derived type which, by definition, contains other
452 // types. So, push this one we're printing onto the type stack to assist with
453 // recursive definitions.
454 TypeStack.push_back(Ty);
455
456 // Print the type definition
457 switch (Ty->getTypeID()) {
458 case Type::FunctionTyID: {
459 const FunctionType* FT = cast<FunctionType>(Ty);
460 Out << "std::vector<const Type*>" << typeName << "_args;";
461 nl(Out);
462 FunctionType::param_iterator PI = FT->param_begin();
463 FunctionType::param_iterator PE = FT->param_end();
464 for (; PI != PE; ++PI) {
465 const Type* argTy = static_cast<const Type*>(*PI);
466 bool isForward = printTypeInternal(argTy);
467 std::string argName(getCppName(argTy));
468 Out << typeName << "_args.push_back(" << argName;
469 if (isForward)
470 Out << "_fwd";
471 Out << ");";
472 nl(Out);
473 }
474 const ParamAttrsList *PAL = FT->getParamAttrs();
475 Out << "ParamAttrsList *" << typeName << "_PAL = 0;";
476 nl(Out);
477 if (PAL) {
478 Out << '{'; in(); nl(Out);
479 Out << "ParamAttrsVector Attrs;"; nl(Out);
480 Out << "ParamAttrsWithIndex PAWI;"; nl(Out);
481 for (unsigned i = 0; i < PAL->size(); ++i) {
482 uint16_t index = PAL->getParamIndex(i);
483 uint16_t attrs = PAL->getParamAttrs(index);
484 Out << "PAWI.index = " << index << "; PAWI.attrs = 0 ";
485 if (attrs & ParamAttr::SExt)
486 Out << " | ParamAttr::SExt";
487 if (attrs & ParamAttr::ZExt)
488 Out << " | ParamAttr::ZExt";
489 if (attrs & ParamAttr::NoAlias)
490 Out << " | ParamAttr::NoAlias";
491 if (attrs & ParamAttr::StructRet)
492 Out << " | ParamAttr::StructRet";
493 if (attrs & ParamAttr::InReg)
494 Out << " | ParamAttr::InReg";
495 if (attrs & ParamAttr::NoReturn)
496 Out << " | ParamAttr::NoReturn";
497 if (attrs & ParamAttr::NoUnwind)
498 Out << " | ParamAttr::NoUnwind";
499 Out << ";";
500 nl(Out);
501 Out << "Attrs.push_back(PAWI);";
502 nl(Out);
503 }
504 Out << typeName << "_PAL = ParamAttrsList::get(Attrs);";
505 nl(Out);
506 out(); nl(Out);
507 Out << '}'; nl(Out);
508 }
509 bool isForward = printTypeInternal(FT->getReturnType());
510 std::string retTypeName(getCppName(FT->getReturnType()));
511 Out << "FunctionType* " << typeName << " = FunctionType::get(";
512 in(); nl(Out) << "/*Result=*/" << retTypeName;
513 if (isForward)
514 Out << "_fwd";
515 Out << ",";
516 nl(Out) << "/*Params=*/" << typeName << "_args,";
517 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true," : "false,") ;
518 nl(Out) << "/*ParamAttrs=*/" << typeName << "_PAL" << ");";
519 out();
520 nl(Out);
521 break;
522 }
523 case Type::StructTyID: {
524 const StructType* ST = cast<StructType>(Ty);
525 Out << "std::vector<const Type*>" << typeName << "_fields;";
526 nl(Out);
527 StructType::element_iterator EI = ST->element_begin();
528 StructType::element_iterator EE = ST->element_end();
529 for (; EI != EE; ++EI) {
530 const Type* fieldTy = static_cast<const Type*>(*EI);
531 bool isForward = printTypeInternal(fieldTy);
532 std::string fieldName(getCppName(fieldTy));
533 Out << typeName << "_fields.push_back(" << fieldName;
534 if (isForward)
535 Out << "_fwd";
536 Out << ");";
537 nl(Out);
538 }
539 Out << "StructType* " << typeName << " = StructType::get("
540 << typeName << "_fields, /*isPacked=*/"
541 << (ST->isPacked() ? "true" : "false") << ");";
542 nl(Out);
543 break;
544 }
545 case Type::ArrayTyID: {
546 const ArrayType* AT = cast<ArrayType>(Ty);
547 const Type* ET = AT->getElementType();
548 bool isForward = printTypeInternal(ET);
549 std::string elemName(getCppName(ET));
550 Out << "ArrayType* " << typeName << " = ArrayType::get("
551 << elemName << (isForward ? "_fwd" : "")
552 << ", " << utostr(AT->getNumElements()) << ");";
553 nl(Out);
554 break;
555 }
556 case Type::PointerTyID: {
557 const PointerType* PT = cast<PointerType>(Ty);
558 const Type* ET = PT->getElementType();
559 bool isForward = printTypeInternal(ET);
560 std::string elemName(getCppName(ET));
561 Out << "PointerType* " << typeName << " = PointerType::get("
562 << elemName << (isForward ? "_fwd" : "") << ");";
563 nl(Out);
564 break;
565 }
566 case Type::VectorTyID: {
567 const VectorType* PT = cast<VectorType>(Ty);
568 const Type* ET = PT->getElementType();
569 bool isForward = printTypeInternal(ET);
570 std::string elemName(getCppName(ET));
571 Out << "VectorType* " << typeName << " = VectorType::get("
572 << elemName << (isForward ? "_fwd" : "")
573 << ", " << utostr(PT->getNumElements()) << ");";
574 nl(Out);
575 break;
576 }
577 case Type::OpaqueTyID: {
578 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
579 nl(Out);
580 break;
581 }
582 default:
583 error("Invalid TypeID");
584 }
585
586 // If the type had a name, make sure we recreate it.
587 const std::string* progTypeName =
588 findTypeName(TheModule->getTypeSymbolTable(),Ty);
589 if (progTypeName) {
590 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
591 << typeName << ");";
592 nl(Out);
593 }
594
595 // Pop us off the type stack
596 TypeStack.pop_back();
597
598 // Indicate that this type is now defined.
599 DefinedTypes.insert(Ty);
600
601 // Early resolve as many unresolved types as possible. Search the unresolved
602 // types map for the type we just printed. Now that its definition is complete
603 // we can resolve any previous references to it. This prevents a cascade of
604 // unresolved types.
605 TypeMap::iterator I = UnresolvedTypes.find(Ty);
606 if (I != UnresolvedTypes.end()) {
607 Out << "cast<OpaqueType>(" << I->second
608 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
609 nl(Out);
610 Out << I->second << " = cast<";
611 switch (Ty->getTypeID()) {
612 case Type::FunctionTyID: Out << "FunctionType"; break;
613 case Type::ArrayTyID: Out << "ArrayType"; break;
614 case Type::StructTyID: Out << "StructType"; break;
615 case Type::VectorTyID: Out << "VectorType"; break;
616 case Type::PointerTyID: Out << "PointerType"; break;
617 case Type::OpaqueTyID: Out << "OpaqueType"; break;
618 default: Out << "NoSuchDerivedType"; break;
619 }
620 Out << ">(" << I->second << "_fwd.get());";
621 nl(Out); nl(Out);
622 UnresolvedTypes.erase(I);
623 }
624
625 // Finally, separate the type definition from other with a newline.
626 nl(Out);
627
628 // We weren't a recursive type
629 return false;
630}
631
632// Prints a type definition. Returns true if it could not resolve all the types
633// in the definition but had to use a forward reference.
634void
635CppWriter::printType(const Type* Ty) {
636 assert(TypeStack.empty());
637 TypeStack.clear();
638 printTypeInternal(Ty);
639 assert(TypeStack.empty());
640}
641
642void
643CppWriter::printTypes(const Module* M) {
644
645 // Walk the symbol table and print out all its types
646 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
647 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
648 TI != TE; ++TI) {
649
650 // For primitive types and types already defined, just add a name
651 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
652 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
653 TNI != TypeNames.end()) {
654 Out << "mod->addTypeName(\"";
655 printEscapedString(TI->first);
656 Out << "\", " << getCppName(TI->second) << ");";
657 nl(Out);
658 // For everything else, define the type
659 } else {
660 printType(TI->second);
661 }
662 }
663
664 // Add all of the global variables to the value table...
665 for (Module::const_global_iterator I = TheModule->global_begin(),
666 E = TheModule->global_end(); I != E; ++I) {
667 if (I->hasInitializer())
668 printType(I->getInitializer()->getType());
669 printType(I->getType());
670 }
671
672 // Add all the functions to the table
673 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
674 FI != FE; ++FI) {
675 printType(FI->getReturnType());
676 printType(FI->getFunctionType());
677 // Add all the function arguments
678 for(Function::const_arg_iterator AI = FI->arg_begin(),
679 AE = FI->arg_end(); AI != AE; ++AI) {
680 printType(AI->getType());
681 }
682
683 // Add all of the basic blocks and instructions
684 for (Function::const_iterator BB = FI->begin(),
685 E = FI->end(); BB != E; ++BB) {
686 printType(BB->getType());
687 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
688 ++I) {
689 printType(I->getType());
690 for (unsigned i = 0; i < I->getNumOperands(); ++i)
691 printType(I->getOperand(i)->getType());
692 }
693 }
694 }
695}
696
697
698// printConstant - Print out a constant pool entry...
699void CppWriter::printConstant(const Constant *CV) {
700 // First, if the constant is actually a GlobalValue (variable or function) or
701 // its already in the constant list then we've printed it already and we can
702 // just return.
703 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
704 return;
705
706 std::string constName(getCppName(CV));
707 std::string typeName(getCppName(CV->getType()));
708 if (CV->isNullValue()) {
709 Out << "Constant* " << constName << " = Constant::getNullValue("
710 << typeName << ");";
711 nl(Out);
712 return;
713 }
714 if (isa<GlobalValue>(CV)) {
715 // Skip variables and functions, we emit them elsewhere
716 return;
717 }
718 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
719 Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
720 << cast<IntegerType>(CI->getType())->getBitWidth() << ", "
721 << " \"" << CI->getValue().toStringSigned(10) << "\", 10));";
722 } else if (isa<ConstantAggregateZero>(CV)) {
723 Out << "ConstantAggregateZero* " << constName
724 << " = ConstantAggregateZero::get(" << typeName << ");";
725 } else if (isa<ConstantPointerNull>(CV)) {
726 Out << "ConstantPointerNull* " << constName
727 << " = ConstanPointerNull::get(" << typeName << ");";
728 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
729 Out << "ConstantFP* " << constName << " = ";
730 printCFP(CFP);
731 Out << ";";
732 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
733 if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
734 Out << "Constant* " << constName << " = ConstantArray::get(\"";
735 std::string tmp = CA->getAsString();
736 bool nullTerminate = false;
737 if (tmp[tmp.length()-1] == 0) {
738 tmp.erase(tmp.length()-1);
739 nullTerminate = true;
740 }
741 printEscapedString(tmp);
742 // Determine if we want null termination or not.
743 if (nullTerminate)
744 Out << "\", true"; // Indicate that the null terminator should be added.
745 else
746 Out << "\", false";// No null terminator
747 Out << ");";
748 } else {
749 Out << "std::vector<Constant*> " << constName << "_elems;";
750 nl(Out);
751 unsigned N = CA->getNumOperands();
752 for (unsigned i = 0; i < N; ++i) {
753 printConstant(CA->getOperand(i)); // recurse to print operands
754 Out << constName << "_elems.push_back("
755 << getCppName(CA->getOperand(i)) << ");";
756 nl(Out);
757 }
758 Out << "Constant* " << constName << " = ConstantArray::get("
759 << typeName << ", " << constName << "_elems);";
760 }
761 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
762 Out << "std::vector<Constant*> " << constName << "_fields;";
763 nl(Out);
764 unsigned N = CS->getNumOperands();
765 for (unsigned i = 0; i < N; i++) {
766 printConstant(CS->getOperand(i));
767 Out << constName << "_fields.push_back("
768 << getCppName(CS->getOperand(i)) << ");";
769 nl(Out);
770 }
771 Out << "Constant* " << constName << " = ConstantStruct::get("
772 << typeName << ", " << constName << "_fields);";
773 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
774 Out << "std::vector<Constant*> " << constName << "_elems;";
775 nl(Out);
776 unsigned N = CP->getNumOperands();
777 for (unsigned i = 0; i < N; ++i) {
778 printConstant(CP->getOperand(i));
779 Out << constName << "_elems.push_back("
780 << getCppName(CP->getOperand(i)) << ");";
781 nl(Out);
782 }
783 Out << "Constant* " << constName << " = ConstantVector::get("
784 << typeName << ", " << constName << "_elems);";
785 } else if (isa<UndefValue>(CV)) {
786 Out << "UndefValue* " << constName << " = UndefValue::get("
787 << typeName << ");";
788 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
789 if (CE->getOpcode() == Instruction::GetElementPtr) {
790 Out << "std::vector<Constant*> " << constName << "_indices;";
791 nl(Out);
792 printConstant(CE->getOperand(0));
793 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
794 printConstant(CE->getOperand(i));
795 Out << constName << "_indices.push_back("
796 << getCppName(CE->getOperand(i)) << ");";
797 nl(Out);
798 }
799 Out << "Constant* " << constName
800 << " = ConstantExpr::getGetElementPtr("
801 << getCppName(CE->getOperand(0)) << ", "
David Greene69fc0d52007-09-04 17:15:07 +0000802 << "&" << constName << "_indices[0], "
803 << constName << "_indices.size()"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000804 << " );";
805 } else if (CE->isCast()) {
806 printConstant(CE->getOperand(0));
807 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
808 switch (CE->getOpcode()) {
809 default: assert(0 && "Invalid cast opcode");
810 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
811 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
812 case Instruction::SExt: Out << "Instruction::SExt"; break;
813 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
814 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
815 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
816 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
817 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
818 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
819 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
820 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
821 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
822 }
823 Out << ", " << getCppName(CE->getOperand(0)) << ", "
824 << getCppName(CE->getType()) << ");";
825 } else {
826 unsigned N = CE->getNumOperands();
827 for (unsigned i = 0; i < N; ++i ) {
828 printConstant(CE->getOperand(i));
829 }
830 Out << "Constant* " << constName << " = ConstantExpr::";
831 switch (CE->getOpcode()) {
832 case Instruction::Add: Out << "getAdd("; break;
833 case Instruction::Sub: Out << "getSub("; break;
834 case Instruction::Mul: Out << "getMul("; break;
835 case Instruction::UDiv: Out << "getUDiv("; break;
836 case Instruction::SDiv: Out << "getSDiv("; break;
837 case Instruction::FDiv: Out << "getFDiv("; break;
838 case Instruction::URem: Out << "getURem("; break;
839 case Instruction::SRem: Out << "getSRem("; break;
840 case Instruction::FRem: Out << "getFRem("; break;
841 case Instruction::And: Out << "getAnd("; break;
842 case Instruction::Or: Out << "getOr("; break;
843 case Instruction::Xor: Out << "getXor("; break;
844 case Instruction::ICmp:
845 Out << "getICmp(ICmpInst::ICMP_";
846 switch (CE->getPredicate()) {
847 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
848 case ICmpInst::ICMP_NE: Out << "NE"; break;
849 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
850 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
851 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
852 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
853 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
854 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
855 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
856 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
857 default: error("Invalid ICmp Predicate");
858 }
859 break;
860 case Instruction::FCmp:
861 Out << "getFCmp(FCmpInst::FCMP_";
862 switch (CE->getPredicate()) {
863 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
864 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
865 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
866 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
867 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
868 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
869 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
870 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
871 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
872 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
873 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
874 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
875 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
876 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
877 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
878 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
879 default: error("Invalid FCmp Predicate");
880 }
881 break;
882 case Instruction::Shl: Out << "getShl("; break;
883 case Instruction::LShr: Out << "getLShr("; break;
884 case Instruction::AShr: Out << "getAShr("; break;
885 case Instruction::Select: Out << "getSelect("; break;
886 case Instruction::ExtractElement: Out << "getExtractElement("; break;
887 case Instruction::InsertElement: Out << "getInsertElement("; break;
888 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
889 default:
890 error("Invalid constant expression");
891 break;
892 }
893 Out << getCppName(CE->getOperand(0));
894 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
895 Out << ", " << getCppName(CE->getOperand(i));
896 Out << ");";
897 }
898 } else {
899 error("Bad Constant");
900 Out << "Constant* " << constName << " = 0; ";
901 }
902 nl(Out);
903}
904
905void
906CppWriter::printConstants(const Module* M) {
907 // Traverse all the global variables looking for constant initializers
908 for (Module::const_global_iterator I = TheModule->global_begin(),
909 E = TheModule->global_end(); I != E; ++I)
910 if (I->hasInitializer())
911 printConstant(I->getInitializer());
912
913 // Traverse the LLVM functions looking for constants
914 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
915 FI != FE; ++FI) {
916 // Add all of the basic blocks and instructions
917 for (Function::const_iterator BB = FI->begin(),
918 E = FI->end(); BB != E; ++BB) {
919 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
920 ++I) {
921 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
922 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
923 printConstant(C);
924 }
925 }
926 }
927 }
928 }
929}
930
931void CppWriter::printVariableUses(const GlobalVariable *GV) {
932 nl(Out) << "// Type Definitions";
933 nl(Out);
934 printType(GV->getType());
935 if (GV->hasInitializer()) {
936 Constant* Init = GV->getInitializer();
937 printType(Init->getType());
938 if (Function* F = dyn_cast<Function>(Init)) {
939 nl(Out)<< "/ Function Declarations"; nl(Out);
940 printFunctionHead(F);
941 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
942 nl(Out) << "// Global Variable Declarations"; nl(Out);
943 printVariableHead(gv);
944 } else {
945 nl(Out) << "// Constant Definitions"; nl(Out);
946 printConstant(gv);
947 }
948 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
949 nl(Out) << "// Global Variable Definitions"; nl(Out);
950 printVariableBody(gv);
951 }
952 }
953}
954
955void CppWriter::printVariableHead(const GlobalVariable *GV) {
956 nl(Out) << "GlobalVariable* " << getCppName(GV);
957 if (is_inline) {
958 Out << " = mod->getGlobalVariable(";
959 printEscapedString(GV->getName());
960 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
961 nl(Out) << "if (!" << getCppName(GV) << ") {";
962 in(); nl(Out) << getCppName(GV);
963 }
964 Out << " = new GlobalVariable(";
965 nl(Out) << "/*Type=*/";
966 printCppName(GV->getType()->getElementType());
967 Out << ",";
968 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
969 Out << ",";
970 nl(Out) << "/*Linkage=*/";
971 printLinkageType(GV->getLinkage());
972 Out << ",";
973 nl(Out) << "/*Initializer=*/0, ";
974 if (GV->hasInitializer()) {
975 Out << "// has initializer, specified below";
976 }
977 nl(Out) << "/*Name=*/\"";
978 printEscapedString(GV->getName());
979 Out << "\",";
980 nl(Out) << "mod);";
981 nl(Out);
982
983 if (GV->hasSection()) {
984 printCppName(GV);
985 Out << "->setSection(\"";
986 printEscapedString(GV->getSection());
987 Out << "\");";
988 nl(Out);
989 }
990 if (GV->getAlignment()) {
991 printCppName(GV);
992 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
993 nl(Out);
994 };
995 if (is_inline) {
996 out(); Out << "}"; nl(Out);
997 }
998}
999
1000void
1001CppWriter::printVariableBody(const GlobalVariable *GV) {
1002 if (GV->hasInitializer()) {
1003 printCppName(GV);
1004 Out << "->setInitializer(";
1005 //if (!isa<GlobalValue(GV->getInitializer()))
1006 //else
1007 Out << getCppName(GV->getInitializer()) << ");";
1008 nl(Out);
1009 }
1010}
1011
1012std::string
1013CppWriter::getOpName(Value* V) {
1014 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1015 return getCppName(V);
1016
1017 // See if its alread in the map of forward references, if so just return the
1018 // name we already set up for it
1019 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1020 if (I != ForwardRefs.end())
1021 return I->second;
1022
1023 // This is a new forward reference. Generate a unique name for it
1024 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1025
1026 // Yes, this is a hack. An Argument is the smallest instantiable value that
1027 // we can make as a placeholder for the real value. We'll replace these
1028 // Argument instances later.
1029 Out << "Argument* " << result << " = new Argument("
1030 << getCppName(V->getType()) << ");";
1031 nl(Out);
1032 ForwardRefs[V] = result;
1033 return result;
1034}
1035
1036// printInstruction - This member is called for each Instruction in a function.
1037void
1038CppWriter::printInstruction(const Instruction *I, const std::string& bbname) {
1039 std::string iName(getCppName(I));
1040
1041 // Before we emit this instruction, we need to take care of generating any
1042 // forward references. So, we get the names of all the operands in advance
1043 std::string* opNames = new std::string[I->getNumOperands()];
1044 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1045 opNames[i] = getOpName(I->getOperand(i));
1046 }
1047
1048 switch (I->getOpcode()) {
1049 case Instruction::Ret: {
1050 const ReturnInst* ret = cast<ReturnInst>(I);
1051 Out << "new ReturnInst("
1052 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1053 break;
1054 }
1055 case Instruction::Br: {
1056 const BranchInst* br = cast<BranchInst>(I);
1057 Out << "new BranchInst(" ;
1058 if (br->getNumOperands() == 3 ) {
1059 Out << opNames[0] << ", "
1060 << opNames[1] << ", "
1061 << opNames[2] << ", ";
1062
1063 } else if (br->getNumOperands() == 1) {
1064 Out << opNames[0] << ", ";
1065 } else {
1066 error("Branch with 2 operands?");
1067 }
1068 Out << bbname << ");";
1069 break;
1070 }
1071 case Instruction::Switch: {
1072 const SwitchInst* sw = cast<SwitchInst>(I);
1073 Out << "SwitchInst* " << iName << " = new SwitchInst("
1074 << opNames[0] << ", "
1075 << opNames[1] << ", "
1076 << sw->getNumCases() << ", " << bbname << ");";
1077 nl(Out);
1078 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1079 Out << iName << "->addCase("
1080 << opNames[i] << ", "
1081 << opNames[i+1] << ");";
1082 nl(Out);
1083 }
1084 break;
1085 }
1086 case Instruction::Invoke: {
1087 const InvokeInst* inv = cast<InvokeInst>(I);
1088 Out << "std::vector<Value*> " << iName << "_params;";
1089 nl(Out);
1090 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1091 Out << iName << "_params.push_back("
1092 << opNames[i] << ");";
1093 nl(Out);
1094 }
1095 Out << "InvokeInst *" << iName << " = new InvokeInst("
1096 << opNames[0] << ", "
1097 << opNames[1] << ", "
1098 << opNames[2] << ", "
David Greene8278ef52007-08-27 19:04:21 +00001099 << iName << "_params.begin(), " << iName << "_params.end(), \"";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001100 printEscapedString(inv->getName());
1101 Out << "\", " << bbname << ");";
1102 nl(Out) << iName << "->setCallingConv(";
1103 printCallingConv(inv->getCallingConv());
1104 Out << ");";
1105 break;
1106 }
1107 case Instruction::Unwind: {
1108 Out << "new UnwindInst("
1109 << bbname << ");";
1110 break;
1111 }
1112 case Instruction::Unreachable:{
1113 Out << "new UnreachableInst("
1114 << bbname << ");";
1115 break;
1116 }
1117 case Instruction::Add:
1118 case Instruction::Sub:
1119 case Instruction::Mul:
1120 case Instruction::UDiv:
1121 case Instruction::SDiv:
1122 case Instruction::FDiv:
1123 case Instruction::URem:
1124 case Instruction::SRem:
1125 case Instruction::FRem:
1126 case Instruction::And:
1127 case Instruction::Or:
1128 case Instruction::Xor:
1129 case Instruction::Shl:
1130 case Instruction::LShr:
1131 case Instruction::AShr:{
1132 Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
1133 switch (I->getOpcode()) {
1134 case Instruction::Add: Out << "Instruction::Add"; break;
1135 case Instruction::Sub: Out << "Instruction::Sub"; break;
1136 case Instruction::Mul: Out << "Instruction::Mul"; break;
1137 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1138 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1139 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1140 case Instruction::URem:Out << "Instruction::URem"; break;
1141 case Instruction::SRem:Out << "Instruction::SRem"; break;
1142 case Instruction::FRem:Out << "Instruction::FRem"; break;
1143 case Instruction::And: Out << "Instruction::And"; break;
1144 case Instruction::Or: Out << "Instruction::Or"; break;
1145 case Instruction::Xor: Out << "Instruction::Xor"; break;
1146 case Instruction::Shl: Out << "Instruction::Shl"; break;
1147 case Instruction::LShr:Out << "Instruction::LShr"; break;
1148 case Instruction::AShr:Out << "Instruction::AShr"; break;
1149 default: Out << "Instruction::BadOpCode"; break;
1150 }
1151 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1152 printEscapedString(I->getName());
1153 Out << "\", " << bbname << ");";
1154 break;
1155 }
1156 case Instruction::FCmp: {
1157 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1158 switch (cast<FCmpInst>(I)->getPredicate()) {
1159 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1160 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1161 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1162 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1163 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1164 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1165 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1166 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1167 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1168 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1169 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1170 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1171 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1172 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1173 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1174 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1175 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1176 }
1177 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1178 printEscapedString(I->getName());
1179 Out << "\", " << bbname << ");";
1180 break;
1181 }
1182 case Instruction::ICmp: {
1183 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1184 switch (cast<ICmpInst>(I)->getPredicate()) {
1185 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1186 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1187 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1188 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1189 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1190 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1191 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1192 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1193 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1194 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1195 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1196 }
1197 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1198 printEscapedString(I->getName());
1199 Out << "\", " << bbname << ");";
1200 break;
1201 }
1202 case Instruction::Malloc: {
1203 const MallocInst* mallocI = cast<MallocInst>(I);
1204 Out << "MallocInst* " << iName << " = new MallocInst("
1205 << getCppName(mallocI->getAllocatedType()) << ", ";
1206 if (mallocI->isArrayAllocation())
1207 Out << opNames[0] << ", " ;
1208 Out << "\"";
1209 printEscapedString(mallocI->getName());
1210 Out << "\", " << bbname << ");";
1211 if (mallocI->getAlignment())
1212 nl(Out) << iName << "->setAlignment("
1213 << mallocI->getAlignment() << ");";
1214 break;
1215 }
1216 case Instruction::Free: {
1217 Out << "FreeInst* " << iName << " = new FreeInst("
1218 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1219 break;
1220 }
1221 case Instruction::Alloca: {
1222 const AllocaInst* allocaI = cast<AllocaInst>(I);
1223 Out << "AllocaInst* " << iName << " = new AllocaInst("
1224 << getCppName(allocaI->getAllocatedType()) << ", ";
1225 if (allocaI->isArrayAllocation())
1226 Out << opNames[0] << ", ";
1227 Out << "\"";
1228 printEscapedString(allocaI->getName());
1229 Out << "\", " << bbname << ");";
1230 if (allocaI->getAlignment())
1231 nl(Out) << iName << "->setAlignment("
1232 << allocaI->getAlignment() << ");";
1233 break;
1234 }
1235 case Instruction::Load:{
1236 const LoadInst* load = cast<LoadInst>(I);
1237 Out << "LoadInst* " << iName << " = new LoadInst("
1238 << opNames[0] << ", \"";
1239 printEscapedString(load->getName());
1240 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1241 << ", " << bbname << ");";
1242 break;
1243 }
1244 case Instruction::Store: {
1245 const StoreInst* store = cast<StoreInst>(I);
1246 Out << "StoreInst* " << iName << " = new StoreInst("
1247 << opNames[0] << ", "
1248 << opNames[1] << ", "
1249 << (store->isVolatile() ? "true" : "false")
1250 << ", " << bbname << ");";
1251 break;
1252 }
1253 case Instruction::GetElementPtr: {
1254 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1255 if (gep->getNumOperands() <= 2) {
1256 Out << "GetElementPtrInst* " << iName << " = new GetElementPtrInst("
1257 << opNames[0];
1258 if (gep->getNumOperands() == 2)
1259 Out << ", " << opNames[1];
1260 } else {
1261 Out << "std::vector<Value*> " << iName << "_indices;";
1262 nl(Out);
1263 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1264 Out << iName << "_indices.push_back("
1265 << opNames[i] << ");";
1266 nl(Out);
1267 }
1268 Out << "Instruction* " << iName << " = new GetElementPtrInst("
David Greene393be882007-09-04 15:46:09 +00001269 << opNames[0] << ", " << iName << "_indices.begin(), "
1270 << iName << "_indices.end()";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001271 }
1272 Out << ", \"";
1273 printEscapedString(gep->getName());
1274 Out << "\", " << bbname << ");";
1275 break;
1276 }
1277 case Instruction::PHI: {
1278 const PHINode* phi = cast<PHINode>(I);
1279
1280 Out << "PHINode* " << iName << " = new PHINode("
1281 << getCppName(phi->getType()) << ", \"";
1282 printEscapedString(phi->getName());
1283 Out << "\", " << bbname << ");";
1284 nl(Out) << iName << "->reserveOperandSpace("
1285 << phi->getNumIncomingValues()
1286 << ");";
1287 nl(Out);
1288 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1289 Out << iName << "->addIncoming("
1290 << opNames[i] << ", " << opNames[i+1] << ");";
1291 nl(Out);
1292 }
1293 break;
1294 }
1295 case Instruction::Trunc:
1296 case Instruction::ZExt:
1297 case Instruction::SExt:
1298 case Instruction::FPTrunc:
1299 case Instruction::FPExt:
1300 case Instruction::FPToUI:
1301 case Instruction::FPToSI:
1302 case Instruction::UIToFP:
1303 case Instruction::SIToFP:
1304 case Instruction::PtrToInt:
1305 case Instruction::IntToPtr:
1306 case Instruction::BitCast: {
1307 const CastInst* cst = cast<CastInst>(I);
1308 Out << "CastInst* " << iName << " = new ";
1309 switch (I->getOpcode()) {
1310 case Instruction::Trunc: Out << "TruncInst"; break;
1311 case Instruction::ZExt: Out << "ZExtInst"; break;
1312 case Instruction::SExt: Out << "SExtInst"; break;
1313 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1314 case Instruction::FPExt: Out << "FPExtInst"; break;
1315 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1316 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1317 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1318 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1319 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1320 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1321 case Instruction::BitCast: Out << "BitCastInst"; break;
1322 default: assert(!"Unreachable"); break;
1323 }
1324 Out << "(" << opNames[0] << ", "
1325 << getCppName(cst->getType()) << ", \"";
1326 printEscapedString(cst->getName());
1327 Out << "\", " << bbname << ");";
1328 break;
1329 }
1330 case Instruction::Call:{
1331 const CallInst* call = cast<CallInst>(I);
1332 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1333 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1334 << getCppName(ila->getFunctionType()) << ", \""
1335 << ila->getAsmString() << "\", \""
1336 << ila->getConstraintString() << "\","
1337 << (ila->hasSideEffects() ? "true" : "false") << ");";
1338 nl(Out);
1339 }
Reid Spencerefbe90e2007-08-02 03:30:26 +00001340 if (call->getNumOperands() > 2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001341 Out << "std::vector<Value*> " << iName << "_params;";
1342 nl(Out);
1343 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1344 Out << iName << "_params.push_back(" << opNames[i] << ");";
1345 nl(Out);
1346 }
1347 Out << "CallInst* " << iName << " = new CallInst("
Reid Spencerefbe90e2007-08-02 03:30:26 +00001348 << opNames[0] << ", " << iName << "_params.begin(), "
1349 << iName << "_params.end(), \"";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001350 } else if (call->getNumOperands() == 2) {
1351 Out << "CallInst* " << iName << " = new CallInst("
1352 << opNames[0] << ", " << opNames[1] << ", \"";
1353 } else {
1354 Out << "CallInst* " << iName << " = new CallInst(" << opNames[0]
1355 << ", \"";
1356 }
1357 printEscapedString(call->getName());
1358 Out << "\", " << bbname << ");";
1359 nl(Out) << iName << "->setCallingConv(";
1360 printCallingConv(call->getCallingConv());
1361 Out << ");";
1362 nl(Out) << iName << "->setTailCall("
1363 << (call->isTailCall() ? "true":"false");
1364 Out << ");";
1365 break;
1366 }
1367 case Instruction::Select: {
1368 const SelectInst* sel = cast<SelectInst>(I);
1369 Out << "SelectInst* " << getCppName(sel) << " = new SelectInst(";
1370 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1371 printEscapedString(sel->getName());
1372 Out << "\", " << bbname << ");";
1373 break;
1374 }
1375 case Instruction::UserOp1:
1376 /// FALL THROUGH
1377 case Instruction::UserOp2: {
1378 /// FIXME: What should be done here?
1379 break;
1380 }
1381 case Instruction::VAArg: {
1382 const VAArgInst* va = cast<VAArgInst>(I);
1383 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1384 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1385 printEscapedString(va->getName());
1386 Out << "\", " << bbname << ");";
1387 break;
1388 }
1389 case Instruction::ExtractElement: {
1390 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1391 Out << "ExtractElementInst* " << getCppName(eei)
1392 << " = new ExtractElementInst(" << opNames[0]
1393 << ", " << opNames[1] << ", \"";
1394 printEscapedString(eei->getName());
1395 Out << "\", " << bbname << ");";
1396 break;
1397 }
1398 case Instruction::InsertElement: {
1399 const InsertElementInst* iei = cast<InsertElementInst>(I);
1400 Out << "InsertElementInst* " << getCppName(iei)
1401 << " = new InsertElementInst(" << opNames[0]
1402 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1403 printEscapedString(iei->getName());
1404 Out << "\", " << bbname << ");";
1405 break;
1406 }
1407 case Instruction::ShuffleVector: {
1408 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1409 Out << "ShuffleVectorInst* " << getCppName(svi)
1410 << " = new ShuffleVectorInst(" << opNames[0]
1411 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1412 printEscapedString(svi->getName());
1413 Out << "\", " << bbname << ");";
1414 break;
1415 }
1416 }
1417 DefinedValues.insert(I);
1418 nl(Out);
1419 delete [] opNames;
1420}
1421
1422// Print out the types, constants and declarations needed by one function
1423void CppWriter::printFunctionUses(const Function* F) {
1424
1425 nl(Out) << "// Type Definitions"; nl(Out);
1426 if (!is_inline) {
1427 // Print the function's return type
1428 printType(F->getReturnType());
1429
1430 // Print the function's function type
1431 printType(F->getFunctionType());
1432
1433 // Print the types of each of the function's arguments
1434 for(Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1435 AI != AE; ++AI) {
1436 printType(AI->getType());
1437 }
1438 }
1439
1440 // Print type definitions for every type referenced by an instruction and
1441 // make a note of any global values or constants that are referenced
1442 SmallPtrSet<GlobalValue*,64> gvs;
1443 SmallPtrSet<Constant*,64> consts;
1444 for (Function::const_iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB){
1445 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1446 I != E; ++I) {
1447 // Print the type of the instruction itself
1448 printType(I->getType());
1449
1450 // Print the type of each of the instruction's operands
1451 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1452 Value* operand = I->getOperand(i);
1453 printType(operand->getType());
1454
1455 // If the operand references a GVal or Constant, make a note of it
1456 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1457 gvs.insert(GV);
1458 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1459 if (GVar->hasInitializer())
1460 consts.insert(GVar->getInitializer());
1461 } else if (Constant* C = dyn_cast<Constant>(operand))
1462 consts.insert(C);
1463 }
1464 }
1465 }
1466
1467 // Print the function declarations for any functions encountered
1468 nl(Out) << "// Function Declarations"; nl(Out);
1469 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1470 I != E; ++I) {
1471 if (Function* Fun = dyn_cast<Function>(*I)) {
1472 if (!is_inline || Fun != F)
1473 printFunctionHead(Fun);
1474 }
1475 }
1476
1477 // Print the global variable declarations for any variables encountered
1478 nl(Out) << "// Global Variable Declarations"; nl(Out);
1479 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1480 I != E; ++I) {
1481 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1482 printVariableHead(F);
1483 }
1484
1485 // Print the constants found
1486 nl(Out) << "// Constant Definitions"; nl(Out);
1487 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(), E = consts.end();
1488 I != E; ++I) {
1489 printConstant(*I);
1490 }
1491
1492 // Process the global variables definitions now that all the constants have
1493 // been emitted. These definitions just couple the gvars with their constant
1494 // initializers.
1495 nl(Out) << "// Global Variable Definitions"; nl(Out);
1496 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1497 I != E; ++I) {
1498 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1499 printVariableBody(GV);
1500 }
1501}
1502
1503void CppWriter::printFunctionHead(const Function* F) {
1504 nl(Out) << "Function* " << getCppName(F);
1505 if (is_inline) {
1506 Out << " = mod->getFunction(\"";
1507 printEscapedString(F->getName());
1508 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1509 nl(Out) << "if (!" << getCppName(F) << ") {";
1510 nl(Out) << getCppName(F);
1511 }
1512 Out<< " = new Function(";
1513 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1514 nl(Out) << "/*Linkage=*/";
1515 printLinkageType(F->getLinkage());
1516 Out << ",";
1517 nl(Out) << "/*Name=*/\"";
1518 printEscapedString(F->getName());
1519 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1520 nl(Out,-1);
1521 printCppName(F);
1522 Out << "->setCallingConv(";
1523 printCallingConv(F->getCallingConv());
1524 Out << ");";
1525 nl(Out);
1526 if (F->hasSection()) {
1527 printCppName(F);
1528 Out << "->setSection(\"" << F->getSection() << "\");";
1529 nl(Out);
1530 }
1531 if (F->getAlignment()) {
1532 printCppName(F);
1533 Out << "->setAlignment(" << F->getAlignment() << ");";
1534 nl(Out);
1535 }
1536 if (is_inline) {
1537 Out << "}";
1538 nl(Out);
1539 }
1540}
1541
1542void CppWriter::printFunctionBody(const Function *F) {
1543 if (F->isDeclaration())
1544 return; // external functions have no bodies.
1545
1546 // Clear the DefinedValues and ForwardRefs maps because we can't have
1547 // cross-function forward refs
1548 ForwardRefs.clear();
1549 DefinedValues.clear();
1550
1551 // Create all the argument values
1552 if (!is_inline) {
1553 if (!F->arg_empty()) {
1554 Out << "Function::arg_iterator args = " << getCppName(F)
1555 << "->arg_begin();";
1556 nl(Out);
1557 }
1558 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1559 AI != AE; ++AI) {
1560 Out << "Value* " << getCppName(AI) << " = args++;";
1561 nl(Out);
1562 if (AI->hasName()) {
1563 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1564 nl(Out);
1565 }
1566 }
1567 }
1568
1569 // Create all the basic blocks
1570 nl(Out);
1571 for (Function::const_iterator BI = F->begin(), BE = F->end();
1572 BI != BE; ++BI) {
1573 std::string bbname(getCppName(BI));
1574 Out << "BasicBlock* " << bbname << " = new BasicBlock(\"";
1575 if (BI->hasName())
1576 printEscapedString(BI->getName());
1577 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1578 nl(Out);
1579 }
1580
1581 // Output all of its basic blocks... for the function
1582 for (Function::const_iterator BI = F->begin(), BE = F->end();
1583 BI != BE; ++BI) {
1584 std::string bbname(getCppName(BI));
1585 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1586 nl(Out);
1587
1588 // Output all of the instructions in the basic block...
1589 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1590 I != E; ++I) {
1591 printInstruction(I,bbname);
1592 }
1593 }
1594
1595 // Loop over the ForwardRefs and resolve them now that all instructions
1596 // are generated.
1597 if (!ForwardRefs.empty()) {
1598 nl(Out) << "// Resolve Forward References";
1599 nl(Out);
1600 }
1601
1602 while (!ForwardRefs.empty()) {
1603 ForwardRefMap::iterator I = ForwardRefs.begin();
1604 Out << I->second << "->replaceAllUsesWith("
1605 << getCppName(I->first) << "); delete " << I->second << ";";
1606 nl(Out);
1607 ForwardRefs.erase(I);
1608 }
1609}
1610
1611void CppWriter::printInline(const std::string& fname, const std::string& func) {
1612 const Function* F = TheModule->getFunction(func);
1613 if (!F) {
1614 error(std::string("Function '") + func + "' not found in input module");
1615 return;
1616 }
1617 if (F->isDeclaration()) {
1618 error(std::string("Function '") + func + "' is external!");
1619 return;
1620 }
1621 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1622 << getCppName(F);
1623 unsigned arg_count = 1;
1624 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1625 AI != AE; ++AI) {
1626 Out << ", Value* arg_" << arg_count;
1627 }
1628 Out << ") {";
1629 nl(Out);
1630 is_inline = true;
1631 printFunctionUses(F);
1632 printFunctionBody(F);
1633 is_inline = false;
1634 Out << "return " << getCppName(F->begin()) << ";";
1635 nl(Out) << "}";
1636 nl(Out);
1637}
1638
1639void CppWriter::printModuleBody() {
1640 // Print out all the type definitions
1641 nl(Out) << "// Type Definitions"; nl(Out);
1642 printTypes(TheModule);
1643
1644 // Functions can call each other and global variables can reference them so
1645 // define all the functions first before emitting their function bodies.
1646 nl(Out) << "// Function Declarations"; nl(Out);
1647 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1648 I != E; ++I)
1649 printFunctionHead(I);
1650
1651 // Process the global variables declarations. We can't initialze them until
1652 // after the constants are printed so just print a header for each global
1653 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1654 for (Module::const_global_iterator I = TheModule->global_begin(),
1655 E = TheModule->global_end(); I != E; ++I) {
1656 printVariableHead(I);
1657 }
1658
1659 // Print out all the constants definitions. Constants don't recurse except
1660 // through GlobalValues. All GlobalValues have been declared at this point
1661 // so we can proceed to generate the constants.
1662 nl(Out) << "// Constant Definitions"; nl(Out);
1663 printConstants(TheModule);
1664
1665 // Process the global variables definitions now that all the constants have
1666 // been emitted. These definitions just couple the gvars with their constant
1667 // initializers.
1668 nl(Out) << "// Global Variable Definitions"; nl(Out);
1669 for (Module::const_global_iterator I = TheModule->global_begin(),
1670 E = TheModule->global_end(); I != E; ++I) {
1671 printVariableBody(I);
1672 }
1673
1674 // Finally, we can safely put out all of the function bodies.
1675 nl(Out) << "// Function Definitions"; nl(Out);
1676 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1677 I != E; ++I) {
1678 if (!I->isDeclaration()) {
1679 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1680 << ")";
1681 nl(Out) << "{";
1682 nl(Out,1);
1683 printFunctionBody(I);
1684 nl(Out,-1) << "}";
1685 nl(Out);
1686 }
1687 }
1688}
1689
1690void CppWriter::printProgram(
1691 const std::string& fname,
1692 const std::string& mName
1693) {
1694 Out << "#include <llvm/Module.h>\n";
1695 Out << "#include <llvm/DerivedTypes.h>\n";
1696 Out << "#include <llvm/Constants.h>\n";
1697 Out << "#include <llvm/GlobalVariable.h>\n";
1698 Out << "#include <llvm/Function.h>\n";
1699 Out << "#include <llvm/CallingConv.h>\n";
1700 Out << "#include <llvm/BasicBlock.h>\n";
1701 Out << "#include <llvm/Instructions.h>\n";
1702 Out << "#include <llvm/InlineAsm.h>\n";
1703 Out << "#include <llvm/ParameterAttributes.h>\n";
1704 Out << "#include <llvm/Support/MathExtras.h>\n";
1705 Out << "#include <llvm/Pass.h>\n";
1706 Out << "#include <llvm/PassManager.h>\n";
1707 Out << "#include <llvm/Analysis/Verifier.h>\n";
1708 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1709 Out << "#include <algorithm>\n";
1710 Out << "#include <iostream>\n\n";
1711 Out << "using namespace llvm;\n\n";
1712 Out << "Module* " << fname << "();\n\n";
1713 Out << "int main(int argc, char**argv) {\n";
1714 Out << " Module* Mod = " << fname << "();\n";
1715 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1716 Out << " std::cerr.flush();\n";
1717 Out << " std::cout.flush();\n";
1718 Out << " PassManager PM;\n";
1719 Out << " PM.add(new PrintModulePass(&llvm::cout));\n";
1720 Out << " PM.run(*Mod);\n";
1721 Out << " return 0;\n";
1722 Out << "}\n\n";
1723 printModule(fname,mName);
1724}
1725
1726void CppWriter::printModule(
1727 const std::string& fname,
1728 const std::string& mName
1729) {
1730 nl(Out) << "Module* " << fname << "() {";
1731 nl(Out,1) << "// Module Construction";
1732 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1733 if (!TheModule->getTargetTriple().empty()) {
1734 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1735 }
1736 if (!TheModule->getTargetTriple().empty()) {
1737 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1738 << "\");";
1739 }
1740
1741 if (!TheModule->getModuleInlineAsm().empty()) {
1742 nl(Out) << "mod->setModuleInlineAsm(\"";
1743 printEscapedString(TheModule->getModuleInlineAsm());
1744 Out << "\");";
1745 }
1746 nl(Out);
1747
1748 // Loop over the dependent libraries and emit them.
1749 Module::lib_iterator LI = TheModule->lib_begin();
1750 Module::lib_iterator LE = TheModule->lib_end();
1751 while (LI != LE) {
1752 Out << "mod->addLibrary(\"" << *LI << "\");";
1753 nl(Out);
1754 ++LI;
1755 }
1756 printModuleBody();
1757 nl(Out) << "return mod;";
1758 nl(Out,-1) << "}";
1759 nl(Out);
1760}
1761
1762void CppWriter::printContents(
1763 const std::string& fname, // Name of generated function
1764 const std::string& mName // Name of module generated module
1765) {
1766 Out << "\nModule* " << fname << "(Module *mod) {\n";
1767 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1768 printModuleBody();
1769 Out << "\nreturn mod;\n";
1770 Out << "\n}\n";
1771}
1772
1773void CppWriter::printFunction(
1774 const std::string& fname, // Name of generated function
1775 const std::string& funcName // Name of function to generate
1776) {
1777 const Function* F = TheModule->getFunction(funcName);
1778 if (!F) {
1779 error(std::string("Function '") + funcName + "' not found in input module");
1780 return;
1781 }
1782 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1783 printFunctionUses(F);
1784 printFunctionHead(F);
1785 printFunctionBody(F);
1786 Out << "return " << getCppName(F) << ";\n";
1787 Out << "}\n";
1788}
1789
Chris Lattner0366a6d2007-11-13 18:22:33 +00001790void CppWriter::printFunctions() {
1791 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1792 Module::const_iterator I = funcs.begin();
1793 Module::const_iterator IE = funcs.end();
1794
1795 for (; I != IE; ++I) {
1796 const Function &func = *I;
1797 if (!func.isDeclaration()) {
1798 std::string name("define_");
1799 name += func.getName();
1800 printFunction(name, func.getName());
1801 }
1802 }
1803}
1804
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001805void CppWriter::printVariable(
1806 const std::string& fname, /// Name of generated function
1807 const std::string& varName // Name of variable to generate
1808) {
1809 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1810
1811 if (!GV) {
1812 error(std::string("Variable '") + varName + "' not found in input module");
1813 return;
1814 }
1815 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1816 printVariableUses(GV);
1817 printVariableHead(GV);
1818 printVariableBody(GV);
1819 Out << "return " << getCppName(GV) << ";\n";
1820 Out << "}\n";
1821}
1822
1823void CppWriter::printType(
1824 const std::string& fname, /// Name of generated function
1825 const std::string& typeName // Name of type to generate
1826) {
1827 const Type* Ty = TheModule->getTypeByName(typeName);
1828 if (!Ty) {
1829 error(std::string("Type '") + typeName + "' not found in input module");
1830 return;
1831 }
1832 Out << "\nType* " << fname << "(Module *mod) {\n";
1833 printType(Ty);
1834 Out << "return " << getCppName(Ty) << ";\n";
1835 Out << "}\n";
1836}
1837
1838} // end anonymous llvm
1839
1840namespace llvm {
1841
1842void WriteModuleToCppFile(Module* mod, std::ostream& o) {
1843 // Initialize a CppWriter for us to use
1844 CppWriter W(o, mod);
1845
1846 // Emit a header
1847 o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1848
1849 // Get the name of the function we're supposed to generate
1850 std::string fname = FuncName.getValue();
1851
1852 // Get the name of the thing we are to generate
1853 std::string tgtname = NameToGenerate.getValue();
1854 if (GenerationType == GenModule ||
1855 GenerationType == GenContents ||
Chris Lattner0366a6d2007-11-13 18:22:33 +00001856 GenerationType == GenProgram ||
1857 GenerationType == GenFunctions) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001858 if (tgtname == "!bad!") {
1859 if (mod->getModuleIdentifier() == "-")
1860 tgtname = "<stdin>";
1861 else
1862 tgtname = mod->getModuleIdentifier();
1863 }
1864 } else if (tgtname == "!bad!") {
1865 W.error("You must use the -for option with -gen-{function,variable,type}");
1866 }
1867
1868 switch (WhatToGenerate(GenerationType)) {
1869 case GenProgram:
1870 if (fname.empty())
1871 fname = "makeLLVMModule";
1872 W.printProgram(fname,tgtname);
1873 break;
1874 case GenModule:
1875 if (fname.empty())
1876 fname = "makeLLVMModule";
1877 W.printModule(fname,tgtname);
1878 break;
1879 case GenContents:
1880 if (fname.empty())
1881 fname = "makeLLVMModuleContents";
1882 W.printContents(fname,tgtname);
1883 break;
1884 case GenFunction:
1885 if (fname.empty())
1886 fname = "makeLLVMFunction";
1887 W.printFunction(fname,tgtname);
1888 break;
Chris Lattner0366a6d2007-11-13 18:22:33 +00001889 case GenFunctions:
1890 W.printFunctions();
1891 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001892 case GenInline:
1893 if (fname.empty())
1894 fname = "makeLLVMInline";
1895 W.printInline(fname,tgtname);
1896 break;
1897 case GenVariable:
1898 if (fname.empty())
1899 fname = "makeLLVMVariable";
1900 W.printVariable(fname,tgtname);
1901 break;
1902 case GenType:
1903 if (fname.empty())
1904 fname = "makeLLVMType";
1905 W.printType(fname,tgtname);
1906 break;
1907 default:
1908 W.error("Invalid generation option");
1909 }
1910}
1911
1912}