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::CSRet: Out << "CallingConv::CSRet"; break;
262 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
263 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
264 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
265 default: Out << cc; break;
270 CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
272 case GlobalValue::InternalLinkage:
273 Out << "GlobalValue::InternalLinkage"; break;
274 case GlobalValue::LinkOnceLinkage:
275 Out << "GlobalValue::LinkOnceLinkage "; break;
276 case GlobalValue::WeakLinkage:
277 Out << "GlobalValue::WeakLinkage"; break;
278 case GlobalValue::AppendingLinkage:
279 Out << "GlobalValue::AppendingLinkage"; break;
280 case GlobalValue::ExternalLinkage:
281 Out << "GlobalValue::ExternalLinkage"; break;
282 case GlobalValue::DLLImportLinkage:
283 Out << "GlobalValue::DllImportLinkage"; break;
284 case GlobalValue::DLLExportLinkage:
285 Out << "GlobalValue::DllExportLinkage"; break;
286 case GlobalValue::ExternalWeakLinkage:
287 Out << "GlobalValue::ExternalWeakLinkage"; break;
288 case GlobalValue::GhostLinkage:
289 Out << "GlobalValue::GhostLinkage"; break;
293 // printEscapedString - Print each character of the specified string, escaping
294 // it if it is not printable or if it is an escape char.
296 CppWriter::printEscapedString(const std::string &Str) {
297 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
298 unsigned char C = Str[i];
299 if (isprint(C) && C != '"' && C != '\\') {
303 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
304 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
310 CppWriter::getCppName(const Type* Ty)
312 // First, handle the primitive types .. easy
313 if (Ty->isPrimitiveType() || Ty->isIntegral()) {
314 switch (Ty->getTypeID()) {
315 case Type::VoidTyID: return "Type::VoidTy";
316 case Type::IntegerTyID: {
317 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
318 return "IntegerType::get(" + utostr(BitWidth) + ")";
320 case Type::FloatTyID: return "Type::FloatTy";
321 case Type::DoubleTyID: return "Type::DoubleTy";
322 case Type::LabelTyID: return "Type::LabelTy";
324 error("Invalid primitive type");
327 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
330 // Now, see if we've seen the type before and return that
331 TypeMap::iterator I = TypeNames.find(Ty);
332 if (I != TypeNames.end())
335 // Okay, let's build a new name for this type. Start with a prefix
336 const char* prefix = 0;
337 switch (Ty->getTypeID()) {
338 case Type::FunctionTyID: prefix = "FuncTy_"; break;
339 case Type::StructTyID: prefix = "StructTy_"; break;
340 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
341 case Type::PointerTyID: prefix = "PointerTy_"; break;
342 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
343 case Type::PackedTyID: prefix = "PackedTy_"; break;
344 default: prefix = "OtherTy_"; break; // prevent breakage
347 // See if the type has a name in the symboltable and build accordingly
348 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
351 name = std::string(prefix) + *tName;
353 name = std::string(prefix) + utostr(uniqueNum++);
357 return TypeNames[Ty] = name;
361 CppWriter::printCppName(const Type* Ty)
363 printEscapedString(getCppName(Ty));
367 CppWriter::getCppName(const Value* val) {
369 ValueMap::iterator I = ValueNames.find(val);
370 if (I != ValueNames.end() && I->first == val)
373 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
374 name = std::string("gvar_") +
375 getTypePrefix(GV->getType()->getElementType());
376 } else if (isa<Function>(val)) {
377 name = std::string("func_");
378 } else if (const Constant* C = dyn_cast<Constant>(val)) {
379 name = std::string("const_") + getTypePrefix(C->getType());
380 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
382 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
383 Function::const_arg_iterator(Arg)) + 1;
384 name = std::string("arg_") + utostr(argNum);
385 NameSet::iterator NI = UsedNames.find(name);
386 if (NI != UsedNames.end())
387 name += std::string("_") + utostr(uniqueNum++);
388 UsedNames.insert(name);
389 return ValueNames[val] = name;
391 name = getTypePrefix(val->getType());
394 name = getTypePrefix(val->getType());
396 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
398 NameSet::iterator NI = UsedNames.find(name);
399 if (NI != UsedNames.end())
400 name += std::string("_") + utostr(uniqueNum++);
401 UsedNames.insert(name);
402 return ValueNames[val] = name;
406 CppWriter::printCppName(const Value* val) {
407 printEscapedString(getCppName(val));
411 CppWriter::printTypeInternal(const Type* Ty) {
412 // We don't print definitions for primitive types
413 if (Ty->isPrimitiveType() || Ty->isIntegral())
416 // If we already defined this type, we don't need to define it again.
417 if (DefinedTypes.find(Ty) != DefinedTypes.end())
420 // Everything below needs the name for the type so get it now.
421 std::string typeName(getCppName(Ty));
423 // Search the type stack for recursion. If we find it, then generate this
424 // as an OpaqueType, but make sure not to do this multiple times because
425 // the type could appear in multiple places on the stack. Once the opaque
426 // definition is issued, it must not be re-issued. Consequently we have to
427 // check the UnresolvedTypes list as well.
428 TypeList::const_iterator TI = std::find(TypeStack.begin(),TypeStack.end(),Ty);
429 if (TI != TypeStack.end()) {
430 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
431 if (I == UnresolvedTypes.end()) {
432 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
434 UnresolvedTypes[Ty] = typeName;
439 // We're going to print a derived type which, by definition, contains other
440 // types. So, push this one we're printing onto the type stack to assist with
441 // recursive definitions.
442 TypeStack.push_back(Ty);
444 // Print the type definition
445 switch (Ty->getTypeID()) {
446 case Type::FunctionTyID: {
447 const FunctionType* FT = cast<FunctionType>(Ty);
448 Out << "std::vector<const Type*>" << typeName << "_args;";
450 FunctionType::param_iterator PI = FT->param_begin();
451 FunctionType::param_iterator PE = FT->param_end();
452 for (; PI != PE; ++PI) {
453 const Type* argTy = static_cast<const Type*>(*PI);
454 bool isForward = printTypeInternal(argTy);
455 std::string argName(getCppName(argTy));
456 Out << typeName << "_args.push_back(" << argName;
462 bool isForward = printTypeInternal(FT->getReturnType());
463 std::string retTypeName(getCppName(FT->getReturnType()));
464 Out << "FunctionType* " << typeName << " = FunctionType::get(";
465 in(); nl(Out) << "/*Result=*/" << retTypeName;
469 nl(Out) << "/*Params=*/" << typeName << "_args,";
470 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
475 case Type::StructTyID: {
476 const StructType* ST = cast<StructType>(Ty);
477 Out << "std::vector<const Type*>" << typeName << "_fields;";
479 StructType::element_iterator EI = ST->element_begin();
480 StructType::element_iterator EE = ST->element_end();
481 for (; EI != EE; ++EI) {
482 const Type* fieldTy = static_cast<const Type*>(*EI);
483 bool isForward = printTypeInternal(fieldTy);
484 std::string fieldName(getCppName(fieldTy));
485 Out << typeName << "_fields.push_back(" << fieldName;
491 Out << "StructType* " << typeName << " = StructType::get("
492 << typeName << "_fields);";
496 case Type::ArrayTyID: {
497 const ArrayType* AT = cast<ArrayType>(Ty);
498 const Type* ET = AT->getElementType();
499 bool isForward = printTypeInternal(ET);
500 std::string elemName(getCppName(ET));
501 Out << "ArrayType* " << typeName << " = ArrayType::get("
502 << elemName << (isForward ? "_fwd" : "")
503 << ", " << utostr(AT->getNumElements()) << ");";
507 case Type::PointerTyID: {
508 const PointerType* PT = cast<PointerType>(Ty);
509 const Type* ET = PT->getElementType();
510 bool isForward = printTypeInternal(ET);
511 std::string elemName(getCppName(ET));
512 Out << "PointerType* " << typeName << " = PointerType::get("
513 << elemName << (isForward ? "_fwd" : "") << ");";
517 case Type::PackedTyID: {
518 const PackedType* PT = cast<PackedType>(Ty);
519 const Type* ET = PT->getElementType();
520 bool isForward = printTypeInternal(ET);
521 std::string elemName(getCppName(ET));
522 Out << "PackedType* " << typeName << " = PackedType::get("
523 << elemName << (isForward ? "_fwd" : "")
524 << ", " << utostr(PT->getNumElements()) << ");";
528 case Type::OpaqueTyID: {
529 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
534 error("Invalid TypeID");
537 // If the type had a name, make sure we recreate it.
538 const std::string* progTypeName =
539 findTypeName(TheModule->getTypeSymbolTable(),Ty);
541 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
545 // Pop us off the type stack
546 TypeStack.pop_back();
548 // Indicate that this type is now defined.
549 DefinedTypes.insert(Ty);
551 // Early resolve as many unresolved types as possible. Search the unresolved
552 // types map for the type we just printed. Now that its definition is complete
553 // we can resolve any previous references to it. This prevents a cascade of
555 TypeMap::iterator I = UnresolvedTypes.find(Ty);
556 if (I != UnresolvedTypes.end()) {
557 Out << "cast<OpaqueType>(" << I->second
558 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
560 Out << I->second << " = cast<";
561 switch (Ty->getTypeID()) {
562 case Type::FunctionTyID: Out << "FunctionType"; break;
563 case Type::ArrayTyID: Out << "ArrayType"; break;
564 case Type::StructTyID: Out << "StructType"; break;
565 case Type::PackedTyID: Out << "PackedType"; break;
566 case Type::PointerTyID: Out << "PointerType"; break;
567 case Type::OpaqueTyID: Out << "OpaqueType"; break;
568 default: Out << "NoSuchDerivedType"; break;
570 Out << ">(" << I->second << "_fwd.get());";
572 UnresolvedTypes.erase(I);
575 // Finally, separate the type definition from other with a newline.
578 // We weren't a recursive type
582 // Prints a type definition. Returns true if it could not resolve all the types
583 // in the definition but had to use a forward reference.
585 CppWriter::printType(const Type* Ty) {
586 assert(TypeStack.empty());
588 printTypeInternal(Ty);
589 assert(TypeStack.empty());
593 CppWriter::printTypes(const Module* M) {
595 // Walk the symbol table and print out all its types
596 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
597 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
600 // For primitive types and types already defined, just add a name
601 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
602 if (TI->second->isIntegral() || TI->second->isPrimitiveType() ||
603 TNI != TypeNames.end()) {
604 Out << "mod->addTypeName(\"";
605 printEscapedString(TI->first);
606 Out << "\", " << getCppName(TI->second) << ");";
608 // For everything else, define the type
610 printType(TI->second);
614 // Add all of the global variables to the value table...
615 for (Module::const_global_iterator I = TheModule->global_begin(),
616 E = TheModule->global_end(); I != E; ++I) {
617 if (I->hasInitializer())
618 printType(I->getInitializer()->getType());
619 printType(I->getType());
622 // Add all the functions to the table
623 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
625 printType(FI->getReturnType());
626 printType(FI->getFunctionType());
627 // Add all the function arguments
628 for(Function::const_arg_iterator AI = FI->arg_begin(),
629 AE = FI->arg_end(); AI != AE; ++AI) {
630 printType(AI->getType());
633 // Add all of the basic blocks and instructions
634 for (Function::const_iterator BB = FI->begin(),
635 E = FI->end(); BB != E; ++BB) {
636 printType(BB->getType());
637 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
639 printType(I->getType());
640 for (unsigned i = 0; i < I->getNumOperands(); ++i)
641 printType(I->getOperand(i)->getType());
648 // printConstant - Print out a constant pool entry...
649 void CppWriter::printConstant(const Constant *CV) {
650 // First, if the constant is actually a GlobalValue (variable or function) or
651 // its already in the constant list then we've printed it already and we can
653 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
656 std::string constName(getCppName(CV));
657 std::string typeName(getCppName(CV->getType()));
658 if (CV->isNullValue()) {
659 Out << "Constant* " << constName << " = Constant::getNullValue("
664 if (isa<GlobalValue>(CV)) {
665 // Skip variables and functions, we emit them elsewhere
668 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
669 Out << "ConstantInt* " << constName << " = ConstantInt::get("
670 << typeName << ", " << CI->getZExtValue() << ");";
671 } else if (isa<ConstantAggregateZero>(CV)) {
672 Out << "ConstantAggregateZero* " << constName
673 << " = ConstantAggregateZero::get(" << typeName << ");";
674 } else if (isa<ConstantPointerNull>(CV)) {
675 Out << "ConstantPointerNull* " << constName
676 << " = ConstanPointerNull::get(" << typeName << ");";
677 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
678 Out << "ConstantFP* " << constName << " = ";
681 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
682 if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
683 Out << "Constant* " << constName << " = ConstantArray::get(\"";
684 printEscapedString(CA->getAsString());
685 // Determine if we want null termination or not.
686 if (CA->getType()->getNumElements() <= CA->getAsString().length())
687 Out << "\", false";// No null terminator
689 Out << "\", true"; // Indicate that the null terminator should be added.
692 Out << "std::vector<Constant*> " << constName << "_elems;";
694 unsigned N = CA->getNumOperands();
695 for (unsigned i = 0; i < N; ++i) {
696 printConstant(CA->getOperand(i)); // recurse to print operands
697 Out << constName << "_elems.push_back("
698 << getCppName(CA->getOperand(i)) << ");";
701 Out << "Constant* " << constName << " = ConstantArray::get("
702 << typeName << ", " << constName << "_elems);";
704 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
705 Out << "std::vector<Constant*> " << constName << "_fields;";
707 unsigned N = CS->getNumOperands();
708 for (unsigned i = 0; i < N; i++) {
709 printConstant(CS->getOperand(i));
710 Out << constName << "_fields.push_back("
711 << getCppName(CS->getOperand(i)) << ");";
714 Out << "Constant* " << constName << " = ConstantStruct::get("
715 << typeName << ", " << constName << "_fields);";
716 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
717 Out << "std::vector<Constant*> " << constName << "_elems;";
719 unsigned N = CP->getNumOperands();
720 for (unsigned i = 0; i < N; ++i) {
721 printConstant(CP->getOperand(i));
722 Out << constName << "_elems.push_back("
723 << getCppName(CP->getOperand(i)) << ");";
726 Out << "Constant* " << constName << " = ConstantPacked::get("
727 << typeName << ", " << constName << "_elems);";
728 } else if (isa<UndefValue>(CV)) {
729 Out << "UndefValue* " << constName << " = UndefValue::get("
731 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
732 if (CE->getOpcode() == Instruction::GetElementPtr) {
733 Out << "std::vector<Constant*> " << constName << "_indices;";
735 printConstant(CE->getOperand(0));
736 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
737 printConstant(CE->getOperand(i));
738 Out << constName << "_indices.push_back("
739 << getCppName(CE->getOperand(i)) << ");";
742 Out << "Constant* " << constName
743 << " = ConstantExpr::getGetElementPtr("
744 << getCppName(CE->getOperand(0)) << ", "
745 << constName << "_indices);";
746 } else if (CE->isCast()) {
747 printConstant(CE->getOperand(0));
748 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
749 switch (CE->getOpcode()) {
750 default: assert(0 && "Invalid cast opcode");
751 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
752 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
753 case Instruction::SExt: Out << "Instruction::SExt"; break;
754 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
755 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
756 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
757 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
758 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
759 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
760 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
761 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
762 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
764 Out << ", " << getCppName(CE->getOperand(0)) << ", "
765 << getCppName(CE->getType()) << ");";
767 unsigned N = CE->getNumOperands();
768 for (unsigned i = 0; i < N; ++i ) {
769 printConstant(CE->getOperand(i));
771 Out << "Constant* " << constName << " = ConstantExpr::";
772 switch (CE->getOpcode()) {
773 case Instruction::Add: Out << "getAdd("; break;
774 case Instruction::Sub: Out << "getSub("; break;
775 case Instruction::Mul: Out << "getMul("; break;
776 case Instruction::UDiv: Out << "getUDiv("; break;
777 case Instruction::SDiv: Out << "getSDiv("; break;
778 case Instruction::FDiv: Out << "getFDiv("; break;
779 case Instruction::URem: Out << "getURem("; break;
780 case Instruction::SRem: Out << "getSRem("; break;
781 case Instruction::FRem: Out << "getFRem("; break;
782 case Instruction::And: Out << "getAnd("; break;
783 case Instruction::Or: Out << "getOr("; break;
784 case Instruction::Xor: Out << "getXor("; break;
785 case Instruction::ICmp:
786 Out << "getICmp(ICmpInst::ICMP_";
787 switch (CE->getPredicate()) {
788 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
789 case ICmpInst::ICMP_NE: Out << "NE"; break;
790 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
791 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
792 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
793 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
794 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
795 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
796 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
797 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
798 default: error("Invalid ICmp Predicate");
801 case Instruction::FCmp:
802 Out << "getFCmp(FCmpInst::FCMP_";
803 switch (CE->getPredicate()) {
804 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
805 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
806 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
807 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
808 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
809 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
810 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
811 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
812 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
813 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
814 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
815 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
816 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
817 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
818 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
819 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
820 default: error("Invalid FCmp Predicate");
823 case Instruction::Shl: Out << "getShl("; break;
824 case Instruction::LShr: Out << "getLShr("; break;
825 case Instruction::AShr: Out << "getAShr("; break;
826 case Instruction::Select: Out << "getSelect("; break;
827 case Instruction::ExtractElement: Out << "getExtractElement("; break;
828 case Instruction::InsertElement: Out << "getInsertElement("; break;
829 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
831 error("Invalid constant expression");
834 Out << getCppName(CE->getOperand(0));
835 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
836 Out << ", " << getCppName(CE->getOperand(i));
840 error("Bad Constant");
841 Out << "Constant* " << constName << " = 0; ";
847 CppWriter::printConstants(const Module* M) {
848 // Traverse all the global variables looking for constant initializers
849 for (Module::const_global_iterator I = TheModule->global_begin(),
850 E = TheModule->global_end(); I != E; ++I)
851 if (I->hasInitializer())
852 printConstant(I->getInitializer());
854 // Traverse the LLVM functions looking for constants
855 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
857 // Add all of the basic blocks and instructions
858 for (Function::const_iterator BB = FI->begin(),
859 E = FI->end(); BB != E; ++BB) {
860 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
862 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
863 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
872 void CppWriter::printVariableUses(const GlobalVariable *GV) {
873 nl(Out) << "// Type Definitions";
875 printType(GV->getType());
876 if (GV->hasInitializer()) {
877 Constant* Init = GV->getInitializer();
878 printType(Init->getType());
879 if (Function* F = dyn_cast<Function>(Init)) {
880 nl(Out)<< "/ Function Declarations"; nl(Out);
881 printFunctionHead(F);
882 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
883 nl(Out) << "// Global Variable Declarations"; nl(Out);
884 printVariableHead(gv);
886 nl(Out) << "// Constant Definitions"; nl(Out);
889 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
890 nl(Out) << "// Global Variable Definitions"; nl(Out);
891 printVariableBody(gv);
896 void CppWriter::printVariableHead(const GlobalVariable *GV) {
897 nl(Out) << "GlobalVariable* " << getCppName(GV);
899 Out << " = mod->getGlobalVariable(";
900 printEscapedString(GV->getName());
901 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
902 nl(Out) << "if (!" << getCppName(GV) << ") {";
903 in(); nl(Out) << getCppName(GV);
905 Out << " = new GlobalVariable(";
906 nl(Out) << "/*Type=*/";
907 printCppName(GV->getType()->getElementType());
909 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
911 nl(Out) << "/*Linkage=*/";
912 printLinkageType(GV->getLinkage());
914 nl(Out) << "/*Initializer=*/0, ";
915 if (GV->hasInitializer()) {
916 Out << "// has initializer, specified below";
918 nl(Out) << "/*Name=*/\"";
919 printEscapedString(GV->getName());
924 if (GV->hasSection()) {
926 Out << "->setSection(\"";
927 printEscapedString(GV->getSection());
931 if (GV->getAlignment()) {
933 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
937 out(); Out << "}"; nl(Out);
942 CppWriter::printVariableBody(const GlobalVariable *GV) {
943 if (GV->hasInitializer()) {
945 Out << "->setInitializer(";
946 //if (!isa<GlobalValue(GV->getInitializer()))
948 Out << getCppName(GV->getInitializer()) << ");";
954 CppWriter::getOpName(Value* V) {
955 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
956 return getCppName(V);
958 // See if its alread in the map of forward references, if so just return the
959 // name we already set up for it
960 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
961 if (I != ForwardRefs.end())
964 // This is a new forward reference. Generate a unique name for it
965 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
967 // Yes, this is a hack. An Argument is the smallest instantiable value that
968 // we can make as a placeholder for the real value. We'll replace these
969 // Argument instances later.
970 Out << "Argument* " << result << " = new Argument("
971 << getCppName(V->getType()) << ");";
973 ForwardRefs[V] = result;
977 // printInstruction - This member is called for each Instruction in a function.
979 CppWriter::printInstruction(const Instruction *I, const std::string& bbname) {
980 std::string iName(getCppName(I));
982 // Before we emit this instruction, we need to take care of generating any
983 // forward references. So, we get the names of all the operands in advance
984 std::string* opNames = new std::string[I->getNumOperands()];
985 for (unsigned i = 0; i < I->getNumOperands(); i++) {
986 opNames[i] = getOpName(I->getOperand(i));
989 switch (I->getOpcode()) {
990 case Instruction::Ret: {
991 const ReturnInst* ret = cast<ReturnInst>(I);
992 Out << "ReturnInst* " << iName << " = new ReturnInst("
993 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
996 case Instruction::Br: {
997 const BranchInst* br = cast<BranchInst>(I);
998 Out << "BranchInst* " << iName << " = new BranchInst(" ;
999 if (br->getNumOperands() == 3 ) {
1000 Out << opNames[0] << ", "
1001 << opNames[1] << ", "
1002 << opNames[2] << ", ";
1004 } else if (br->getNumOperands() == 1) {
1005 Out << opNames[0] << ", ";
1007 error("Branch with 2 operands?");
1009 Out << bbname << ");";
1012 case Instruction::Switch: {
1013 const SwitchInst* sw = cast<SwitchInst>(I);
1014 Out << "SwitchInst* " << iName << " = new SwitchInst("
1015 << opNames[0] << ", "
1016 << opNames[1] << ", "
1017 << sw->getNumCases() << ", " << bbname << ");";
1019 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1020 Out << iName << "->addCase("
1021 << opNames[i] << ", "
1022 << opNames[i+1] << ");";
1027 case Instruction::Invoke: {
1028 const InvokeInst* inv = cast<InvokeInst>(I);
1029 Out << "std::vector<Value*> " << iName << "_params;";
1031 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1032 Out << iName << "_params.push_back("
1033 << opNames[i] << ");";
1036 Out << "InvokeInst* " << iName << " = new InvokeInst("
1037 << opNames[0] << ", "
1038 << opNames[1] << ", "
1039 << opNames[2] << ", "
1040 << iName << "_params, \"";
1041 printEscapedString(inv->getName());
1042 Out << "\", " << bbname << ");";
1043 nl(Out) << iName << "->setCallingConv(";
1044 printCallingConv(inv->getCallingConv());
1048 case Instruction::Unwind: {
1049 Out << "UnwindInst* " << iName << " = new UnwindInst("
1053 case Instruction::Unreachable:{
1054 Out << "UnreachableInst* " << iName << " = new UnreachableInst("
1058 case Instruction::Add:
1059 case Instruction::Sub:
1060 case Instruction::Mul:
1061 case Instruction::UDiv:
1062 case Instruction::SDiv:
1063 case Instruction::FDiv:
1064 case Instruction::URem:
1065 case Instruction::SRem:
1066 case Instruction::FRem:
1067 case Instruction::And:
1068 case Instruction::Or:
1069 case Instruction::Xor:
1070 case Instruction::Shl:
1071 case Instruction::LShr:
1072 case Instruction::AShr:{
1073 Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
1074 switch (I->getOpcode()) {
1075 case Instruction::Add: Out << "Instruction::Add"; break;
1076 case Instruction::Sub: Out << "Instruction::Sub"; break;
1077 case Instruction::Mul: Out << "Instruction::Mul"; break;
1078 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1079 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1080 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1081 case Instruction::URem:Out << "Instruction::URem"; break;
1082 case Instruction::SRem:Out << "Instruction::SRem"; break;
1083 case Instruction::FRem:Out << "Instruction::FRem"; break;
1084 case Instruction::And: Out << "Instruction::And"; break;
1085 case Instruction::Or: Out << "Instruction::Or"; break;
1086 case Instruction::Xor: Out << "Instruction::Xor"; break;
1087 case Instruction::Shl: Out << "Instruction::Shl"; break;
1088 case Instruction::LShr:Out << "Instruction::LShr"; break;
1089 case Instruction::AShr:Out << "Instruction::AShr"; break;
1090 default: Out << "Instruction::BadOpCode"; break;
1092 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1093 printEscapedString(I->getName());
1094 Out << "\", " << bbname << ");";
1097 case Instruction::FCmp: {
1098 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1099 switch (cast<FCmpInst>(I)->getPredicate()) {
1100 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1101 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1102 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1103 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1104 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1105 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1106 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1107 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1108 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1109 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1110 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1111 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1112 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1113 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1114 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1115 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1116 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1118 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1119 printEscapedString(I->getName());
1120 Out << "\", " << bbname << ");";
1123 case Instruction::ICmp: {
1124 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1125 switch (cast<ICmpInst>(I)->getPredicate()) {
1126 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1127 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1128 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1129 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1130 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1131 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1132 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1133 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1134 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1135 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1136 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1138 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1139 printEscapedString(I->getName());
1140 Out << "\", " << bbname << ");";
1143 case Instruction::Malloc: {
1144 const MallocInst* mallocI = cast<MallocInst>(I);
1145 Out << "MallocInst* " << iName << " = new MallocInst("
1146 << getCppName(mallocI->getAllocatedType()) << ", ";
1147 if (mallocI->isArrayAllocation())
1148 Out << opNames[0] << ", " ;
1150 printEscapedString(mallocI->getName());
1151 Out << "\", " << bbname << ");";
1152 if (mallocI->getAlignment())
1153 nl(Out) << iName << "->setAlignment("
1154 << mallocI->getAlignment() << ");";
1157 case Instruction::Free: {
1158 Out << "FreeInst* " << iName << " = new FreeInst("
1159 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1162 case Instruction::Alloca: {
1163 const AllocaInst* allocaI = cast<AllocaInst>(I);
1164 Out << "AllocaInst* " << iName << " = new AllocaInst("
1165 << getCppName(allocaI->getAllocatedType()) << ", ";
1166 if (allocaI->isArrayAllocation())
1167 Out << opNames[0] << ", ";
1169 printEscapedString(allocaI->getName());
1170 Out << "\", " << bbname << ");";
1171 if (allocaI->getAlignment())
1172 nl(Out) << iName << "->setAlignment("
1173 << allocaI->getAlignment() << ");";
1176 case Instruction::Load:{
1177 const LoadInst* load = cast<LoadInst>(I);
1178 Out << "LoadInst* " << iName << " = new LoadInst("
1179 << opNames[0] << ", \"";
1180 printEscapedString(load->getName());
1181 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1182 << ", " << bbname << ");";
1185 case Instruction::Store: {
1186 const StoreInst* store = cast<StoreInst>(I);
1187 Out << "StoreInst* " << iName << " = new StoreInst("
1188 << opNames[0] << ", "
1189 << opNames[1] << ", "
1190 << (store->isVolatile() ? "true" : "false")
1191 << ", " << bbname << ");";
1194 case Instruction::GetElementPtr: {
1195 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1196 if (gep->getNumOperands() <= 2) {
1197 Out << "GetElementPtrInst* " << iName << " = new GetElementPtrInst("
1199 if (gep->getNumOperands() == 2)
1200 Out << ", " << opNames[1];
1202 Out << "std::vector<Value*> " << iName << "_indices;";
1204 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1205 Out << iName << "_indices.push_back("
1206 << opNames[i] << ");";
1209 Out << "Instruction* " << iName << " = new GetElementPtrInst("
1210 << opNames[0] << ", " << iName << "_indices";
1213 printEscapedString(gep->getName());
1214 Out << "\", " << bbname << ");";
1217 case Instruction::PHI: {
1218 const PHINode* phi = cast<PHINode>(I);
1220 Out << "PHINode* " << iName << " = new PHINode("
1221 << getCppName(phi->getType()) << ", \"";
1222 printEscapedString(phi->getName());
1223 Out << "\", " << bbname << ");";
1224 nl(Out) << iName << "->reserveOperandSpace("
1225 << phi->getNumIncomingValues()
1228 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1229 Out << iName << "->addIncoming("
1230 << opNames[i] << ", " << opNames[i+1] << ");";
1235 case Instruction::Trunc:
1236 case Instruction::ZExt:
1237 case Instruction::SExt:
1238 case Instruction::FPTrunc:
1239 case Instruction::FPExt:
1240 case Instruction::FPToUI:
1241 case Instruction::FPToSI:
1242 case Instruction::UIToFP:
1243 case Instruction::SIToFP:
1244 case Instruction::PtrToInt:
1245 case Instruction::IntToPtr:
1246 case Instruction::BitCast: {
1247 const CastInst* cst = cast<CastInst>(I);
1248 Out << "CastInst* " << iName << " = new ";
1249 switch (I->getOpcode()) {
1250 case Instruction::Trunc: Out << "TruncInst";
1251 case Instruction::ZExt: Out << "ZExtInst";
1252 case Instruction::SExt: Out << "SExtInst";
1253 case Instruction::FPTrunc: Out << "FPTruncInst";
1254 case Instruction::FPExt: Out << "FPExtInst";
1255 case Instruction::FPToUI: Out << "FPToUIInst";
1256 case Instruction::FPToSI: Out << "FPToSIInst";
1257 case Instruction::UIToFP: Out << "UIToFPInst";
1258 case Instruction::SIToFP: Out << "SIToFPInst";
1259 case Instruction::PtrToInt: Out << "PtrToInst";
1260 case Instruction::IntToPtr: Out << "IntToPtrInst";
1261 case Instruction::BitCast: Out << "BitCastInst";
1262 default: assert(!"Unreachable"); break;
1264 Out << "(" << opNames[0] << ", "
1265 << getCppName(cst->getType()) << ", \"";
1266 printEscapedString(cst->getName());
1267 Out << "\", " << bbname << ");";
1270 case Instruction::Call:{
1271 const CallInst* call = cast<CallInst>(I);
1272 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1273 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1274 << getCppName(ila->getFunctionType()) << ", \""
1275 << ila->getAsmString() << "\", \""
1276 << ila->getConstraintString() << "\","
1277 << (ila->hasSideEffects() ? "true" : "false") << ");";
1280 if (call->getNumOperands() > 3) {
1281 Out << "std::vector<Value*> " << iName << "_params;";
1283 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1284 Out << iName << "_params.push_back(" << opNames[i] << ");";
1287 Out << "CallInst* " << iName << " = new CallInst("
1288 << opNames[0] << ", " << iName << "_params, \"";
1289 } else if (call->getNumOperands() == 3) {
1290 Out << "CallInst* " << iName << " = new CallInst("
1291 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1292 } else if (call->getNumOperands() == 2) {
1293 Out << "CallInst* " << iName << " = new CallInst("
1294 << opNames[0] << ", " << opNames[1] << ", \"";
1296 Out << "CallInst* " << iName << " = new CallInst(" << opNames[0]
1299 printEscapedString(call->getName());
1300 Out << "\", " << bbname << ");";
1301 nl(Out) << iName << "->setCallingConv(";
1302 printCallingConv(call->getCallingConv());
1304 nl(Out) << iName << "->setTailCall("
1305 << (call->isTailCall() ? "true":"false");
1309 case Instruction::Select: {
1310 const SelectInst* sel = cast<SelectInst>(I);
1311 Out << "SelectInst* " << getCppName(sel) << " = new SelectInst(";
1312 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1313 printEscapedString(sel->getName());
1314 Out << "\", " << bbname << ");";
1317 case Instruction::UserOp1:
1319 case Instruction::UserOp2: {
1320 /// FIXME: What should be done here?
1323 case Instruction::VAArg: {
1324 const VAArgInst* va = cast<VAArgInst>(I);
1325 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1326 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1327 printEscapedString(va->getName());
1328 Out << "\", " << bbname << ");";
1331 case Instruction::ExtractElement: {
1332 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1333 Out << "ExtractElementInst* " << getCppName(eei)
1334 << " = new ExtractElementInst(" << opNames[0]
1335 << ", " << opNames[1] << ", \"";
1336 printEscapedString(eei->getName());
1337 Out << "\", " << bbname << ");";
1340 case Instruction::InsertElement: {
1341 const InsertElementInst* iei = cast<InsertElementInst>(I);
1342 Out << "InsertElementInst* " << getCppName(iei)
1343 << " = new InsertElementInst(" << opNames[0]
1344 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1345 printEscapedString(iei->getName());
1346 Out << "\", " << bbname << ");";
1349 case Instruction::ShuffleVector: {
1350 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1351 Out << "ShuffleVectorInst* " << getCppName(svi)
1352 << " = new ShuffleVectorInst(" << opNames[0]
1353 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1354 printEscapedString(svi->getName());
1355 Out << "\", " << bbname << ");";
1359 DefinedValues.insert(I);
1364 // Print out the types, constants and declarations needed by one function
1365 void CppWriter::printFunctionUses(const Function* F) {
1367 nl(Out) << "// Type Definitions"; nl(Out);
1369 // Print the function's return type
1370 printType(F->getReturnType());
1372 // Print the function's function type
1373 printType(F->getFunctionType());
1375 // Print the types of each of the function's arguments
1376 for(Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1378 printType(AI->getType());
1382 // Print type definitions for every type referenced by an instruction and
1383 // make a note of any global values or constants that are referenced
1384 std::vector<GlobalValue*> gvs;
1385 std::vector<Constant*> consts;
1386 for (Function::const_iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB){
1387 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1389 // Print the type of the instruction itself
1390 printType(I->getType());
1392 // Print the type of each of the instruction's operands
1393 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1394 Value* operand = I->getOperand(i);
1395 printType(operand->getType());
1396 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand))
1398 else if (Constant* C = dyn_cast<Constant>(operand))
1399 consts.push_back(C);
1404 // Print the function declarations for any functions encountered
1405 nl(Out) << "// Function Declarations"; nl(Out);
1406 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1408 if (Function* Fun = dyn_cast<Function>(*I)) {
1409 if (!is_inline || Fun != F)
1410 printFunctionHead(Fun);
1414 // Print the global variable declarations for any variables encountered
1415 nl(Out) << "// Global Variable Declarations"; nl(Out);
1416 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1418 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1419 printVariableHead(F);
1422 // Print the constants found
1423 nl(Out) << "// Constant Definitions"; nl(Out);
1424 for (std::vector<Constant*>::iterator I = consts.begin(), E = consts.end();
1429 // Process the global variables definitions now that all the constants have
1430 // been emitted. These definitions just couple the gvars with their constant
1432 nl(Out) << "// Global Variable Definitions"; nl(Out);
1433 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1435 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1436 printVariableBody(GV);
1440 void CppWriter::printFunctionHead(const Function* F) {
1441 nl(Out) << "Function* " << getCppName(F);
1443 Out << " = mod->getFunction(\"";
1444 printEscapedString(F->getName());
1445 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1446 nl(Out) << "if (!" << getCppName(F) << ") {";
1447 nl(Out) << getCppName(F);
1449 Out<< " = new Function(";
1450 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1451 nl(Out) << "/*Linkage=*/";
1452 printLinkageType(F->getLinkage());
1454 nl(Out) << "/*Name=*/\"";
1455 printEscapedString(F->getName());
1456 Out << "\", mod); " << (F->isExternal()? "// (external, no body)" : "");
1459 Out << "->setCallingConv(";
1460 printCallingConv(F->getCallingConv());
1463 if (F->hasSection()) {
1465 Out << "->setSection(\"" << F->getSection() << "\");";
1468 if (F->getAlignment()) {
1470 Out << "->setAlignment(" << F->getAlignment() << ");";
1479 void CppWriter::printFunctionBody(const Function *F) {
1480 if (F->isExternal())
1481 return; // external functions have no bodies.
1483 // Clear the DefinedValues and ForwardRefs maps because we can't have
1484 // cross-function forward refs
1485 ForwardRefs.clear();
1486 DefinedValues.clear();
1488 // Create all the argument values
1490 if (!F->arg_empty()) {
1491 Out << "Function::arg_iterator args = " << getCppName(F)
1492 << "->arg_begin();";
1495 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1497 Out << "Value* " << getCppName(AI) << " = args++;";
1499 if (AI->hasName()) {
1500 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1506 // Create all the basic blocks
1508 for (Function::const_iterator BI = F->begin(), BE = F->end();
1510 std::string bbname(getCppName(BI));
1511 Out << "BasicBlock* " << bbname << " = new BasicBlock(\"";
1513 printEscapedString(BI->getName());
1514 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1518 // Output all of its basic blocks... for the function
1519 for (Function::const_iterator BI = F->begin(), BE = F->end();
1521 std::string bbname(getCppName(BI));
1522 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1525 // Output all of the instructions in the basic block...
1526 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1528 printInstruction(I,bbname);
1532 // Loop over the ForwardRefs and resolve them now that all instructions
1534 if (!ForwardRefs.empty()) {
1535 nl(Out) << "// Resolve Forward References";
1539 while (!ForwardRefs.empty()) {
1540 ForwardRefMap::iterator I = ForwardRefs.begin();
1541 Out << I->second << "->replaceAllUsesWith("
1542 << getCppName(I->first) << "); delete " << I->second << ";";
1544 ForwardRefs.erase(I);
1548 void CppWriter::printInline(const std::string& fname, const std::string& func) {
1549 const Function* F = TheModule->getNamedFunction(func);
1551 error(std::string("Function '") + func + "' not found in input module");
1554 if (F->isExternal()) {
1555 error(std::string("Function '") + func + "' is external!");
1558 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1560 unsigned arg_count = 1;
1561 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1563 Out << ", Value* arg_" << arg_count;
1568 printFunctionUses(F);
1569 printFunctionBody(F);
1571 Out << "return " << getCppName(F->begin()) << ";";
1576 void CppWriter::printModuleBody() {
1577 // Print out all the type definitions
1578 nl(Out) << "// Type Definitions"; nl(Out);
1579 printTypes(TheModule);
1581 // Functions can call each other and global variables can reference them so
1582 // define all the functions first before emitting their function bodies.
1583 nl(Out) << "// Function Declarations"; nl(Out);
1584 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1586 printFunctionHead(I);
1588 // Process the global variables declarations. We can't initialze them until
1589 // after the constants are printed so just print a header for each global
1590 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1591 for (Module::const_global_iterator I = TheModule->global_begin(),
1592 E = TheModule->global_end(); I != E; ++I) {
1593 printVariableHead(I);
1596 // Print out all the constants definitions. Constants don't recurse except
1597 // through GlobalValues. All GlobalValues have been declared at this point
1598 // so we can proceed to generate the constants.
1599 nl(Out) << "// Constant Definitions"; nl(Out);
1600 printConstants(TheModule);
1602 // Process the global variables definitions now that all the constants have
1603 // been emitted. These definitions just couple the gvars with their constant
1605 nl(Out) << "// Global Variable Definitions"; nl(Out);
1606 for (Module::const_global_iterator I = TheModule->global_begin(),
1607 E = TheModule->global_end(); I != E; ++I) {
1608 printVariableBody(I);
1611 // Finally, we can safely put out all of the function bodies.
1612 nl(Out) << "// Function Definitions"; nl(Out);
1613 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1615 if (!I->isExternal()) {
1616 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1620 printFunctionBody(I);
1627 void CppWriter::printProgram(
1628 const std::string& fname,
1629 const std::string& mName
1631 Out << "#include <llvm/Module.h>\n";
1632 Out << "#include <llvm/DerivedTypes.h>\n";
1633 Out << "#include <llvm/Constants.h>\n";
1634 Out << "#include <llvm/GlobalVariable.h>\n";
1635 Out << "#include <llvm/Function.h>\n";
1636 Out << "#include <llvm/CallingConv.h>\n";
1637 Out << "#include <llvm/BasicBlock.h>\n";
1638 Out << "#include <llvm/Instructions.h>\n";
1639 Out << "#include <llvm/InlineAsm.h>\n";
1640 Out << "#include <llvm/Support/MathExtras.h>\n";
1641 Out << "#include <llvm/Pass.h>\n";
1642 Out << "#include <llvm/PassManager.h>\n";
1643 Out << "#include <llvm/Analysis/Verifier.h>\n";
1644 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1645 Out << "#include <algorithm>\n";
1646 Out << "#include <iostream>\n\n";
1647 Out << "using namespace llvm;\n\n";
1648 Out << "Module* " << fname << "();\n\n";
1649 Out << "int main(int argc, char**argv) {\n";
1650 Out << " Module* Mod = makeLLVMModule();\n";
1651 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1652 Out << " std::cerr.flush();\n";
1653 Out << " std::cout.flush();\n";
1654 Out << " PassManager PM;\n";
1655 Out << " PM.add(new PrintModulePass(&std::cout));\n";
1656 Out << " PM.run(*Mod);\n";
1657 Out << " return 0;\n";
1659 printModule(fname,mName);
1662 void CppWriter::printModule(
1663 const std::string& fname,
1664 const std::string& mName
1666 nl(Out) << "Module* " << fname << "() {";
1667 nl(Out,1) << "// Module Construction";
1668 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1669 nl(Out) << "mod->setEndianness(";
1670 switch (TheModule->getEndianness()) {
1671 case Module::LittleEndian: Out << "Module::LittleEndian);"; break;
1672 case Module::BigEndian: Out << "Module::BigEndian);"; break;
1673 case Module::AnyEndianness:Out << "Module::AnyEndianness);"; break;
1675 nl(Out) << "mod->setPointerSize(";
1676 switch (TheModule->getPointerSize()) {
1677 case Module::Pointer32: Out << "Module::Pointer32);"; break;
1678 case Module::Pointer64: Out << "Module::Pointer64);"; break;
1679 case Module::AnyPointerSize: Out << "Module::AnyPointerSize);"; break;
1682 if (!TheModule->getTargetTriple().empty()) {
1683 Out << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1688 if (!TheModule->getModuleInlineAsm().empty()) {
1689 Out << "mod->setModuleInlineAsm(\"";
1690 printEscapedString(TheModule->getModuleInlineAsm());
1695 // Loop over the dependent libraries and emit them.
1696 Module::lib_iterator LI = TheModule->lib_begin();
1697 Module::lib_iterator LE = TheModule->lib_end();
1699 Out << "mod->addLibrary(\"" << *LI << "\");";
1704 nl(Out) << "return mod;";
1709 void CppWriter::printContents(
1710 const std::string& fname, // Name of generated function
1711 const std::string& mName // Name of module generated module
1713 Out << "\nModule* " << fname << "(Module *mod) {\n";
1714 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1716 Out << "\nreturn mod;\n";
1720 void CppWriter::printFunction(
1721 const std::string& fname, // Name of generated function
1722 const std::string& funcName // Name of function to generate
1724 const Function* F = TheModule->getNamedFunction(funcName);
1726 error(std::string("Function '") + funcName + "' not found in input module");
1729 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1730 printFunctionUses(F);
1731 printFunctionHead(F);
1732 printFunctionBody(F);
1733 Out << "return " << getCppName(F) << ";\n";
1737 void CppWriter::printVariable(
1738 const std::string& fname, /// Name of generated function
1739 const std::string& varName // Name of variable to generate
1741 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1744 error(std::string("Variable '") + varName + "' not found in input module");
1747 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1748 printVariableUses(GV);
1749 printVariableHead(GV);
1750 printVariableBody(GV);
1751 Out << "return " << getCppName(GV) << ";\n";
1755 void CppWriter::printType(
1756 const std::string& fname, /// Name of generated function
1757 const std::string& typeName // Name of type to generate
1759 const Type* Ty = TheModule->getTypeByName(typeName);
1761 error(std::string("Type '") + typeName + "' not found in input module");
1764 Out << "\nType* " << fname << "(Module *mod) {\n";
1766 Out << "return " << getCppName(Ty) << ";\n";
1770 } // end anonymous llvm
1774 void WriteModuleToCppFile(Module* mod, std::ostream& o) {
1775 // Initialize a CppWriter for us to use
1776 CppWriter W(o, mod);
1779 o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1781 // Get the name of the function we're supposed to generate
1782 std::string fname = FuncName.getValue();
1784 // Get the name of the thing we are to generate
1785 std::string tgtname = NameToGenerate.getValue();
1786 if (GenerationType == GenModule ||
1787 GenerationType == GenContents ||
1788 GenerationType == GenProgram) {
1789 if (tgtname == "!bad!") {
1790 if (mod->getModuleIdentifier() == "-")
1791 tgtname = "<stdin>";
1793 tgtname = mod->getModuleIdentifier();
1795 } else if (tgtname == "!bad!") {
1796 W.error("You must use the -for option with -gen-{function,variable,type}");
1799 switch (WhatToGenerate(GenerationType)) {
1802 fname = "makeLLVMModule";
1803 W.printProgram(fname,tgtname);
1807 fname = "makeLLVMModule";
1808 W.printModule(fname,tgtname);
1812 fname = "makeLLVMModuleContents";
1813 W.printContents(fname,tgtname);
1817 fname = "makeLLVMFunction";
1818 W.printFunction(fname,tgtname);
1822 fname = "makeLLVMInline";
1823 W.printInline(fname,tgtname);
1827 fname = "makeLLVMVariable";
1828 W.printVariable(fname,tgtname);
1832 fname = "makeLLVMType";
1833 W.printType(fname,tgtname);
1836 W.error("Invalid generation option");