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/ParameterAttributes.h"
22 #include "llvm/Module.h"
23 #include "llvm/TypeSymbolTable.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/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::VectorTyID: 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::VectorTyID: prefix = "VectorTy_"; 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 const ParamAttrsList *PAL = FT->getParamAttrs();
462 Out << "ParamAttrsList *" << typeName << "_PAL = 0;";
465 Out << '{'; in(); nl(Out);
466 Out << "ParamAttrsVector Attrs;"; nl(Out);
467 Out << "ParamAttrsWithIndex PAWI;"; nl(Out);
468 for (unsigned i = 0; i < PAL->size(); ++i) {
469 uint16_t index = PAL->getParamIndex(i);
470 uint16_t attrs = PAL->getParamAttrs(index);
471 Out << "PAWI.index = " << index << "; PAWI.attrs = 0 ";
472 if (attrs & ParamAttr::SExt)
473 Out << " | ParamAttr::SExt";
474 if (attrs & ParamAttr::ZExt)
475 Out << " | ParamAttr::ZExt";
476 if (attrs & ParamAttr::StructRet)
477 Out << " | ParamAttr::StructRet";
478 if (attrs & ParamAttr::InReg)
479 Out << " | ParamAttr::InReg";
480 if (attrs & ParamAttr::NoReturn)
481 Out << " | ParamAttr::NoReturn";
482 if (attrs & ParamAttr::NoUnwind)
483 Out << " | ParamAttr::NoUnwind";
486 Out << "Attrs.push_back(PAWI);";
489 Out << typeName << "_PAL = ParamAttrsList::get(Attrs);";
494 bool isForward = printTypeInternal(FT->getReturnType());
495 std::string retTypeName(getCppName(FT->getReturnType()));
496 Out << "FunctionType* " << typeName << " = FunctionType::get(";
497 in(); nl(Out) << "/*Result=*/" << retTypeName;
501 nl(Out) << "/*Params=*/" << typeName << "_args,";
502 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true," : "false,") ;
503 nl(Out) << "/*ParamAttrs=*/" << typeName << "_PAL" << ");";
508 case Type::StructTyID: {
509 const StructType* ST = cast<StructType>(Ty);
510 Out << "std::vector<const Type*>" << typeName << "_fields;";
512 StructType::element_iterator EI = ST->element_begin();
513 StructType::element_iterator EE = ST->element_end();
514 for (; EI != EE; ++EI) {
515 const Type* fieldTy = static_cast<const Type*>(*EI);
516 bool isForward = printTypeInternal(fieldTy);
517 std::string fieldName(getCppName(fieldTy));
518 Out << typeName << "_fields.push_back(" << fieldName;
524 Out << "StructType* " << typeName << " = StructType::get("
525 << typeName << "_fields, /*isPacked=*/"
526 << (ST->isPacked() ? "true" : "false") << ");";
530 case Type::ArrayTyID: {
531 const ArrayType* AT = cast<ArrayType>(Ty);
532 const Type* ET = AT->getElementType();
533 bool isForward = printTypeInternal(ET);
534 std::string elemName(getCppName(ET));
535 Out << "ArrayType* " << typeName << " = ArrayType::get("
536 << elemName << (isForward ? "_fwd" : "")
537 << ", " << utostr(AT->getNumElements()) << ");";
541 case Type::PointerTyID: {
542 const PointerType* PT = cast<PointerType>(Ty);
543 const Type* ET = PT->getElementType();
544 bool isForward = printTypeInternal(ET);
545 std::string elemName(getCppName(ET));
546 Out << "PointerType* " << typeName << " = PointerType::get("
547 << elemName << (isForward ? "_fwd" : "") << ");";
551 case Type::VectorTyID: {
552 const VectorType* PT = cast<VectorType>(Ty);
553 const Type* ET = PT->getElementType();
554 bool isForward = printTypeInternal(ET);
555 std::string elemName(getCppName(ET));
556 Out << "VectorType* " << typeName << " = VectorType::get("
557 << elemName << (isForward ? "_fwd" : "")
558 << ", " << utostr(PT->getNumElements()) << ");";
562 case Type::OpaqueTyID: {
563 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
568 error("Invalid TypeID");
571 // If the type had a name, make sure we recreate it.
572 const std::string* progTypeName =
573 findTypeName(TheModule->getTypeSymbolTable(),Ty);
575 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
580 // Pop us off the type stack
581 TypeStack.pop_back();
583 // Indicate that this type is now defined.
584 DefinedTypes.insert(Ty);
586 // Early resolve as many unresolved types as possible. Search the unresolved
587 // types map for the type we just printed. Now that its definition is complete
588 // we can resolve any previous references to it. This prevents a cascade of
590 TypeMap::iterator I = UnresolvedTypes.find(Ty);
591 if (I != UnresolvedTypes.end()) {
592 Out << "cast<OpaqueType>(" << I->second
593 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
595 Out << I->second << " = cast<";
596 switch (Ty->getTypeID()) {
597 case Type::FunctionTyID: Out << "FunctionType"; break;
598 case Type::ArrayTyID: Out << "ArrayType"; break;
599 case Type::StructTyID: Out << "StructType"; break;
600 case Type::VectorTyID: Out << "VectorType"; break;
601 case Type::PointerTyID: Out << "PointerType"; break;
602 case Type::OpaqueTyID: Out << "OpaqueType"; break;
603 default: Out << "NoSuchDerivedType"; break;
605 Out << ">(" << I->second << "_fwd.get());";
607 UnresolvedTypes.erase(I);
610 // Finally, separate the type definition from other with a newline.
613 // We weren't a recursive type
617 // Prints a type definition. Returns true if it could not resolve all the types
618 // in the definition but had to use a forward reference.
620 CppWriter::printType(const Type* Ty) {
621 assert(TypeStack.empty());
623 printTypeInternal(Ty);
624 assert(TypeStack.empty());
628 CppWriter::printTypes(const Module* M) {
630 // Walk the symbol table and print out all its types
631 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
632 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
635 // For primitive types and types already defined, just add a name
636 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
637 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
638 TNI != TypeNames.end()) {
639 Out << "mod->addTypeName(\"";
640 printEscapedString(TI->first);
641 Out << "\", " << getCppName(TI->second) << ");";
643 // For everything else, define the type
645 printType(TI->second);
649 // Add all of the global variables to the value table...
650 for (Module::const_global_iterator I = TheModule->global_begin(),
651 E = TheModule->global_end(); I != E; ++I) {
652 if (I->hasInitializer())
653 printType(I->getInitializer()->getType());
654 printType(I->getType());
657 // Add all the functions to the table
658 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
660 printType(FI->getReturnType());
661 printType(FI->getFunctionType());
662 // Add all the function arguments
663 for(Function::const_arg_iterator AI = FI->arg_begin(),
664 AE = FI->arg_end(); AI != AE; ++AI) {
665 printType(AI->getType());
668 // Add all of the basic blocks and instructions
669 for (Function::const_iterator BB = FI->begin(),
670 E = FI->end(); BB != E; ++BB) {
671 printType(BB->getType());
672 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
674 printType(I->getType());
675 for (unsigned i = 0; i < I->getNumOperands(); ++i)
676 printType(I->getOperand(i)->getType());
683 // printConstant - Print out a constant pool entry...
684 void CppWriter::printConstant(const Constant *CV) {
685 // First, if the constant is actually a GlobalValue (variable or function) or
686 // its already in the constant list then we've printed it already and we can
688 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
691 std::string constName(getCppName(CV));
692 std::string typeName(getCppName(CV->getType()));
693 if (CV->isNullValue()) {
694 Out << "Constant* " << constName << " = Constant::getNullValue("
699 if (isa<GlobalValue>(CV)) {
700 // Skip variables and functions, we emit them elsewhere
703 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
704 Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
705 << cast<IntegerType>(CI->getType())->getBitWidth() << ", "
706 << " \"" << CI->getValue().toStringSigned(10) << "\", 10));";
707 } else if (isa<ConstantAggregateZero>(CV)) {
708 Out << "ConstantAggregateZero* " << constName
709 << " = ConstantAggregateZero::get(" << typeName << ");";
710 } else if (isa<ConstantPointerNull>(CV)) {
711 Out << "ConstantPointerNull* " << constName
712 << " = ConstanPointerNull::get(" << typeName << ");";
713 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
714 Out << "ConstantFP* " << constName << " = ";
717 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
718 if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
719 Out << "Constant* " << constName << " = ConstantArray::get(\"";
720 printEscapedString(CA->getAsString());
721 // Determine if we want null termination or not.
722 if (CA->getType()->getNumElements() <= CA->getAsString().length())
723 Out << "\", false";// No null terminator
725 Out << "\", true"; // Indicate that the null terminator should be added.
728 Out << "std::vector<Constant*> " << constName << "_elems;";
730 unsigned N = CA->getNumOperands();
731 for (unsigned i = 0; i < N; ++i) {
732 printConstant(CA->getOperand(i)); // recurse to print operands
733 Out << constName << "_elems.push_back("
734 << getCppName(CA->getOperand(i)) << ");";
737 Out << "Constant* " << constName << " = ConstantArray::get("
738 << typeName << ", " << constName << "_elems);";
740 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
741 Out << "std::vector<Constant*> " << constName << "_fields;";
743 unsigned N = CS->getNumOperands();
744 for (unsigned i = 0; i < N; i++) {
745 printConstant(CS->getOperand(i));
746 Out << constName << "_fields.push_back("
747 << getCppName(CS->getOperand(i)) << ");";
750 Out << "Constant* " << constName << " = ConstantStruct::get("
751 << typeName << ", " << constName << "_fields);";
752 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
753 Out << "std::vector<Constant*> " << constName << "_elems;";
755 unsigned N = CP->getNumOperands();
756 for (unsigned i = 0; i < N; ++i) {
757 printConstant(CP->getOperand(i));
758 Out << constName << "_elems.push_back("
759 << getCppName(CP->getOperand(i)) << ");";
762 Out << "Constant* " << constName << " = ConstantVector::get("
763 << typeName << ", " << constName << "_elems);";
764 } else if (isa<UndefValue>(CV)) {
765 Out << "UndefValue* " << constName << " = UndefValue::get("
767 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
768 if (CE->getOpcode() == Instruction::GetElementPtr) {
769 Out << "std::vector<Constant*> " << constName << "_indices;";
771 printConstant(CE->getOperand(0));
772 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
773 printConstant(CE->getOperand(i));
774 Out << constName << "_indices.push_back("
775 << getCppName(CE->getOperand(i)) << ");";
778 Out << "Constant* " << constName
779 << " = ConstantExpr::getGetElementPtr("
780 << getCppName(CE->getOperand(0)) << ", "
781 << "&" << constName << "_indices[0], " << CE->getNumOperands() - 1
783 } else if (CE->isCast()) {
784 printConstant(CE->getOperand(0));
785 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
786 switch (CE->getOpcode()) {
787 default: assert(0 && "Invalid cast opcode");
788 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
789 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
790 case Instruction::SExt: Out << "Instruction::SExt"; break;
791 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
792 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
793 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
794 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
795 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
796 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
797 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
798 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
799 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
801 Out << ", " << getCppName(CE->getOperand(0)) << ", "
802 << getCppName(CE->getType()) << ");";
804 unsigned N = CE->getNumOperands();
805 for (unsigned i = 0; i < N; ++i ) {
806 printConstant(CE->getOperand(i));
808 Out << "Constant* " << constName << " = ConstantExpr::";
809 switch (CE->getOpcode()) {
810 case Instruction::Add: Out << "getAdd("; break;
811 case Instruction::Sub: Out << "getSub("; break;
812 case Instruction::Mul: Out << "getMul("; break;
813 case Instruction::UDiv: Out << "getUDiv("; break;
814 case Instruction::SDiv: Out << "getSDiv("; break;
815 case Instruction::FDiv: Out << "getFDiv("; break;
816 case Instruction::URem: Out << "getURem("; break;
817 case Instruction::SRem: Out << "getSRem("; break;
818 case Instruction::FRem: Out << "getFRem("; break;
819 case Instruction::And: Out << "getAnd("; break;
820 case Instruction::Or: Out << "getOr("; break;
821 case Instruction::Xor: Out << "getXor("; break;
822 case Instruction::ICmp:
823 Out << "getICmp(ICmpInst::ICMP_";
824 switch (CE->getPredicate()) {
825 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
826 case ICmpInst::ICMP_NE: Out << "NE"; break;
827 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
828 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
829 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
830 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
831 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
832 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
833 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
834 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
835 default: error("Invalid ICmp Predicate");
838 case Instruction::FCmp:
839 Out << "getFCmp(FCmpInst::FCMP_";
840 switch (CE->getPredicate()) {
841 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
842 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
843 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
844 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
845 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
846 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
847 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
848 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
849 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
850 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
851 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
852 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
853 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
854 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
855 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
856 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
857 default: error("Invalid FCmp Predicate");
860 case Instruction::Shl: Out << "getShl("; break;
861 case Instruction::LShr: Out << "getLShr("; break;
862 case Instruction::AShr: Out << "getAShr("; break;
863 case Instruction::Select: Out << "getSelect("; break;
864 case Instruction::ExtractElement: Out << "getExtractElement("; break;
865 case Instruction::InsertElement: Out << "getInsertElement("; break;
866 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
868 error("Invalid constant expression");
871 Out << getCppName(CE->getOperand(0));
872 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
873 Out << ", " << getCppName(CE->getOperand(i));
877 error("Bad Constant");
878 Out << "Constant* " << constName << " = 0; ";
884 CppWriter::printConstants(const Module* M) {
885 // Traverse all the global variables looking for constant initializers
886 for (Module::const_global_iterator I = TheModule->global_begin(),
887 E = TheModule->global_end(); I != E; ++I)
888 if (I->hasInitializer())
889 printConstant(I->getInitializer());
891 // Traverse the LLVM functions looking for constants
892 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
894 // Add all of the basic blocks and instructions
895 for (Function::const_iterator BB = FI->begin(),
896 E = FI->end(); BB != E; ++BB) {
897 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
899 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
900 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
909 void CppWriter::printVariableUses(const GlobalVariable *GV) {
910 nl(Out) << "// Type Definitions";
912 printType(GV->getType());
913 if (GV->hasInitializer()) {
914 Constant* Init = GV->getInitializer();
915 printType(Init->getType());
916 if (Function* F = dyn_cast<Function>(Init)) {
917 nl(Out)<< "/ Function Declarations"; nl(Out);
918 printFunctionHead(F);
919 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
920 nl(Out) << "// Global Variable Declarations"; nl(Out);
921 printVariableHead(gv);
923 nl(Out) << "// Constant Definitions"; nl(Out);
926 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
927 nl(Out) << "// Global Variable Definitions"; nl(Out);
928 printVariableBody(gv);
933 void CppWriter::printVariableHead(const GlobalVariable *GV) {
934 nl(Out) << "GlobalVariable* " << getCppName(GV);
936 Out << " = mod->getGlobalVariable(";
937 printEscapedString(GV->getName());
938 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
939 nl(Out) << "if (!" << getCppName(GV) << ") {";
940 in(); nl(Out) << getCppName(GV);
942 Out << " = new GlobalVariable(";
943 nl(Out) << "/*Type=*/";
944 printCppName(GV->getType()->getElementType());
946 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
948 nl(Out) << "/*Linkage=*/";
949 printLinkageType(GV->getLinkage());
951 nl(Out) << "/*Initializer=*/0, ";
952 if (GV->hasInitializer()) {
953 Out << "// has initializer, specified below";
955 nl(Out) << "/*Name=*/\"";
956 printEscapedString(GV->getName());
961 if (GV->hasSection()) {
963 Out << "->setSection(\"";
964 printEscapedString(GV->getSection());
968 if (GV->getAlignment()) {
970 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
974 out(); Out << "}"; nl(Out);
979 CppWriter::printVariableBody(const GlobalVariable *GV) {
980 if (GV->hasInitializer()) {
982 Out << "->setInitializer(";
983 //if (!isa<GlobalValue(GV->getInitializer()))
985 Out << getCppName(GV->getInitializer()) << ");";
991 CppWriter::getOpName(Value* V) {
992 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
993 return getCppName(V);
995 // See if its alread in the map of forward references, if so just return the
996 // name we already set up for it
997 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
998 if (I != ForwardRefs.end())
1001 // This is a new forward reference. Generate a unique name for it
1002 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1004 // Yes, this is a hack. An Argument is the smallest instantiable value that
1005 // we can make as a placeholder for the real value. We'll replace these
1006 // Argument instances later.
1007 Out << "Argument* " << result << " = new Argument("
1008 << getCppName(V->getType()) << ");";
1010 ForwardRefs[V] = result;
1014 // printInstruction - This member is called for each Instruction in a function.
1016 CppWriter::printInstruction(const Instruction *I, const std::string& bbname) {
1017 std::string iName(getCppName(I));
1019 // Before we emit this instruction, we need to take care of generating any
1020 // forward references. So, we get the names of all the operands in advance
1021 std::string* opNames = new std::string[I->getNumOperands()];
1022 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1023 opNames[i] = getOpName(I->getOperand(i));
1026 switch (I->getOpcode()) {
1027 case Instruction::Ret: {
1028 const ReturnInst* ret = cast<ReturnInst>(I);
1029 Out << "new ReturnInst("
1030 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1033 case Instruction::Br: {
1034 const BranchInst* br = cast<BranchInst>(I);
1035 Out << "new BranchInst(" ;
1036 if (br->getNumOperands() == 3 ) {
1037 Out << opNames[0] << ", "
1038 << opNames[1] << ", "
1039 << opNames[2] << ", ";
1041 } else if (br->getNumOperands() == 1) {
1042 Out << opNames[0] << ", ";
1044 error("Branch with 2 operands?");
1046 Out << bbname << ");";
1049 case Instruction::Switch: {
1050 const SwitchInst* sw = cast<SwitchInst>(I);
1051 Out << "SwitchInst* " << iName << " = new SwitchInst("
1052 << opNames[0] << ", "
1053 << opNames[1] << ", "
1054 << sw->getNumCases() << ", " << bbname << ");";
1056 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1057 Out << iName << "->addCase("
1058 << opNames[i] << ", "
1059 << opNames[i+1] << ");";
1064 case Instruction::Invoke: {
1065 const InvokeInst* inv = cast<InvokeInst>(I);
1066 Out << "std::vector<Value*> " << iName << "_params;";
1068 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1069 Out << iName << "_params.push_back("
1070 << opNames[i] << ");";
1073 Out << "InvokeInst *" << iName << " = new InvokeInst("
1074 << opNames[0] << ", "
1075 << opNames[1] << ", "
1076 << opNames[2] << ", "
1077 << "&" << iName << "_params[0], " << inv->getNumOperands() - 3
1079 printEscapedString(inv->getName());
1080 Out << "\", " << bbname << ");";
1081 nl(Out) << iName << "->setCallingConv(";
1082 printCallingConv(inv->getCallingConv());
1086 case Instruction::Unwind: {
1087 Out << "new UnwindInst("
1091 case Instruction::Unreachable:{
1092 Out << "new UnreachableInst("
1096 case Instruction::Add:
1097 case Instruction::Sub:
1098 case Instruction::Mul:
1099 case Instruction::UDiv:
1100 case Instruction::SDiv:
1101 case Instruction::FDiv:
1102 case Instruction::URem:
1103 case Instruction::SRem:
1104 case Instruction::FRem:
1105 case Instruction::And:
1106 case Instruction::Or:
1107 case Instruction::Xor:
1108 case Instruction::Shl:
1109 case Instruction::LShr:
1110 case Instruction::AShr:{
1111 Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
1112 switch (I->getOpcode()) {
1113 case Instruction::Add: Out << "Instruction::Add"; break;
1114 case Instruction::Sub: Out << "Instruction::Sub"; break;
1115 case Instruction::Mul: Out << "Instruction::Mul"; break;
1116 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1117 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1118 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1119 case Instruction::URem:Out << "Instruction::URem"; break;
1120 case Instruction::SRem:Out << "Instruction::SRem"; break;
1121 case Instruction::FRem:Out << "Instruction::FRem"; break;
1122 case Instruction::And: Out << "Instruction::And"; break;
1123 case Instruction::Or: Out << "Instruction::Or"; break;
1124 case Instruction::Xor: Out << "Instruction::Xor"; break;
1125 case Instruction::Shl: Out << "Instruction::Shl"; break;
1126 case Instruction::LShr:Out << "Instruction::LShr"; break;
1127 case Instruction::AShr:Out << "Instruction::AShr"; break;
1128 default: Out << "Instruction::BadOpCode"; break;
1130 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1131 printEscapedString(I->getName());
1132 Out << "\", " << bbname << ");";
1135 case Instruction::FCmp: {
1136 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1137 switch (cast<FCmpInst>(I)->getPredicate()) {
1138 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1139 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1140 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1141 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1142 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1143 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1144 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1145 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1146 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1147 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1148 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1149 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1150 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1151 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1152 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1153 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1154 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1156 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1157 printEscapedString(I->getName());
1158 Out << "\", " << bbname << ");";
1161 case Instruction::ICmp: {
1162 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1163 switch (cast<ICmpInst>(I)->getPredicate()) {
1164 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1165 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1166 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1167 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1168 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1169 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1170 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1171 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1172 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1173 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1174 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1176 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1177 printEscapedString(I->getName());
1178 Out << "\", " << bbname << ");";
1181 case Instruction::Malloc: {
1182 const MallocInst* mallocI = cast<MallocInst>(I);
1183 Out << "MallocInst* " << iName << " = new MallocInst("
1184 << getCppName(mallocI->getAllocatedType()) << ", ";
1185 if (mallocI->isArrayAllocation())
1186 Out << opNames[0] << ", " ;
1188 printEscapedString(mallocI->getName());
1189 Out << "\", " << bbname << ");";
1190 if (mallocI->getAlignment())
1191 nl(Out) << iName << "->setAlignment("
1192 << mallocI->getAlignment() << ");";
1195 case Instruction::Free: {
1196 Out << "FreeInst* " << iName << " = new FreeInst("
1197 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1200 case Instruction::Alloca: {
1201 const AllocaInst* allocaI = cast<AllocaInst>(I);
1202 Out << "AllocaInst* " << iName << " = new AllocaInst("
1203 << getCppName(allocaI->getAllocatedType()) << ", ";
1204 if (allocaI->isArrayAllocation())
1205 Out << opNames[0] << ", ";
1207 printEscapedString(allocaI->getName());
1208 Out << "\", " << bbname << ");";
1209 if (allocaI->getAlignment())
1210 nl(Out) << iName << "->setAlignment("
1211 << allocaI->getAlignment() << ");";
1214 case Instruction::Load:{
1215 const LoadInst* load = cast<LoadInst>(I);
1216 Out << "LoadInst* " << iName << " = new LoadInst("
1217 << opNames[0] << ", \"";
1218 printEscapedString(load->getName());
1219 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1220 << ", " << bbname << ");";
1223 case Instruction::Store: {
1224 const StoreInst* store = cast<StoreInst>(I);
1225 Out << "StoreInst* " << iName << " = new StoreInst("
1226 << opNames[0] << ", "
1227 << opNames[1] << ", "
1228 << (store->isVolatile() ? "true" : "false")
1229 << ", " << bbname << ");";
1232 case Instruction::GetElementPtr: {
1233 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1234 if (gep->getNumOperands() <= 2) {
1235 Out << "GetElementPtrInst* " << iName << " = new GetElementPtrInst("
1237 if (gep->getNumOperands() == 2)
1238 Out << ", " << opNames[1];
1240 Out << "std::vector<Value*> " << iName << "_indices;";
1242 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1243 Out << iName << "_indices.push_back("
1244 << opNames[i] << ");";
1247 Out << "Instruction* " << iName << " = new GetElementPtrInst("
1248 << opNames[0] << ", &" << iName << "_indices[0], "
1249 << gep->getNumOperands() - 1;
1252 printEscapedString(gep->getName());
1253 Out << "\", " << bbname << ");";
1256 case Instruction::PHI: {
1257 const PHINode* phi = cast<PHINode>(I);
1259 Out << "PHINode* " << iName << " = new PHINode("
1260 << getCppName(phi->getType()) << ", \"";
1261 printEscapedString(phi->getName());
1262 Out << "\", " << bbname << ");";
1263 nl(Out) << iName << "->reserveOperandSpace("
1264 << phi->getNumIncomingValues()
1267 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1268 Out << iName << "->addIncoming("
1269 << opNames[i] << ", " << opNames[i+1] << ");";
1274 case Instruction::Trunc:
1275 case Instruction::ZExt:
1276 case Instruction::SExt:
1277 case Instruction::FPTrunc:
1278 case Instruction::FPExt:
1279 case Instruction::FPToUI:
1280 case Instruction::FPToSI:
1281 case Instruction::UIToFP:
1282 case Instruction::SIToFP:
1283 case Instruction::PtrToInt:
1284 case Instruction::IntToPtr:
1285 case Instruction::BitCast: {
1286 const CastInst* cst = cast<CastInst>(I);
1287 Out << "CastInst* " << iName << " = new ";
1288 switch (I->getOpcode()) {
1289 case Instruction::Trunc: Out << "TruncInst"; break;
1290 case Instruction::ZExt: Out << "ZExtInst"; break;
1291 case Instruction::SExt: Out << "SExtInst"; break;
1292 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1293 case Instruction::FPExt: Out << "FPExtInst"; break;
1294 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1295 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1296 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1297 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1298 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1299 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1300 case Instruction::BitCast: Out << "BitCastInst"; break;
1301 default: assert(!"Unreachable"); break;
1303 Out << "(" << opNames[0] << ", "
1304 << getCppName(cst->getType()) << ", \"";
1305 printEscapedString(cst->getName());
1306 Out << "\", " << bbname << ");";
1309 case Instruction::Call:{
1310 const CallInst* call = cast<CallInst>(I);
1311 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1312 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1313 << getCppName(ila->getFunctionType()) << ", \""
1314 << ila->getAsmString() << "\", \""
1315 << ila->getConstraintString() << "\","
1316 << (ila->hasSideEffects() ? "true" : "false") << ");";
1319 if (call->getNumOperands() > 3) {
1320 Out << "std::vector<Value*> " << iName << "_params;";
1322 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1323 Out << iName << "_params.push_back(" << opNames[i] << ");";
1326 Out << "CallInst* " << iName << " = new CallInst("
1327 << opNames[0] << ", &" << iName << "_params[0], "
1328 << call->getNumOperands() - 1 << ", \"";
1329 } else if (call->getNumOperands() == 3) {
1330 Out << "CallInst* " << iName << " = new CallInst("
1331 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1332 } else if (call->getNumOperands() == 2) {
1333 Out << "CallInst* " << iName << " = new CallInst("
1334 << opNames[0] << ", " << opNames[1] << ", \"";
1336 Out << "CallInst* " << iName << " = new CallInst(" << opNames[0]
1339 printEscapedString(call->getName());
1340 Out << "\", " << bbname << ");";
1341 nl(Out) << iName << "->setCallingConv(";
1342 printCallingConv(call->getCallingConv());
1344 nl(Out) << iName << "->setTailCall("
1345 << (call->isTailCall() ? "true":"false");
1349 case Instruction::Select: {
1350 const SelectInst* sel = cast<SelectInst>(I);
1351 Out << "SelectInst* " << getCppName(sel) << " = new SelectInst(";
1352 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1353 printEscapedString(sel->getName());
1354 Out << "\", " << bbname << ");";
1357 case Instruction::UserOp1:
1359 case Instruction::UserOp2: {
1360 /// FIXME: What should be done here?
1363 case Instruction::VAArg: {
1364 const VAArgInst* va = cast<VAArgInst>(I);
1365 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1366 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1367 printEscapedString(va->getName());
1368 Out << "\", " << bbname << ");";
1371 case Instruction::ExtractElement: {
1372 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1373 Out << "ExtractElementInst* " << getCppName(eei)
1374 << " = new ExtractElementInst(" << opNames[0]
1375 << ", " << opNames[1] << ", \"";
1376 printEscapedString(eei->getName());
1377 Out << "\", " << bbname << ");";
1380 case Instruction::InsertElement: {
1381 const InsertElementInst* iei = cast<InsertElementInst>(I);
1382 Out << "InsertElementInst* " << getCppName(iei)
1383 << " = new InsertElementInst(" << opNames[0]
1384 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1385 printEscapedString(iei->getName());
1386 Out << "\", " << bbname << ");";
1389 case Instruction::ShuffleVector: {
1390 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1391 Out << "ShuffleVectorInst* " << getCppName(svi)
1392 << " = new ShuffleVectorInst(" << opNames[0]
1393 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1394 printEscapedString(svi->getName());
1395 Out << "\", " << bbname << ");";
1399 DefinedValues.insert(I);
1404 // Print out the types, constants and declarations needed by one function
1405 void CppWriter::printFunctionUses(const Function* F) {
1407 nl(Out) << "// Type Definitions"; nl(Out);
1409 // Print the function's return type
1410 printType(F->getReturnType());
1412 // Print the function's function type
1413 printType(F->getFunctionType());
1415 // Print the types of each of the function's arguments
1416 for(Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1418 printType(AI->getType());
1422 // Print type definitions for every type referenced by an instruction and
1423 // make a note of any global values or constants that are referenced
1424 std::vector<GlobalValue*> gvs;
1425 std::vector<Constant*> consts;
1426 for (Function::const_iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB){
1427 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1429 // Print the type of the instruction itself
1430 printType(I->getType());
1432 // Print the type of each of the instruction's operands
1433 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1434 Value* operand = I->getOperand(i);
1435 printType(operand->getType());
1436 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand))
1438 else if (Constant* C = dyn_cast<Constant>(operand))
1439 consts.push_back(C);
1444 // Print the function declarations for any functions encountered
1445 nl(Out) << "// Function Declarations"; nl(Out);
1446 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1448 if (Function* Fun = dyn_cast<Function>(*I)) {
1449 if (!is_inline || Fun != F)
1450 printFunctionHead(Fun);
1454 // Print the global variable declarations for any variables encountered
1455 nl(Out) << "// Global Variable Declarations"; nl(Out);
1456 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1458 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1459 printVariableHead(F);
1462 // Print the constants found
1463 nl(Out) << "// Constant Definitions"; nl(Out);
1464 for (std::vector<Constant*>::iterator I = consts.begin(), E = consts.end();
1469 // Process the global variables definitions now that all the constants have
1470 // been emitted. These definitions just couple the gvars with their constant
1472 nl(Out) << "// Global Variable Definitions"; nl(Out);
1473 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1475 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1476 printVariableBody(GV);
1480 void CppWriter::printFunctionHead(const Function* F) {
1481 nl(Out) << "Function* " << getCppName(F);
1483 Out << " = mod->getFunction(\"";
1484 printEscapedString(F->getName());
1485 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1486 nl(Out) << "if (!" << getCppName(F) << ") {";
1487 nl(Out) << getCppName(F);
1489 Out<< " = new Function(";
1490 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1491 nl(Out) << "/*Linkage=*/";
1492 printLinkageType(F->getLinkage());
1494 nl(Out) << "/*Name=*/\"";
1495 printEscapedString(F->getName());
1496 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1499 Out << "->setCallingConv(";
1500 printCallingConv(F->getCallingConv());
1503 if (F->hasSection()) {
1505 Out << "->setSection(\"" << F->getSection() << "\");";
1508 if (F->getAlignment()) {
1510 Out << "->setAlignment(" << F->getAlignment() << ");";
1519 void CppWriter::printFunctionBody(const Function *F) {
1520 if (F->isDeclaration())
1521 return; // external functions have no bodies.
1523 // Clear the DefinedValues and ForwardRefs maps because we can't have
1524 // cross-function forward refs
1525 ForwardRefs.clear();
1526 DefinedValues.clear();
1528 // Create all the argument values
1530 if (!F->arg_empty()) {
1531 Out << "Function::arg_iterator args = " << getCppName(F)
1532 << "->arg_begin();";
1535 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1537 Out << "Value* " << getCppName(AI) << " = args++;";
1539 if (AI->hasName()) {
1540 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1546 // Create all the basic blocks
1548 for (Function::const_iterator BI = F->begin(), BE = F->end();
1550 std::string bbname(getCppName(BI));
1551 Out << "BasicBlock* " << bbname << " = new BasicBlock(\"";
1553 printEscapedString(BI->getName());
1554 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1558 // Output all of its basic blocks... for the function
1559 for (Function::const_iterator BI = F->begin(), BE = F->end();
1561 std::string bbname(getCppName(BI));
1562 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1565 // Output all of the instructions in the basic block...
1566 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1568 printInstruction(I,bbname);
1572 // Loop over the ForwardRefs and resolve them now that all instructions
1574 if (!ForwardRefs.empty()) {
1575 nl(Out) << "// Resolve Forward References";
1579 while (!ForwardRefs.empty()) {
1580 ForwardRefMap::iterator I = ForwardRefs.begin();
1581 Out << I->second << "->replaceAllUsesWith("
1582 << getCppName(I->first) << "); delete " << I->second << ";";
1584 ForwardRefs.erase(I);
1588 void CppWriter::printInline(const std::string& fname, const std::string& func) {
1589 const Function* F = TheModule->getFunction(func);
1591 error(std::string("Function '") + func + "' not found in input module");
1594 if (F->isDeclaration()) {
1595 error(std::string("Function '") + func + "' is external!");
1598 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1600 unsigned arg_count = 1;
1601 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1603 Out << ", Value* arg_" << arg_count;
1608 printFunctionUses(F);
1609 printFunctionBody(F);
1611 Out << "return " << getCppName(F->begin()) << ";";
1616 void CppWriter::printModuleBody() {
1617 // Print out all the type definitions
1618 nl(Out) << "// Type Definitions"; nl(Out);
1619 printTypes(TheModule);
1621 // Functions can call each other and global variables can reference them so
1622 // define all the functions first before emitting their function bodies.
1623 nl(Out) << "// Function Declarations"; nl(Out);
1624 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1626 printFunctionHead(I);
1628 // Process the global variables declarations. We can't initialze them until
1629 // after the constants are printed so just print a header for each global
1630 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1631 for (Module::const_global_iterator I = TheModule->global_begin(),
1632 E = TheModule->global_end(); I != E; ++I) {
1633 printVariableHead(I);
1636 // Print out all the constants definitions. Constants don't recurse except
1637 // through GlobalValues. All GlobalValues have been declared at this point
1638 // so we can proceed to generate the constants.
1639 nl(Out) << "// Constant Definitions"; nl(Out);
1640 printConstants(TheModule);
1642 // Process the global variables definitions now that all the constants have
1643 // been emitted. These definitions just couple the gvars with their constant
1645 nl(Out) << "// Global Variable Definitions"; nl(Out);
1646 for (Module::const_global_iterator I = TheModule->global_begin(),
1647 E = TheModule->global_end(); I != E; ++I) {
1648 printVariableBody(I);
1651 // Finally, we can safely put out all of the function bodies.
1652 nl(Out) << "// Function Definitions"; nl(Out);
1653 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1655 if (!I->isDeclaration()) {
1656 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1660 printFunctionBody(I);
1667 void CppWriter::printProgram(
1668 const std::string& fname,
1669 const std::string& mName
1671 Out << "#include <llvm/Module.h>\n";
1672 Out << "#include <llvm/DerivedTypes.h>\n";
1673 Out << "#include <llvm/Constants.h>\n";
1674 Out << "#include <llvm/GlobalVariable.h>\n";
1675 Out << "#include <llvm/Function.h>\n";
1676 Out << "#include <llvm/CallingConv.h>\n";
1677 Out << "#include <llvm/BasicBlock.h>\n";
1678 Out << "#include <llvm/Instructions.h>\n";
1679 Out << "#include <llvm/InlineAsm.h>\n";
1680 Out << "#include <llvm/ParameterAttributes.h>\n";
1681 Out << "#include <llvm/Support/MathExtras.h>\n";
1682 Out << "#include <llvm/Pass.h>\n";
1683 Out << "#include <llvm/PassManager.h>\n";
1684 Out << "#include <llvm/Analysis/Verifier.h>\n";
1685 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1686 Out << "#include <algorithm>\n";
1687 Out << "#include <iostream>\n\n";
1688 Out << "using namespace llvm;\n\n";
1689 Out << "Module* " << fname << "();\n\n";
1690 Out << "int main(int argc, char**argv) {\n";
1691 Out << " Module* Mod = makeLLVMModule();\n";
1692 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1693 Out << " std::cerr.flush();\n";
1694 Out << " std::cout.flush();\n";
1695 Out << " PassManager PM;\n";
1696 Out << " PM.add(new PrintModulePass(&llvm::cout));\n";
1697 Out << " PM.run(*Mod);\n";
1698 Out << " return 0;\n";
1700 printModule(fname,mName);
1703 void CppWriter::printModule(
1704 const std::string& fname,
1705 const std::string& mName
1707 nl(Out) << "Module* " << fname << "() {";
1708 nl(Out,1) << "// Module Construction";
1709 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1710 if (!TheModule->getTargetTriple().empty()) {
1711 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1713 if (!TheModule->getTargetTriple().empty()) {
1714 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1718 if (!TheModule->getModuleInlineAsm().empty()) {
1719 nl(Out) << "mod->setModuleInlineAsm(\"";
1720 printEscapedString(TheModule->getModuleInlineAsm());
1725 // Loop over the dependent libraries and emit them.
1726 Module::lib_iterator LI = TheModule->lib_begin();
1727 Module::lib_iterator LE = TheModule->lib_end();
1729 Out << "mod->addLibrary(\"" << *LI << "\");";
1734 nl(Out) << "return mod;";
1739 void CppWriter::printContents(
1740 const std::string& fname, // Name of generated function
1741 const std::string& mName // Name of module generated module
1743 Out << "\nModule* " << fname << "(Module *mod) {\n";
1744 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1746 Out << "\nreturn mod;\n";
1750 void CppWriter::printFunction(
1751 const std::string& fname, // Name of generated function
1752 const std::string& funcName // Name of function to generate
1754 const Function* F = TheModule->getFunction(funcName);
1756 error(std::string("Function '") + funcName + "' not found in input module");
1759 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1760 printFunctionUses(F);
1761 printFunctionHead(F);
1762 printFunctionBody(F);
1763 Out << "return " << getCppName(F) << ";\n";
1767 void CppWriter::printVariable(
1768 const std::string& fname, /// Name of generated function
1769 const std::string& varName // Name of variable to generate
1771 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1774 error(std::string("Variable '") + varName + "' not found in input module");
1777 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1778 printVariableUses(GV);
1779 printVariableHead(GV);
1780 printVariableBody(GV);
1781 Out << "return " << getCppName(GV) << ";\n";
1785 void CppWriter::printType(
1786 const std::string& fname, /// Name of generated function
1787 const std::string& typeName // Name of type to generate
1789 const Type* Ty = TheModule->getTypeByName(typeName);
1791 error(std::string("Type '") + typeName + "' not found in input module");
1794 Out << "\nType* " << fname << "(Module *mod) {\n";
1796 Out << "return " << getCppName(Ty) << ";\n";
1800 } // end anonymous llvm
1804 void WriteModuleToCppFile(Module* mod, std::ostream& o) {
1805 // Initialize a CppWriter for us to use
1806 CppWriter W(o, mod);
1809 o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1811 // Get the name of the function we're supposed to generate
1812 std::string fname = FuncName.getValue();
1814 // Get the name of the thing we are to generate
1815 std::string tgtname = NameToGenerate.getValue();
1816 if (GenerationType == GenModule ||
1817 GenerationType == GenContents ||
1818 GenerationType == GenProgram) {
1819 if (tgtname == "!bad!") {
1820 if (mod->getModuleIdentifier() == "-")
1821 tgtname = "<stdin>";
1823 tgtname = mod->getModuleIdentifier();
1825 } else if (tgtname == "!bad!") {
1826 W.error("You must use the -for option with -gen-{function,variable,type}");
1829 switch (WhatToGenerate(GenerationType)) {
1832 fname = "makeLLVMModule";
1833 W.printProgram(fname,tgtname);
1837 fname = "makeLLVMModule";
1838 W.printModule(fname,tgtname);
1842 fname = "makeLLVMModuleContents";
1843 W.printContents(fname,tgtname);
1847 fname = "makeLLVMFunction";
1848 W.printFunction(fname,tgtname);
1852 fname = "makeLLVMInline";
1853 W.printInline(fname,tgtname);
1857 fname = "makeLLVMVariable";
1858 W.printVariable(fname,tgtname);
1862 fname = "makeLLVMType";
1863 W.printType(fname,tgtname);
1866 W.error("Invalid generation option");