1 //===-- CppWriter.cpp - Printing LLVM IR as a C++ Source File -------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
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 "llvm/Support/CommandLine.h"
28 #include "llvm/Config/config.h"
35 static cl::opt<std::string>
36 FuncName("funcname", cl::desc("Specify the name of the generated function"),
37 cl::value_desc("function name"));
49 static cl::opt<WhatToGenerate> GenerationType(cl::Optional,
50 cl::desc("Choose what kind of output to generate"),
53 clEnumValN(GenProgram, "gen-program", "Generate a complete program"),
54 clEnumValN(GenModule, "gen-module", "Generate a module definition"),
55 clEnumValN(GenContents,"gen-contents", "Generate contents of a module"),
56 clEnumValN(GenFunction,"gen-function", "Generate a function definition"),
57 clEnumValN(GenInline, "gen-inline", "Generate an inline function"),
58 clEnumValN(GenVariable,"gen-variable", "Generate a variable definition"),
59 clEnumValN(GenType, "gen-type", "Generate a type definition"),
64 static cl::opt<std::string> NameToGenerate("for", cl::Optional,
65 cl::desc("Specify the name of the thing to generate"),
69 typedef std::vector<const Type*> TypeList;
70 typedef std::map<const Type*,std::string> TypeMap;
71 typedef std::map<const Value*,std::string> ValueMap;
72 typedef std::set<std::string> NameSet;
73 typedef std::set<const Type*> TypeSet;
74 typedef std::set<const Value*> ValueSet;
75 typedef std::map<const Value*,std::string> ForwardRefMap;
80 const Module *TheModule;
84 TypeMap UnresolvedTypes;
88 ValueSet DefinedValues;
89 ForwardRefMap ForwardRefs;
93 inline CppWriter(std::ostream &o, const Module *M, const char* pn="llvm2cpp")
94 : progname(pn), Out(o), TheModule(M), uniqueNum(0), TypeNames(),
95 ValueNames(), UnresolvedTypes(), TypeStack(), is_inline(false) { }
97 const Module* getModule() { return TheModule; }
99 void printProgram(const std::string& fname, const std::string& modName );
100 void printModule(const std::string& fname, const std::string& modName );
101 void printContents(const std::string& fname, const std::string& modName );
102 void printFunction(const std::string& fname, const std::string& funcName );
103 void printInline(const std::string& fname, const std::string& funcName );
104 void printVariable(const std::string& fname, const std::string& varName );
105 void printType(const std::string& fname, const std::string& typeName );
107 void error(const std::string& msg);
110 void printLinkageType(GlobalValue::LinkageTypes LT);
111 void printCallingConv(unsigned cc);
112 void printEscapedString(const std::string& str);
113 void printCFP(const ConstantFP* CFP);
115 std::string getCppName(const Type* val);
116 inline void printCppName(const Type* val);
118 std::string getCppName(const Value* val);
119 inline void printCppName(const Value* val);
121 bool printTypeInternal(const Type* Ty);
122 inline void printType(const Type* Ty);
123 void printTypes(const Module* M);
125 void printConstant(const Constant *CPV);
126 void printConstants(const Module* M);
128 void printVariableUses(const GlobalVariable *GV);
129 void printVariableHead(const GlobalVariable *GV);
130 void printVariableBody(const GlobalVariable *GV);
132 void printFunctionUses(const Function *F);
133 void printFunctionHead(const Function *F);
134 void printFunctionBody(const Function *F);
135 void printInstruction(const Instruction *I, const std::string& bbname);
136 std::string getOpName(Value*);
138 void printModuleBody();
143 sanitize(std::string& str) {
144 for (size_t i = 0; i < str.length(); ++i)
145 if (!isalnum(str[i]) && str[i] != '_')
150 getTypePrefix(const Type* Ty ) {
152 switch (Ty->getTypeID()) {
153 case Type::VoidTyID: prefix = "void_"; break;
154 case Type::BoolTyID: prefix = "bool_"; break;
155 case Type::UByteTyID: prefix = "ubyte_"; break;
156 case Type::SByteTyID: prefix = "sbyte_"; break;
157 case Type::UShortTyID: prefix = "ushort_"; break;
158 case Type::ShortTyID: prefix = "short_"; break;
159 case Type::UIntTyID: prefix = "uint_"; break;
160 case Type::IntTyID: prefix = "int_"; break;
161 case Type::ULongTyID: prefix = "ulong_"; break;
162 case Type::LongTyID: prefix = "long_"; break;
163 case Type::FloatTyID: prefix = "float_"; break;
164 case Type::DoubleTyID: prefix = "double_"; break;
165 case Type::LabelTyID: prefix = "label_"; break;
166 case Type::FunctionTyID: prefix = "func_"; break;
167 case Type::StructTyID: prefix = "struct_"; break;
168 case Type::ArrayTyID: prefix = "array_"; break;
169 case Type::PointerTyID: prefix = "ptr_"; break;
170 case Type::PackedTyID: prefix = "packed_"; break;
171 case Type::OpaqueTyID: prefix = "opaque_"; break;
172 default: prefix = "other_"; break;
177 // Looks up the type in the symbol table and returns a pointer to its name or
178 // a null pointer if it wasn't found. Note that this isn't the same as the
179 // Mode::getTypeName function which will return an empty string, not a null
180 // pointer if the name is not found.
181 inline const std::string*
182 findTypeName(const SymbolTable& ST, const Type* Ty)
184 SymbolTable::type_const_iterator TI = ST.type_begin();
185 SymbolTable::type_const_iterator TE = ST.type_end();
186 for (;TI != TE; ++TI)
187 if (TI->second == Ty)
193 CppWriter::error(const std::string& msg) {
194 std::cerr << progname << ": " << msg << "\n";
198 // printCFP - Print a floating point constant .. very carefully :)
199 // This makes sure that conversion to/from floating yields the same binary
200 // result so that we don't lose precision.
202 CppWriter::printCFP(const ConstantFP *CFP) {
203 Out << "ConstantFP::get(";
204 if (CFP->getType() == Type::DoubleTy)
205 Out << "Type::DoubleTy, ";
207 Out << "Type::FloatTy, ";
210 sprintf(Buffer, "%A", CFP->getValue());
211 if ((!strncmp(Buffer, "0x", 2) ||
212 !strncmp(Buffer, "-0x", 3) ||
213 !strncmp(Buffer, "+0x", 3)) &&
214 (atof(Buffer) == CFP->getValue()))
215 if (CFP->getType() == Type::DoubleTy)
216 Out << "BitsToDouble(" << Buffer << ")";
218 Out << "BitsToFloat(" << Buffer << ")";
221 std::string StrVal = ftostr(CFP->getValue());
223 while (StrVal[0] == ' ')
224 StrVal.erase(StrVal.begin());
226 // Check to make sure that the stringized number is not some string like
227 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
228 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
229 ((StrVal[0] == '-' || StrVal[0] == '+') &&
230 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
231 (atof(StrVal.c_str()) == CFP->getValue()))
232 if (CFP->getType() == Type::DoubleTy)
236 else if (CFP->getType() == Type::DoubleTy)
237 Out << "BitsToDouble(0x" << std::hex << DoubleToBits(CFP->getValue())
238 << std::dec << "ULL) /* " << StrVal << " */";
240 Out << "BitsToFloat(0x" << std::hex << FloatToBits(CFP->getValue())
241 << std::dec << "U) /* " << StrVal << " */";
249 CppWriter::printCallingConv(unsigned cc){
250 // Print the calling convention.
252 case CallingConv::C: Out << "CallingConv::C"; break;
253 case CallingConv::CSRet: Out << "CallingConv::CSRet"; break;
254 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
255 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
256 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
257 default: Out << cc; break;
262 CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
264 case GlobalValue::InternalLinkage:
265 Out << "GlobalValue::InternalLinkage"; break;
266 case GlobalValue::LinkOnceLinkage:
267 Out << "GlobalValue::LinkOnceLinkage "; break;
268 case GlobalValue::WeakLinkage:
269 Out << "GlobalValue::WeakLinkage"; break;
270 case GlobalValue::AppendingLinkage:
271 Out << "GlobalValue::AppendingLinkage"; break;
272 case GlobalValue::ExternalLinkage:
273 Out << "GlobalValue::ExternalLinkage"; break;
274 case GlobalValue::GhostLinkage:
275 Out << "GlobalValue::GhostLinkage"; break;
279 // printEscapedString - Print each character of the specified string, escaping
280 // it if it is not printable or if it is an escape char.
282 CppWriter::printEscapedString(const std::string &Str) {
283 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
284 unsigned char C = Str[i];
285 if (isprint(C) && C != '"' && C != '\\') {
289 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
290 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
296 CppWriter::getCppName(const Type* Ty)
298 // First, handle the primitive types .. easy
299 if (Ty->isPrimitiveType()) {
300 switch (Ty->getTypeID()) {
301 case Type::VoidTyID: return "Type::VoidTy";
302 case Type::BoolTyID: return "Type::BoolTy";
303 case Type::UByteTyID: return "Type::UByteTy";
304 case Type::SByteTyID: return "Type::SByteTy";
305 case Type::UShortTyID: return "Type::UShortTy";
306 case Type::ShortTyID: return "Type::ShortTy";
307 case Type::UIntTyID: return "Type::UIntTy";
308 case Type::IntTyID: return "Type::IntTy";
309 case Type::ULongTyID: return "Type::ULongTy";
310 case Type::LongTyID: return "Type::LongTy";
311 case Type::FloatTyID: return "Type::FloatTy";
312 case Type::DoubleTyID: return "Type::DoubleTy";
313 case Type::LabelTyID: return "Type::LabelTy";
315 error("Invalid primitive type");
318 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
321 // Now, see if we've seen the type before and return that
322 TypeMap::iterator I = TypeNames.find(Ty);
323 if (I != TypeNames.end())
326 // Okay, let's build a new name for this type. Start with a prefix
327 const char* prefix = 0;
328 switch (Ty->getTypeID()) {
329 case Type::FunctionTyID: prefix = "FuncTy_"; break;
330 case Type::StructTyID: prefix = "StructTy_"; break;
331 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
332 case Type::PointerTyID: prefix = "PointerTy_"; break;
333 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
334 case Type::PackedTyID: prefix = "PackedTy_"; break;
335 default: prefix = "OtherTy_"; break; // prevent breakage
338 // See if the type has a name in the symboltable and build accordingly
339 const std::string* tName = findTypeName(TheModule->getSymbolTable(), Ty);
342 name = std::string(prefix) + *tName;
344 name = std::string(prefix) + utostr(uniqueNum++);
348 return TypeNames[Ty] = name;
352 CppWriter::printCppName(const Type* Ty)
354 printEscapedString(getCppName(Ty));
358 CppWriter::getCppName(const Value* val) {
360 ValueMap::iterator I = ValueNames.find(val);
361 if (I != ValueNames.end() && I->first == val)
364 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
365 name = std::string("gvar_") +
366 getTypePrefix(GV->getType()->getElementType());
367 } else if (const Function* F = dyn_cast<Function>(val)) {
368 name = std::string("func_");
369 } else if (const Constant* C = dyn_cast<Constant>(val)) {
370 name = std::string("const_") + getTypePrefix(C->getType());
371 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
373 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
374 Function::const_arg_iterator(Arg)) + 1;
375 name = std::string("arg_") + utostr(argNum);
376 NameSet::iterator NI = UsedNames.find(name);
377 if (NI != UsedNames.end())
378 name += std::string("_") + utostr(uniqueNum++);
379 UsedNames.insert(name);
380 return ValueNames[val] = name;
382 name = getTypePrefix(val->getType());
385 name = getTypePrefix(val->getType());
387 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
389 NameSet::iterator NI = UsedNames.find(name);
390 if (NI != UsedNames.end())
391 name += std::string("_") + utostr(uniqueNum++);
392 UsedNames.insert(name);
393 return ValueNames[val] = name;
397 CppWriter::printCppName(const Value* val) {
398 printEscapedString(getCppName(val));
402 CppWriter::printTypeInternal(const Type* Ty) {
403 // We don't print definitions for primitive types
404 if (Ty->isPrimitiveType())
407 // If we already defined this type, we don't need to define it again.
408 if (DefinedTypes.find(Ty) != DefinedTypes.end())
411 // Everything below needs the name for the type so get it now.
412 std::string typeName(getCppName(Ty));
414 // Search the type stack for recursion. If we find it, then generate this
415 // as an OpaqueType, but make sure not to do this multiple times because
416 // the type could appear in multiple places on the stack. Once the opaque
417 // definition is issued, it must not be re-issued. Consequently we have to
418 // check the UnresolvedTypes list as well.
419 TypeList::const_iterator TI = std::find(TypeStack.begin(),TypeStack.end(),Ty);
420 if (TI != TypeStack.end()) {
421 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
422 if (I == UnresolvedTypes.end()) {
423 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();\n";
424 UnresolvedTypes[Ty] = typeName;
429 // We're going to print a derived type which, by definition, contains other
430 // types. So, push this one we're printing onto the type stack to assist with
431 // recursive definitions.
432 TypeStack.push_back(Ty);
434 // Print the type definition
435 switch (Ty->getTypeID()) {
436 case Type::FunctionTyID: {
437 const FunctionType* FT = cast<FunctionType>(Ty);
438 Out << "std::vector<const Type*>" << typeName << "_args;\n";
439 FunctionType::param_iterator PI = FT->param_begin();
440 FunctionType::param_iterator PE = FT->param_end();
441 for (; PI != PE; ++PI) {
442 const Type* argTy = static_cast<const Type*>(*PI);
443 bool isForward = printTypeInternal(argTy);
444 std::string argName(getCppName(argTy));
445 Out << typeName << "_args.push_back(" << argName;
450 bool isForward = printTypeInternal(FT->getReturnType());
451 std::string retTypeName(getCppName(FT->getReturnType()));
452 Out << "FunctionType* " << typeName << " = FunctionType::get(\n"
453 << " /*Result=*/" << retTypeName;
456 Out << ",\n /*Params=*/" << typeName << "_args,\n /*isVarArg=*/"
457 << (FT->isVarArg() ? "true" : "false") << ");\n";
460 case Type::StructTyID: {
461 const StructType* ST = cast<StructType>(Ty);
462 Out << "std::vector<const Type*>" << typeName << "_fields;\n";
463 StructType::element_iterator EI = ST->element_begin();
464 StructType::element_iterator EE = ST->element_end();
465 for (; EI != EE; ++EI) {
466 const Type* fieldTy = static_cast<const Type*>(*EI);
467 bool isForward = printTypeInternal(fieldTy);
468 std::string fieldName(getCppName(fieldTy));
469 Out << typeName << "_fields.push_back(" << fieldName;
474 Out << "StructType* " << typeName << " = StructType::get("
475 << typeName << "_fields);\n";
478 case Type::ArrayTyID: {
479 const ArrayType* AT = cast<ArrayType>(Ty);
480 const Type* ET = AT->getElementType();
481 bool isForward = printTypeInternal(ET);
482 std::string elemName(getCppName(ET));
483 Out << "ArrayType* " << typeName << " = ArrayType::get("
484 << elemName << (isForward ? "_fwd" : "")
485 << ", " << utostr(AT->getNumElements()) << ");\n";
488 case Type::PointerTyID: {
489 const PointerType* PT = cast<PointerType>(Ty);
490 const Type* ET = PT->getElementType();
491 bool isForward = printTypeInternal(ET);
492 std::string elemName(getCppName(ET));
493 Out << "PointerType* " << typeName << " = PointerType::get("
494 << elemName << (isForward ? "_fwd" : "") << ");\n";
497 case Type::PackedTyID: {
498 const PackedType* PT = cast<PackedType>(Ty);
499 const Type* ET = PT->getElementType();
500 bool isForward = printTypeInternal(ET);
501 std::string elemName(getCppName(ET));
502 Out << "PackedType* " << typeName << " = PackedType::get("
503 << elemName << (isForward ? "_fwd" : "")
504 << ", " << utostr(PT->getNumElements()) << ");\n";
507 case Type::OpaqueTyID: {
508 const OpaqueType* OT = cast<OpaqueType>(Ty);
509 Out << "OpaqueType* " << typeName << " = OpaqueType::get();\n";
513 error("Invalid TypeID");
516 // If the type had a name, make sure we recreate it.
517 const std::string* progTypeName =
518 findTypeName(TheModule->getSymbolTable(),Ty);
520 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
521 << typeName << ");\n";
523 // Pop us off the type stack
524 TypeStack.pop_back();
526 // Indicate that this type is now defined.
527 DefinedTypes.insert(Ty);
529 // Early resolve as many unresolved types as possible. Search the unresolved
530 // types map for the type we just printed. Now that its definition is complete
531 // we can resolve any previous references to it. This prevents a cascade of
533 TypeMap::iterator I = UnresolvedTypes.find(Ty);
534 if (I != UnresolvedTypes.end()) {
535 Out << "cast<OpaqueType>(" << I->second
536 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");\n";
537 Out << I->second << " = cast<";
538 switch (Ty->getTypeID()) {
539 case Type::FunctionTyID: Out << "FunctionType"; break;
540 case Type::ArrayTyID: Out << "ArrayType"; break;
541 case Type::StructTyID: Out << "StructType"; break;
542 case Type::PackedTyID: Out << "PackedType"; break;
543 case Type::PointerTyID: Out << "PointerType"; break;
544 case Type::OpaqueTyID: Out << "OpaqueType"; break;
545 default: Out << "NoSuchDerivedType"; break;
547 Out << ">(" << I->second << "_fwd.get());\n\n";
548 UnresolvedTypes.erase(I);
551 // Finally, separate the type definition from other with a newline.
554 // We weren't a recursive type
558 // Prints a type definition. Returns true if it could not resolve all the types
559 // in the definition but had to use a forward reference.
561 CppWriter::printType(const Type* Ty) {
562 assert(TypeStack.empty());
564 printTypeInternal(Ty);
565 assert(TypeStack.empty());
569 CppWriter::printTypes(const Module* M) {
571 // Walk the symbol table and print out all its types
572 const SymbolTable& symtab = M->getSymbolTable();
573 for (SymbolTable::type_const_iterator TI = symtab.type_begin(),
574 TE = symtab.type_end(); TI != TE; ++TI) {
576 // For primitive types and types already defined, just add a name
577 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
578 if (TI->second->isPrimitiveType() || TNI != TypeNames.end()) {
579 Out << "mod->addTypeName(\"";
580 printEscapedString(TI->first);
581 Out << "\", " << getCppName(TI->second) << ");\n";
582 // For everything else, define the type
584 printType(TI->second);
588 // Add all of the global variables to the value table...
589 for (Module::const_global_iterator I = TheModule->global_begin(),
590 E = TheModule->global_end(); I != E; ++I) {
591 if (I->hasInitializer())
592 printType(I->getInitializer()->getType());
593 printType(I->getType());
596 // Add all the functions to the table
597 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
599 printType(FI->getReturnType());
600 printType(FI->getFunctionType());
601 // Add all the function arguments
602 for(Function::const_arg_iterator AI = FI->arg_begin(),
603 AE = FI->arg_end(); AI != AE; ++AI) {
604 printType(AI->getType());
607 // Add all of the basic blocks and instructions
608 for (Function::const_iterator BB = FI->begin(),
609 E = FI->end(); BB != E; ++BB) {
610 printType(BB->getType());
611 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
613 printType(I->getType());
614 for (unsigned i = 0; i < I->getNumOperands(); ++i)
615 printType(I->getOperand(i)->getType());
622 // printConstant - Print out a constant pool entry...
623 void CppWriter::printConstant(const Constant *CV) {
624 // First, if the constant is actually a GlobalValue (variable or function) or
625 // its already in the constant list then we've printed it already and we can
627 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
630 const int IndentSize = 2;
631 static std::string Indent = "\n";
632 std::string constName(getCppName(CV));
633 std::string typeName(getCppName(CV->getType()));
634 if (CV->isNullValue()) {
635 Out << "Constant* " << constName << " = Constant::getNullValue("
636 << typeName << ");\n";
639 if (isa<GlobalValue>(CV)) {
640 // Skip variables and functions, we emit them elsewhere
643 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
644 Out << "ConstantBool* " << constName << " = ConstantBool::get("
645 << (CB == ConstantBool::True ? "true" : "false")
647 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
648 Out << "ConstantSInt* " << constName << " = ConstantSInt::get("
649 << typeName << ", " << CI->getValue() << ");";
650 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
651 Out << "ConstantUInt* " << constName << " = ConstantUInt::get("
652 << typeName << ", " << CI->getValue() << ");";
653 } else if (isa<ConstantAggregateZero>(CV)) {
654 Out << "ConstantAggregateZero* " << constName
655 << " = ConstantAggregateZero::get(" << typeName << ");";
656 } else if (isa<ConstantPointerNull>(CV)) {
657 Out << "ConstantPointerNull* " << constName
658 << " = ConstanPointerNull::get(" << typeName << ");";
659 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
660 Out << "ConstantFP* " << constName << " = ";
663 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
664 if (CA->isString() && CA->getType()->getElementType() == Type::SByteTy) {
665 Out << "Constant* " << constName << " = ConstantArray::get(\"";
666 printEscapedString(CA->getAsString());
667 // Determine if we want null termination or not.
668 if (CA->getType()->getNumElements() <= CA->getAsString().length())
669 Out << "\", false";// No null terminator
671 Out << "\", true"; // Indicate that the null terminator should be added.
674 Out << "std::vector<Constant*> " << constName << "_elems;\n";
675 unsigned N = CA->getNumOperands();
676 for (unsigned i = 0; i < N; ++i) {
677 printConstant(CA->getOperand(i)); // recurse to print operands
678 Out << constName << "_elems.push_back("
679 << getCppName(CA->getOperand(i)) << ");\n";
681 Out << "Constant* " << constName << " = ConstantArray::get("
682 << typeName << ", " << constName << "_elems);";
684 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
685 Out << "std::vector<Constant*> " << constName << "_fields;\n";
686 unsigned N = CS->getNumOperands();
687 for (unsigned i = 0; i < N; i++) {
688 printConstant(CS->getOperand(i));
689 Out << constName << "_fields.push_back("
690 << getCppName(CS->getOperand(i)) << ");\n";
692 Out << "Constant* " << constName << " = ConstantStruct::get("
693 << typeName << ", " << constName << "_fields);";
694 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
695 Out << "std::vector<Constant*> " << constName << "_elems;\n";
696 unsigned N = CP->getNumOperands();
697 for (unsigned i = 0; i < N; ++i) {
698 printConstant(CP->getOperand(i));
699 Out << constName << "_elems.push_back("
700 << getCppName(CP->getOperand(i)) << ");\n";
702 Out << "Constant* " << constName << " = ConstantPacked::get("
703 << typeName << ", " << constName << "_elems);";
704 } else if (isa<UndefValue>(CV)) {
705 Out << "UndefValue* " << constName << " = UndefValue::get("
707 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
708 if (CE->getOpcode() == Instruction::GetElementPtr) {
709 Out << "std::vector<Constant*> " << constName << "_indices;\n";
710 printConstant(CE->getOperand(0));
711 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
712 printConstant(CE->getOperand(i));
713 Out << constName << "_indices.push_back("
714 << getCppName(CE->getOperand(i)) << ");\n";
716 Out << "Constant* " << constName
717 << " = ConstantExpr::getGetElementPtr("
718 << getCppName(CE->getOperand(0)) << ", "
719 << constName << "_indices);";
720 } else if (CE->getOpcode() == Instruction::Cast) {
721 printConstant(CE->getOperand(0));
722 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
723 Out << getCppName(CE->getOperand(0)) << ", " << getCppName(CE->getType())
726 unsigned N = CE->getNumOperands();
727 for (unsigned i = 0; i < N; ++i ) {
728 printConstant(CE->getOperand(i));
730 Out << "Constant* " << constName << " = ConstantExpr::";
731 switch (CE->getOpcode()) {
732 case Instruction::Add: Out << "getAdd"; break;
733 case Instruction::Sub: Out << "getSub"; break;
734 case Instruction::Mul: Out << "getMul"; break;
735 case Instruction::Div: Out << "getDiv"; break;
736 case Instruction::Rem: Out << "getRem"; break;
737 case Instruction::And: Out << "getAnd"; break;
738 case Instruction::Or: Out << "getOr"; break;
739 case Instruction::Xor: Out << "getXor"; break;
740 case Instruction::SetEQ: Out << "getSetEQ"; break;
741 case Instruction::SetNE: Out << "getSetNE"; break;
742 case Instruction::SetLE: Out << "getSetLE"; break;
743 case Instruction::SetGE: Out << "getSetGE"; break;
744 case Instruction::SetLT: Out << "getSetLT"; break;
745 case Instruction::SetGT: Out << "getSetGT"; break;
746 case Instruction::Shl: Out << "getShl"; break;
747 case Instruction::Shr: Out << "getShr"; break;
748 case Instruction::Select: Out << "getSelect"; break;
749 case Instruction::ExtractElement: Out << "getExtractElement"; break;
750 case Instruction::InsertElement: Out << "getInsertElement"; break;
751 case Instruction::ShuffleVector: Out << "getShuffleVector"; break;
753 error("Invalid constant expression");
756 Out << getCppName(CE->getOperand(0));
757 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
758 Out << ", " << getCppName(CE->getOperand(i));
762 error("Bad Constant");
763 Out << "Constant* " << constName << " = 0; ";
769 CppWriter::printConstants(const Module* M) {
770 // Traverse all the global variables looking for constant initializers
771 for (Module::const_global_iterator I = TheModule->global_begin(),
772 E = TheModule->global_end(); I != E; ++I)
773 if (I->hasInitializer())
774 printConstant(I->getInitializer());
776 // Traverse the LLVM functions looking for constants
777 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
779 // Add all of the basic blocks and instructions
780 for (Function::const_iterator BB = FI->begin(),
781 E = FI->end(); BB != E; ++BB) {
782 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
784 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
785 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
794 void CppWriter::printVariableUses(const GlobalVariable *GV) {
795 Out << "\n// Type Definitions\n";
796 printType(GV->getType());
797 if (GV->hasInitializer()) {
798 Constant* Init = GV->getInitializer();
799 printType(Init->getType());
800 if (Function* F = dyn_cast<Function>(Init)) {
801 Out << "\n// Function Declarations\n";
802 printFunctionHead(F);
803 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
804 Out << "\n// Global Variable Declarations\n";
805 printVariableHead(gv);
807 Out << "\n// Constant Definitions\n";
810 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
811 Out << "\n// Global Variable Definitions\n";
812 printVariableBody(gv);
817 void CppWriter::printVariableHead(const GlobalVariable *GV) {
818 Out << "\nGlobalVariable* " << getCppName(GV);
820 Out << " = mod->getGlobalVariable(";
821 printEscapedString(GV->getName());
822 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)\n";
823 Out << "if (!" << getCppName(GV) << ") {\n " << getCppName(GV);
825 Out << " = new GlobalVariable(\n";
827 printCppName(GV->getType()->getElementType());
829 Out << " /*isConstant=*/" << (GV->isConstant()?"true":"false")
830 << ",\n /*Linkage=*/";
831 printLinkageType(GV->getLinkage());
832 Out << ",\n /*Initializer=*/0, ";
833 if (GV->hasInitializer()) {
834 Out << "// has initializer, specified below";
836 Out << "\n /*Name=*/\"";
837 printEscapedString(GV->getName());
838 Out << "\",\n mod);\n";
840 if (GV->hasSection()) {
842 Out << "->setSection(\"";
843 printEscapedString(GV->getSection());
846 if (GV->getAlignment()) {
848 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");\n";
855 CppWriter::printVariableBody(const GlobalVariable *GV) {
856 if (GV->hasInitializer()) {
858 Out << "->setInitializer(";
859 //if (!isa<GlobalValue(GV->getInitializer()))
861 Out << getCppName(GV->getInitializer()) << ");\n";
866 CppWriter::getOpName(Value* V) {
867 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
868 return getCppName(V);
870 // See if its alread in the map of forward references, if so just return the
871 // name we already set up for it
872 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
873 if (I != ForwardRefs.end())
876 // This is a new forward reference. Generate a unique name for it
877 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
879 // Yes, this is a hack. An Argument is the smallest instantiable value that
880 // we can make as a placeholder for the real value. We'll replace these
881 // Argument instances later.
882 Out << " Argument* " << result << " = new Argument("
883 << getCppName(V->getType()) << ");\n";
884 ForwardRefs[V] = result;
888 // printInstruction - This member is called for each Instruction in a function.
890 CppWriter::printInstruction(const Instruction *I, const std::string& bbname) {
891 std::string iName(getCppName(I));
893 // Before we emit this instruction, we need to take care of generating any
894 // forward references. So, we get the names of all the operands in advance
895 std::string* opNames = new std::string[I->getNumOperands()];
896 for (unsigned i = 0; i < I->getNumOperands(); i++) {
897 opNames[i] = getOpName(I->getOperand(i));
900 switch (I->getOpcode()) {
901 case Instruction::Ret: {
902 const ReturnInst* ret = cast<ReturnInst>(I);
903 Out << " ReturnInst* " << iName << " = new ReturnInst("
904 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
907 case Instruction::Br: {
908 const BranchInst* br = cast<BranchInst>(I);
909 Out << " BranchInst* " << iName << " = new BranchInst(" ;
910 if (br->getNumOperands() == 3 ) {
911 Out << opNames[0] << ", "
912 << opNames[1] << ", "
913 << opNames[2] << ", ";
915 } else if (br->getNumOperands() == 1) {
916 Out << opNames[0] << ", ";
918 error("Branch with 2 operands?");
920 Out << bbname << ");";
923 case Instruction::Switch: {
924 const SwitchInst* sw = cast<SwitchInst>(I);
925 Out << " SwitchInst* " << iName << " = new SwitchInst("
926 << opNames[0] << ", "
927 << opNames[1] << ", "
928 << sw->getNumCases() << ", " << bbname << ");\n";
929 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
930 Out << " " << iName << "->addCase("
931 << opNames[i] << ", "
932 << opNames[i+1] << ");\n";
936 case Instruction::Invoke: {
937 const InvokeInst* inv = cast<InvokeInst>(I);
938 Out << " std::vector<Value*> " << iName << "_params;\n";
939 for (unsigned i = 3; i < inv->getNumOperands(); ++i)
940 Out << " " << iName << "_params.push_back("
941 << opNames[i] << ");\n";
942 Out << " InvokeInst* " << iName << " = new InvokeInst("
943 << opNames[0] << ", "
944 << opNames[1] << ", "
945 << opNames[2] << ", "
946 << iName << "_params, \"";
947 printEscapedString(inv->getName());
948 Out << "\", " << bbname << ");\n";
949 Out << iName << "->setCallingConv(";
950 printCallingConv(inv->getCallingConv());
954 case Instruction::Unwind: {
955 Out << " UnwindInst* " << iName << " = new UnwindInst("
959 case Instruction::Unreachable:{
960 Out << " UnreachableInst* " << iName << " = new UnreachableInst("
964 case Instruction::Add:
965 case Instruction::Sub:
966 case Instruction::Mul:
967 case Instruction::Div:
968 case Instruction::Rem:
969 case Instruction::And:
970 case Instruction::Or:
971 case Instruction::Xor:
972 case Instruction::Shl:
973 case Instruction::Shr:{
974 Out << " BinaryOperator* " << iName << " = BinaryOperator::create(";
975 switch (I->getOpcode()) {
976 case Instruction::Add: Out << "Instruction::Add"; break;
977 case Instruction::Sub: Out << "Instruction::Sub"; break;
978 case Instruction::Mul: Out << "Instruction::Mul"; break;
979 case Instruction::Div: Out << "Instruction::Div"; break;
980 case Instruction::Rem: Out << "Instruction::Rem"; break;
981 case Instruction::And: Out << "Instruction::And"; break;
982 case Instruction::Or: Out << "Instruction::Or"; break;
983 case Instruction::Xor: Out << "Instruction::Xor"; break;
984 case Instruction::Shl: Out << "Instruction::Shl"; break;
985 case Instruction::Shr: Out << "Instruction::Shr"; break;
986 default: Out << "Instruction::BadOpCode"; break;
988 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
989 printEscapedString(I->getName());
990 Out << "\", " << bbname << ");";
993 case Instruction::SetEQ:
994 case Instruction::SetNE:
995 case Instruction::SetLE:
996 case Instruction::SetGE:
997 case Instruction::SetLT:
998 case Instruction::SetGT: {
999 Out << " SetCondInst* " << iName << " = new SetCondInst(";
1000 switch (I->getOpcode()) {
1001 case Instruction::SetEQ: Out << "Instruction::SetEQ"; break;
1002 case Instruction::SetNE: Out << "Instruction::SetNE"; break;
1003 case Instruction::SetLE: Out << "Instruction::SetLE"; break;
1004 case Instruction::SetGE: Out << "Instruction::SetGE"; break;
1005 case Instruction::SetLT: Out << "Instruction::SetLT"; break;
1006 case Instruction::SetGT: Out << "Instruction::SetGT"; break;
1007 default: Out << "Instruction::BadOpCode"; break;
1009 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1010 printEscapedString(I->getName());
1011 Out << "\", " << bbname << ");";
1014 case Instruction::Malloc: {
1015 const MallocInst* mallocI = cast<MallocInst>(I);
1016 Out << " MallocInst* " << iName << " = new MallocInst("
1017 << getCppName(mallocI->getAllocatedType()) << ", ";
1018 if (mallocI->isArrayAllocation())
1019 Out << opNames[0] << ", " ;
1021 printEscapedString(mallocI->getName());
1022 Out << "\", " << bbname << ");";
1023 if (mallocI->getAlignment())
1024 Out << "\n " << iName << "->setAlignment("
1025 << mallocI->getAlignment() << ");";
1028 case Instruction::Free: {
1029 Out << " FreeInst* " << iName << " = new FreeInst("
1030 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1033 case Instruction::Alloca: {
1034 const AllocaInst* allocaI = cast<AllocaInst>(I);
1035 Out << " AllocaInst* " << iName << " = new AllocaInst("
1036 << getCppName(allocaI->getAllocatedType()) << ", ";
1037 if (allocaI->isArrayAllocation())
1038 Out << opNames[0] << ", ";
1040 printEscapedString(allocaI->getName());
1041 Out << "\", " << bbname << ");";
1042 if (allocaI->getAlignment())
1043 Out << "\n " << iName << "->setAlignment("
1044 << allocaI->getAlignment() << ");";
1047 case Instruction::Load:{
1048 const LoadInst* load = cast<LoadInst>(I);
1049 Out << " LoadInst* " << iName << " = new LoadInst("
1050 << opNames[0] << ", \"";
1051 printEscapedString(load->getName());
1052 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1053 << ", " << bbname << ");\n";
1056 case Instruction::Store: {
1057 const StoreInst* store = cast<StoreInst>(I);
1058 Out << " StoreInst* " << iName << " = new StoreInst("
1059 << opNames[0] << ", "
1060 << opNames[1] << ", "
1061 << (store->isVolatile() ? "true" : "false")
1062 << ", " << bbname << ");\n";
1065 case Instruction::GetElementPtr: {
1066 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1067 if (gep->getNumOperands() <= 2) {
1068 Out << " GetElementPtrInst* " << iName << " = new GetElementPtrInst("
1070 if (gep->getNumOperands() == 2)
1071 Out << ", " << opNames[1];
1073 Out << " std::vector<Value*> " << iName << "_indices;\n";
1074 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1075 Out << " " << iName << "_indices.push_back("
1076 << opNames[i] << ");\n";
1078 Out << " Instruction* " << iName << " = new GetElementPtrInst("
1079 << opNames[0] << ", " << iName << "_indices";
1082 printEscapedString(gep->getName());
1083 Out << "\", " << bbname << ");";
1086 case Instruction::PHI: {
1087 const PHINode* phi = cast<PHINode>(I);
1089 Out << " PHINode* " << iName << " = new PHINode("
1090 << getCppName(phi->getType()) << ", \"";
1091 printEscapedString(phi->getName());
1092 Out << "\", " << bbname << ");\n";
1093 Out << " " << iName << "->reserveOperandSpace("
1094 << phi->getNumIncomingValues()
1096 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1097 Out << " " << iName << "->addIncoming("
1098 << opNames[i] << ", " << opNames[i+1] << ");\n";
1102 case Instruction::Cast: {
1103 const CastInst* cst = cast<CastInst>(I);
1104 Out << " CastInst* " << iName << " = new CastInst("
1105 << opNames[0] << ", "
1106 << getCppName(cst->getType()) << ", \"";
1107 printEscapedString(cst->getName());
1108 Out << "\", " << bbname << ");\n";
1111 case Instruction::Call:{
1112 const CallInst* call = cast<CallInst>(I);
1113 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1114 Out << " InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1115 << getCppName(ila->getFunctionType()) << ", \""
1116 << ila->getAsmString() << "\", \""
1117 << ila->getConstraintString() << "\","
1118 << (ila->hasSideEffects() ? "true" : "false") << ");\n";
1120 if (call->getNumOperands() > 3) {
1121 Out << " std::vector<Value*> " << iName << "_params;\n";
1122 for (unsigned i = 1; i < call->getNumOperands(); ++i)
1123 Out << " " << iName << "_params.push_back(" << opNames[i] << ");\n";
1124 Out << " CallInst* " << iName << " = new CallInst("
1125 << opNames[0] << ", " << iName << "_params, \"";
1126 } else if (call->getNumOperands() == 3) {
1127 Out << " CallInst* " << iName << " = new CallInst("
1128 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1129 } else if (call->getNumOperands() == 2) {
1130 Out << " CallInst* " << iName << " = new CallInst("
1131 << opNames[0] << ", " << opNames[1] << ", \"";
1133 Out << " CallInst* " << iName << " = new CallInst(" << opNames[0]
1136 printEscapedString(call->getName());
1137 Out << "\", " << bbname << ");\n";
1138 Out << " " << iName << "->setCallingConv(";
1139 printCallingConv(call->getCallingConv());
1141 Out << " " << iName << "->setTailCall("
1142 << (call->isTailCall() ? "true":"false");
1146 case Instruction::Select: {
1147 const SelectInst* sel = cast<SelectInst>(I);
1148 Out << " SelectInst* " << getCppName(sel) << " = new SelectInst(";
1149 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1150 printEscapedString(sel->getName());
1151 Out << "\", " << bbname << ");\n";
1154 case Instruction::UserOp1:
1156 case Instruction::UserOp2: {
1157 /// FIXME: What should be done here?
1160 case Instruction::VAArg: {
1161 const VAArgInst* va = cast<VAArgInst>(I);
1162 Out << " VAArgInst* " << getCppName(va) << " = new VAArgInst("
1163 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1164 printEscapedString(va->getName());
1165 Out << "\", " << bbname << ");\n";
1168 case Instruction::ExtractElement: {
1169 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1170 Out << " ExtractElementInst* " << getCppName(eei)
1171 << " = new ExtractElementInst(" << opNames[0]
1172 << ", " << opNames[1] << ", \"";
1173 printEscapedString(eei->getName());
1174 Out << "\", " << bbname << ");\n";
1177 case Instruction::InsertElement: {
1178 const InsertElementInst* iei = cast<InsertElementInst>(I);
1179 Out << " InsertElementInst* " << getCppName(iei)
1180 << " = new InsertElementInst(" << opNames[0]
1181 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1182 printEscapedString(iei->getName());
1183 Out << "\", " << bbname << ");\n";
1186 case Instruction::ShuffleVector: {
1187 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1188 Out << " ShuffleVectorInst* " << getCppName(svi)
1189 << " = new ShuffleVectorInst(" << opNames[0]
1190 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1191 printEscapedString(svi->getName());
1192 Out << "\", " << bbname << ");\n";
1196 DefinedValues.insert(I);
1201 // Print out the types, constants and declarations needed by one function
1202 void CppWriter::printFunctionUses(const Function* F) {
1204 Out << "\n// Type Definitions\n";
1206 // Print the function's return type
1207 printType(F->getReturnType());
1209 // Print the function's function type
1210 printType(F->getFunctionType());
1212 // Print the types of each of the function's arguments
1213 for(Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1215 printType(AI->getType());
1219 // Print type definitions for every type referenced by an instruction and
1220 // make a note of any global values or constants that are referenced
1221 std::vector<GlobalValue*> gvs;
1222 std::vector<Constant*> consts;
1223 for (Function::const_iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB){
1224 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1226 // Print the type of the instruction itself
1227 printType(I->getType());
1229 // Print the type of each of the instruction's operands
1230 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1231 Value* operand = I->getOperand(i);
1232 printType(operand->getType());
1233 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand))
1235 else if (Constant* C = dyn_cast<Constant>(operand))
1236 consts.push_back(C);
1241 // Print the function declarations for any functions encountered
1242 Out << "\n// Function Declarations\n";
1243 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1245 if (Function* Fun = dyn_cast<Function>(*I)) {
1246 if (!is_inline || Fun != F)
1247 printFunctionHead(Fun);
1251 // Print the global variable declarations for any variables encountered
1252 Out << "\n// Global Variable Declarations\n";
1253 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1255 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1256 printVariableHead(F);
1259 // Print the constants found
1260 Out << "\n// Constant Definitions\n";
1261 for (std::vector<Constant*>::iterator I = consts.begin(), E = consts.end();
1266 // Process the global variables definitions now that all the constants have
1267 // been emitted. These definitions just couple the gvars with their constant
1269 Out << "\n// Global Variable Definitions\n";
1270 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1272 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1273 printVariableBody(GV);
1277 void CppWriter::printFunctionHead(const Function* F) {
1278 Out << "\nFunction* " << getCppName(F);
1280 Out << " = mod->getFunction(\"";
1281 printEscapedString(F->getName());
1282 Out << "\", " << getCppName(F->getFunctionType()) << ");\n";
1283 Out << "if (!" << getCppName(F) << ") {\n";
1284 Out << getCppName(F);
1286 Out<< " = new Function(\n"
1287 << " /*Type=*/" << getCppName(F->getFunctionType()) << ",\n"
1289 printLinkageType(F->getLinkage());
1290 Out << ",\n /*Name=*/\"";
1291 printEscapedString(F->getName());
1293 << (F->isExternal()? "// (external, no body)" : "") << "\n";
1295 Out << "->setCallingConv(";
1296 printCallingConv(F->getCallingConv());
1298 if (F->hasSection()) {
1300 Out << "->setSection(\"" << F->getSection() << "\");\n";
1302 if (F->getAlignment()) {
1304 Out << "->setAlignment(" << F->getAlignment() << ");\n";
1311 void CppWriter::printFunctionBody(const Function *F) {
1312 if (F->isExternal())
1313 return; // external functions have no bodies.
1315 // Clear the DefinedValues and ForwardRefs maps because we can't have
1316 // cross-function forward refs
1317 ForwardRefs.clear();
1318 DefinedValues.clear();
1320 // Create all the argument values
1322 if (!F->arg_empty()) {
1323 Out << " Function::arg_iterator args = " << getCppName(F)
1324 << "->arg_begin();\n";
1326 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1328 Out << " Value* " << getCppName(AI) << " = args++;\n";
1330 Out << " " << getCppName(AI) << "->setName(\"" << AI->getName()
1335 // Create all the basic blocks
1337 for (Function::const_iterator BI = F->begin(), BE = F->end();
1339 std::string bbname(getCppName(BI));
1340 Out << " BasicBlock* " << bbname << " = new BasicBlock(\"";
1342 printEscapedString(BI->getName());
1343 Out << "\"," << getCppName(BI->getParent()) << ",0);\n";
1346 // Output all of its basic blocks... for the function
1347 for (Function::const_iterator BI = F->begin(), BE = F->end();
1349 std::string bbname(getCppName(BI));
1350 Out << "\n // Block " << BI->getName() << " (" << bbname << ")\n";
1352 // Output all of the instructions in the basic block...
1353 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1355 printInstruction(I,bbname);
1359 // Loop over the ForwardRefs and resolve them now that all instructions
1361 if (!ForwardRefs.empty())
1362 Out << "\n // Resolve Forward References\n";
1363 while (!ForwardRefs.empty()) {
1364 ForwardRefMap::iterator I = ForwardRefs.begin();
1365 Out << " " << I->second << "->replaceAllUsesWith("
1366 << getCppName(I->first) << "); delete " << I->second << ";\n";
1367 ForwardRefs.erase(I);
1371 void CppWriter::printInline(const std::string& fname, const std::string& func) {
1372 const Function* F = TheModule->getNamedFunction(func);
1374 error(std::string("Function '") + func + "' not found in input module");
1377 if (F->isExternal()) {
1378 error(std::string("Function '") + func + "' is external!");
1381 Out << "\nBasicBlock* " << fname << "(Module* mod, Function *"
1383 unsigned arg_count = 1;
1384 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1386 Out << ", Value* arg_" << arg_count;
1390 printFunctionUses(F);
1391 printFunctionBody(F);
1393 Out << "return " << getCppName(F->begin()) << ";\n";
1397 void CppWriter::printModuleBody() {
1398 // Print out all the type definitions
1399 Out << "\n// Type Definitions\n";
1400 printTypes(TheModule);
1402 // Functions can call each other and global variables can reference them so
1403 // define all the functions first before emitting their function bodies.
1404 Out << "\n// Function Declarations\n";
1405 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1407 printFunctionHead(I);
1409 // Process the global variables declarations. We can't initialze them until
1410 // after the constants are printed so just print a header for each global
1411 Out << "\n// Global Variable Declarations\n";
1412 for (Module::const_global_iterator I = TheModule->global_begin(),
1413 E = TheModule->global_end(); I != E; ++I) {
1414 printVariableHead(I);
1417 // Print out all the constants definitions. Constants don't recurse except
1418 // through GlobalValues. All GlobalValues have been declared at this point
1419 // so we can proceed to generate the constants.
1420 Out << "\n// Constant Definitions\n";
1421 printConstants(TheModule);
1423 // Process the global variables definitions now that all the constants have
1424 // been emitted. These definitions just couple the gvars with their constant
1426 Out << "\n// Global Variable Definitions\n";
1427 for (Module::const_global_iterator I = TheModule->global_begin(),
1428 E = TheModule->global_end(); I != E; ++I) {
1429 printVariableBody(I);
1432 // Finally, we can safely put out all of the function bodies.
1433 Out << "\n// Function Definitions\n";
1434 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1436 if (!I->isExternal()) {
1437 Out << "\n// Function: " << I->getName() << " (" << getCppName(I)
1439 printFunctionBody(I);
1445 void CppWriter::printProgram(
1446 const std::string& fname,
1447 const std::string& mName
1449 Out << "#include <llvm/Module.h>\n";
1450 Out << "#include <llvm/DerivedTypes.h>\n";
1451 Out << "#include <llvm/Constants.h>\n";
1452 Out << "#include <llvm/GlobalVariable.h>\n";
1453 Out << "#include <llvm/Function.h>\n";
1454 Out << "#include <llvm/CallingConv.h>\n";
1455 Out << "#include <llvm/BasicBlock.h>\n";
1456 Out << "#include <llvm/Instructions.h>\n";
1457 Out << "#include <llvm/InlineAsm.h>\n";
1458 Out << "#include <llvm/Support/MathExtras.h>\n";
1459 Out << "#include <llvm/Pass.h>\n";
1460 Out << "#include <llvm/PassManager.h>\n";
1461 Out << "#include <llvm/Analysis/Verifier.h>\n";
1462 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1463 Out << "#include <algorithm>\n";
1464 Out << "#include <iostream>\n\n";
1465 Out << "using namespace llvm;\n\n";
1466 Out << "Module* " << fname << "();\n\n";
1467 Out << "int main(int argc, char**argv) {\n";
1468 Out << " Module* Mod = makeLLVMModule();\n";
1469 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1470 Out << " std::cerr.flush();\n";
1471 Out << " std::cout.flush();\n";
1472 Out << " PassManager PM;\n";
1473 Out << " PM.add(new PrintModulePass(&std::cout));\n";
1474 Out << " PM.run(*Mod);\n";
1475 Out << " return 0;\n";
1477 printModule(fname,mName);
1480 void CppWriter::printModule(
1481 const std::string& fname,
1482 const std::string& mName
1484 Out << "\nModule* " << fname << "() {\n";
1485 Out << "\n// Module Construction\n";
1486 Out << "\nModule* mod = new Module(\"" << mName << "\");\n";
1487 Out << "mod->setEndianness(";
1488 switch (TheModule->getEndianness()) {
1489 case Module::LittleEndian: Out << "Module::LittleEndian);\n"; break;
1490 case Module::BigEndian: Out << "Module::BigEndian);\n"; break;
1491 case Module::AnyEndianness:Out << "Module::AnyEndianness);\n"; break;
1493 Out << "mod->setPointerSize(";
1494 switch (TheModule->getPointerSize()) {
1495 case Module::Pointer32: Out << "Module::Pointer32);\n"; break;
1496 case Module::Pointer64: Out << "Module::Pointer64);\n"; break;
1497 case Module::AnyPointerSize: Out << "Module::AnyPointerSize);\n"; break;
1499 if (!TheModule->getTargetTriple().empty())
1500 Out << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1503 if (!TheModule->getModuleInlineAsm().empty()) {
1504 Out << "mod->setModuleInlineAsm(\"";
1505 printEscapedString(TheModule->getModuleInlineAsm());
1509 // Loop over the dependent libraries and emit them.
1510 Module::lib_iterator LI = TheModule->lib_begin();
1511 Module::lib_iterator LE = TheModule->lib_end();
1513 Out << "mod->addLibrary(\"" << *LI << "\");\n";
1517 Out << "\nreturn mod;\n";
1521 void CppWriter::printContents(
1522 const std::string& fname, // Name of generated function
1523 const std::string& mName // Name of module generated module
1525 Out << "\nModule* " << fname << "(Module *mod) {\n";
1526 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1528 Out << "\nreturn mod;\n";
1532 void CppWriter::printFunction(
1533 const std::string& fname, // Name of generated function
1534 const std::string& funcName // Name of function to generate
1536 const Function* F = TheModule->getNamedFunction(funcName);
1538 error(std::string("Function '") + funcName + "' not found in input module");
1541 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1542 printFunctionUses(F);
1543 printFunctionHead(F);
1544 printFunctionBody(F);
1545 Out << "return " << getCppName(F) << ";\n";
1549 void CppWriter::printVariable(
1550 const std::string& fname, /// Name of generated function
1551 const std::string& varName // Name of variable to generate
1553 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1556 error(std::string("Variable '") + varName + "' not found in input module");
1559 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1560 printVariableUses(GV);
1561 printVariableHead(GV);
1562 printVariableBody(GV);
1563 Out << "return " << getCppName(GV) << ";\n";
1567 void CppWriter::printType(
1568 const std::string& fname, /// Name of generated function
1569 const std::string& typeName // Name of type to generate
1571 const Type* Ty = TheModule->getTypeByName(typeName);
1573 error(std::string("Type '") + typeName + "' not found in input module");
1576 Out << "\nType* " << fname << "(Module *mod) {\n";
1578 Out << "return " << getCppName(Ty) << ";\n";
1582 } // end anonymous llvm
1586 void WriteModuleToCppFile(Module* mod, std::ostream& o) {
1587 // Initialize a CppWriter for us to use
1588 CppWriter W(o, mod);
1591 o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1593 // Get the name of the function we're supposed to generate
1594 std::string fname = FuncName.getValue();
1596 // Get the name of the thing we are to generate
1597 std::string tgtname = NameToGenerate.getValue();
1598 if (GenerationType == GenModule ||
1599 GenerationType == GenContents ||
1600 GenerationType == GenProgram) {
1601 if (tgtname == "!bad!") {
1602 if (mod->getModuleIdentifier() == "-")
1603 tgtname = "<stdin>";
1605 tgtname = mod->getModuleIdentifier();
1607 } else if (tgtname == "!bad!") {
1608 W.error("You must use the -for option with -gen-{function,variable,type}");
1611 switch (WhatToGenerate(GenerationType)) {
1614 fname = "makeLLVMModule";
1615 W.printProgram(fname,tgtname);
1619 fname = "makeLLVMModule";
1620 W.printModule(fname,tgtname);
1624 fname = "makeLLVMModuleContents";
1625 W.printContents(fname,tgtname);
1629 fname = "makeLLVMFunction";
1630 W.printFunction(fname,tgtname);
1634 fname = "makeLLVMInline";
1635 W.printInline(fname,tgtname);
1639 fname = "makeLLVMVariable";
1640 W.printVariable(fname,tgtname);
1644 fname = "makeLLVMType";
1645 W.printType(fname,tgtname);
1648 W.error("Invalid generation option");