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/TypeSymbolTable.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/CFG.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Config/config.h"
37 static cl::opt<std::string>
38 FuncName("funcname", cl::desc("Specify the name of the generated function"),
39 cl::value_desc("function name"));
51 static cl::opt<WhatToGenerate> GenerationType(cl::Optional,
52 cl::desc("Choose what kind of output to generate"),
55 clEnumValN(GenProgram, "gen-program", "Generate a complete program"),
56 clEnumValN(GenModule, "gen-module", "Generate a module definition"),
57 clEnumValN(GenContents,"gen-contents", "Generate contents of a module"),
58 clEnumValN(GenFunction,"gen-function", "Generate a function definition"),
59 clEnumValN(GenInline, "gen-inline", "Generate an inline function"),
60 clEnumValN(GenVariable,"gen-variable", "Generate a variable definition"),
61 clEnumValN(GenType, "gen-type", "Generate a type definition"),
66 static cl::opt<std::string> NameToGenerate("for", cl::Optional,
67 cl::desc("Specify the name of the thing to generate"),
71 typedef std::vector<const Type*> TypeList;
72 typedef std::map<const Type*,std::string> TypeMap;
73 typedef std::map<const Value*,std::string> ValueMap;
74 typedef std::set<std::string> NameSet;
75 typedef std::set<const Type*> TypeSet;
76 typedef std::set<const Value*> ValueSet;
77 typedef std::map<const Value*,std::string> ForwardRefMap;
82 const Module *TheModule;
86 TypeMap UnresolvedTypes;
90 ValueSet DefinedValues;
91 ForwardRefMap ForwardRefs;
95 inline CppWriter(std::ostream &o, const Module *M, const char* pn="llvm2cpp")
96 : progname(pn), Out(o), TheModule(M), uniqueNum(0), TypeNames(),
97 ValueNames(), UnresolvedTypes(), TypeStack(), is_inline(false) { }
99 const Module* getModule() { return TheModule; }
101 void printProgram(const std::string& fname, const std::string& modName );
102 void printModule(const std::string& fname, const std::string& modName );
103 void printContents(const std::string& fname, const std::string& modName );
104 void printFunction(const std::string& fname, const std::string& funcName );
105 void printInline(const std::string& fname, const std::string& funcName );
106 void printVariable(const std::string& fname, const std::string& varName );
107 void printType(const std::string& fname, const std::string& typeName );
109 void error(const std::string& msg);
112 void printLinkageType(GlobalValue::LinkageTypes LT);
113 void printCallingConv(unsigned cc);
114 void printEscapedString(const std::string& str);
115 void printCFP(const ConstantFP* CFP);
117 std::string getCppName(const Type* val);
118 inline void printCppName(const Type* val);
120 std::string getCppName(const Value* val);
121 inline void printCppName(const Value* val);
123 bool printTypeInternal(const Type* Ty);
124 inline void printType(const Type* Ty);
125 void printTypes(const Module* M);
127 void printConstant(const Constant *CPV);
128 void printConstants(const Module* M);
130 void printVariableUses(const GlobalVariable *GV);
131 void printVariableHead(const GlobalVariable *GV);
132 void printVariableBody(const GlobalVariable *GV);
134 void printFunctionUses(const Function *F);
135 void printFunctionHead(const Function *F);
136 void printFunctionBody(const Function *F);
137 void printInstruction(const Instruction *I, const std::string& bbname);
138 std::string getOpName(Value*);
140 void printModuleBody();
144 static unsigned indent_level = 0;
145 inline std::ostream& nl(std::ostream& Out, int delta = 0) {
147 if (delta >= 0 || indent_level >= unsigned(-delta))
148 indent_level += delta;
149 for (unsigned i = 0; i < indent_level; ++i)
154 inline void in() { indent_level++; }
155 inline void out() { if (indent_level >0) indent_level--; }
158 sanitize(std::string& str) {
159 for (size_t i = 0; i < str.length(); ++i)
160 if (!isalnum(str[i]) && str[i] != '_')
165 getTypePrefix(const Type* Ty ) {
166 switch (Ty->getTypeID()) {
167 case Type::VoidTyID: return "void_";
168 case Type::IntegerTyID:
169 return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
171 case Type::FloatTyID: return "float_";
172 case Type::DoubleTyID: return "double_";
173 case Type::LabelTyID: return "label_";
174 case Type::FunctionTyID: return "func_";
175 case Type::StructTyID: return "struct_";
176 case Type::ArrayTyID: return "array_";
177 case Type::PointerTyID: return "ptr_";
178 case Type::PackedTyID: return "packed_";
179 case Type::OpaqueTyID: return "opaque_";
180 default: return "other_";
185 // Looks up the type in the symbol table and returns a pointer to its name or
186 // a null pointer if it wasn't found. Note that this isn't the same as the
187 // Mode::getTypeName function which will return an empty string, not a null
188 // pointer if the name is not found.
189 inline const std::string*
190 findTypeName(const TypeSymbolTable& ST, const Type* Ty)
192 TypeSymbolTable::const_iterator TI = ST.begin();
193 TypeSymbolTable::const_iterator TE = ST.end();
194 for (;TI != TE; ++TI)
195 if (TI->second == Ty)
201 CppWriter::error(const std::string& msg) {
202 std::cerr << progname << ": " << msg << "\n";
206 // printCFP - Print a floating point constant .. very carefully :)
207 // This makes sure that conversion to/from floating yields the same binary
208 // result so that we don't lose precision.
210 CppWriter::printCFP(const ConstantFP *CFP) {
211 Out << "ConstantFP::get(";
212 if (CFP->getType() == Type::DoubleTy)
213 Out << "Type::DoubleTy, ";
215 Out << "Type::FloatTy, ";
218 sprintf(Buffer, "%A", CFP->getValue());
219 if ((!strncmp(Buffer, "0x", 2) ||
220 !strncmp(Buffer, "-0x", 3) ||
221 !strncmp(Buffer, "+0x", 3)) &&
222 (atof(Buffer) == CFP->getValue()))
223 if (CFP->getType() == Type::DoubleTy)
224 Out << "BitsToDouble(" << Buffer << ")";
226 Out << "BitsToFloat(" << Buffer << ")";
229 std::string StrVal = ftostr(CFP->getValue());
231 while (StrVal[0] == ' ')
232 StrVal.erase(StrVal.begin());
234 // Check to make sure that the stringized number is not some string like
235 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
236 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
237 ((StrVal[0] == '-' || StrVal[0] == '+') &&
238 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
239 (atof(StrVal.c_str()) == CFP->getValue()))
240 if (CFP->getType() == Type::DoubleTy)
244 else if (CFP->getType() == Type::DoubleTy)
245 Out << "BitsToDouble(0x" << std::hex << DoubleToBits(CFP->getValue())
246 << std::dec << "ULL) /* " << StrVal << " */";
248 Out << "BitsToFloat(0x" << std::hex << FloatToBits(CFP->getValue())
249 << std::dec << "U) /* " << StrVal << " */";
257 CppWriter::printCallingConv(unsigned cc){
258 // Print the calling convention.
260 case CallingConv::C: Out << "CallingConv::C"; break;
261 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
262 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
263 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
264 default: Out << cc; break;
269 CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
271 case GlobalValue::InternalLinkage:
272 Out << "GlobalValue::InternalLinkage"; break;
273 case GlobalValue::LinkOnceLinkage:
274 Out << "GlobalValue::LinkOnceLinkage "; break;
275 case GlobalValue::WeakLinkage:
276 Out << "GlobalValue::WeakLinkage"; break;
277 case GlobalValue::AppendingLinkage:
278 Out << "GlobalValue::AppendingLinkage"; break;
279 case GlobalValue::ExternalLinkage:
280 Out << "GlobalValue::ExternalLinkage"; break;
281 case GlobalValue::DLLImportLinkage:
282 Out << "GlobalValue::DllImportLinkage"; break;
283 case GlobalValue::DLLExportLinkage:
284 Out << "GlobalValue::DllExportLinkage"; break;
285 case GlobalValue::ExternalWeakLinkage:
286 Out << "GlobalValue::ExternalWeakLinkage"; break;
287 case GlobalValue::GhostLinkage:
288 Out << "GlobalValue::GhostLinkage"; break;
292 // printEscapedString - Print each character of the specified string, escaping
293 // it if it is not printable or if it is an escape char.
295 CppWriter::printEscapedString(const std::string &Str) {
296 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
297 unsigned char C = Str[i];
298 if (isprint(C) && C != '"' && C != '\\') {
302 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
303 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
309 CppWriter::getCppName(const Type* Ty)
311 // First, handle the primitive types .. easy
312 if (Ty->isPrimitiveType() || Ty->isInteger()) {
313 switch (Ty->getTypeID()) {
314 case Type::VoidTyID: return "Type::VoidTy";
315 case Type::IntegerTyID: {
316 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
317 return "IntegerType::get(" + utostr(BitWidth) + ")";
319 case Type::FloatTyID: return "Type::FloatTy";
320 case Type::DoubleTyID: return "Type::DoubleTy";
321 case Type::LabelTyID: return "Type::LabelTy";
323 error("Invalid primitive type");
326 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
329 // Now, see if we've seen the type before and return that
330 TypeMap::iterator I = TypeNames.find(Ty);
331 if (I != TypeNames.end())
334 // Okay, let's build a new name for this type. Start with a prefix
335 const char* prefix = 0;
336 switch (Ty->getTypeID()) {
337 case Type::FunctionTyID: prefix = "FuncTy_"; break;
338 case Type::StructTyID: prefix = "StructTy_"; break;
339 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
340 case Type::PointerTyID: prefix = "PointerTy_"; break;
341 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
342 case Type::PackedTyID: prefix = "PackedTy_"; break;
343 default: prefix = "OtherTy_"; break; // prevent breakage
346 // See if the type has a name in the symboltable and build accordingly
347 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
350 name = std::string(prefix) + *tName;
352 name = std::string(prefix) + utostr(uniqueNum++);
356 return TypeNames[Ty] = name;
360 CppWriter::printCppName(const Type* Ty)
362 printEscapedString(getCppName(Ty));
366 CppWriter::getCppName(const Value* val) {
368 ValueMap::iterator I = ValueNames.find(val);
369 if (I != ValueNames.end() && I->first == val)
372 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
373 name = std::string("gvar_") +
374 getTypePrefix(GV->getType()->getElementType());
375 } else if (isa<Function>(val)) {
376 name = std::string("func_");
377 } else if (const Constant* C = dyn_cast<Constant>(val)) {
378 name = std::string("const_") + getTypePrefix(C->getType());
379 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
381 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
382 Function::const_arg_iterator(Arg)) + 1;
383 name = std::string("arg_") + utostr(argNum);
384 NameSet::iterator NI = UsedNames.find(name);
385 if (NI != UsedNames.end())
386 name += std::string("_") + utostr(uniqueNum++);
387 UsedNames.insert(name);
388 return ValueNames[val] = name;
390 name = getTypePrefix(val->getType());
393 name = getTypePrefix(val->getType());
395 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
397 NameSet::iterator NI = UsedNames.find(name);
398 if (NI != UsedNames.end())
399 name += std::string("_") + utostr(uniqueNum++);
400 UsedNames.insert(name);
401 return ValueNames[val] = name;
405 CppWriter::printCppName(const Value* val) {
406 printEscapedString(getCppName(val));
410 CppWriter::printTypeInternal(const Type* Ty) {
411 // We don't print definitions for primitive types
412 if (Ty->isPrimitiveType() || Ty->isInteger())
415 // If we already defined this type, we don't need to define it again.
416 if (DefinedTypes.find(Ty) != DefinedTypes.end())
419 // Everything below needs the name for the type so get it now.
420 std::string typeName(getCppName(Ty));
422 // Search the type stack for recursion. If we find it, then generate this
423 // as an OpaqueType, but make sure not to do this multiple times because
424 // the type could appear in multiple places on the stack. Once the opaque
425 // definition is issued, it must not be re-issued. Consequently we have to
426 // check the UnresolvedTypes list as well.
427 TypeList::const_iterator TI = std::find(TypeStack.begin(),TypeStack.end(),Ty);
428 if (TI != TypeStack.end()) {
429 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
430 if (I == UnresolvedTypes.end()) {
431 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
433 UnresolvedTypes[Ty] = typeName;
438 // We're going to print a derived type which, by definition, contains other
439 // types. So, push this one we're printing onto the type stack to assist with
440 // recursive definitions.
441 TypeStack.push_back(Ty);
443 // Print the type definition
444 switch (Ty->getTypeID()) {
445 case Type::FunctionTyID: {
446 const FunctionType* FT = cast<FunctionType>(Ty);
447 Out << "std::vector<const Type*>" << typeName << "_args;";
449 FunctionType::param_iterator PI = FT->param_begin();
450 FunctionType::param_iterator PE = FT->param_end();
451 for (; PI != PE; ++PI) {
452 const Type* argTy = static_cast<const Type*>(*PI);
453 bool isForward = printTypeInternal(argTy);
454 std::string argName(getCppName(argTy));
455 Out << typeName << "_args.push_back(" << argName;
461 bool isForward = printTypeInternal(FT->getReturnType());
462 std::string retTypeName(getCppName(FT->getReturnType()));
463 Out << "FunctionType* " << typeName << " = FunctionType::get(";
464 in(); nl(Out) << "/*Result=*/" << retTypeName;
468 nl(Out) << "/*Params=*/" << typeName << "_args,";
469 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
474 case Type::StructTyID: {
475 const StructType* ST = cast<StructType>(Ty);
476 Out << "std::vector<const Type*>" << typeName << "_fields;";
478 StructType::element_iterator EI = ST->element_begin();
479 StructType::element_iterator EE = ST->element_end();
480 for (; EI != EE; ++EI) {
481 const Type* fieldTy = static_cast<const Type*>(*EI);
482 bool isForward = printTypeInternal(fieldTy);
483 std::string fieldName(getCppName(fieldTy));
484 Out << typeName << "_fields.push_back(" << fieldName;
490 Out << "StructType* " << typeName << " = StructType::get("
491 << typeName << "_fields);";
495 case Type::ArrayTyID: {
496 const ArrayType* AT = cast<ArrayType>(Ty);
497 const Type* ET = AT->getElementType();
498 bool isForward = printTypeInternal(ET);
499 std::string elemName(getCppName(ET));
500 Out << "ArrayType* " << typeName << " = ArrayType::get("
501 << elemName << (isForward ? "_fwd" : "")
502 << ", " << utostr(AT->getNumElements()) << ");";
506 case Type::PointerTyID: {
507 const PointerType* PT = cast<PointerType>(Ty);
508 const Type* ET = PT->getElementType();
509 bool isForward = printTypeInternal(ET);
510 std::string elemName(getCppName(ET));
511 Out << "PointerType* " << typeName << " = PointerType::get("
512 << elemName << (isForward ? "_fwd" : "") << ");";
516 case Type::PackedTyID: {
517 const PackedType* PT = cast<PackedType>(Ty);
518 const Type* ET = PT->getElementType();
519 bool isForward = printTypeInternal(ET);
520 std::string elemName(getCppName(ET));
521 Out << "PackedType* " << typeName << " = PackedType::get("
522 << elemName << (isForward ? "_fwd" : "")
523 << ", " << utostr(PT->getNumElements()) << ");";
527 case Type::OpaqueTyID: {
528 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
533 error("Invalid TypeID");
536 // If the type had a name, make sure we recreate it.
537 const std::string* progTypeName =
538 findTypeName(TheModule->getTypeSymbolTable(),Ty);
540 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
544 // Pop us off the type stack
545 TypeStack.pop_back();
547 // Indicate that this type is now defined.
548 DefinedTypes.insert(Ty);
550 // Early resolve as many unresolved types as possible. Search the unresolved
551 // types map for the type we just printed. Now that its definition is complete
552 // we can resolve any previous references to it. This prevents a cascade of
554 TypeMap::iterator I = UnresolvedTypes.find(Ty);
555 if (I != UnresolvedTypes.end()) {
556 Out << "cast<OpaqueType>(" << I->second
557 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
559 Out << I->second << " = cast<";
560 switch (Ty->getTypeID()) {
561 case Type::FunctionTyID: Out << "FunctionType"; break;
562 case Type::ArrayTyID: Out << "ArrayType"; break;
563 case Type::StructTyID: Out << "StructType"; break;
564 case Type::PackedTyID: Out << "PackedType"; break;
565 case Type::PointerTyID: Out << "PointerType"; break;
566 case Type::OpaqueTyID: Out << "OpaqueType"; break;
567 default: Out << "NoSuchDerivedType"; break;
569 Out << ">(" << I->second << "_fwd.get());";
571 UnresolvedTypes.erase(I);
574 // Finally, separate the type definition from other with a newline.
577 // We weren't a recursive type
581 // Prints a type definition. Returns true if it could not resolve all the types
582 // in the definition but had to use a forward reference.
584 CppWriter::printType(const Type* Ty) {
585 assert(TypeStack.empty());
587 printTypeInternal(Ty);
588 assert(TypeStack.empty());
592 CppWriter::printTypes(const Module* M) {
594 // Walk the symbol table and print out all its types
595 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
596 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
599 // For primitive types and types already defined, just add a name
600 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
601 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
602 TNI != TypeNames.end()) {
603 Out << "mod->addTypeName(\"";
604 printEscapedString(TI->first);
605 Out << "\", " << getCppName(TI->second) << ");";
607 // For everything else, define the type
609 printType(TI->second);
613 // Add all of the global variables to the value table...
614 for (Module::const_global_iterator I = TheModule->global_begin(),
615 E = TheModule->global_end(); I != E; ++I) {
616 if (I->hasInitializer())
617 printType(I->getInitializer()->getType());
618 printType(I->getType());
621 // Add all the functions to the table
622 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
624 printType(FI->getReturnType());
625 printType(FI->getFunctionType());
626 // Add all the function arguments
627 for(Function::const_arg_iterator AI = FI->arg_begin(),
628 AE = FI->arg_end(); AI != AE; ++AI) {
629 printType(AI->getType());
632 // Add all of the basic blocks and instructions
633 for (Function::const_iterator BB = FI->begin(),
634 E = FI->end(); BB != E; ++BB) {
635 printType(BB->getType());
636 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
638 printType(I->getType());
639 for (unsigned i = 0; i < I->getNumOperands(); ++i)
640 printType(I->getOperand(i)->getType());
647 // printConstant - Print out a constant pool entry...
648 void CppWriter::printConstant(const Constant *CV) {
649 // First, if the constant is actually a GlobalValue (variable or function) or
650 // its already in the constant list then we've printed it already and we can
652 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
655 std::string constName(getCppName(CV));
656 std::string typeName(getCppName(CV->getType()));
657 if (CV->isNullValue()) {
658 Out << "Constant* " << constName << " = Constant::getNullValue("
663 if (isa<GlobalValue>(CV)) {
664 // Skip variables and functions, we emit them elsewhere
667 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
668 Out << "ConstantInt* " << constName << " = ConstantInt::get("
669 << typeName << ", " << CI->getZExtValue() << ");";
670 } else if (isa<ConstantAggregateZero>(CV)) {
671 Out << "ConstantAggregateZero* " << constName
672 << " = ConstantAggregateZero::get(" << typeName << ");";
673 } else if (isa<ConstantPointerNull>(CV)) {
674 Out << "ConstantPointerNull* " << constName
675 << " = ConstanPointerNull::get(" << typeName << ");";
676 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
677 Out << "ConstantFP* " << constName << " = ";
680 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
681 if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
682 Out << "Constant* " << constName << " = ConstantArray::get(\"";
683 printEscapedString(CA->getAsString());
684 // Determine if we want null termination or not.
685 if (CA->getType()->getNumElements() <= CA->getAsString().length())
686 Out << "\", false";// No null terminator
688 Out << "\", true"; // Indicate that the null terminator should be added.
691 Out << "std::vector<Constant*> " << constName << "_elems;";
693 unsigned N = CA->getNumOperands();
694 for (unsigned i = 0; i < N; ++i) {
695 printConstant(CA->getOperand(i)); // recurse to print operands
696 Out << constName << "_elems.push_back("
697 << getCppName(CA->getOperand(i)) << ");";
700 Out << "Constant* " << constName << " = ConstantArray::get("
701 << typeName << ", " << constName << "_elems);";
703 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
704 Out << "std::vector<Constant*> " << constName << "_fields;";
706 unsigned N = CS->getNumOperands();
707 for (unsigned i = 0; i < N; i++) {
708 printConstant(CS->getOperand(i));
709 Out << constName << "_fields.push_back("
710 << getCppName(CS->getOperand(i)) << ");";
713 Out << "Constant* " << constName << " = ConstantStruct::get("
714 << typeName << ", " << constName << "_fields);";
715 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
716 Out << "std::vector<Constant*> " << constName << "_elems;";
718 unsigned N = CP->getNumOperands();
719 for (unsigned i = 0; i < N; ++i) {
720 printConstant(CP->getOperand(i));
721 Out << constName << "_elems.push_back("
722 << getCppName(CP->getOperand(i)) << ");";
725 Out << "Constant* " << constName << " = ConstantPacked::get("
726 << typeName << ", " << constName << "_elems);";
727 } else if (isa<UndefValue>(CV)) {
728 Out << "UndefValue* " << constName << " = UndefValue::get("
730 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
731 if (CE->getOpcode() == Instruction::GetElementPtr) {
732 Out << "std::vector<Constant*> " << constName << "_indices;";
734 printConstant(CE->getOperand(0));
735 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
736 printConstant(CE->getOperand(i));
737 Out << constName << "_indices.push_back("
738 << getCppName(CE->getOperand(i)) << ");";
741 Out << "Constant* " << constName
742 << " = ConstantExpr::getGetElementPtr("
743 << getCppName(CE->getOperand(0)) << ", "
744 << constName << "_indices);";
745 } else if (CE->isCast()) {
746 printConstant(CE->getOperand(0));
747 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
748 switch (CE->getOpcode()) {
749 default: assert(0 && "Invalid cast opcode");
750 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
751 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
752 case Instruction::SExt: Out << "Instruction::SExt"; break;
753 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
754 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
755 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
756 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
757 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
758 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
759 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
760 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
761 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
763 Out << ", " << getCppName(CE->getOperand(0)) << ", "
764 << getCppName(CE->getType()) << ");";
766 unsigned N = CE->getNumOperands();
767 for (unsigned i = 0; i < N; ++i ) {
768 printConstant(CE->getOperand(i));
770 Out << "Constant* " << constName << " = ConstantExpr::";
771 switch (CE->getOpcode()) {
772 case Instruction::Add: Out << "getAdd("; break;
773 case Instruction::Sub: Out << "getSub("; break;
774 case Instruction::Mul: Out << "getMul("; break;
775 case Instruction::UDiv: Out << "getUDiv("; break;
776 case Instruction::SDiv: Out << "getSDiv("; break;
777 case Instruction::FDiv: Out << "getFDiv("; break;
778 case Instruction::URem: Out << "getURem("; break;
779 case Instruction::SRem: Out << "getSRem("; break;
780 case Instruction::FRem: Out << "getFRem("; break;
781 case Instruction::And: Out << "getAnd("; break;
782 case Instruction::Or: Out << "getOr("; break;
783 case Instruction::Xor: Out << "getXor("; break;
784 case Instruction::ICmp:
785 Out << "getICmp(ICmpInst::ICMP_";
786 switch (CE->getPredicate()) {
787 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
788 case ICmpInst::ICMP_NE: Out << "NE"; break;
789 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
790 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
791 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
792 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
793 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
794 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
795 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
796 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
797 default: error("Invalid ICmp Predicate");
800 case Instruction::FCmp:
801 Out << "getFCmp(FCmpInst::FCMP_";
802 switch (CE->getPredicate()) {
803 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
804 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
805 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
806 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
807 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
808 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
809 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
810 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
811 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
812 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
813 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
814 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
815 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
816 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
817 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
818 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
819 default: error("Invalid FCmp Predicate");
822 case Instruction::Shl: Out << "getShl("; break;
823 case Instruction::LShr: Out << "getLShr("; break;
824 case Instruction::AShr: Out << "getAShr("; break;
825 case Instruction::Select: Out << "getSelect("; break;
826 case Instruction::ExtractElement: Out << "getExtractElement("; break;
827 case Instruction::InsertElement: Out << "getInsertElement("; break;
828 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
830 error("Invalid constant expression");
833 Out << getCppName(CE->getOperand(0));
834 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
835 Out << ", " << getCppName(CE->getOperand(i));
839 error("Bad Constant");
840 Out << "Constant* " << constName << " = 0; ";
846 CppWriter::printConstants(const Module* M) {
847 // Traverse all the global variables looking for constant initializers
848 for (Module::const_global_iterator I = TheModule->global_begin(),
849 E = TheModule->global_end(); I != E; ++I)
850 if (I->hasInitializer())
851 printConstant(I->getInitializer());
853 // Traverse the LLVM functions looking for constants
854 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
856 // Add all of the basic blocks and instructions
857 for (Function::const_iterator BB = FI->begin(),
858 E = FI->end(); BB != E; ++BB) {
859 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
861 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
862 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
871 void CppWriter::printVariableUses(const GlobalVariable *GV) {
872 nl(Out) << "// Type Definitions";
874 printType(GV->getType());
875 if (GV->hasInitializer()) {
876 Constant* Init = GV->getInitializer();
877 printType(Init->getType());
878 if (Function* F = dyn_cast<Function>(Init)) {
879 nl(Out)<< "/ Function Declarations"; nl(Out);
880 printFunctionHead(F);
881 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
882 nl(Out) << "// Global Variable Declarations"; nl(Out);
883 printVariableHead(gv);
885 nl(Out) << "// Constant Definitions"; nl(Out);
888 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
889 nl(Out) << "// Global Variable Definitions"; nl(Out);
890 printVariableBody(gv);
895 void CppWriter::printVariableHead(const GlobalVariable *GV) {
896 nl(Out) << "GlobalVariable* " << getCppName(GV);
898 Out << " = mod->getGlobalVariable(";
899 printEscapedString(GV->getName());
900 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
901 nl(Out) << "if (!" << getCppName(GV) << ") {";
902 in(); nl(Out) << getCppName(GV);
904 Out << " = new GlobalVariable(";
905 nl(Out) << "/*Type=*/";
906 printCppName(GV->getType()->getElementType());
908 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
910 nl(Out) << "/*Linkage=*/";
911 printLinkageType(GV->getLinkage());
913 nl(Out) << "/*Initializer=*/0, ";
914 if (GV->hasInitializer()) {
915 Out << "// has initializer, specified below";
917 nl(Out) << "/*Name=*/\"";
918 printEscapedString(GV->getName());
923 if (GV->hasSection()) {
925 Out << "->setSection(\"";
926 printEscapedString(GV->getSection());
930 if (GV->getAlignment()) {
932 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
936 out(); Out << "}"; nl(Out);
941 CppWriter::printVariableBody(const GlobalVariable *GV) {
942 if (GV->hasInitializer()) {
944 Out << "->setInitializer(";
945 //if (!isa<GlobalValue(GV->getInitializer()))
947 Out << getCppName(GV->getInitializer()) << ");";
953 CppWriter::getOpName(Value* V) {
954 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
955 return getCppName(V);
957 // See if its alread in the map of forward references, if so just return the
958 // name we already set up for it
959 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
960 if (I != ForwardRefs.end())
963 // This is a new forward reference. Generate a unique name for it
964 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
966 // Yes, this is a hack. An Argument is the smallest instantiable value that
967 // we can make as a placeholder for the real value. We'll replace these
968 // Argument instances later.
969 Out << "Argument* " << result << " = new Argument("
970 << getCppName(V->getType()) << ");";
972 ForwardRefs[V] = result;
976 // printInstruction - This member is called for each Instruction in a function.
978 CppWriter::printInstruction(const Instruction *I, const std::string& bbname) {
979 std::string iName(getCppName(I));
981 // Before we emit this instruction, we need to take care of generating any
982 // forward references. So, we get the names of all the operands in advance
983 std::string* opNames = new std::string[I->getNumOperands()];
984 for (unsigned i = 0; i < I->getNumOperands(); i++) {
985 opNames[i] = getOpName(I->getOperand(i));
988 switch (I->getOpcode()) {
989 case Instruction::Ret: {
990 const ReturnInst* ret = cast<ReturnInst>(I);
991 Out << "ReturnInst* " << iName << " = new ReturnInst("
992 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
995 case Instruction::Br: {
996 const BranchInst* br = cast<BranchInst>(I);
997 Out << "BranchInst* " << iName << " = new BranchInst(" ;
998 if (br->getNumOperands() == 3 ) {
999 Out << opNames[0] << ", "
1000 << opNames[1] << ", "
1001 << opNames[2] << ", ";
1003 } else if (br->getNumOperands() == 1) {
1004 Out << opNames[0] << ", ";
1006 error("Branch with 2 operands?");
1008 Out << bbname << ");";
1011 case Instruction::Switch: {
1012 const SwitchInst* sw = cast<SwitchInst>(I);
1013 Out << "SwitchInst* " << iName << " = new SwitchInst("
1014 << opNames[0] << ", "
1015 << opNames[1] << ", "
1016 << sw->getNumCases() << ", " << bbname << ");";
1018 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1019 Out << iName << "->addCase("
1020 << opNames[i] << ", "
1021 << opNames[i+1] << ");";
1026 case Instruction::Invoke: {
1027 const InvokeInst* inv = cast<InvokeInst>(I);
1028 Out << "std::vector<Value*> " << iName << "_params;";
1030 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1031 Out << iName << "_params.push_back("
1032 << opNames[i] << ");";
1035 Out << "InvokeInst* " << iName << " = new InvokeInst("
1036 << opNames[0] << ", "
1037 << opNames[1] << ", "
1038 << opNames[2] << ", "
1039 << iName << "_params, \"";
1040 printEscapedString(inv->getName());
1041 Out << "\", " << bbname << ");";
1042 nl(Out) << iName << "->setCallingConv(";
1043 printCallingConv(inv->getCallingConv());
1047 case Instruction::Unwind: {
1048 Out << "UnwindInst* " << iName << " = new UnwindInst("
1052 case Instruction::Unreachable:{
1053 Out << "UnreachableInst* " << iName << " = new UnreachableInst("
1057 case Instruction::Add:
1058 case Instruction::Sub:
1059 case Instruction::Mul:
1060 case Instruction::UDiv:
1061 case Instruction::SDiv:
1062 case Instruction::FDiv:
1063 case Instruction::URem:
1064 case Instruction::SRem:
1065 case Instruction::FRem:
1066 case Instruction::And:
1067 case Instruction::Or:
1068 case Instruction::Xor:
1069 case Instruction::Shl:
1070 case Instruction::LShr:
1071 case Instruction::AShr:{
1072 Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
1073 switch (I->getOpcode()) {
1074 case Instruction::Add: Out << "Instruction::Add"; break;
1075 case Instruction::Sub: Out << "Instruction::Sub"; break;
1076 case Instruction::Mul: Out << "Instruction::Mul"; break;
1077 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1078 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1079 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1080 case Instruction::URem:Out << "Instruction::URem"; break;
1081 case Instruction::SRem:Out << "Instruction::SRem"; break;
1082 case Instruction::FRem:Out << "Instruction::FRem"; break;
1083 case Instruction::And: Out << "Instruction::And"; break;
1084 case Instruction::Or: Out << "Instruction::Or"; break;
1085 case Instruction::Xor: Out << "Instruction::Xor"; break;
1086 case Instruction::Shl: Out << "Instruction::Shl"; break;
1087 case Instruction::LShr:Out << "Instruction::LShr"; break;
1088 case Instruction::AShr:Out << "Instruction::AShr"; break;
1089 default: Out << "Instruction::BadOpCode"; break;
1091 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1092 printEscapedString(I->getName());
1093 Out << "\", " << bbname << ");";
1096 case Instruction::FCmp: {
1097 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1098 switch (cast<FCmpInst>(I)->getPredicate()) {
1099 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1100 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1101 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1102 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1103 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1104 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1105 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1106 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1107 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1108 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1109 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1110 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1111 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1112 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1113 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1114 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1115 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1117 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1118 printEscapedString(I->getName());
1119 Out << "\", " << bbname << ");";
1122 case Instruction::ICmp: {
1123 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1124 switch (cast<ICmpInst>(I)->getPredicate()) {
1125 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1126 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1127 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1128 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1129 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1130 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1131 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1132 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1133 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1134 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1135 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1137 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1138 printEscapedString(I->getName());
1139 Out << "\", " << bbname << ");";
1142 case Instruction::Malloc: {
1143 const MallocInst* mallocI = cast<MallocInst>(I);
1144 Out << "MallocInst* " << iName << " = new MallocInst("
1145 << getCppName(mallocI->getAllocatedType()) << ", ";
1146 if (mallocI->isArrayAllocation())
1147 Out << opNames[0] << ", " ;
1149 printEscapedString(mallocI->getName());
1150 Out << "\", " << bbname << ");";
1151 if (mallocI->getAlignment())
1152 nl(Out) << iName << "->setAlignment("
1153 << mallocI->getAlignment() << ");";
1156 case Instruction::Free: {
1157 Out << "FreeInst* " << iName << " = new FreeInst("
1158 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1161 case Instruction::Alloca: {
1162 const AllocaInst* allocaI = cast<AllocaInst>(I);
1163 Out << "AllocaInst* " << iName << " = new AllocaInst("
1164 << getCppName(allocaI->getAllocatedType()) << ", ";
1165 if (allocaI->isArrayAllocation())
1166 Out << opNames[0] << ", ";
1168 printEscapedString(allocaI->getName());
1169 Out << "\", " << bbname << ");";
1170 if (allocaI->getAlignment())
1171 nl(Out) << iName << "->setAlignment("
1172 << allocaI->getAlignment() << ");";
1175 case Instruction::Load:{
1176 const LoadInst* load = cast<LoadInst>(I);
1177 Out << "LoadInst* " << iName << " = new LoadInst("
1178 << opNames[0] << ", \"";
1179 printEscapedString(load->getName());
1180 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1181 << ", " << bbname << ");";
1184 case Instruction::Store: {
1185 const StoreInst* store = cast<StoreInst>(I);
1186 Out << "StoreInst* " << iName << " = new StoreInst("
1187 << opNames[0] << ", "
1188 << opNames[1] << ", "
1189 << (store->isVolatile() ? "true" : "false")
1190 << ", " << bbname << ");";
1193 case Instruction::GetElementPtr: {
1194 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1195 if (gep->getNumOperands() <= 2) {
1196 Out << "GetElementPtrInst* " << iName << " = new GetElementPtrInst("
1198 if (gep->getNumOperands() == 2)
1199 Out << ", " << opNames[1];
1201 Out << "std::vector<Value*> " << iName << "_indices;";
1203 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1204 Out << iName << "_indices.push_back("
1205 << opNames[i] << ");";
1208 Out << "Instruction* " << iName << " = new GetElementPtrInst("
1209 << opNames[0] << ", " << iName << "_indices";
1212 printEscapedString(gep->getName());
1213 Out << "\", " << bbname << ");";
1216 case Instruction::PHI: {
1217 const PHINode* phi = cast<PHINode>(I);
1219 Out << "PHINode* " << iName << " = new PHINode("
1220 << getCppName(phi->getType()) << ", \"";
1221 printEscapedString(phi->getName());
1222 Out << "\", " << bbname << ");";
1223 nl(Out) << iName << "->reserveOperandSpace("
1224 << phi->getNumIncomingValues()
1227 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1228 Out << iName << "->addIncoming("
1229 << opNames[i] << ", " << opNames[i+1] << ");";
1234 case Instruction::Trunc:
1235 case Instruction::ZExt:
1236 case Instruction::SExt:
1237 case Instruction::FPTrunc:
1238 case Instruction::FPExt:
1239 case Instruction::FPToUI:
1240 case Instruction::FPToSI:
1241 case Instruction::UIToFP:
1242 case Instruction::SIToFP:
1243 case Instruction::PtrToInt:
1244 case Instruction::IntToPtr:
1245 case Instruction::BitCast: {
1246 const CastInst* cst = cast<CastInst>(I);
1247 Out << "CastInst* " << iName << " = new ";
1248 switch (I->getOpcode()) {
1249 case Instruction::Trunc: Out << "TruncInst";
1250 case Instruction::ZExt: Out << "ZExtInst";
1251 case Instruction::SExt: Out << "SExtInst";
1252 case Instruction::FPTrunc: Out << "FPTruncInst";
1253 case Instruction::FPExt: Out << "FPExtInst";
1254 case Instruction::FPToUI: Out << "FPToUIInst";
1255 case Instruction::FPToSI: Out << "FPToSIInst";
1256 case Instruction::UIToFP: Out << "UIToFPInst";
1257 case Instruction::SIToFP: Out << "SIToFPInst";
1258 case Instruction::PtrToInt: Out << "PtrToInst";
1259 case Instruction::IntToPtr: Out << "IntToPtrInst";
1260 case Instruction::BitCast: Out << "BitCastInst";
1261 default: assert(!"Unreachable"); break;
1263 Out << "(" << opNames[0] << ", "
1264 << getCppName(cst->getType()) << ", \"";
1265 printEscapedString(cst->getName());
1266 Out << "\", " << bbname << ");";
1269 case Instruction::Call:{
1270 const CallInst* call = cast<CallInst>(I);
1271 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1272 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1273 << getCppName(ila->getFunctionType()) << ", \""
1274 << ila->getAsmString() << "\", \""
1275 << ila->getConstraintString() << "\","
1276 << (ila->hasSideEffects() ? "true" : "false") << ");";
1279 if (call->getNumOperands() > 3) {
1280 Out << "std::vector<Value*> " << iName << "_params;";
1282 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1283 Out << iName << "_params.push_back(" << opNames[i] << ");";
1286 Out << "CallInst* " << iName << " = new CallInst("
1287 << opNames[0] << ", " << iName << "_params, \"";
1288 } else if (call->getNumOperands() == 3) {
1289 Out << "CallInst* " << iName << " = new CallInst("
1290 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1291 } else if (call->getNumOperands() == 2) {
1292 Out << "CallInst* " << iName << " = new CallInst("
1293 << opNames[0] << ", " << opNames[1] << ", \"";
1295 Out << "CallInst* " << iName << " = new CallInst(" << opNames[0]
1298 printEscapedString(call->getName());
1299 Out << "\", " << bbname << ");";
1300 nl(Out) << iName << "->setCallingConv(";
1301 printCallingConv(call->getCallingConv());
1303 nl(Out) << iName << "->setTailCall("
1304 << (call->isTailCall() ? "true":"false");
1308 case Instruction::Select: {
1309 const SelectInst* sel = cast<SelectInst>(I);
1310 Out << "SelectInst* " << getCppName(sel) << " = new SelectInst(";
1311 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1312 printEscapedString(sel->getName());
1313 Out << "\", " << bbname << ");";
1316 case Instruction::UserOp1:
1318 case Instruction::UserOp2: {
1319 /// FIXME: What should be done here?
1322 case Instruction::VAArg: {
1323 const VAArgInst* va = cast<VAArgInst>(I);
1324 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1325 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1326 printEscapedString(va->getName());
1327 Out << "\", " << bbname << ");";
1330 case Instruction::ExtractElement: {
1331 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1332 Out << "ExtractElementInst* " << getCppName(eei)
1333 << " = new ExtractElementInst(" << opNames[0]
1334 << ", " << opNames[1] << ", \"";
1335 printEscapedString(eei->getName());
1336 Out << "\", " << bbname << ");";
1339 case Instruction::InsertElement: {
1340 const InsertElementInst* iei = cast<InsertElementInst>(I);
1341 Out << "InsertElementInst* " << getCppName(iei)
1342 << " = new InsertElementInst(" << opNames[0]
1343 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1344 printEscapedString(iei->getName());
1345 Out << "\", " << bbname << ");";
1348 case Instruction::ShuffleVector: {
1349 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1350 Out << "ShuffleVectorInst* " << getCppName(svi)
1351 << " = new ShuffleVectorInst(" << opNames[0]
1352 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1353 printEscapedString(svi->getName());
1354 Out << "\", " << bbname << ");";
1358 DefinedValues.insert(I);
1363 // Print out the types, constants and declarations needed by one function
1364 void CppWriter::printFunctionUses(const Function* F) {
1366 nl(Out) << "// Type Definitions"; nl(Out);
1368 // Print the function's return type
1369 printType(F->getReturnType());
1371 // Print the function's function type
1372 printType(F->getFunctionType());
1374 // Print the types of each of the function's arguments
1375 for(Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1377 printType(AI->getType());
1381 // Print type definitions for every type referenced by an instruction and
1382 // make a note of any global values or constants that are referenced
1383 std::vector<GlobalValue*> gvs;
1384 std::vector<Constant*> consts;
1385 for (Function::const_iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB){
1386 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1388 // Print the type of the instruction itself
1389 printType(I->getType());
1391 // Print the type of each of the instruction's operands
1392 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1393 Value* operand = I->getOperand(i);
1394 printType(operand->getType());
1395 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand))
1397 else if (Constant* C = dyn_cast<Constant>(operand))
1398 consts.push_back(C);
1403 // Print the function declarations for any functions encountered
1404 nl(Out) << "// Function Declarations"; nl(Out);
1405 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1407 if (Function* Fun = dyn_cast<Function>(*I)) {
1408 if (!is_inline || Fun != F)
1409 printFunctionHead(Fun);
1413 // Print the global variable declarations for any variables encountered
1414 nl(Out) << "// Global Variable Declarations"; nl(Out);
1415 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1417 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1418 printVariableHead(F);
1421 // Print the constants found
1422 nl(Out) << "// Constant Definitions"; nl(Out);
1423 for (std::vector<Constant*>::iterator I = consts.begin(), E = consts.end();
1428 // Process the global variables definitions now that all the constants have
1429 // been emitted. These definitions just couple the gvars with their constant
1431 nl(Out) << "// Global Variable Definitions"; nl(Out);
1432 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1434 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1435 printVariableBody(GV);
1439 void CppWriter::printFunctionHead(const Function* F) {
1440 nl(Out) << "Function* " << getCppName(F);
1442 Out << " = mod->getFunction(\"";
1443 printEscapedString(F->getName());
1444 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1445 nl(Out) << "if (!" << getCppName(F) << ") {";
1446 nl(Out) << getCppName(F);
1448 Out<< " = new Function(";
1449 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1450 nl(Out) << "/*Linkage=*/";
1451 printLinkageType(F->getLinkage());
1453 nl(Out) << "/*Name=*/\"";
1454 printEscapedString(F->getName());
1455 Out << "\", mod); " << (F->isExternal()? "// (external, no body)" : "");
1458 Out << "->setCallingConv(";
1459 printCallingConv(F->getCallingConv());
1462 if (F->hasSection()) {
1464 Out << "->setSection(\"" << F->getSection() << "\");";
1467 if (F->getAlignment()) {
1469 Out << "->setAlignment(" << F->getAlignment() << ");";
1478 void CppWriter::printFunctionBody(const Function *F) {
1479 if (F->isExternal())
1480 return; // external functions have no bodies.
1482 // Clear the DefinedValues and ForwardRefs maps because we can't have
1483 // cross-function forward refs
1484 ForwardRefs.clear();
1485 DefinedValues.clear();
1487 // Create all the argument values
1489 if (!F->arg_empty()) {
1490 Out << "Function::arg_iterator args = " << getCppName(F)
1491 << "->arg_begin();";
1494 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1496 Out << "Value* " << getCppName(AI) << " = args++;";
1498 if (AI->hasName()) {
1499 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1505 // Create all the basic blocks
1507 for (Function::const_iterator BI = F->begin(), BE = F->end();
1509 std::string bbname(getCppName(BI));
1510 Out << "BasicBlock* " << bbname << " = new BasicBlock(\"";
1512 printEscapedString(BI->getName());
1513 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1517 // Output all of its basic blocks... for the function
1518 for (Function::const_iterator BI = F->begin(), BE = F->end();
1520 std::string bbname(getCppName(BI));
1521 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1524 // Output all of the instructions in the basic block...
1525 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1527 printInstruction(I,bbname);
1531 // Loop over the ForwardRefs and resolve them now that all instructions
1533 if (!ForwardRefs.empty()) {
1534 nl(Out) << "// Resolve Forward References";
1538 while (!ForwardRefs.empty()) {
1539 ForwardRefMap::iterator I = ForwardRefs.begin();
1540 Out << I->second << "->replaceAllUsesWith("
1541 << getCppName(I->first) << "); delete " << I->second << ";";
1543 ForwardRefs.erase(I);
1547 void CppWriter::printInline(const std::string& fname, const std::string& func) {
1548 const Function* F = TheModule->getNamedFunction(func);
1550 error(std::string("Function '") + func + "' not found in input module");
1553 if (F->isExternal()) {
1554 error(std::string("Function '") + func + "' is external!");
1557 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1559 unsigned arg_count = 1;
1560 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1562 Out << ", Value* arg_" << arg_count;
1567 printFunctionUses(F);
1568 printFunctionBody(F);
1570 Out << "return " << getCppName(F->begin()) << ";";
1575 void CppWriter::printModuleBody() {
1576 // Print out all the type definitions
1577 nl(Out) << "// Type Definitions"; nl(Out);
1578 printTypes(TheModule);
1580 // Functions can call each other and global variables can reference them so
1581 // define all the functions first before emitting their function bodies.
1582 nl(Out) << "// Function Declarations"; nl(Out);
1583 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1585 printFunctionHead(I);
1587 // Process the global variables declarations. We can't initialze them until
1588 // after the constants are printed so just print a header for each global
1589 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1590 for (Module::const_global_iterator I = TheModule->global_begin(),
1591 E = TheModule->global_end(); I != E; ++I) {
1592 printVariableHead(I);
1595 // Print out all the constants definitions. Constants don't recurse except
1596 // through GlobalValues. All GlobalValues have been declared at this point
1597 // so we can proceed to generate the constants.
1598 nl(Out) << "// Constant Definitions"; nl(Out);
1599 printConstants(TheModule);
1601 // Process the global variables definitions now that all the constants have
1602 // been emitted. These definitions just couple the gvars with their constant
1604 nl(Out) << "// Global Variable Definitions"; nl(Out);
1605 for (Module::const_global_iterator I = TheModule->global_begin(),
1606 E = TheModule->global_end(); I != E; ++I) {
1607 printVariableBody(I);
1610 // Finally, we can safely put out all of the function bodies.
1611 nl(Out) << "// Function Definitions"; nl(Out);
1612 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1614 if (!I->isExternal()) {
1615 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1619 printFunctionBody(I);
1626 void CppWriter::printProgram(
1627 const std::string& fname,
1628 const std::string& mName
1630 Out << "#include <llvm/Module.h>\n";
1631 Out << "#include <llvm/DerivedTypes.h>\n";
1632 Out << "#include <llvm/Constants.h>\n";
1633 Out << "#include <llvm/GlobalVariable.h>\n";
1634 Out << "#include <llvm/Function.h>\n";
1635 Out << "#include <llvm/CallingConv.h>\n";
1636 Out << "#include <llvm/BasicBlock.h>\n";
1637 Out << "#include <llvm/Instructions.h>\n";
1638 Out << "#include <llvm/InlineAsm.h>\n";
1639 Out << "#include <llvm/Support/MathExtras.h>\n";
1640 Out << "#include <llvm/Pass.h>\n";
1641 Out << "#include <llvm/PassManager.h>\n";
1642 Out << "#include <llvm/Analysis/Verifier.h>\n";
1643 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1644 Out << "#include <algorithm>\n";
1645 Out << "#include <iostream>\n\n";
1646 Out << "using namespace llvm;\n\n";
1647 Out << "Module* " << fname << "();\n\n";
1648 Out << "int main(int argc, char**argv) {\n";
1649 Out << " Module* Mod = makeLLVMModule();\n";
1650 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1651 Out << " std::cerr.flush();\n";
1652 Out << " std::cout.flush();\n";
1653 Out << " PassManager PM;\n";
1654 Out << " PM.add(new PrintModulePass(&std::cout));\n";
1655 Out << " PM.run(*Mod);\n";
1656 Out << " return 0;\n";
1658 printModule(fname,mName);
1661 void CppWriter::printModule(
1662 const std::string& fname,
1663 const std::string& mName
1665 nl(Out) << "Module* " << fname << "() {";
1666 nl(Out,1) << "// Module Construction";
1667 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1668 nl(Out) << "mod->setEndianness(";
1669 switch (TheModule->getEndianness()) {
1670 case Module::LittleEndian: Out << "Module::LittleEndian);"; break;
1671 case Module::BigEndian: Out << "Module::BigEndian);"; break;
1672 case Module::AnyEndianness:Out << "Module::AnyEndianness);"; break;
1674 nl(Out) << "mod->setPointerSize(";
1675 switch (TheModule->getPointerSize()) {
1676 case Module::Pointer32: Out << "Module::Pointer32);"; break;
1677 case Module::Pointer64: Out << "Module::Pointer64);"; break;
1678 case Module::AnyPointerSize: Out << "Module::AnyPointerSize);"; break;
1681 if (!TheModule->getTargetTriple().empty()) {
1682 Out << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1687 if (!TheModule->getModuleInlineAsm().empty()) {
1688 Out << "mod->setModuleInlineAsm(\"";
1689 printEscapedString(TheModule->getModuleInlineAsm());
1694 // Loop over the dependent libraries and emit them.
1695 Module::lib_iterator LI = TheModule->lib_begin();
1696 Module::lib_iterator LE = TheModule->lib_end();
1698 Out << "mod->addLibrary(\"" << *LI << "\");";
1703 nl(Out) << "return mod;";
1708 void CppWriter::printContents(
1709 const std::string& fname, // Name of generated function
1710 const std::string& mName // Name of module generated module
1712 Out << "\nModule* " << fname << "(Module *mod) {\n";
1713 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1715 Out << "\nreturn mod;\n";
1719 void CppWriter::printFunction(
1720 const std::string& fname, // Name of generated function
1721 const std::string& funcName // Name of function to generate
1723 const Function* F = TheModule->getNamedFunction(funcName);
1725 error(std::string("Function '") + funcName + "' not found in input module");
1728 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1729 printFunctionUses(F);
1730 printFunctionHead(F);
1731 printFunctionBody(F);
1732 Out << "return " << getCppName(F) << ";\n";
1736 void CppWriter::printVariable(
1737 const std::string& fname, /// Name of generated function
1738 const std::string& varName // Name of variable to generate
1740 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1743 error(std::string("Variable '") + varName + "' not found in input module");
1746 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1747 printVariableUses(GV);
1748 printVariableHead(GV);
1749 printVariableBody(GV);
1750 Out << "return " << getCppName(GV) << ";\n";
1754 void CppWriter::printType(
1755 const std::string& fname, /// Name of generated function
1756 const std::string& typeName // Name of type to generate
1758 const Type* Ty = TheModule->getTypeByName(typeName);
1760 error(std::string("Type '") + typeName + "' not found in input module");
1763 Out << "\nType* " << fname << "(Module *mod) {\n";
1765 Out << "return " << getCppName(Ty) << ";\n";
1769 } // end anonymous llvm
1773 void WriteModuleToCppFile(Module* mod, std::ostream& o) {
1774 // Initialize a CppWriter for us to use
1775 CppWriter W(o, mod);
1778 o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1780 // Get the name of the function we're supposed to generate
1781 std::string fname = FuncName.getValue();
1783 // Get the name of the thing we are to generate
1784 std::string tgtname = NameToGenerate.getValue();
1785 if (GenerationType == GenModule ||
1786 GenerationType == GenContents ||
1787 GenerationType == GenProgram) {
1788 if (tgtname == "!bad!") {
1789 if (mod->getModuleIdentifier() == "-")
1790 tgtname = "<stdin>";
1792 tgtname = mod->getModuleIdentifier();
1794 } else if (tgtname == "!bad!") {
1795 W.error("You must use the -for option with -gen-{function,variable,type}");
1798 switch (WhatToGenerate(GenerationType)) {
1801 fname = "makeLLVMModule";
1802 W.printProgram(fname,tgtname);
1806 fname = "makeLLVMModule";
1807 W.printModule(fname,tgtname);
1811 fname = "makeLLVMModuleContents";
1812 W.printContents(fname,tgtname);
1816 fname = "makeLLVMFunction";
1817 W.printFunction(fname,tgtname);
1821 fname = "makeLLVMInline";
1822 W.printInline(fname,tgtname);
1826 fname = "makeLLVMVariable";
1827 W.printVariable(fname,tgtname);
1831 fname = "makeLLVMType";
1832 W.printType(fname,tgtname);
1835 W.error("Invalid generation option");