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/TypeSymbolTable.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/CFG.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Config/config.h"
36 static cl::opt<std::string>
37 FuncName("funcname", cl::desc("Specify the name of the generated function"),
38 cl::value_desc("function name"));
50 static cl::opt<WhatToGenerate> GenerationType(cl::Optional,
51 cl::desc("Choose what kind of output to generate"),
54 clEnumValN(GenProgram, "gen-program", "Generate a complete program"),
55 clEnumValN(GenModule, "gen-module", "Generate a module definition"),
56 clEnumValN(GenContents,"gen-contents", "Generate contents of a module"),
57 clEnumValN(GenFunction,"gen-function", "Generate a function definition"),
58 clEnumValN(GenInline, "gen-inline", "Generate an inline function"),
59 clEnumValN(GenVariable,"gen-variable", "Generate a variable definition"),
60 clEnumValN(GenType, "gen-type", "Generate a type definition"),
65 static cl::opt<std::string> NameToGenerate("for", cl::Optional,
66 cl::desc("Specify the name of the thing to generate"),
70 typedef std::vector<const Type*> TypeList;
71 typedef std::map<const Type*,std::string> TypeMap;
72 typedef std::map<const Value*,std::string> ValueMap;
73 typedef std::set<std::string> NameSet;
74 typedef std::set<const Type*> TypeSet;
75 typedef std::set<const Value*> ValueSet;
76 typedef std::map<const Value*,std::string> ForwardRefMap;
81 const Module *TheModule;
85 TypeMap UnresolvedTypes;
89 ValueSet DefinedValues;
90 ForwardRefMap ForwardRefs;
94 inline CppWriter(std::ostream &o, const Module *M, const char* pn="llvm2cpp")
95 : progname(pn), Out(o), TheModule(M), uniqueNum(0), TypeNames(),
96 ValueNames(), UnresolvedTypes(), TypeStack(), is_inline(false) { }
98 const Module* getModule() { return TheModule; }
100 void printProgram(const std::string& fname, const std::string& modName );
101 void printModule(const std::string& fname, const std::string& modName );
102 void printContents(const std::string& fname, const std::string& modName );
103 void printFunction(const std::string& fname, const std::string& funcName );
104 void printInline(const std::string& fname, const std::string& funcName );
105 void printVariable(const std::string& fname, const std::string& varName );
106 void printType(const std::string& fname, const std::string& typeName );
108 void error(const std::string& msg);
111 void printLinkageType(GlobalValue::LinkageTypes LT);
112 void printCallingConv(unsigned cc);
113 void printEscapedString(const std::string& str);
114 void printCFP(const ConstantFP* CFP);
116 std::string getCppName(const Type* val);
117 inline void printCppName(const Type* val);
119 std::string getCppName(const Value* val);
120 inline void printCppName(const Value* val);
122 bool printTypeInternal(const Type* Ty);
123 inline void printType(const Type* Ty);
124 void printTypes(const Module* M);
126 void printConstant(const Constant *CPV);
127 void printConstants(const Module* M);
129 void printVariableUses(const GlobalVariable *GV);
130 void printVariableHead(const GlobalVariable *GV);
131 void printVariableBody(const GlobalVariable *GV);
133 void printFunctionUses(const Function *F);
134 void printFunctionHead(const Function *F);
135 void printFunctionBody(const Function *F);
136 void printInstruction(const Instruction *I, const std::string& bbname);
137 std::string getOpName(Value*);
139 void printModuleBody();
143 static unsigned indent_level = 0;
144 inline std::ostream& nl(std::ostream& Out, int delta = 0) {
146 if (delta >= 0 || indent_level >= unsigned(-delta))
147 indent_level += delta;
148 for (unsigned i = 0; i < indent_level; ++i)
153 inline void in() { indent_level++; }
154 inline void out() { if (indent_level >0) indent_level--; }
157 sanitize(std::string& str) {
158 for (size_t i = 0; i < str.length(); ++i)
159 if (!isalnum(str[i]) && str[i] != '_')
164 getTypePrefix(const Type* Ty ) {
165 switch (Ty->getTypeID()) {
166 case Type::VoidTyID: return "void_";
167 case Type::IntegerTyID:
168 return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
170 case Type::FloatTyID: return "float_";
171 case Type::DoubleTyID: return "double_";
172 case Type::LabelTyID: return "label_";
173 case Type::FunctionTyID: return "func_";
174 case Type::StructTyID: return "struct_";
175 case Type::ArrayTyID: return "array_";
176 case Type::PointerTyID: return "ptr_";
177 case Type::PackedTyID: return "packed_";
178 case Type::OpaqueTyID: return "opaque_";
179 default: return "other_";
184 // Looks up the type in the symbol table and returns a pointer to its name or
185 // a null pointer if it wasn't found. Note that this isn't the same as the
186 // Mode::getTypeName function which will return an empty string, not a null
187 // pointer if the name is not found.
188 inline const std::string*
189 findTypeName(const TypeSymbolTable& ST, const Type* Ty)
191 TypeSymbolTable::const_iterator TI = ST.begin();
192 TypeSymbolTable::const_iterator TE = ST.end();
193 for (;TI != TE; ++TI)
194 if (TI->second == Ty)
200 CppWriter::error(const std::string& msg) {
201 std::cerr << progname << ": " << msg << "\n";
205 // printCFP - Print a floating point constant .. very carefully :)
206 // This makes sure that conversion to/from floating yields the same binary
207 // result so that we don't lose precision.
209 CppWriter::printCFP(const ConstantFP *CFP) {
210 Out << "ConstantFP::get(";
211 if (CFP->getType() == Type::DoubleTy)
212 Out << "Type::DoubleTy, ";
214 Out << "Type::FloatTy, ";
217 sprintf(Buffer, "%A", CFP->getValue());
218 if ((!strncmp(Buffer, "0x", 2) ||
219 !strncmp(Buffer, "-0x", 3) ||
220 !strncmp(Buffer, "+0x", 3)) &&
221 (atof(Buffer) == CFP->getValue()))
222 if (CFP->getType() == Type::DoubleTy)
223 Out << "BitsToDouble(" << Buffer << ")";
225 Out << "BitsToFloat(" << Buffer << ")";
228 std::string StrVal = ftostr(CFP->getValue());
230 while (StrVal[0] == ' ')
231 StrVal.erase(StrVal.begin());
233 // Check to make sure that the stringized number is not some string like
234 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
235 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
236 ((StrVal[0] == '-' || StrVal[0] == '+') &&
237 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
238 (atof(StrVal.c_str()) == CFP->getValue()))
239 if (CFP->getType() == Type::DoubleTy)
243 else if (CFP->getType() == Type::DoubleTy)
244 Out << "BitsToDouble(0x" << std::hex << DoubleToBits(CFP->getValue())
245 << std::dec << "ULL) /* " << StrVal << " */";
247 Out << "BitsToFloat(0x" << std::hex << FloatToBits(CFP->getValue())
248 << std::dec << "U) /* " << StrVal << " */";
256 CppWriter::printCallingConv(unsigned cc){
257 // Print the calling convention.
259 case CallingConv::C: Out << "CallingConv::C"; break;
260 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
261 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
262 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
263 default: Out << cc; break;
268 CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
270 case GlobalValue::InternalLinkage:
271 Out << "GlobalValue::InternalLinkage"; break;
272 case GlobalValue::LinkOnceLinkage:
273 Out << "GlobalValue::LinkOnceLinkage "; break;
274 case GlobalValue::WeakLinkage:
275 Out << "GlobalValue::WeakLinkage"; break;
276 case GlobalValue::AppendingLinkage:
277 Out << "GlobalValue::AppendingLinkage"; break;
278 case GlobalValue::ExternalLinkage:
279 Out << "GlobalValue::ExternalLinkage"; break;
280 case GlobalValue::DLLImportLinkage:
281 Out << "GlobalValue::DllImportLinkage"; break;
282 case GlobalValue::DLLExportLinkage:
283 Out << "GlobalValue::DllExportLinkage"; break;
284 case GlobalValue::ExternalWeakLinkage:
285 Out << "GlobalValue::ExternalWeakLinkage"; break;
286 case GlobalValue::GhostLinkage:
287 Out << "GlobalValue::GhostLinkage"; break;
291 // printEscapedString - Print each character of the specified string, escaping
292 // it if it is not printable or if it is an escape char.
294 CppWriter::printEscapedString(const std::string &Str) {
295 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
296 unsigned char C = Str[i];
297 if (isprint(C) && C != '"' && C != '\\') {
301 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
302 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
308 CppWriter::getCppName(const Type* Ty)
310 // First, handle the primitive types .. easy
311 if (Ty->isPrimitiveType() || Ty->isInteger()) {
312 switch (Ty->getTypeID()) {
313 case Type::VoidTyID: return "Type::VoidTy";
314 case Type::IntegerTyID: {
315 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
316 return "IntegerType::get(" + utostr(BitWidth) + ")";
318 case Type::FloatTyID: return "Type::FloatTy";
319 case Type::DoubleTyID: return "Type::DoubleTy";
320 case Type::LabelTyID: return "Type::LabelTy";
322 error("Invalid primitive type");
325 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
328 // Now, see if we've seen the type before and return that
329 TypeMap::iterator I = TypeNames.find(Ty);
330 if (I != TypeNames.end())
333 // Okay, let's build a new name for this type. Start with a prefix
334 const char* prefix = 0;
335 switch (Ty->getTypeID()) {
336 case Type::FunctionTyID: prefix = "FuncTy_"; break;
337 case Type::StructTyID: prefix = "StructTy_"; break;
338 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
339 case Type::PointerTyID: prefix = "PointerTy_"; break;
340 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
341 case Type::PackedTyID: prefix = "PackedTy_"; break;
342 default: prefix = "OtherTy_"; break; // prevent breakage
345 // See if the type has a name in the symboltable and build accordingly
346 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
349 name = std::string(prefix) + *tName;
351 name = std::string(prefix) + utostr(uniqueNum++);
355 return TypeNames[Ty] = name;
359 CppWriter::printCppName(const Type* Ty)
361 printEscapedString(getCppName(Ty));
365 CppWriter::getCppName(const Value* val) {
367 ValueMap::iterator I = ValueNames.find(val);
368 if (I != ValueNames.end() && I->first == val)
371 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
372 name = std::string("gvar_") +
373 getTypePrefix(GV->getType()->getElementType());
374 } else if (isa<Function>(val)) {
375 name = std::string("func_");
376 } else if (const Constant* C = dyn_cast<Constant>(val)) {
377 name = std::string("const_") + getTypePrefix(C->getType());
378 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
380 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
381 Function::const_arg_iterator(Arg)) + 1;
382 name = std::string("arg_") + utostr(argNum);
383 NameSet::iterator NI = UsedNames.find(name);
384 if (NI != UsedNames.end())
385 name += std::string("_") + utostr(uniqueNum++);
386 UsedNames.insert(name);
387 return ValueNames[val] = name;
389 name = getTypePrefix(val->getType());
392 name = getTypePrefix(val->getType());
394 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
396 NameSet::iterator NI = UsedNames.find(name);
397 if (NI != UsedNames.end())
398 name += std::string("_") + utostr(uniqueNum++);
399 UsedNames.insert(name);
400 return ValueNames[val] = name;
404 CppWriter::printCppName(const Value* val) {
405 printEscapedString(getCppName(val));
409 CppWriter::printTypeInternal(const Type* Ty) {
410 // We don't print definitions for primitive types
411 if (Ty->isPrimitiveType() || Ty->isInteger())
414 // If we already defined this type, we don't need to define it again.
415 if (DefinedTypes.find(Ty) != DefinedTypes.end())
418 // Everything below needs the name for the type so get it now.
419 std::string typeName(getCppName(Ty));
421 // Search the type stack for recursion. If we find it, then generate this
422 // as an OpaqueType, but make sure not to do this multiple times because
423 // the type could appear in multiple places on the stack. Once the opaque
424 // definition is issued, it must not be re-issued. Consequently we have to
425 // check the UnresolvedTypes list as well.
426 TypeList::const_iterator TI = std::find(TypeStack.begin(),TypeStack.end(),Ty);
427 if (TI != TypeStack.end()) {
428 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
429 if (I == UnresolvedTypes.end()) {
430 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
432 UnresolvedTypes[Ty] = typeName;
437 // We're going to print a derived type which, by definition, contains other
438 // types. So, push this one we're printing onto the type stack to assist with
439 // recursive definitions.
440 TypeStack.push_back(Ty);
442 // Print the type definition
443 switch (Ty->getTypeID()) {
444 case Type::FunctionTyID: {
445 const FunctionType* FT = cast<FunctionType>(Ty);
446 Out << "std::vector<const Type*>" << typeName << "_args;";
448 FunctionType::param_iterator PI = FT->param_begin();
449 FunctionType::param_iterator PE = FT->param_end();
450 for (; PI != PE; ++PI) {
451 const Type* argTy = static_cast<const Type*>(*PI);
452 bool isForward = printTypeInternal(argTy);
453 std::string argName(getCppName(argTy));
454 Out << typeName << "_args.push_back(" << argName;
460 bool isForward = printTypeInternal(FT->getReturnType());
461 std::string retTypeName(getCppName(FT->getReturnType()));
462 Out << "FunctionType* " << typeName << " = FunctionType::get(";
463 in(); nl(Out) << "/*Result=*/" << retTypeName;
467 nl(Out) << "/*Params=*/" << typeName << "_args,";
468 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
473 case Type::StructTyID: {
474 const StructType* ST = cast<StructType>(Ty);
475 Out << "std::vector<const Type*>" << typeName << "_fields;";
477 StructType::element_iterator EI = ST->element_begin();
478 StructType::element_iterator EE = ST->element_end();
479 for (; EI != EE; ++EI) {
480 const Type* fieldTy = static_cast<const Type*>(*EI);
481 bool isForward = printTypeInternal(fieldTy);
482 std::string fieldName(getCppName(fieldTy));
483 Out << typeName << "_fields.push_back(" << fieldName;
489 Out << "StructType* " << typeName << " = StructType::get("
490 << typeName << "_fields);";
494 case Type::ArrayTyID: {
495 const ArrayType* AT = cast<ArrayType>(Ty);
496 const Type* ET = AT->getElementType();
497 bool isForward = printTypeInternal(ET);
498 std::string elemName(getCppName(ET));
499 Out << "ArrayType* " << typeName << " = ArrayType::get("
500 << elemName << (isForward ? "_fwd" : "")
501 << ", " << utostr(AT->getNumElements()) << ");";
505 case Type::PointerTyID: {
506 const PointerType* PT = cast<PointerType>(Ty);
507 const Type* ET = PT->getElementType();
508 bool isForward = printTypeInternal(ET);
509 std::string elemName(getCppName(ET));
510 Out << "PointerType* " << typeName << " = PointerType::get("
511 << elemName << (isForward ? "_fwd" : "") << ");";
515 case Type::PackedTyID: {
516 const PackedType* PT = cast<PackedType>(Ty);
517 const Type* ET = PT->getElementType();
518 bool isForward = printTypeInternal(ET);
519 std::string elemName(getCppName(ET));
520 Out << "PackedType* " << typeName << " = PackedType::get("
521 << elemName << (isForward ? "_fwd" : "")
522 << ", " << utostr(PT->getNumElements()) << ");";
526 case Type::OpaqueTyID: {
527 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
532 error("Invalid TypeID");
535 // If the type had a name, make sure we recreate it.
536 const std::string* progTypeName =
537 findTypeName(TheModule->getTypeSymbolTable(),Ty);
539 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
543 // Pop us off the type stack
544 TypeStack.pop_back();
546 // Indicate that this type is now defined.
547 DefinedTypes.insert(Ty);
549 // Early resolve as many unresolved types as possible. Search the unresolved
550 // types map for the type we just printed. Now that its definition is complete
551 // we can resolve any previous references to it. This prevents a cascade of
553 TypeMap::iterator I = UnresolvedTypes.find(Ty);
554 if (I != UnresolvedTypes.end()) {
555 Out << "cast<OpaqueType>(" << I->second
556 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
558 Out << I->second << " = cast<";
559 switch (Ty->getTypeID()) {
560 case Type::FunctionTyID: Out << "FunctionType"; break;
561 case Type::ArrayTyID: Out << "ArrayType"; break;
562 case Type::StructTyID: Out << "StructType"; break;
563 case Type::PackedTyID: Out << "PackedType"; break;
564 case Type::PointerTyID: Out << "PointerType"; break;
565 case Type::OpaqueTyID: Out << "OpaqueType"; break;
566 default: Out << "NoSuchDerivedType"; break;
568 Out << ">(" << I->second << "_fwd.get());";
570 UnresolvedTypes.erase(I);
573 // Finally, separate the type definition from other with a newline.
576 // We weren't a recursive type
580 // Prints a type definition. Returns true if it could not resolve all the types
581 // in the definition but had to use a forward reference.
583 CppWriter::printType(const Type* Ty) {
584 assert(TypeStack.empty());
586 printTypeInternal(Ty);
587 assert(TypeStack.empty());
591 CppWriter::printTypes(const Module* M) {
593 // Walk the symbol table and print out all its types
594 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
595 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
598 // For primitive types and types already defined, just add a name
599 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
600 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
601 TNI != TypeNames.end()) {
602 Out << "mod->addTypeName(\"";
603 printEscapedString(TI->first);
604 Out << "\", " << getCppName(TI->second) << ");";
606 // For everything else, define the type
608 printType(TI->second);
612 // Add all of the global variables to the value table...
613 for (Module::const_global_iterator I = TheModule->global_begin(),
614 E = TheModule->global_end(); I != E; ++I) {
615 if (I->hasInitializer())
616 printType(I->getInitializer()->getType());
617 printType(I->getType());
620 // Add all the functions to the table
621 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
623 printType(FI->getReturnType());
624 printType(FI->getFunctionType());
625 // Add all the function arguments
626 for(Function::const_arg_iterator AI = FI->arg_begin(),
627 AE = FI->arg_end(); AI != AE; ++AI) {
628 printType(AI->getType());
631 // Add all of the basic blocks and instructions
632 for (Function::const_iterator BB = FI->begin(),
633 E = FI->end(); BB != E; ++BB) {
634 printType(BB->getType());
635 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
637 printType(I->getType());
638 for (unsigned i = 0; i < I->getNumOperands(); ++i)
639 printType(I->getOperand(i)->getType());
646 // printConstant - Print out a constant pool entry...
647 void CppWriter::printConstant(const Constant *CV) {
648 // First, if the constant is actually a GlobalValue (variable or function) or
649 // its already in the constant list then we've printed it already and we can
651 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
654 std::string constName(getCppName(CV));
655 std::string typeName(getCppName(CV->getType()));
656 if (CV->isNullValue()) {
657 Out << "Constant* " << constName << " = Constant::getNullValue("
662 if (isa<GlobalValue>(CV)) {
663 // Skip variables and functions, we emit them elsewhere
666 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
667 Out << "ConstantInt* " << constName << " = ConstantInt::get("
668 << typeName << ", " << CI->getZExtValue() << ");";
669 } else if (isa<ConstantAggregateZero>(CV)) {
670 Out << "ConstantAggregateZero* " << constName
671 << " = ConstantAggregateZero::get(" << typeName << ");";
672 } else if (isa<ConstantPointerNull>(CV)) {
673 Out << "ConstantPointerNull* " << constName
674 << " = ConstanPointerNull::get(" << typeName << ");";
675 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
676 Out << "ConstantFP* " << constName << " = ";
679 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
680 if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
681 Out << "Constant* " << constName << " = ConstantArray::get(\"";
682 printEscapedString(CA->getAsString());
683 // Determine if we want null termination or not.
684 if (CA->getType()->getNumElements() <= CA->getAsString().length())
685 Out << "\", false";// No null terminator
687 Out << "\", true"; // Indicate that the null terminator should be added.
690 Out << "std::vector<Constant*> " << constName << "_elems;";
692 unsigned N = CA->getNumOperands();
693 for (unsigned i = 0; i < N; ++i) {
694 printConstant(CA->getOperand(i)); // recurse to print operands
695 Out << constName << "_elems.push_back("
696 << getCppName(CA->getOperand(i)) << ");";
699 Out << "Constant* " << constName << " = ConstantArray::get("
700 << typeName << ", " << constName << "_elems);";
702 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
703 Out << "std::vector<Constant*> " << constName << "_fields;";
705 unsigned N = CS->getNumOperands();
706 for (unsigned i = 0; i < N; i++) {
707 printConstant(CS->getOperand(i));
708 Out << constName << "_fields.push_back("
709 << getCppName(CS->getOperand(i)) << ");";
712 Out << "Constant* " << constName << " = ConstantStruct::get("
713 << typeName << ", " << constName << "_fields);";
714 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
715 Out << "std::vector<Constant*> " << constName << "_elems;";
717 unsigned N = CP->getNumOperands();
718 for (unsigned i = 0; i < N; ++i) {
719 printConstant(CP->getOperand(i));
720 Out << constName << "_elems.push_back("
721 << getCppName(CP->getOperand(i)) << ");";
724 Out << "Constant* " << constName << " = ConstantPacked::get("
725 << typeName << ", " << constName << "_elems);";
726 } else if (isa<UndefValue>(CV)) {
727 Out << "UndefValue* " << constName << " = UndefValue::get("
729 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
730 if (CE->getOpcode() == Instruction::GetElementPtr) {
731 Out << "std::vector<Constant*> " << constName << "_indices;";
733 printConstant(CE->getOperand(0));
734 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
735 printConstant(CE->getOperand(i));
736 Out << constName << "_indices.push_back("
737 << getCppName(CE->getOperand(i)) << ");";
740 Out << "Constant* " << constName
741 << " = ConstantExpr::getGetElementPtr("
742 << getCppName(CE->getOperand(0)) << ", "
743 << constName << "_indices);";
744 } else if (CE->isCast()) {
745 printConstant(CE->getOperand(0));
746 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
747 switch (CE->getOpcode()) {
748 default: assert(0 && "Invalid cast opcode");
749 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
750 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
751 case Instruction::SExt: Out << "Instruction::SExt"; break;
752 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
753 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
754 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
755 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
756 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
757 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
758 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
759 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
760 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
762 Out << ", " << getCppName(CE->getOperand(0)) << ", "
763 << getCppName(CE->getType()) << ");";
765 unsigned N = CE->getNumOperands();
766 for (unsigned i = 0; i < N; ++i ) {
767 printConstant(CE->getOperand(i));
769 Out << "Constant* " << constName << " = ConstantExpr::";
770 switch (CE->getOpcode()) {
771 case Instruction::Add: Out << "getAdd("; break;
772 case Instruction::Sub: Out << "getSub("; break;
773 case Instruction::Mul: Out << "getMul("; break;
774 case Instruction::UDiv: Out << "getUDiv("; break;
775 case Instruction::SDiv: Out << "getSDiv("; break;
776 case Instruction::FDiv: Out << "getFDiv("; break;
777 case Instruction::URem: Out << "getURem("; break;
778 case Instruction::SRem: Out << "getSRem("; break;
779 case Instruction::FRem: Out << "getFRem("; break;
780 case Instruction::And: Out << "getAnd("; break;
781 case Instruction::Or: Out << "getOr("; break;
782 case Instruction::Xor: Out << "getXor("; break;
783 case Instruction::ICmp:
784 Out << "getICmp(ICmpInst::ICMP_";
785 switch (CE->getPredicate()) {
786 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
787 case ICmpInst::ICMP_NE: Out << "NE"; break;
788 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
789 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
790 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
791 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
792 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
793 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
794 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
795 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
796 default: error("Invalid ICmp Predicate");
799 case Instruction::FCmp:
800 Out << "getFCmp(FCmpInst::FCMP_";
801 switch (CE->getPredicate()) {
802 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
803 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
804 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
805 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
806 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
807 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
808 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
809 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
810 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
811 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
812 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
813 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
814 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
815 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
816 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
817 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
818 default: error("Invalid FCmp Predicate");
821 case Instruction::Shl: Out << "getShl("; break;
822 case Instruction::LShr: Out << "getLShr("; break;
823 case Instruction::AShr: Out << "getAShr("; break;
824 case Instruction::Select: Out << "getSelect("; break;
825 case Instruction::ExtractElement: Out << "getExtractElement("; break;
826 case Instruction::InsertElement: Out << "getInsertElement("; break;
827 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
829 error("Invalid constant expression");
832 Out << getCppName(CE->getOperand(0));
833 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
834 Out << ", " << getCppName(CE->getOperand(i));
838 error("Bad Constant");
839 Out << "Constant* " << constName << " = 0; ";
845 CppWriter::printConstants(const Module* M) {
846 // Traverse all the global variables looking for constant initializers
847 for (Module::const_global_iterator I = TheModule->global_begin(),
848 E = TheModule->global_end(); I != E; ++I)
849 if (I->hasInitializer())
850 printConstant(I->getInitializer());
852 // Traverse the LLVM functions looking for constants
853 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
855 // Add all of the basic blocks and instructions
856 for (Function::const_iterator BB = FI->begin(),
857 E = FI->end(); BB != E; ++BB) {
858 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
860 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
861 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
870 void CppWriter::printVariableUses(const GlobalVariable *GV) {
871 nl(Out) << "// Type Definitions";
873 printType(GV->getType());
874 if (GV->hasInitializer()) {
875 Constant* Init = GV->getInitializer();
876 printType(Init->getType());
877 if (Function* F = dyn_cast<Function>(Init)) {
878 nl(Out)<< "/ Function Declarations"; nl(Out);
879 printFunctionHead(F);
880 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
881 nl(Out) << "// Global Variable Declarations"; nl(Out);
882 printVariableHead(gv);
884 nl(Out) << "// Constant Definitions"; nl(Out);
887 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
888 nl(Out) << "// Global Variable Definitions"; nl(Out);
889 printVariableBody(gv);
894 void CppWriter::printVariableHead(const GlobalVariable *GV) {
895 nl(Out) << "GlobalVariable* " << getCppName(GV);
897 Out << " = mod->getGlobalVariable(";
898 printEscapedString(GV->getName());
899 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
900 nl(Out) << "if (!" << getCppName(GV) << ") {";
901 in(); nl(Out) << getCppName(GV);
903 Out << " = new GlobalVariable(";
904 nl(Out) << "/*Type=*/";
905 printCppName(GV->getType()->getElementType());
907 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
909 nl(Out) << "/*Linkage=*/";
910 printLinkageType(GV->getLinkage());
912 nl(Out) << "/*Initializer=*/0, ";
913 if (GV->hasInitializer()) {
914 Out << "// has initializer, specified below";
916 nl(Out) << "/*Name=*/\"";
917 printEscapedString(GV->getName());
922 if (GV->hasSection()) {
924 Out << "->setSection(\"";
925 printEscapedString(GV->getSection());
929 if (GV->getAlignment()) {
931 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
935 out(); Out << "}"; nl(Out);
940 CppWriter::printVariableBody(const GlobalVariable *GV) {
941 if (GV->hasInitializer()) {
943 Out << "->setInitializer(";
944 //if (!isa<GlobalValue(GV->getInitializer()))
946 Out << getCppName(GV->getInitializer()) << ");";
952 CppWriter::getOpName(Value* V) {
953 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
954 return getCppName(V);
956 // See if its alread in the map of forward references, if so just return the
957 // name we already set up for it
958 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
959 if (I != ForwardRefs.end())
962 // This is a new forward reference. Generate a unique name for it
963 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
965 // Yes, this is a hack. An Argument is the smallest instantiable value that
966 // we can make as a placeholder for the real value. We'll replace these
967 // Argument instances later.
968 Out << "Argument* " << result << " = new Argument("
969 << getCppName(V->getType()) << ");";
971 ForwardRefs[V] = result;
975 // printInstruction - This member is called for each Instruction in a function.
977 CppWriter::printInstruction(const Instruction *I, const std::string& bbname) {
978 std::string iName(getCppName(I));
980 // Before we emit this instruction, we need to take care of generating any
981 // forward references. So, we get the names of all the operands in advance
982 std::string* opNames = new std::string[I->getNumOperands()];
983 for (unsigned i = 0; i < I->getNumOperands(); i++) {
984 opNames[i] = getOpName(I->getOperand(i));
987 switch (I->getOpcode()) {
988 case Instruction::Ret: {
989 const ReturnInst* ret = cast<ReturnInst>(I);
990 Out << "ReturnInst* " << iName << " = new ReturnInst("
991 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
994 case Instruction::Br: {
995 const BranchInst* br = cast<BranchInst>(I);
996 Out << "BranchInst* " << iName << " = new BranchInst(" ;
997 if (br->getNumOperands() == 3 ) {
998 Out << opNames[0] << ", "
999 << opNames[1] << ", "
1000 << opNames[2] << ", ";
1002 } else if (br->getNumOperands() == 1) {
1003 Out << opNames[0] << ", ";
1005 error("Branch with 2 operands?");
1007 Out << bbname << ");";
1010 case Instruction::Switch: {
1011 const SwitchInst* sw = cast<SwitchInst>(I);
1012 Out << "SwitchInst* " << iName << " = new SwitchInst("
1013 << opNames[0] << ", "
1014 << opNames[1] << ", "
1015 << sw->getNumCases() << ", " << bbname << ");";
1017 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1018 Out << iName << "->addCase("
1019 << opNames[i] << ", "
1020 << opNames[i+1] << ");";
1025 case Instruction::Invoke: {
1026 const InvokeInst* inv = cast<InvokeInst>(I);
1027 Out << "std::vector<Value*> " << iName << "_params;";
1029 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1030 Out << iName << "_params.push_back("
1031 << opNames[i] << ");";
1034 Out << "InvokeInst* " << iName << " = new InvokeInst("
1035 << opNames[0] << ", "
1036 << opNames[1] << ", "
1037 << opNames[2] << ", "
1038 << iName << "_params, \"";
1039 printEscapedString(inv->getName());
1040 Out << "\", " << bbname << ");";
1041 nl(Out) << iName << "->setCallingConv(";
1042 printCallingConv(inv->getCallingConv());
1046 case Instruction::Unwind: {
1047 Out << "UnwindInst* " << iName << " = new UnwindInst("
1051 case Instruction::Unreachable:{
1052 Out << "UnreachableInst* " << iName << " = new UnreachableInst("
1056 case Instruction::Add:
1057 case Instruction::Sub:
1058 case Instruction::Mul:
1059 case Instruction::UDiv:
1060 case Instruction::SDiv:
1061 case Instruction::FDiv:
1062 case Instruction::URem:
1063 case Instruction::SRem:
1064 case Instruction::FRem:
1065 case Instruction::And:
1066 case Instruction::Or:
1067 case Instruction::Xor:
1068 case Instruction::Shl:
1069 case Instruction::LShr:
1070 case Instruction::AShr:{
1071 Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
1072 switch (I->getOpcode()) {
1073 case Instruction::Add: Out << "Instruction::Add"; break;
1074 case Instruction::Sub: Out << "Instruction::Sub"; break;
1075 case Instruction::Mul: Out << "Instruction::Mul"; break;
1076 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1077 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1078 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1079 case Instruction::URem:Out << "Instruction::URem"; break;
1080 case Instruction::SRem:Out << "Instruction::SRem"; break;
1081 case Instruction::FRem:Out << "Instruction::FRem"; break;
1082 case Instruction::And: Out << "Instruction::And"; break;
1083 case Instruction::Or: Out << "Instruction::Or"; break;
1084 case Instruction::Xor: Out << "Instruction::Xor"; break;
1085 case Instruction::Shl: Out << "Instruction::Shl"; break;
1086 case Instruction::LShr:Out << "Instruction::LShr"; break;
1087 case Instruction::AShr:Out << "Instruction::AShr"; break;
1088 default: Out << "Instruction::BadOpCode"; break;
1090 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1091 printEscapedString(I->getName());
1092 Out << "\", " << bbname << ");";
1095 case Instruction::FCmp: {
1096 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1097 switch (cast<FCmpInst>(I)->getPredicate()) {
1098 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1099 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1100 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1101 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1102 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1103 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1104 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1105 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1106 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1107 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1108 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1109 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1110 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1111 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1112 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1113 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1114 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1116 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1117 printEscapedString(I->getName());
1118 Out << "\", " << bbname << ");";
1121 case Instruction::ICmp: {
1122 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1123 switch (cast<ICmpInst>(I)->getPredicate()) {
1124 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1125 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1126 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1127 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1128 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1129 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1130 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1131 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1132 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1133 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1134 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1136 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1137 printEscapedString(I->getName());
1138 Out << "\", " << bbname << ");";
1141 case Instruction::Malloc: {
1142 const MallocInst* mallocI = cast<MallocInst>(I);
1143 Out << "MallocInst* " << iName << " = new MallocInst("
1144 << getCppName(mallocI->getAllocatedType()) << ", ";
1145 if (mallocI->isArrayAllocation())
1146 Out << opNames[0] << ", " ;
1148 printEscapedString(mallocI->getName());
1149 Out << "\", " << bbname << ");";
1150 if (mallocI->getAlignment())
1151 nl(Out) << iName << "->setAlignment("
1152 << mallocI->getAlignment() << ");";
1155 case Instruction::Free: {
1156 Out << "FreeInst* " << iName << " = new FreeInst("
1157 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1160 case Instruction::Alloca: {
1161 const AllocaInst* allocaI = cast<AllocaInst>(I);
1162 Out << "AllocaInst* " << iName << " = new AllocaInst("
1163 << getCppName(allocaI->getAllocatedType()) << ", ";
1164 if (allocaI->isArrayAllocation())
1165 Out << opNames[0] << ", ";
1167 printEscapedString(allocaI->getName());
1168 Out << "\", " << bbname << ");";
1169 if (allocaI->getAlignment())
1170 nl(Out) << iName << "->setAlignment("
1171 << allocaI->getAlignment() << ");";
1174 case Instruction::Load:{
1175 const LoadInst* load = cast<LoadInst>(I);
1176 Out << "LoadInst* " << iName << " = new LoadInst("
1177 << opNames[0] << ", \"";
1178 printEscapedString(load->getName());
1179 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1180 << ", " << bbname << ");";
1183 case Instruction::Store: {
1184 const StoreInst* store = cast<StoreInst>(I);
1185 Out << "StoreInst* " << iName << " = new StoreInst("
1186 << opNames[0] << ", "
1187 << opNames[1] << ", "
1188 << (store->isVolatile() ? "true" : "false")
1189 << ", " << bbname << ");";
1192 case Instruction::GetElementPtr: {
1193 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1194 if (gep->getNumOperands() <= 2) {
1195 Out << "GetElementPtrInst* " << iName << " = new GetElementPtrInst("
1197 if (gep->getNumOperands() == 2)
1198 Out << ", " << opNames[1];
1200 Out << "std::vector<Value*> " << iName << "_indices;";
1202 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1203 Out << iName << "_indices.push_back("
1204 << opNames[i] << ");";
1207 Out << "Instruction* " << iName << " = new GetElementPtrInst("
1208 << opNames[0] << ", " << iName << "_indices";
1211 printEscapedString(gep->getName());
1212 Out << "\", " << bbname << ");";
1215 case Instruction::PHI: {
1216 const PHINode* phi = cast<PHINode>(I);
1218 Out << "PHINode* " << iName << " = new PHINode("
1219 << getCppName(phi->getType()) << ", \"";
1220 printEscapedString(phi->getName());
1221 Out << "\", " << bbname << ");";
1222 nl(Out) << iName << "->reserveOperandSpace("
1223 << phi->getNumIncomingValues()
1226 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1227 Out << iName << "->addIncoming("
1228 << opNames[i] << ", " << opNames[i+1] << ");";
1233 case Instruction::Trunc:
1234 case Instruction::ZExt:
1235 case Instruction::SExt:
1236 case Instruction::FPTrunc:
1237 case Instruction::FPExt:
1238 case Instruction::FPToUI:
1239 case Instruction::FPToSI:
1240 case Instruction::UIToFP:
1241 case Instruction::SIToFP:
1242 case Instruction::PtrToInt:
1243 case Instruction::IntToPtr:
1244 case Instruction::BitCast: {
1245 const CastInst* cst = cast<CastInst>(I);
1246 Out << "CastInst* " << iName << " = new ";
1247 switch (I->getOpcode()) {
1248 case Instruction::Trunc: Out << "TruncInst";
1249 case Instruction::ZExt: Out << "ZExtInst";
1250 case Instruction::SExt: Out << "SExtInst";
1251 case Instruction::FPTrunc: Out << "FPTruncInst";
1252 case Instruction::FPExt: Out << "FPExtInst";
1253 case Instruction::FPToUI: Out << "FPToUIInst";
1254 case Instruction::FPToSI: Out << "FPToSIInst";
1255 case Instruction::UIToFP: Out << "UIToFPInst";
1256 case Instruction::SIToFP: Out << "SIToFPInst";
1257 case Instruction::PtrToInt: Out << "PtrToInst";
1258 case Instruction::IntToPtr: Out << "IntToPtrInst";
1259 case Instruction::BitCast: Out << "BitCastInst";
1260 default: assert(!"Unreachable"); break;
1262 Out << "(" << opNames[0] << ", "
1263 << getCppName(cst->getType()) << ", \"";
1264 printEscapedString(cst->getName());
1265 Out << "\", " << bbname << ");";
1268 case Instruction::Call:{
1269 const CallInst* call = cast<CallInst>(I);
1270 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1271 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1272 << getCppName(ila->getFunctionType()) << ", \""
1273 << ila->getAsmString() << "\", \""
1274 << ila->getConstraintString() << "\","
1275 << (ila->hasSideEffects() ? "true" : "false") << ");";
1278 if (call->getNumOperands() > 3) {
1279 Out << "std::vector<Value*> " << iName << "_params;";
1281 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1282 Out << iName << "_params.push_back(" << opNames[i] << ");";
1285 Out << "CallInst* " << iName << " = new CallInst("
1286 << opNames[0] << ", " << iName << "_params, \"";
1287 } else if (call->getNumOperands() == 3) {
1288 Out << "CallInst* " << iName << " = new CallInst("
1289 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1290 } else if (call->getNumOperands() == 2) {
1291 Out << "CallInst* " << iName << " = new CallInst("
1292 << opNames[0] << ", " << opNames[1] << ", \"";
1294 Out << "CallInst* " << iName << " = new CallInst(" << opNames[0]
1297 printEscapedString(call->getName());
1298 Out << "\", " << bbname << ");";
1299 nl(Out) << iName << "->setCallingConv(";
1300 printCallingConv(call->getCallingConv());
1302 nl(Out) << iName << "->setTailCall("
1303 << (call->isTailCall() ? "true":"false");
1307 case Instruction::Select: {
1308 const SelectInst* sel = cast<SelectInst>(I);
1309 Out << "SelectInst* " << getCppName(sel) << " = new SelectInst(";
1310 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1311 printEscapedString(sel->getName());
1312 Out << "\", " << bbname << ");";
1315 case Instruction::UserOp1:
1317 case Instruction::UserOp2: {
1318 /// FIXME: What should be done here?
1321 case Instruction::VAArg: {
1322 const VAArgInst* va = cast<VAArgInst>(I);
1323 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1324 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1325 printEscapedString(va->getName());
1326 Out << "\", " << bbname << ");";
1329 case Instruction::ExtractElement: {
1330 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1331 Out << "ExtractElementInst* " << getCppName(eei)
1332 << " = new ExtractElementInst(" << opNames[0]
1333 << ", " << opNames[1] << ", \"";
1334 printEscapedString(eei->getName());
1335 Out << "\", " << bbname << ");";
1338 case Instruction::InsertElement: {
1339 const InsertElementInst* iei = cast<InsertElementInst>(I);
1340 Out << "InsertElementInst* " << getCppName(iei)
1341 << " = new InsertElementInst(" << opNames[0]
1342 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1343 printEscapedString(iei->getName());
1344 Out << "\", " << bbname << ");";
1347 case Instruction::ShuffleVector: {
1348 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1349 Out << "ShuffleVectorInst* " << getCppName(svi)
1350 << " = new ShuffleVectorInst(" << opNames[0]
1351 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1352 printEscapedString(svi->getName());
1353 Out << "\", " << bbname << ");";
1357 DefinedValues.insert(I);
1362 // Print out the types, constants and declarations needed by one function
1363 void CppWriter::printFunctionUses(const Function* F) {
1365 nl(Out) << "// Type Definitions"; nl(Out);
1367 // Print the function's return type
1368 printType(F->getReturnType());
1370 // Print the function's function type
1371 printType(F->getFunctionType());
1373 // Print the types of each of the function's arguments
1374 for(Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1376 printType(AI->getType());
1380 // Print type definitions for every type referenced by an instruction and
1381 // make a note of any global values or constants that are referenced
1382 std::vector<GlobalValue*> gvs;
1383 std::vector<Constant*> consts;
1384 for (Function::const_iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB){
1385 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1387 // Print the type of the instruction itself
1388 printType(I->getType());
1390 // Print the type of each of the instruction's operands
1391 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1392 Value* operand = I->getOperand(i);
1393 printType(operand->getType());
1394 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand))
1396 else if (Constant* C = dyn_cast<Constant>(operand))
1397 consts.push_back(C);
1402 // Print the function declarations for any functions encountered
1403 nl(Out) << "// Function Declarations"; nl(Out);
1404 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1406 if (Function* Fun = dyn_cast<Function>(*I)) {
1407 if (!is_inline || Fun != F)
1408 printFunctionHead(Fun);
1412 // Print the global variable declarations for any variables encountered
1413 nl(Out) << "// Global Variable Declarations"; nl(Out);
1414 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1416 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1417 printVariableHead(F);
1420 // Print the constants found
1421 nl(Out) << "// Constant Definitions"; nl(Out);
1422 for (std::vector<Constant*>::iterator I = consts.begin(), E = consts.end();
1427 // Process the global variables definitions now that all the constants have
1428 // been emitted. These definitions just couple the gvars with their constant
1430 nl(Out) << "// Global Variable Definitions"; nl(Out);
1431 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1433 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1434 printVariableBody(GV);
1438 void CppWriter::printFunctionHead(const Function* F) {
1439 nl(Out) << "Function* " << getCppName(F);
1441 Out << " = mod->getFunction(\"";
1442 printEscapedString(F->getName());
1443 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1444 nl(Out) << "if (!" << getCppName(F) << ") {";
1445 nl(Out) << getCppName(F);
1447 Out<< " = new Function(";
1448 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1449 nl(Out) << "/*Linkage=*/";
1450 printLinkageType(F->getLinkage());
1452 nl(Out) << "/*Name=*/\"";
1453 printEscapedString(F->getName());
1454 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1457 Out << "->setCallingConv(";
1458 printCallingConv(F->getCallingConv());
1461 if (F->hasSection()) {
1463 Out << "->setSection(\"" << F->getSection() << "\");";
1466 if (F->getAlignment()) {
1468 Out << "->setAlignment(" << F->getAlignment() << ");";
1477 void CppWriter::printFunctionBody(const Function *F) {
1478 if (F->isDeclaration())
1479 return; // external functions have no bodies.
1481 // Clear the DefinedValues and ForwardRefs maps because we can't have
1482 // cross-function forward refs
1483 ForwardRefs.clear();
1484 DefinedValues.clear();
1486 // Create all the argument values
1488 if (!F->arg_empty()) {
1489 Out << "Function::arg_iterator args = " << getCppName(F)
1490 << "->arg_begin();";
1493 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1495 Out << "Value* " << getCppName(AI) << " = args++;";
1497 if (AI->hasName()) {
1498 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1504 // Create all the basic blocks
1506 for (Function::const_iterator BI = F->begin(), BE = F->end();
1508 std::string bbname(getCppName(BI));
1509 Out << "BasicBlock* " << bbname << " = new BasicBlock(\"";
1511 printEscapedString(BI->getName());
1512 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1516 // Output all of its basic blocks... for the function
1517 for (Function::const_iterator BI = F->begin(), BE = F->end();
1519 std::string bbname(getCppName(BI));
1520 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1523 // Output all of the instructions in the basic block...
1524 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1526 printInstruction(I,bbname);
1530 // Loop over the ForwardRefs and resolve them now that all instructions
1532 if (!ForwardRefs.empty()) {
1533 nl(Out) << "// Resolve Forward References";
1537 while (!ForwardRefs.empty()) {
1538 ForwardRefMap::iterator I = ForwardRefs.begin();
1539 Out << I->second << "->replaceAllUsesWith("
1540 << getCppName(I->first) << "); delete " << I->second << ";";
1542 ForwardRefs.erase(I);
1546 void CppWriter::printInline(const std::string& fname, const std::string& func) {
1547 const Function* F = TheModule->getNamedFunction(func);
1549 error(std::string("Function '") + func + "' not found in input module");
1552 if (F->isDeclaration()) {
1553 error(std::string("Function '") + func + "' is external!");
1556 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1558 unsigned arg_count = 1;
1559 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1561 Out << ", Value* arg_" << arg_count;
1566 printFunctionUses(F);
1567 printFunctionBody(F);
1569 Out << "return " << getCppName(F->begin()) << ";";
1574 void CppWriter::printModuleBody() {
1575 // Print out all the type definitions
1576 nl(Out) << "// Type Definitions"; nl(Out);
1577 printTypes(TheModule);
1579 // Functions can call each other and global variables can reference them so
1580 // define all the functions first before emitting their function bodies.
1581 nl(Out) << "// Function Declarations"; nl(Out);
1582 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1584 printFunctionHead(I);
1586 // Process the global variables declarations. We can't initialze them until
1587 // after the constants are printed so just print a header for each global
1588 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1589 for (Module::const_global_iterator I = TheModule->global_begin(),
1590 E = TheModule->global_end(); I != E; ++I) {
1591 printVariableHead(I);
1594 // Print out all the constants definitions. Constants don't recurse except
1595 // through GlobalValues. All GlobalValues have been declared at this point
1596 // so we can proceed to generate the constants.
1597 nl(Out) << "// Constant Definitions"; nl(Out);
1598 printConstants(TheModule);
1600 // Process the global variables definitions now that all the constants have
1601 // been emitted. These definitions just couple the gvars with their constant
1603 nl(Out) << "// Global Variable Definitions"; nl(Out);
1604 for (Module::const_global_iterator I = TheModule->global_begin(),
1605 E = TheModule->global_end(); I != E; ++I) {
1606 printVariableBody(I);
1609 // Finally, we can safely put out all of the function bodies.
1610 nl(Out) << "// Function Definitions"; nl(Out);
1611 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1613 if (!I->isDeclaration()) {
1614 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1618 printFunctionBody(I);
1625 void CppWriter::printProgram(
1626 const std::string& fname,
1627 const std::string& mName
1629 Out << "#include <llvm/Module.h>\n";
1630 Out << "#include <llvm/DerivedTypes.h>\n";
1631 Out << "#include <llvm/Constants.h>\n";
1632 Out << "#include <llvm/GlobalVariable.h>\n";
1633 Out << "#include <llvm/Function.h>\n";
1634 Out << "#include <llvm/CallingConv.h>\n";
1635 Out << "#include <llvm/BasicBlock.h>\n";
1636 Out << "#include <llvm/Instructions.h>\n";
1637 Out << "#include <llvm/InlineAsm.h>\n";
1638 Out << "#include <llvm/Support/MathExtras.h>\n";
1639 Out << "#include <llvm/Pass.h>\n";
1640 Out << "#include <llvm/PassManager.h>\n";
1641 Out << "#include <llvm/Analysis/Verifier.h>\n";
1642 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1643 Out << "#include <algorithm>\n";
1644 Out << "#include <iostream>\n\n";
1645 Out << "using namespace llvm;\n\n";
1646 Out << "Module* " << fname << "();\n\n";
1647 Out << "int main(int argc, char**argv) {\n";
1648 Out << " Module* Mod = makeLLVMModule();\n";
1649 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1650 Out << " std::cerr.flush();\n";
1651 Out << " std::cout.flush();\n";
1652 Out << " PassManager PM;\n";
1653 Out << " PM.add(new PrintModulePass(&std::cout));\n";
1654 Out << " PM.run(*Mod);\n";
1655 Out << " return 0;\n";
1657 printModule(fname,mName);
1660 void CppWriter::printModule(
1661 const std::string& fname,
1662 const std::string& mName
1664 nl(Out) << "Module* " << fname << "() {";
1665 nl(Out,1) << "// Module Construction";
1666 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1667 nl(Out) << "mod->setEndianness(";
1668 switch (TheModule->getEndianness()) {
1669 case Module::LittleEndian: Out << "Module::LittleEndian);"; break;
1670 case Module::BigEndian: Out << "Module::BigEndian);"; break;
1671 case Module::AnyEndianness:Out << "Module::AnyEndianness);"; break;
1673 nl(Out) << "mod->setPointerSize(";
1674 switch (TheModule->getPointerSize()) {
1675 case Module::Pointer32: Out << "Module::Pointer32);"; break;
1676 case Module::Pointer64: Out << "Module::Pointer64);"; break;
1677 case Module::AnyPointerSize: Out << "Module::AnyPointerSize);"; break;
1680 if (!TheModule->getTargetTriple().empty()) {
1681 Out << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1686 if (!TheModule->getModuleInlineAsm().empty()) {
1687 Out << "mod->setModuleInlineAsm(\"";
1688 printEscapedString(TheModule->getModuleInlineAsm());
1693 // Loop over the dependent libraries and emit them.
1694 Module::lib_iterator LI = TheModule->lib_begin();
1695 Module::lib_iterator LE = TheModule->lib_end();
1697 Out << "mod->addLibrary(\"" << *LI << "\");";
1702 nl(Out) << "return mod;";
1707 void CppWriter::printContents(
1708 const std::string& fname, // Name of generated function
1709 const std::string& mName // Name of module generated module
1711 Out << "\nModule* " << fname << "(Module *mod) {\n";
1712 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1714 Out << "\nreturn mod;\n";
1718 void CppWriter::printFunction(
1719 const std::string& fname, // Name of generated function
1720 const std::string& funcName // Name of function to generate
1722 const Function* F = TheModule->getNamedFunction(funcName);
1724 error(std::string("Function '") + funcName + "' not found in input module");
1727 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1728 printFunctionUses(F);
1729 printFunctionHead(F);
1730 printFunctionBody(F);
1731 Out << "return " << getCppName(F) << ";\n";
1735 void CppWriter::printVariable(
1736 const std::string& fname, /// Name of generated function
1737 const std::string& varName // Name of variable to generate
1739 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1742 error(std::string("Variable '") + varName + "' not found in input module");
1745 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1746 printVariableUses(GV);
1747 printVariableHead(GV);
1748 printVariableBody(GV);
1749 Out << "return " << getCppName(GV) << ";\n";
1753 void CppWriter::printType(
1754 const std::string& fname, /// Name of generated function
1755 const std::string& typeName // Name of type to generate
1757 const Type* Ty = TheModule->getTypeByName(typeName);
1759 error(std::string("Type '") + typeName + "' not found in input module");
1762 Out << "\nType* " << fname << "(Module *mod) {\n";
1764 Out << "return " << getCppName(Ty) << ";\n";
1768 } // end anonymous llvm
1772 void WriteModuleToCppFile(Module* mod, std::ostream& o) {
1773 // Initialize a CppWriter for us to use
1774 CppWriter W(o, mod);
1777 o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1779 // Get the name of the function we're supposed to generate
1780 std::string fname = FuncName.getValue();
1782 // Get the name of the thing we are to generate
1783 std::string tgtname = NameToGenerate.getValue();
1784 if (GenerationType == GenModule ||
1785 GenerationType == GenContents ||
1786 GenerationType == GenProgram) {
1787 if (tgtname == "!bad!") {
1788 if (mod->getModuleIdentifier() == "-")
1789 tgtname = "<stdin>";
1791 tgtname = mod->getModuleIdentifier();
1793 } else if (tgtname == "!bad!") {
1794 W.error("You must use the -for option with -gen-{function,variable,type}");
1797 switch (WhatToGenerate(GenerationType)) {
1800 fname = "makeLLVMModule";
1801 W.printProgram(fname,tgtname);
1805 fname = "makeLLVMModule";
1806 W.printModule(fname,tgtname);
1810 fname = "makeLLVMModuleContents";
1811 W.printContents(fname,tgtname);
1815 fname = "makeLLVMFunction";
1816 W.printFunction(fname,tgtname);
1820 fname = "makeLLVMInline";
1821 W.printInline(fname,tgtname);
1825 fname = "makeLLVMVariable";
1826 W.printVariable(fname,tgtname);
1830 fname = "makeLLVMType";
1831 W.printType(fname,tgtname);
1834 W.error("Invalid generation option");