1 //===-- CppWriter.cpp - Printing LLVM IR as a C++ Source File -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Reid Spencer and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the writing of the LLVM IR as a set of C++ calls to the
11 // LLVM IR interface. The input module is assumed to be verified.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CallingConv.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/InlineAsm.h"
19 #include "llvm/Instruction.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/SymbolTable.h"
23 #include "llvm/Support/CFG.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Config/config.h"
35 static cl::opt<std::string>
36 FuncName("funcname", cl::desc("Specify the name of the generated function"),
37 cl::value_desc("function name"));
49 static cl::opt<WhatToGenerate> GenerationType(cl::Optional,
50 cl::desc("Choose what kind of output to generate"),
53 clEnumValN(GenProgram, "gen-program", "Generate a complete program"),
54 clEnumValN(GenModule, "gen-module", "Generate a module definition"),
55 clEnumValN(GenContents,"gen-contents", "Generate contents of a module"),
56 clEnumValN(GenFunction,"gen-function", "Generate a function definition"),
57 clEnumValN(GenInline, "gen-inline", "Generate an inline function"),
58 clEnumValN(GenVariable,"gen-variable", "Generate a variable definition"),
59 clEnumValN(GenType, "gen-type", "Generate a type definition"),
64 static cl::opt<std::string> NameToGenerate("for", cl::Optional,
65 cl::desc("Specify the name of the thing to generate"),
69 typedef std::vector<const Type*> TypeList;
70 typedef std::map<const Type*,std::string> TypeMap;
71 typedef std::map<const Value*,std::string> ValueMap;
72 typedef std::set<std::string> NameSet;
73 typedef std::set<const Type*> TypeSet;
74 typedef std::set<const Value*> ValueSet;
75 typedef std::map<const Value*,std::string> ForwardRefMap;
80 const Module *TheModule;
84 TypeMap UnresolvedTypes;
88 ValueSet DefinedValues;
89 ForwardRefMap ForwardRefs;
93 inline CppWriter(std::ostream &o, const Module *M, const char* pn="llvm2cpp")
94 : progname(pn), Out(o), TheModule(M), uniqueNum(0), TypeNames(),
95 ValueNames(), UnresolvedTypes(), TypeStack(), is_inline(false) { }
97 const Module* getModule() { return TheModule; }
99 void printProgram(const std::string& fname, const std::string& modName );
100 void printModule(const std::string& fname, const std::string& modName );
101 void printContents(const std::string& fname, const std::string& modName );
102 void printFunction(const std::string& fname, const std::string& funcName );
103 void printInline(const std::string& fname, const std::string& funcName );
104 void printVariable(const std::string& fname, const std::string& varName );
105 void printType(const std::string& fname, const std::string& typeName );
107 void error(const std::string& msg);
110 void printLinkageType(GlobalValue::LinkageTypes LT);
111 void printCallingConv(unsigned cc);
112 void printEscapedString(const std::string& str);
113 void printCFP(const ConstantFP* CFP);
115 std::string getCppName(const Type* val);
116 inline void printCppName(const Type* val);
118 std::string getCppName(const Value* val);
119 inline void printCppName(const Value* val);
121 bool printTypeInternal(const Type* Ty);
122 inline void printType(const Type* Ty);
123 void printTypes(const Module* M);
125 void printConstant(const Constant *CPV);
126 void printConstants(const Module* M);
128 void printVariableUses(const GlobalVariable *GV);
129 void printVariableHead(const GlobalVariable *GV);
130 void printVariableBody(const GlobalVariable *GV);
132 void printFunctionUses(const Function *F);
133 void printFunctionHead(const Function *F);
134 void printFunctionBody(const Function *F);
135 void printInstruction(const Instruction *I, const std::string& bbname);
136 std::string getOpName(Value*);
138 void printModuleBody();
142 static unsigned indent_level = 0;
143 inline std::ostream& nl(std::ostream& Out, int delta = 0) {
145 if (delta >= 0 || indent_level >= unsigned(-delta))
146 indent_level += delta;
147 for (unsigned i = 0; i < indent_level; ++i)
152 inline void in() { indent_level++; }
153 inline void out() { if (indent_level >0) indent_level--; }
156 sanitize(std::string& str) {
157 for (size_t i = 0; i < str.length(); ++i)
158 if (!isalnum(str[i]) && str[i] != '_')
163 getTypePrefix(const Type* Ty ) {
165 switch (Ty->getTypeID()) {
166 case Type::VoidTyID: prefix = "void_"; break;
167 case Type::BoolTyID: prefix = "bool_"; break;
168 case Type::UByteTyID: prefix = "ubyte_"; break;
169 case Type::SByteTyID: prefix = "sbyte_"; break;
170 case Type::UShortTyID: prefix = "ushort_"; break;
171 case Type::ShortTyID: prefix = "short_"; break;
172 case Type::UIntTyID: prefix = "uint_"; break;
173 case Type::IntTyID: prefix = "int_"; break;
174 case Type::ULongTyID: prefix = "ulong_"; break;
175 case Type::LongTyID: prefix = "long_"; break;
176 case Type::FloatTyID: prefix = "float_"; break;
177 case Type::DoubleTyID: prefix = "double_"; break;
178 case Type::LabelTyID: prefix = "label_"; break;
179 case Type::FunctionTyID: prefix = "func_"; break;
180 case Type::StructTyID: prefix = "struct_"; break;
181 case Type::ArrayTyID: prefix = "array_"; break;
182 case Type::PointerTyID: prefix = "ptr_"; break;
183 case Type::PackedTyID: prefix = "packed_"; break;
184 case Type::OpaqueTyID: prefix = "opaque_"; break;
185 default: prefix = "other_"; break;
190 // Looks up the type in the symbol table and returns a pointer to its name or
191 // a null pointer if it wasn't found. Note that this isn't the same as the
192 // Mode::getTypeName function which will return an empty string, not a null
193 // pointer if the name is not found.
194 inline const std::string*
195 findTypeName(const SymbolTable& ST, const Type* Ty)
197 SymbolTable::type_const_iterator TI = ST.type_begin();
198 SymbolTable::type_const_iterator TE = ST.type_end();
199 for (;TI != TE; ++TI)
200 if (TI->second == Ty)
206 CppWriter::error(const std::string& msg) {
207 std::cerr << progname << ": " << msg << "\n";
211 // printCFP - Print a floating point constant .. very carefully :)
212 // This makes sure that conversion to/from floating yields the same binary
213 // result so that we don't lose precision.
215 CppWriter::printCFP(const ConstantFP *CFP) {
216 Out << "ConstantFP::get(";
217 if (CFP->getType() == Type::DoubleTy)
218 Out << "Type::DoubleTy, ";
220 Out << "Type::FloatTy, ";
223 sprintf(Buffer, "%A", CFP->getValue());
224 if ((!strncmp(Buffer, "0x", 2) ||
225 !strncmp(Buffer, "-0x", 3) ||
226 !strncmp(Buffer, "+0x", 3)) &&
227 (atof(Buffer) == CFP->getValue()))
228 if (CFP->getType() == Type::DoubleTy)
229 Out << "BitsToDouble(" << Buffer << ")";
231 Out << "BitsToFloat(" << Buffer << ")";
234 std::string StrVal = ftostr(CFP->getValue());
236 while (StrVal[0] == ' ')
237 StrVal.erase(StrVal.begin());
239 // Check to make sure that the stringized number is not some string like
240 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
241 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
242 ((StrVal[0] == '-' || StrVal[0] == '+') &&
243 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
244 (atof(StrVal.c_str()) == CFP->getValue()))
245 if (CFP->getType() == Type::DoubleTy)
249 else if (CFP->getType() == Type::DoubleTy)
250 Out << "BitsToDouble(0x" << std::hex << DoubleToBits(CFP->getValue())
251 << std::dec << "ULL) /* " << StrVal << " */";
253 Out << "BitsToFloat(0x" << std::hex << FloatToBits(CFP->getValue())
254 << std::dec << "U) /* " << StrVal << " */";
262 CppWriter::printCallingConv(unsigned cc){
263 // Print the calling convention.
265 case CallingConv::C: Out << "CallingConv::C"; break;
266 case CallingConv::CSRet: Out << "CallingConv::CSRet"; break;
267 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
268 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
269 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
270 default: Out << cc; break;
275 CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
277 case GlobalValue::InternalLinkage:
278 Out << "GlobalValue::InternalLinkage"; break;
279 case GlobalValue::LinkOnceLinkage:
280 Out << "GlobalValue::LinkOnceLinkage "; break;
281 case GlobalValue::WeakLinkage:
282 Out << "GlobalValue::WeakLinkage"; break;
283 case GlobalValue::AppendingLinkage:
284 Out << "GlobalValue::AppendingLinkage"; break;
285 case GlobalValue::ExternalLinkage:
286 Out << "GlobalValue::ExternalLinkage"; break;
287 case GlobalValue::DLLImportLinkage:
288 Out << "GlobalValue::DllImportLinkage"; break;
289 case GlobalValue::DLLExportLinkage:
290 Out << "GlobalValue::DllExportLinkage"; break;
291 case GlobalValue::ExternalWeakLinkage:
292 Out << "GlobalValue::ExternalWeakLinkage"; break;
293 case GlobalValue::GhostLinkage:
294 Out << "GlobalValue::GhostLinkage"; break;
298 // printEscapedString - Print each character of the specified string, escaping
299 // it if it is not printable or if it is an escape char.
301 CppWriter::printEscapedString(const std::string &Str) {
302 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
303 unsigned char C = Str[i];
304 if (isprint(C) && C != '"' && C != '\\') {
308 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
309 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
315 CppWriter::getCppName(const Type* Ty)
317 // First, handle the primitive types .. easy
318 if (Ty->isPrimitiveType()) {
319 switch (Ty->getTypeID()) {
320 case Type::VoidTyID: return "Type::VoidTy";
321 case Type::BoolTyID: return "Type::BoolTy";
322 case Type::UByteTyID: return "Type::UByteTy";
323 case Type::SByteTyID: return "Type::SByteTy";
324 case Type::UShortTyID: return "Type::UShortTy";
325 case Type::ShortTyID: return "Type::ShortTy";
326 case Type::UIntTyID: return "Type::UIntTy";
327 case Type::IntTyID: return "Type::IntTy";
328 case Type::ULongTyID: return "Type::ULongTy";
329 case Type::LongTyID: return "Type::LongTy";
330 case Type::FloatTyID: return "Type::FloatTy";
331 case Type::DoubleTyID: return "Type::DoubleTy";
332 case Type::LabelTyID: return "Type::LabelTy";
334 error("Invalid primitive type");
337 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
340 // Now, see if we've seen the type before and return that
341 TypeMap::iterator I = TypeNames.find(Ty);
342 if (I != TypeNames.end())
345 // Okay, let's build a new name for this type. Start with a prefix
346 const char* prefix = 0;
347 switch (Ty->getTypeID()) {
348 case Type::FunctionTyID: prefix = "FuncTy_"; break;
349 case Type::StructTyID: prefix = "StructTy_"; break;
350 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
351 case Type::PointerTyID: prefix = "PointerTy_"; break;
352 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
353 case Type::PackedTyID: prefix = "PackedTy_"; break;
354 default: prefix = "OtherTy_"; break; // prevent breakage
357 // See if the type has a name in the symboltable and build accordingly
358 const std::string* tName = findTypeName(TheModule->getSymbolTable(), Ty);
361 name = std::string(prefix) + *tName;
363 name = std::string(prefix) + utostr(uniqueNum++);
367 return TypeNames[Ty] = name;
371 CppWriter::printCppName(const Type* Ty)
373 printEscapedString(getCppName(Ty));
377 CppWriter::getCppName(const Value* val) {
379 ValueMap::iterator I = ValueNames.find(val);
380 if (I != ValueNames.end() && I->first == val)
383 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
384 name = std::string("gvar_") +
385 getTypePrefix(GV->getType()->getElementType());
386 } else if (const Function* F = dyn_cast<Function>(val)) {
387 name = std::string("func_");
388 } else if (const Constant* C = dyn_cast<Constant>(val)) {
389 name = std::string("const_") + getTypePrefix(C->getType());
390 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
392 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
393 Function::const_arg_iterator(Arg)) + 1;
394 name = std::string("arg_") + utostr(argNum);
395 NameSet::iterator NI = UsedNames.find(name);
396 if (NI != UsedNames.end())
397 name += std::string("_") + utostr(uniqueNum++);
398 UsedNames.insert(name);
399 return ValueNames[val] = name;
401 name = getTypePrefix(val->getType());
404 name = getTypePrefix(val->getType());
406 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
408 NameSet::iterator NI = UsedNames.find(name);
409 if (NI != UsedNames.end())
410 name += std::string("_") + utostr(uniqueNum++);
411 UsedNames.insert(name);
412 return ValueNames[val] = name;
416 CppWriter::printCppName(const Value* val) {
417 printEscapedString(getCppName(val));
421 CppWriter::printTypeInternal(const Type* Ty) {
422 // We don't print definitions for primitive types
423 if (Ty->isPrimitiveType())
426 // If we already defined this type, we don't need to define it again.
427 if (DefinedTypes.find(Ty) != DefinedTypes.end())
430 // Everything below needs the name for the type so get it now.
431 std::string typeName(getCppName(Ty));
433 // Search the type stack for recursion. If we find it, then generate this
434 // as an OpaqueType, but make sure not to do this multiple times because
435 // the type could appear in multiple places on the stack. Once the opaque
436 // definition is issued, it must not be re-issued. Consequently we have to
437 // check the UnresolvedTypes list as well.
438 TypeList::const_iterator TI = std::find(TypeStack.begin(),TypeStack.end(),Ty);
439 if (TI != TypeStack.end()) {
440 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
441 if (I == UnresolvedTypes.end()) {
442 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
444 UnresolvedTypes[Ty] = typeName;
449 // We're going to print a derived type which, by definition, contains other
450 // types. So, push this one we're printing onto the type stack to assist with
451 // recursive definitions.
452 TypeStack.push_back(Ty);
454 // Print the type definition
455 switch (Ty->getTypeID()) {
456 case Type::FunctionTyID: {
457 const FunctionType* FT = cast<FunctionType>(Ty);
458 Out << "std::vector<const Type*>" << typeName << "_args;";
460 FunctionType::param_iterator PI = FT->param_begin();
461 FunctionType::param_iterator PE = FT->param_end();
462 for (; PI != PE; ++PI) {
463 const Type* argTy = static_cast<const Type*>(*PI);
464 bool isForward = printTypeInternal(argTy);
465 std::string argName(getCppName(argTy));
466 Out << typeName << "_args.push_back(" << argName;
472 bool isForward = printTypeInternal(FT->getReturnType());
473 std::string retTypeName(getCppName(FT->getReturnType()));
474 Out << "FunctionType* " << typeName << " = FunctionType::get(";
475 in(); nl(Out) << "/*Result=*/" << retTypeName;
479 nl(Out) << "/*Params=*/" << typeName << "_args,";
480 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
485 case Type::StructTyID: {
486 const StructType* ST = cast<StructType>(Ty);
487 Out << "std::vector<const Type*>" << typeName << "_fields;";
489 StructType::element_iterator EI = ST->element_begin();
490 StructType::element_iterator EE = ST->element_end();
491 for (; EI != EE; ++EI) {
492 const Type* fieldTy = static_cast<const Type*>(*EI);
493 bool isForward = printTypeInternal(fieldTy);
494 std::string fieldName(getCppName(fieldTy));
495 Out << typeName << "_fields.push_back(" << fieldName;
501 Out << "StructType* " << typeName << " = StructType::get("
502 << typeName << "_fields);";
506 case Type::ArrayTyID: {
507 const ArrayType* AT = cast<ArrayType>(Ty);
508 const Type* ET = AT->getElementType();
509 bool isForward = printTypeInternal(ET);
510 std::string elemName(getCppName(ET));
511 Out << "ArrayType* " << typeName << " = ArrayType::get("
512 << elemName << (isForward ? "_fwd" : "")
513 << ", " << utostr(AT->getNumElements()) << ");";
517 case Type::PointerTyID: {
518 const PointerType* PT = cast<PointerType>(Ty);
519 const Type* ET = PT->getElementType();
520 bool isForward = printTypeInternal(ET);
521 std::string elemName(getCppName(ET));
522 Out << "PointerType* " << typeName << " = PointerType::get("
523 << elemName << (isForward ? "_fwd" : "") << ");";
527 case Type::PackedTyID: {
528 const PackedType* PT = cast<PackedType>(Ty);
529 const Type* ET = PT->getElementType();
530 bool isForward = printTypeInternal(ET);
531 std::string elemName(getCppName(ET));
532 Out << "PackedType* " << typeName << " = PackedType::get("
533 << elemName << (isForward ? "_fwd" : "")
534 << ", " << utostr(PT->getNumElements()) << ");";
538 case Type::OpaqueTyID: {
539 const OpaqueType* OT = cast<OpaqueType>(Ty);
540 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
545 error("Invalid TypeID");
548 // If the type had a name, make sure we recreate it.
549 const std::string* progTypeName =
550 findTypeName(TheModule->getSymbolTable(),Ty);
552 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
556 // Pop us off the type stack
557 TypeStack.pop_back();
559 // Indicate that this type is now defined.
560 DefinedTypes.insert(Ty);
562 // Early resolve as many unresolved types as possible. Search the unresolved
563 // types map for the type we just printed. Now that its definition is complete
564 // we can resolve any previous references to it. This prevents a cascade of
566 TypeMap::iterator I = UnresolvedTypes.find(Ty);
567 if (I != UnresolvedTypes.end()) {
568 Out << "cast<OpaqueType>(" << I->second
569 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
571 Out << I->second << " = cast<";
572 switch (Ty->getTypeID()) {
573 case Type::FunctionTyID: Out << "FunctionType"; break;
574 case Type::ArrayTyID: Out << "ArrayType"; break;
575 case Type::StructTyID: Out << "StructType"; break;
576 case Type::PackedTyID: Out << "PackedType"; break;
577 case Type::PointerTyID: Out << "PointerType"; break;
578 case Type::OpaqueTyID: Out << "OpaqueType"; break;
579 default: Out << "NoSuchDerivedType"; break;
581 Out << ">(" << I->second << "_fwd.get());";
583 UnresolvedTypes.erase(I);
586 // Finally, separate the type definition from other with a newline.
589 // We weren't a recursive type
593 // Prints a type definition. Returns true if it could not resolve all the types
594 // in the definition but had to use a forward reference.
596 CppWriter::printType(const Type* Ty) {
597 assert(TypeStack.empty());
599 printTypeInternal(Ty);
600 assert(TypeStack.empty());
604 CppWriter::printTypes(const Module* M) {
606 // Walk the symbol table and print out all its types
607 const SymbolTable& symtab = M->getSymbolTable();
608 for (SymbolTable::type_const_iterator TI = symtab.type_begin(),
609 TE = symtab.type_end(); TI != TE; ++TI) {
611 // For primitive types and types already defined, just add a name
612 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
613 if (TI->second->isPrimitiveType() || TNI != TypeNames.end()) {
614 Out << "mod->addTypeName(\"";
615 printEscapedString(TI->first);
616 Out << "\", " << getCppName(TI->second) << ");";
618 // For everything else, define the type
620 printType(TI->second);
624 // Add all of the global variables to the value table...
625 for (Module::const_global_iterator I = TheModule->global_begin(),
626 E = TheModule->global_end(); I != E; ++I) {
627 if (I->hasInitializer())
628 printType(I->getInitializer()->getType());
629 printType(I->getType());
632 // Add all the functions to the table
633 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
635 printType(FI->getReturnType());
636 printType(FI->getFunctionType());
637 // Add all the function arguments
638 for(Function::const_arg_iterator AI = FI->arg_begin(),
639 AE = FI->arg_end(); AI != AE; ++AI) {
640 printType(AI->getType());
643 // Add all of the basic blocks and instructions
644 for (Function::const_iterator BB = FI->begin(),
645 E = FI->end(); BB != E; ++BB) {
646 printType(BB->getType());
647 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
649 printType(I->getType());
650 for (unsigned i = 0; i < I->getNumOperands(); ++i)
651 printType(I->getOperand(i)->getType());
658 // printConstant - Print out a constant pool entry...
659 void CppWriter::printConstant(const Constant *CV) {
660 // First, if the constant is actually a GlobalValue (variable or function) or
661 // its already in the constant list then we've printed it already and we can
663 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
666 std::string constName(getCppName(CV));
667 std::string typeName(getCppName(CV->getType()));
668 if (CV->isNullValue()) {
669 Out << "Constant* " << constName << " = Constant::getNullValue("
674 if (isa<GlobalValue>(CV)) {
675 // Skip variables and functions, we emit them elsewhere
678 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
679 Out << "ConstantBool* " << constName << " = ConstantBool::get("
680 << (CB->getValue() ? "true" : "false") << ");";
681 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
682 Out << "ConstantInt* " << constName << " = ConstantInt::get("
684 << (CV->getType()->isSigned() ? CI->getSExtValue() : CI->getZExtValue())
686 } else if (isa<ConstantAggregateZero>(CV)) {
687 Out << "ConstantAggregateZero* " << constName
688 << " = ConstantAggregateZero::get(" << typeName << ");";
689 } else if (isa<ConstantPointerNull>(CV)) {
690 Out << "ConstantPointerNull* " << constName
691 << " = ConstanPointerNull::get(" << typeName << ");";
692 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
693 Out << "ConstantFP* " << constName << " = ";
696 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
697 if (CA->isString() && CA->getType()->getElementType() == Type::SByteTy) {
698 Out << "Constant* " << constName << " = ConstantArray::get(\"";
699 printEscapedString(CA->getAsString());
700 // Determine if we want null termination or not.
701 if (CA->getType()->getNumElements() <= CA->getAsString().length())
702 Out << "\", false";// No null terminator
704 Out << "\", true"; // Indicate that the null terminator should be added.
707 Out << "std::vector<Constant*> " << constName << "_elems;";
709 unsigned N = CA->getNumOperands();
710 for (unsigned i = 0; i < N; ++i) {
711 printConstant(CA->getOperand(i)); // recurse to print operands
712 Out << constName << "_elems.push_back("
713 << getCppName(CA->getOperand(i)) << ");";
716 Out << "Constant* " << constName << " = ConstantArray::get("
717 << typeName << ", " << constName << "_elems);";
719 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
720 Out << "std::vector<Constant*> " << constName << "_fields;";
722 unsigned N = CS->getNumOperands();
723 for (unsigned i = 0; i < N; i++) {
724 printConstant(CS->getOperand(i));
725 Out << constName << "_fields.push_back("
726 << getCppName(CS->getOperand(i)) << ");";
729 Out << "Constant* " << constName << " = ConstantStruct::get("
730 << typeName << ", " << constName << "_fields);";
731 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
732 Out << "std::vector<Constant*> " << constName << "_elems;";
734 unsigned N = CP->getNumOperands();
735 for (unsigned i = 0; i < N; ++i) {
736 printConstant(CP->getOperand(i));
737 Out << constName << "_elems.push_back("
738 << getCppName(CP->getOperand(i)) << ");";
741 Out << "Constant* " << constName << " = ConstantPacked::get("
742 << typeName << ", " << constName << "_elems);";
743 } else if (isa<UndefValue>(CV)) {
744 Out << "UndefValue* " << constName << " = UndefValue::get("
746 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
747 if (CE->getOpcode() == Instruction::GetElementPtr) {
748 Out << "std::vector<Constant*> " << constName << "_indices;";
750 printConstant(CE->getOperand(0));
751 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
752 printConstant(CE->getOperand(i));
753 Out << constName << "_indices.push_back("
754 << getCppName(CE->getOperand(i)) << ");";
757 Out << "Constant* " << constName
758 << " = ConstantExpr::getGetElementPtr("
759 << getCppName(CE->getOperand(0)) << ", "
760 << constName << "_indices);";
761 } else if (CE->getOpcode() == Instruction::Cast) {
762 printConstant(CE->getOperand(0));
763 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
764 Out << getCppName(CE->getOperand(0)) << ", " << 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::SetEQ: Out << "getSetEQ"; break;
786 case Instruction::SetNE: Out << "getSetNE"; break;
787 case Instruction::SetLE: Out << "getSetLE"; break;
788 case Instruction::SetGE: Out << "getSetGE"; break;
789 case Instruction::SetLT: Out << "getSetLT"; break;
790 case Instruction::SetGT: Out << "getSetGT"; break;
791 case Instruction::Shl: Out << "getShl"; break;
792 case Instruction::Shr: Out << "getShr"; break;
793 case Instruction::Select: Out << "getSelect"; break;
794 case Instruction::ExtractElement: Out << "getExtractElement"; break;
795 case Instruction::InsertElement: Out << "getInsertElement"; break;
796 case Instruction::ShuffleVector: Out << "getShuffleVector"; break;
798 error("Invalid constant expression");
801 Out << getCppName(CE->getOperand(0));
802 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
803 Out << ", " << getCppName(CE->getOperand(i));
807 error("Bad Constant");
808 Out << "Constant* " << constName << " = 0; ";
814 CppWriter::printConstants(const Module* M) {
815 // Traverse all the global variables looking for constant initializers
816 for (Module::const_global_iterator I = TheModule->global_begin(),
817 E = TheModule->global_end(); I != E; ++I)
818 if (I->hasInitializer())
819 printConstant(I->getInitializer());
821 // Traverse the LLVM functions looking for constants
822 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
824 // Add all of the basic blocks and instructions
825 for (Function::const_iterator BB = FI->begin(),
826 E = FI->end(); BB != E; ++BB) {
827 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
829 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
830 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
839 void CppWriter::printVariableUses(const GlobalVariable *GV) {
840 nl(Out) << "// Type Definitions";
842 printType(GV->getType());
843 if (GV->hasInitializer()) {
844 Constant* Init = GV->getInitializer();
845 printType(Init->getType());
846 if (Function* F = dyn_cast<Function>(Init)) {
847 nl(Out)<< "/ Function Declarations"; nl(Out);
848 printFunctionHead(F);
849 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
850 nl(Out) << "// Global Variable Declarations"; nl(Out);
851 printVariableHead(gv);
853 nl(Out) << "// Constant Definitions"; nl(Out);
856 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
857 nl(Out) << "// Global Variable Definitions"; nl(Out);
858 printVariableBody(gv);
863 void CppWriter::printVariableHead(const GlobalVariable *GV) {
864 nl(Out) << "GlobalVariable* " << getCppName(GV);
866 Out << " = mod->getGlobalVariable(";
867 printEscapedString(GV->getName());
868 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
869 nl(Out) << "if (!" << getCppName(GV) << ") {";
870 in(); nl(Out) << getCppName(GV);
872 Out << " = new GlobalVariable(";
873 nl(Out) << "/*Type=*/";
874 printCppName(GV->getType()->getElementType());
876 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
878 nl(Out) << "/*Linkage=*/";
879 printLinkageType(GV->getLinkage());
881 nl(Out) << "/*Initializer=*/0, ";
882 if (GV->hasInitializer()) {
883 Out << "// has initializer, specified below";
885 nl(Out) << "/*Name=*/\"";
886 printEscapedString(GV->getName());
891 if (GV->hasSection()) {
893 Out << "->setSection(\"";
894 printEscapedString(GV->getSection());
898 if (GV->getAlignment()) {
900 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
904 out(); Out << "}"; nl(Out);
909 CppWriter::printVariableBody(const GlobalVariable *GV) {
910 if (GV->hasInitializer()) {
912 Out << "->setInitializer(";
913 //if (!isa<GlobalValue(GV->getInitializer()))
915 Out << getCppName(GV->getInitializer()) << ");";
921 CppWriter::getOpName(Value* V) {
922 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
923 return getCppName(V);
925 // See if its alread in the map of forward references, if so just return the
926 // name we already set up for it
927 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
928 if (I != ForwardRefs.end())
931 // This is a new forward reference. Generate a unique name for it
932 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
934 // Yes, this is a hack. An Argument is the smallest instantiable value that
935 // we can make as a placeholder for the real value. We'll replace these
936 // Argument instances later.
937 Out << "Argument* " << result << " = new Argument("
938 << getCppName(V->getType()) << ");";
940 ForwardRefs[V] = result;
944 // printInstruction - This member is called for each Instruction in a function.
946 CppWriter::printInstruction(const Instruction *I, const std::string& bbname) {
947 std::string iName(getCppName(I));
949 // Before we emit this instruction, we need to take care of generating any
950 // forward references. So, we get the names of all the operands in advance
951 std::string* opNames = new std::string[I->getNumOperands()];
952 for (unsigned i = 0; i < I->getNumOperands(); i++) {
953 opNames[i] = getOpName(I->getOperand(i));
956 switch (I->getOpcode()) {
957 case Instruction::Ret: {
958 const ReturnInst* ret = cast<ReturnInst>(I);
959 Out << "ReturnInst* " << iName << " = new ReturnInst("
960 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
963 case Instruction::Br: {
964 const BranchInst* br = cast<BranchInst>(I);
965 Out << "BranchInst* " << iName << " = new BranchInst(" ;
966 if (br->getNumOperands() == 3 ) {
967 Out << opNames[0] << ", "
968 << opNames[1] << ", "
969 << opNames[2] << ", ";
971 } else if (br->getNumOperands() == 1) {
972 Out << opNames[0] << ", ";
974 error("Branch with 2 operands?");
976 Out << bbname << ");";
979 case Instruction::Switch: {
980 const SwitchInst* sw = cast<SwitchInst>(I);
981 Out << "SwitchInst* " << iName << " = new SwitchInst("
982 << opNames[0] << ", "
983 << opNames[1] << ", "
984 << sw->getNumCases() << ", " << bbname << ");";
986 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
987 Out << iName << "->addCase("
988 << opNames[i] << ", "
989 << opNames[i+1] << ");";
994 case Instruction::Invoke: {
995 const InvokeInst* inv = cast<InvokeInst>(I);
996 Out << "std::vector<Value*> " << iName << "_params;";
998 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
999 Out << iName << "_params.push_back("
1000 << opNames[i] << ");";
1003 Out << "InvokeInst* " << iName << " = new InvokeInst("
1004 << opNames[0] << ", "
1005 << opNames[1] << ", "
1006 << opNames[2] << ", "
1007 << iName << "_params, \"";
1008 printEscapedString(inv->getName());
1009 Out << "\", " << bbname << ");";
1010 nl(Out) << iName << "->setCallingConv(";
1011 printCallingConv(inv->getCallingConv());
1015 case Instruction::Unwind: {
1016 Out << "UnwindInst* " << iName << " = new UnwindInst("
1020 case Instruction::Unreachable:{
1021 Out << "UnreachableInst* " << iName << " = new UnreachableInst("
1025 case Instruction::Add:
1026 case Instruction::Sub:
1027 case Instruction::Mul:
1028 case Instruction::UDiv:
1029 case Instruction::SDiv:
1030 case Instruction::FDiv:
1031 case Instruction::URem:
1032 case Instruction::SRem:
1033 case Instruction::FRem:
1034 case Instruction::And:
1035 case Instruction::Or:
1036 case Instruction::Xor:
1037 case Instruction::Shl:
1038 case Instruction::Shr:{
1039 Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
1040 switch (I->getOpcode()) {
1041 case Instruction::Add: Out << "Instruction::Add"; break;
1042 case Instruction::Sub: Out << "Instruction::Sub"; break;
1043 case Instruction::Mul: Out << "Instruction::Mul"; break;
1044 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1045 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1046 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1047 case Instruction::URem:Out << "Instruction::URem"; break;
1048 case Instruction::SRem:Out << "Instruction::SRem"; break;
1049 case Instruction::FRem:Out << "Instruction::FRem"; break;
1050 case Instruction::And: Out << "Instruction::And"; break;
1051 case Instruction::Or: Out << "Instruction::Or"; break;
1052 case Instruction::Xor: Out << "Instruction::Xor"; break;
1053 case Instruction::Shl: Out << "Instruction::Shl"; break;
1054 case Instruction::Shr: Out << "Instruction::Shr"; break;
1055 default: Out << "Instruction::BadOpCode"; break;
1057 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1058 printEscapedString(I->getName());
1059 Out << "\", " << bbname << ");";
1062 case Instruction::SetEQ:
1063 case Instruction::SetNE:
1064 case Instruction::SetLE:
1065 case Instruction::SetGE:
1066 case Instruction::SetLT:
1067 case Instruction::SetGT: {
1068 Out << "SetCondInst* " << iName << " = new SetCondInst(";
1069 switch (I->getOpcode()) {
1070 case Instruction::SetEQ: Out << "Instruction::SetEQ"; break;
1071 case Instruction::SetNE: Out << "Instruction::SetNE"; break;
1072 case Instruction::SetLE: Out << "Instruction::SetLE"; break;
1073 case Instruction::SetGE: Out << "Instruction::SetGE"; break;
1074 case Instruction::SetLT: Out << "Instruction::SetLT"; break;
1075 case Instruction::SetGT: Out << "Instruction::SetGT"; break;
1076 default: Out << "Instruction::BadOpCode"; break;
1078 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1079 printEscapedString(I->getName());
1080 Out << "\", " << bbname << ");";
1083 case Instruction::Malloc: {
1084 const MallocInst* mallocI = cast<MallocInst>(I);
1085 Out << "MallocInst* " << iName << " = new MallocInst("
1086 << getCppName(mallocI->getAllocatedType()) << ", ";
1087 if (mallocI->isArrayAllocation())
1088 Out << opNames[0] << ", " ;
1090 printEscapedString(mallocI->getName());
1091 Out << "\", " << bbname << ");";
1092 if (mallocI->getAlignment())
1093 nl(Out) << iName << "->setAlignment("
1094 << mallocI->getAlignment() << ");";
1097 case Instruction::Free: {
1098 Out << "FreeInst* " << iName << " = new FreeInst("
1099 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1102 case Instruction::Alloca: {
1103 const AllocaInst* allocaI = cast<AllocaInst>(I);
1104 Out << "AllocaInst* " << iName << " = new AllocaInst("
1105 << getCppName(allocaI->getAllocatedType()) << ", ";
1106 if (allocaI->isArrayAllocation())
1107 Out << opNames[0] << ", ";
1109 printEscapedString(allocaI->getName());
1110 Out << "\", " << bbname << ");";
1111 if (allocaI->getAlignment())
1112 nl(Out) << iName << "->setAlignment("
1113 << allocaI->getAlignment() << ");";
1116 case Instruction::Load:{
1117 const LoadInst* load = cast<LoadInst>(I);
1118 Out << "LoadInst* " << iName << " = new LoadInst("
1119 << opNames[0] << ", \"";
1120 printEscapedString(load->getName());
1121 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1122 << ", " << bbname << ");";
1125 case Instruction::Store: {
1126 const StoreInst* store = cast<StoreInst>(I);
1127 Out << "StoreInst* " << iName << " = new StoreInst("
1128 << opNames[0] << ", "
1129 << opNames[1] << ", "
1130 << (store->isVolatile() ? "true" : "false")
1131 << ", " << bbname << ");";
1134 case Instruction::GetElementPtr: {
1135 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1136 if (gep->getNumOperands() <= 2) {
1137 Out << "GetElementPtrInst* " << iName << " = new GetElementPtrInst("
1139 if (gep->getNumOperands() == 2)
1140 Out << ", " << opNames[1];
1142 Out << "std::vector<Value*> " << iName << "_indices;";
1144 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1145 Out << iName << "_indices.push_back("
1146 << opNames[i] << ");";
1149 Out << "Instruction* " << iName << " = new GetElementPtrInst("
1150 << opNames[0] << ", " << iName << "_indices";
1153 printEscapedString(gep->getName());
1154 Out << "\", " << bbname << ");";
1157 case Instruction::PHI: {
1158 const PHINode* phi = cast<PHINode>(I);
1160 Out << "PHINode* " << iName << " = new PHINode("
1161 << getCppName(phi->getType()) << ", \"";
1162 printEscapedString(phi->getName());
1163 Out << "\", " << bbname << ");";
1164 nl(Out) << iName << "->reserveOperandSpace("
1165 << phi->getNumIncomingValues()
1168 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1169 Out << iName << "->addIncoming("
1170 << opNames[i] << ", " << opNames[i+1] << ");";
1175 case Instruction::Cast: {
1176 const CastInst* cst = cast<CastInst>(I);
1177 Out << "CastInst* " << iName << " = new CastInst("
1178 << opNames[0] << ", "
1179 << getCppName(cst->getType()) << ", \"";
1180 printEscapedString(cst->getName());
1181 Out << "\", " << bbname << ");";
1184 case Instruction::Call:{
1185 const CallInst* call = cast<CallInst>(I);
1186 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1187 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1188 << getCppName(ila->getFunctionType()) << ", \""
1189 << ila->getAsmString() << "\", \""
1190 << ila->getConstraintString() << "\","
1191 << (ila->hasSideEffects() ? "true" : "false") << ");";
1194 if (call->getNumOperands() > 3) {
1195 Out << "std::vector<Value*> " << iName << "_params;";
1197 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1198 Out << iName << "_params.push_back(" << opNames[i] << ");";
1201 Out << "CallInst* " << iName << " = new CallInst("
1202 << opNames[0] << ", " << iName << "_params, \"";
1203 } else if (call->getNumOperands() == 3) {
1204 Out << "CallInst* " << iName << " = new CallInst("
1205 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1206 } else if (call->getNumOperands() == 2) {
1207 Out << "CallInst* " << iName << " = new CallInst("
1208 << opNames[0] << ", " << opNames[1] << ", \"";
1210 Out << "CallInst* " << iName << " = new CallInst(" << opNames[0]
1213 printEscapedString(call->getName());
1214 Out << "\", " << bbname << ");";
1215 nl(Out) << iName << "->setCallingConv(";
1216 printCallingConv(call->getCallingConv());
1218 nl(Out) << iName << "->setTailCall("
1219 << (call->isTailCall() ? "true":"false");
1223 case Instruction::Select: {
1224 const SelectInst* sel = cast<SelectInst>(I);
1225 Out << "SelectInst* " << getCppName(sel) << " = new SelectInst(";
1226 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1227 printEscapedString(sel->getName());
1228 Out << "\", " << bbname << ");";
1231 case Instruction::UserOp1:
1233 case Instruction::UserOp2: {
1234 /// FIXME: What should be done here?
1237 case Instruction::VAArg: {
1238 const VAArgInst* va = cast<VAArgInst>(I);
1239 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1240 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1241 printEscapedString(va->getName());
1242 Out << "\", " << bbname << ");";
1245 case Instruction::ExtractElement: {
1246 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1247 Out << "ExtractElementInst* " << getCppName(eei)
1248 << " = new ExtractElementInst(" << opNames[0]
1249 << ", " << opNames[1] << ", \"";
1250 printEscapedString(eei->getName());
1251 Out << "\", " << bbname << ");";
1254 case Instruction::InsertElement: {
1255 const InsertElementInst* iei = cast<InsertElementInst>(I);
1256 Out << "InsertElementInst* " << getCppName(iei)
1257 << " = new InsertElementInst(" << opNames[0]
1258 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1259 printEscapedString(iei->getName());
1260 Out << "\", " << bbname << ");";
1263 case Instruction::ShuffleVector: {
1264 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1265 Out << "ShuffleVectorInst* " << getCppName(svi)
1266 << " = new ShuffleVectorInst(" << opNames[0]
1267 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1268 printEscapedString(svi->getName());
1269 Out << "\", " << bbname << ");";
1273 DefinedValues.insert(I);
1278 // Print out the types, constants and declarations needed by one function
1279 void CppWriter::printFunctionUses(const Function* F) {
1281 nl(Out) << "// Type Definitions"; nl(Out);
1283 // Print the function's return type
1284 printType(F->getReturnType());
1286 // Print the function's function type
1287 printType(F->getFunctionType());
1289 // Print the types of each of the function's arguments
1290 for(Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1292 printType(AI->getType());
1296 // Print type definitions for every type referenced by an instruction and
1297 // make a note of any global values or constants that are referenced
1298 std::vector<GlobalValue*> gvs;
1299 std::vector<Constant*> consts;
1300 for (Function::const_iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB){
1301 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1303 // Print the type of the instruction itself
1304 printType(I->getType());
1306 // Print the type of each of the instruction's operands
1307 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1308 Value* operand = I->getOperand(i);
1309 printType(operand->getType());
1310 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand))
1312 else if (Constant* C = dyn_cast<Constant>(operand))
1313 consts.push_back(C);
1318 // Print the function declarations for any functions encountered
1319 nl(Out) << "// Function Declarations"; nl(Out);
1320 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1322 if (Function* Fun = dyn_cast<Function>(*I)) {
1323 if (!is_inline || Fun != F)
1324 printFunctionHead(Fun);
1328 // Print the global variable declarations for any variables encountered
1329 nl(Out) << "// Global Variable Declarations"; nl(Out);
1330 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1332 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1333 printVariableHead(F);
1336 // Print the constants found
1337 nl(Out) << "// Constant Definitions"; nl(Out);
1338 for (std::vector<Constant*>::iterator I = consts.begin(), E = consts.end();
1343 // Process the global variables definitions now that all the constants have
1344 // been emitted. These definitions just couple the gvars with their constant
1346 nl(Out) << "// Global Variable Definitions"; nl(Out);
1347 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1349 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1350 printVariableBody(GV);
1354 void CppWriter::printFunctionHead(const Function* F) {
1355 nl(Out) << "Function* " << getCppName(F);
1357 Out << " = mod->getFunction(\"";
1358 printEscapedString(F->getName());
1359 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1360 nl(Out) << "if (!" << getCppName(F) << ") {";
1361 nl(Out) << getCppName(F);
1363 Out<< " = new Function(";
1364 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1365 nl(Out) << "/*Linkage=*/";
1366 printLinkageType(F->getLinkage());
1368 nl(Out) << "/*Name=*/\"";
1369 printEscapedString(F->getName());
1370 Out << "\", mod); " << (F->isExternal()? "// (external, no body)" : "");
1373 Out << "->setCallingConv(";
1374 printCallingConv(F->getCallingConv());
1377 if (F->hasSection()) {
1379 Out << "->setSection(\"" << F->getSection() << "\");";
1382 if (F->getAlignment()) {
1384 Out << "->setAlignment(" << F->getAlignment() << ");";
1393 void CppWriter::printFunctionBody(const Function *F) {
1394 if (F->isExternal())
1395 return; // external functions have no bodies.
1397 // Clear the DefinedValues and ForwardRefs maps because we can't have
1398 // cross-function forward refs
1399 ForwardRefs.clear();
1400 DefinedValues.clear();
1402 // Create all the argument values
1404 if (!F->arg_empty()) {
1405 Out << "Function::arg_iterator args = " << getCppName(F)
1406 << "->arg_begin();";
1409 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1411 Out << "Value* " << getCppName(AI) << " = args++;";
1413 if (AI->hasName()) {
1414 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1420 // Create all the basic blocks
1422 for (Function::const_iterator BI = F->begin(), BE = F->end();
1424 std::string bbname(getCppName(BI));
1425 Out << "BasicBlock* " << bbname << " = new BasicBlock(\"";
1427 printEscapedString(BI->getName());
1428 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1432 // Output all of its basic blocks... for the function
1433 for (Function::const_iterator BI = F->begin(), BE = F->end();
1435 std::string bbname(getCppName(BI));
1436 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1439 // Output all of the instructions in the basic block...
1440 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1442 printInstruction(I,bbname);
1446 // Loop over the ForwardRefs and resolve them now that all instructions
1448 if (!ForwardRefs.empty()) {
1449 nl(Out) << "// Resolve Forward References";
1453 while (!ForwardRefs.empty()) {
1454 ForwardRefMap::iterator I = ForwardRefs.begin();
1455 Out << I->second << "->replaceAllUsesWith("
1456 << getCppName(I->first) << "); delete " << I->second << ";";
1458 ForwardRefs.erase(I);
1462 void CppWriter::printInline(const std::string& fname, const std::string& func) {
1463 const Function* F = TheModule->getNamedFunction(func);
1465 error(std::string("Function '") + func + "' not found in input module");
1468 if (F->isExternal()) {
1469 error(std::string("Function '") + func + "' is external!");
1472 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1474 unsigned arg_count = 1;
1475 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1477 Out << ", Value* arg_" << arg_count;
1482 printFunctionUses(F);
1483 printFunctionBody(F);
1485 Out << "return " << getCppName(F->begin()) << ";";
1490 void CppWriter::printModuleBody() {
1491 // Print out all the type definitions
1492 nl(Out) << "// Type Definitions"; nl(Out);
1493 printTypes(TheModule);
1495 // Functions can call each other and global variables can reference them so
1496 // define all the functions first before emitting their function bodies.
1497 nl(Out) << "// Function Declarations"; nl(Out);
1498 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1500 printFunctionHead(I);
1502 // Process the global variables declarations. We can't initialze them until
1503 // after the constants are printed so just print a header for each global
1504 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1505 for (Module::const_global_iterator I = TheModule->global_begin(),
1506 E = TheModule->global_end(); I != E; ++I) {
1507 printVariableHead(I);
1510 // Print out all the constants definitions. Constants don't recurse except
1511 // through GlobalValues. All GlobalValues have been declared at this point
1512 // so we can proceed to generate the constants.
1513 nl(Out) << "// Constant Definitions"; nl(Out);
1514 printConstants(TheModule);
1516 // Process the global variables definitions now that all the constants have
1517 // been emitted. These definitions just couple the gvars with their constant
1519 nl(Out) << "// Global Variable Definitions"; nl(Out);
1520 for (Module::const_global_iterator I = TheModule->global_begin(),
1521 E = TheModule->global_end(); I != E; ++I) {
1522 printVariableBody(I);
1525 // Finally, we can safely put out all of the function bodies.
1526 nl(Out) << "// Function Definitions"; nl(Out);
1527 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1529 if (!I->isExternal()) {
1530 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1534 printFunctionBody(I);
1541 void CppWriter::printProgram(
1542 const std::string& fname,
1543 const std::string& mName
1545 Out << "#include <llvm/Module.h>\n";
1546 Out << "#include <llvm/DerivedTypes.h>\n";
1547 Out << "#include <llvm/Constants.h>\n";
1548 Out << "#include <llvm/GlobalVariable.h>\n";
1549 Out << "#include <llvm/Function.h>\n";
1550 Out << "#include <llvm/CallingConv.h>\n";
1551 Out << "#include <llvm/BasicBlock.h>\n";
1552 Out << "#include <llvm/Instructions.h>\n";
1553 Out << "#include <llvm/InlineAsm.h>\n";
1554 Out << "#include <llvm/Support/MathExtras.h>\n";
1555 Out << "#include <llvm/Pass.h>\n";
1556 Out << "#include <llvm/PassManager.h>\n";
1557 Out << "#include <llvm/Analysis/Verifier.h>\n";
1558 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1559 Out << "#include <algorithm>\n";
1560 Out << "#include <iostream>\n\n";
1561 Out << "using namespace llvm;\n\n";
1562 Out << "Module* " << fname << "();\n\n";
1563 Out << "int main(int argc, char**argv) {\n";
1564 Out << " Module* Mod = makeLLVMModule();\n";
1565 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1566 Out << " std::cerr.flush();\n";
1567 Out << " std::cout.flush();\n";
1568 Out << " PassManager PM;\n";
1569 Out << " PM.add(new PrintModulePass(&std::cout));\n";
1570 Out << " PM.run(*Mod);\n";
1571 Out << " return 0;\n";
1573 printModule(fname,mName);
1576 void CppWriter::printModule(
1577 const std::string& fname,
1578 const std::string& mName
1580 nl(Out) << "Module* " << fname << "() {";
1581 nl(Out,1) << "// Module Construction";
1582 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1583 nl(Out) << "mod->setEndianness(";
1584 switch (TheModule->getEndianness()) {
1585 case Module::LittleEndian: Out << "Module::LittleEndian);"; break;
1586 case Module::BigEndian: Out << "Module::BigEndian);"; break;
1587 case Module::AnyEndianness:Out << "Module::AnyEndianness);"; break;
1589 nl(Out) << "mod->setPointerSize(";
1590 switch (TheModule->getPointerSize()) {
1591 case Module::Pointer32: Out << "Module::Pointer32);"; break;
1592 case Module::Pointer64: Out << "Module::Pointer64);"; break;
1593 case Module::AnyPointerSize: Out << "Module::AnyPointerSize);"; break;
1596 if (!TheModule->getTargetTriple().empty()) {
1597 Out << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1602 if (!TheModule->getModuleInlineAsm().empty()) {
1603 Out << "mod->setModuleInlineAsm(\"";
1604 printEscapedString(TheModule->getModuleInlineAsm());
1609 // Loop over the dependent libraries and emit them.
1610 Module::lib_iterator LI = TheModule->lib_begin();
1611 Module::lib_iterator LE = TheModule->lib_end();
1613 Out << "mod->addLibrary(\"" << *LI << "\");";
1618 nl(Out) << "return mod;";
1623 void CppWriter::printContents(
1624 const std::string& fname, // Name of generated function
1625 const std::string& mName // Name of module generated module
1627 Out << "\nModule* " << fname << "(Module *mod) {\n";
1628 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1630 Out << "\nreturn mod;\n";
1634 void CppWriter::printFunction(
1635 const std::string& fname, // Name of generated function
1636 const std::string& funcName // Name of function to generate
1638 const Function* F = TheModule->getNamedFunction(funcName);
1640 error(std::string("Function '") + funcName + "' not found in input module");
1643 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1644 printFunctionUses(F);
1645 printFunctionHead(F);
1646 printFunctionBody(F);
1647 Out << "return " << getCppName(F) << ";\n";
1651 void CppWriter::printVariable(
1652 const std::string& fname, /// Name of generated function
1653 const std::string& varName // Name of variable to generate
1655 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1658 error(std::string("Variable '") + varName + "' not found in input module");
1661 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1662 printVariableUses(GV);
1663 printVariableHead(GV);
1664 printVariableBody(GV);
1665 Out << "return " << getCppName(GV) << ";\n";
1669 void CppWriter::printType(
1670 const std::string& fname, /// Name of generated function
1671 const std::string& typeName // Name of type to generate
1673 const Type* Ty = TheModule->getTypeByName(typeName);
1675 error(std::string("Type '") + typeName + "' not found in input module");
1678 Out << "\nType* " << fname << "(Module *mod) {\n";
1680 Out << "return " << getCppName(Ty) << ";\n";
1684 } // end anonymous llvm
1688 void WriteModuleToCppFile(Module* mod, std::ostream& o) {
1689 // Initialize a CppWriter for us to use
1690 CppWriter W(o, mod);
1693 o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1695 // Get the name of the function we're supposed to generate
1696 std::string fname = FuncName.getValue();
1698 // Get the name of the thing we are to generate
1699 std::string tgtname = NameToGenerate.getValue();
1700 if (GenerationType == GenModule ||
1701 GenerationType == GenContents ||
1702 GenerationType == GenProgram) {
1703 if (tgtname == "!bad!") {
1704 if (mod->getModuleIdentifier() == "-")
1705 tgtname = "<stdin>";
1707 tgtname = mod->getModuleIdentifier();
1709 } else if (tgtname == "!bad!") {
1710 W.error("You must use the -for option with -gen-{function,variable,type}");
1713 switch (WhatToGenerate(GenerationType)) {
1716 fname = "makeLLVMModule";
1717 W.printProgram(fname,tgtname);
1721 fname = "makeLLVMModule";
1722 W.printModule(fname,tgtname);
1726 fname = "makeLLVMModuleContents";
1727 W.printContents(fname,tgtname);
1731 fname = "makeLLVMFunction";
1732 W.printFunction(fname,tgtname);
1736 fname = "makeLLVMInline";
1737 W.printInline(fname,tgtname);
1741 fname = "makeLLVMVariable";
1742 W.printVariable(fname,tgtname);
1746 fname = "makeLLVMType";
1747 W.printType(fname,tgtname);
1750 W.error("Invalid generation option");