1 //===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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 "CPPTargetMachine.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instruction.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/PassManager.h"
25 #include "llvm/TypeSymbolTable.h"
26 #include "llvm/Target/TargetMachineRegistry.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Config/config.h"
38 static cl::opt<std::string>
39 FuncName("cppfname", cl::desc("Specify the name of the generated function"),
40 cl::value_desc("function name"));
53 static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
54 cl::desc("Choose what kind of output to generate"),
57 clEnumValN(GenProgram, "program", "Generate a complete program"),
58 clEnumValN(GenModule, "module", "Generate a module definition"),
59 clEnumValN(GenContents, "contents", "Generate contents of a module"),
60 clEnumValN(GenFunction, "function", "Generate a function definition"),
61 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
62 clEnumValN(GenInline, "inline", "Generate an inline function"),
63 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
64 clEnumValN(GenType, "type", "Generate a type definition"),
69 static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
70 cl::desc("Specify the name of the thing to generate"),
74 // Register the target.
75 RegisterTarget<CPPTargetMachine> X("cpp", " C++ backend");
77 typedef std::vector<const Type*> TypeList;
78 typedef std::map<const Type*,std::string> TypeMap;
79 typedef std::map<const Value*,std::string> ValueMap;
80 typedef std::set<std::string> NameSet;
81 typedef std::set<const Type*> TypeSet;
82 typedef std::set<const Value*> ValueSet;
83 typedef std::map<const Value*,std::string> ForwardRefMap;
85 /// CppWriter - This class is the main chunk of code that converts an LLVM
86 /// module to a C++ translation unit.
87 class CppWriter : public ModulePass {
90 const Module *TheModule;
94 TypeMap UnresolvedTypes;
98 ValueSet DefinedValues;
99 ForwardRefMap ForwardRefs;
104 explicit CppWriter(std::ostream &o) : ModulePass((intptr_t)&ID), Out(o) {}
106 virtual const char *getPassName() const { return "C++ backend"; }
108 bool runOnModule(Module &M);
110 bool doInitialization(Module &M) {
116 UnresolvedTypes.clear();
119 DefinedTypes.clear();
120 DefinedValues.clear();
126 void printProgram(const std::string& fname, const std::string& modName );
127 void printModule(const std::string& fname, const std::string& modName );
128 void printContents(const std::string& fname, const std::string& modName );
129 void printFunction(const std::string& fname, const std::string& funcName );
130 void printFunctions();
131 void printInline(const std::string& fname, const std::string& funcName );
132 void printVariable(const std::string& fname, const std::string& varName );
133 void printType(const std::string& fname, const std::string& typeName );
135 void error(const std::string& msg);
138 void printLinkageType(GlobalValue::LinkageTypes LT);
139 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
140 void printCallingConv(unsigned cc);
141 void printEscapedString(const std::string& str);
142 void printCFP(const ConstantFP* CFP);
144 std::string getCppName(const Type* val);
145 inline void printCppName(const Type* val);
147 std::string getCppName(const Value* val);
148 inline void printCppName(const Value* val);
150 void printParamAttrs(const PAListPtr &PAL, const std::string &name);
151 bool printTypeInternal(const Type* Ty);
152 inline void printType(const Type* Ty);
153 void printTypes(const Module* M);
155 void printConstant(const Constant *CPV);
156 void printConstants(const Module* M);
158 void printVariableUses(const GlobalVariable *GV);
159 void printVariableHead(const GlobalVariable *GV);
160 void printVariableBody(const GlobalVariable *GV);
162 void printFunctionUses(const Function *F);
163 void printFunctionHead(const Function *F);
164 void printFunctionBody(const Function *F);
165 void printInstruction(const Instruction *I, const std::string& bbname);
166 std::string getOpName(Value*);
168 void printModuleBody();
171 static unsigned indent_level = 0;
172 inline std::ostream& nl(std::ostream& Out, int delta = 0) {
174 if (delta >= 0 || indent_level >= unsigned(-delta))
175 indent_level += delta;
176 for (unsigned i = 0; i < indent_level; ++i)
181 inline void in() { indent_level++; }
182 inline void out() { if (indent_level >0) indent_level--; }
185 sanitize(std::string& str) {
186 for (size_t i = 0; i < str.length(); ++i)
187 if (!isalnum(str[i]) && str[i] != '_')
192 getTypePrefix(const Type* Ty ) {
193 switch (Ty->getTypeID()) {
194 case Type::VoidTyID: return "void_";
195 case Type::IntegerTyID:
196 return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
198 case Type::FloatTyID: return "float_";
199 case Type::DoubleTyID: return "double_";
200 case Type::LabelTyID: return "label_";
201 case Type::FunctionTyID: return "func_";
202 case Type::StructTyID: return "struct_";
203 case Type::ArrayTyID: return "array_";
204 case Type::PointerTyID: return "ptr_";
205 case Type::VectorTyID: return "packed_";
206 case Type::OpaqueTyID: return "opaque_";
207 default: return "other_";
212 // Looks up the type in the symbol table and returns a pointer to its name or
213 // a null pointer if it wasn't found. Note that this isn't the same as the
214 // Mode::getTypeName function which will return an empty string, not a null
215 // pointer if the name is not found.
216 inline const std::string*
217 findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
218 TypeSymbolTable::const_iterator TI = ST.begin();
219 TypeSymbolTable::const_iterator TE = ST.end();
220 for (;TI != TE; ++TI)
221 if (TI->second == Ty)
226 void CppWriter::error(const std::string& msg) {
227 std::cerr << progname << ": " << msg << "\n";
231 // printCFP - Print a floating point constant .. very carefully :)
232 // This makes sure that conversion to/from floating yields the same binary
233 // result so that we don't lose precision.
234 void CppWriter::printCFP(const ConstantFP *CFP) {
235 APFloat APF = APFloat(CFP->getValueAPF()); // copy
236 if (CFP->getType() == Type::FloatTy)
237 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
238 Out << "ConstantFP::get(";
239 if (CFP->getType() == Type::DoubleTy)
240 Out << "Type::DoubleTy, ";
242 Out << "Type::FloatTy, ";
246 sprintf(Buffer, "%A", APF.convertToDouble());
247 if ((!strncmp(Buffer, "0x", 2) ||
248 !strncmp(Buffer, "-0x", 3) ||
249 !strncmp(Buffer, "+0x", 3)) &&
250 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
251 if (CFP->getType() == Type::DoubleTy)
252 Out << "BitsToDouble(" << Buffer << ")";
254 Out << "BitsToFloat((float)" << Buffer << ")";
258 std::string StrVal = ftostr(CFP->getValueAPF());
260 while (StrVal[0] == ' ')
261 StrVal.erase(StrVal.begin());
263 // Check to make sure that the stringized number is not some string like
264 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
265 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
266 ((StrVal[0] == '-' || StrVal[0] == '+') &&
267 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
268 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
269 if (CFP->getType() == Type::DoubleTy)
272 Out << StrVal << "f";
273 } else if (CFP->getType() == Type::DoubleTy)
274 Out << "BitsToDouble(0x" << std::hex
275 << CFP->getValueAPF().convertToAPInt().getZExtValue()
276 << std::dec << "ULL) /* " << StrVal << " */";
278 Out << "BitsToFloat(0x" << std::hex
279 << (uint32_t)CFP->getValueAPF().convertToAPInt().getZExtValue()
280 << std::dec << "U) /* " << StrVal << " */";
288 void CppWriter::printCallingConv(unsigned cc){
289 // Print the calling convention.
291 case CallingConv::C: Out << "CallingConv::C"; break;
292 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
293 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
294 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
295 default: Out << cc; break;
299 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
301 case GlobalValue::InternalLinkage:
302 Out << "GlobalValue::InternalLinkage"; break;
303 case GlobalValue::LinkOnceLinkage:
304 Out << "GlobalValue::LinkOnceLinkage "; break;
305 case GlobalValue::WeakLinkage:
306 Out << "GlobalValue::WeakLinkage"; break;
307 case GlobalValue::AppendingLinkage:
308 Out << "GlobalValue::AppendingLinkage"; break;
309 case GlobalValue::ExternalLinkage:
310 Out << "GlobalValue::ExternalLinkage"; break;
311 case GlobalValue::DLLImportLinkage:
312 Out << "GlobalValue::DLLImportLinkage"; break;
313 case GlobalValue::DLLExportLinkage:
314 Out << "GlobalValue::DLLExportLinkage"; break;
315 case GlobalValue::ExternalWeakLinkage:
316 Out << "GlobalValue::ExternalWeakLinkage"; break;
317 case GlobalValue::GhostLinkage:
318 Out << "GlobalValue::GhostLinkage"; break;
322 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
324 default: assert(0 && "Unknown GVar visibility");
325 case GlobalValue::DefaultVisibility:
326 Out << "GlobalValue::DefaultVisibility";
328 case GlobalValue::HiddenVisibility:
329 Out << "GlobalValue::HiddenVisibility";
331 case GlobalValue::ProtectedVisibility:
332 Out << "GlobalValue::ProtectedVisibility";
337 // printEscapedString - Print each character of the specified string, escaping
338 // it if it is not printable or if it is an escape char.
339 void CppWriter::printEscapedString(const std::string &Str) {
340 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
341 unsigned char C = Str[i];
342 if (isprint(C) && C != '"' && C != '\\') {
346 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
347 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
352 std::string CppWriter::getCppName(const Type* Ty) {
353 // First, handle the primitive types .. easy
354 if (Ty->isPrimitiveType() || Ty->isInteger()) {
355 switch (Ty->getTypeID()) {
356 case Type::VoidTyID: return "Type::VoidTy";
357 case Type::IntegerTyID: {
358 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
359 return "IntegerType::get(" + utostr(BitWidth) + ")";
361 case Type::FloatTyID: return "Type::FloatTy";
362 case Type::DoubleTyID: return "Type::DoubleTy";
363 case Type::LabelTyID: return "Type::LabelTy";
365 error("Invalid primitive type");
368 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
371 // Now, see if we've seen the type before and return that
372 TypeMap::iterator I = TypeNames.find(Ty);
373 if (I != TypeNames.end())
376 // Okay, let's build a new name for this type. Start with a prefix
377 const char* prefix = 0;
378 switch (Ty->getTypeID()) {
379 case Type::FunctionTyID: prefix = "FuncTy_"; break;
380 case Type::StructTyID: prefix = "StructTy_"; break;
381 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
382 case Type::PointerTyID: prefix = "PointerTy_"; break;
383 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
384 case Type::VectorTyID: prefix = "VectorTy_"; break;
385 default: prefix = "OtherTy_"; break; // prevent breakage
388 // See if the type has a name in the symboltable and build accordingly
389 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
392 name = std::string(prefix) + *tName;
394 name = std::string(prefix) + utostr(uniqueNum++);
398 return TypeNames[Ty] = name;
401 void CppWriter::printCppName(const Type* Ty) {
402 printEscapedString(getCppName(Ty));
405 std::string CppWriter::getCppName(const Value* val) {
407 ValueMap::iterator I = ValueNames.find(val);
408 if (I != ValueNames.end() && I->first == val)
411 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
412 name = std::string("gvar_") +
413 getTypePrefix(GV->getType()->getElementType());
414 } else if (isa<Function>(val)) {
415 name = std::string("func_");
416 } else if (const Constant* C = dyn_cast<Constant>(val)) {
417 name = std::string("const_") + getTypePrefix(C->getType());
418 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
420 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
421 Function::const_arg_iterator(Arg)) + 1;
422 name = std::string("arg_") + utostr(argNum);
423 NameSet::iterator NI = UsedNames.find(name);
424 if (NI != UsedNames.end())
425 name += std::string("_") + utostr(uniqueNum++);
426 UsedNames.insert(name);
427 return ValueNames[val] = name;
429 name = getTypePrefix(val->getType());
432 name = getTypePrefix(val->getType());
434 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
436 NameSet::iterator NI = UsedNames.find(name);
437 if (NI != UsedNames.end())
438 name += std::string("_") + utostr(uniqueNum++);
439 UsedNames.insert(name);
440 return ValueNames[val] = name;
443 void CppWriter::printCppName(const Value* val) {
444 printEscapedString(getCppName(val));
447 void CppWriter::printParamAttrs(const PAListPtr &PAL,
448 const std::string &name) {
449 Out << "PAListPtr " << name << "_PAL = 0;";
451 if (!PAL.isEmpty()) {
452 Out << '{'; in(); nl(Out);
453 Out << "SmallVector<ParamAttrsWithIndex, 4> Attrs;"; nl(Out);
454 Out << "ParamAttrsWithIndex PAWI;"; nl(Out);
455 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
456 uint16_t index = PAL.getSlot(i).Index;
457 ParameterAttributes attrs = PAL.getSlot(i).Attrs;
458 Out << "PAWI.index = " << index << "; PAWI.attrs = 0 ";
459 if (attrs & ParamAttr::SExt)
460 Out << " | ParamAttr::SExt";
461 if (attrs & ParamAttr::ZExt)
462 Out << " | ParamAttr::ZExt";
463 if (attrs & ParamAttr::StructRet)
464 Out << " | ParamAttr::StructRet";
465 if (attrs & ParamAttr::InReg)
466 Out << " | ParamAttr::InReg";
467 if (attrs & ParamAttr::NoReturn)
468 Out << " | ParamAttr::NoReturn";
469 if (attrs & ParamAttr::NoUnwind)
470 Out << " | ParamAttr::NoUnwind";
471 if (attrs & ParamAttr::ByVal)
472 Out << " | ParamAttr::ByVal";
473 if (attrs & ParamAttr::NoAlias)
474 Out << " | ParamAttr::NoAlias";
475 if (attrs & ParamAttr::Nest)
476 Out << " | ParamAttr::Nest";
477 if (attrs & ParamAttr::ReadNone)
478 Out << " | ParamAttr::ReadNone";
479 if (attrs & ParamAttr::ReadOnly)
480 Out << " | ParamAttr::ReadOnly";
483 Out << "Attrs.push_back(PAWI);";
486 Out << name << "_PAL = PAListPtr::get(Attrs.begin(), Attrs.end());";
493 bool CppWriter::printTypeInternal(const Type* Ty) {
494 // We don't print definitions for primitive types
495 if (Ty->isPrimitiveType() || Ty->isInteger())
498 // If we already defined this type, we don't need to define it again.
499 if (DefinedTypes.find(Ty) != DefinedTypes.end())
502 // Everything below needs the name for the type so get it now.
503 std::string typeName(getCppName(Ty));
505 // Search the type stack for recursion. If we find it, then generate this
506 // as an OpaqueType, but make sure not to do this multiple times because
507 // the type could appear in multiple places on the stack. Once the opaque
508 // definition is issued, it must not be re-issued. Consequently we have to
509 // check the UnresolvedTypes list as well.
510 TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
512 if (TI != TypeStack.end()) {
513 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
514 if (I == UnresolvedTypes.end()) {
515 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
517 UnresolvedTypes[Ty] = typeName;
522 // We're going to print a derived type which, by definition, contains other
523 // types. So, push this one we're printing onto the type stack to assist with
524 // recursive definitions.
525 TypeStack.push_back(Ty);
527 // Print the type definition
528 switch (Ty->getTypeID()) {
529 case Type::FunctionTyID: {
530 const FunctionType* FT = cast<FunctionType>(Ty);
531 Out << "std::vector<const Type*>" << typeName << "_args;";
533 FunctionType::param_iterator PI = FT->param_begin();
534 FunctionType::param_iterator PE = FT->param_end();
535 for (; PI != PE; ++PI) {
536 const Type* argTy = static_cast<const Type*>(*PI);
537 bool isForward = printTypeInternal(argTy);
538 std::string argName(getCppName(argTy));
539 Out << typeName << "_args.push_back(" << argName;
545 bool isForward = printTypeInternal(FT->getReturnType());
546 std::string retTypeName(getCppName(FT->getReturnType()));
547 Out << "FunctionType* " << typeName << " = FunctionType::get(";
548 in(); nl(Out) << "/*Result=*/" << retTypeName;
552 nl(Out) << "/*Params=*/" << typeName << "_args,";
553 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
558 case Type::StructTyID: {
559 const StructType* ST = cast<StructType>(Ty);
560 Out << "std::vector<const Type*>" << typeName << "_fields;";
562 StructType::element_iterator EI = ST->element_begin();
563 StructType::element_iterator EE = ST->element_end();
564 for (; EI != EE; ++EI) {
565 const Type* fieldTy = static_cast<const Type*>(*EI);
566 bool isForward = printTypeInternal(fieldTy);
567 std::string fieldName(getCppName(fieldTy));
568 Out << typeName << "_fields.push_back(" << fieldName;
574 Out << "StructType* " << typeName << " = StructType::get("
575 << typeName << "_fields, /*isPacked=*/"
576 << (ST->isPacked() ? "true" : "false") << ");";
580 case Type::ArrayTyID: {
581 const ArrayType* AT = cast<ArrayType>(Ty);
582 const Type* ET = AT->getElementType();
583 bool isForward = printTypeInternal(ET);
584 std::string elemName(getCppName(ET));
585 Out << "ArrayType* " << typeName << " = ArrayType::get("
586 << elemName << (isForward ? "_fwd" : "")
587 << ", " << utostr(AT->getNumElements()) << ");";
591 case Type::PointerTyID: {
592 const PointerType* PT = cast<PointerType>(Ty);
593 const Type* ET = PT->getElementType();
594 bool isForward = printTypeInternal(ET);
595 std::string elemName(getCppName(ET));
596 Out << "PointerType* " << typeName << " = PointerType::get("
597 << elemName << (isForward ? "_fwd" : "")
598 << ", " << utostr(PT->getAddressSpace()) << ");";
602 case Type::VectorTyID: {
603 const VectorType* PT = cast<VectorType>(Ty);
604 const Type* ET = PT->getElementType();
605 bool isForward = printTypeInternal(ET);
606 std::string elemName(getCppName(ET));
607 Out << "VectorType* " << typeName << " = VectorType::get("
608 << elemName << (isForward ? "_fwd" : "")
609 << ", " << utostr(PT->getNumElements()) << ");";
613 case Type::OpaqueTyID: {
614 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
619 error("Invalid TypeID");
622 // If the type had a name, make sure we recreate it.
623 const std::string* progTypeName =
624 findTypeName(TheModule->getTypeSymbolTable(),Ty);
626 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
631 // Pop us off the type stack
632 TypeStack.pop_back();
634 // Indicate that this type is now defined.
635 DefinedTypes.insert(Ty);
637 // Early resolve as many unresolved types as possible. Search the unresolved
638 // types map for the type we just printed. Now that its definition is complete
639 // we can resolve any previous references to it. This prevents a cascade of
641 TypeMap::iterator I = UnresolvedTypes.find(Ty);
642 if (I != UnresolvedTypes.end()) {
643 Out << "cast<OpaqueType>(" << I->second
644 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
646 Out << I->second << " = cast<";
647 switch (Ty->getTypeID()) {
648 case Type::FunctionTyID: Out << "FunctionType"; break;
649 case Type::ArrayTyID: Out << "ArrayType"; break;
650 case Type::StructTyID: Out << "StructType"; break;
651 case Type::VectorTyID: Out << "VectorType"; break;
652 case Type::PointerTyID: Out << "PointerType"; break;
653 case Type::OpaqueTyID: Out << "OpaqueType"; break;
654 default: Out << "NoSuchDerivedType"; break;
656 Out << ">(" << I->second << "_fwd.get());";
658 UnresolvedTypes.erase(I);
661 // Finally, separate the type definition from other with a newline.
664 // We weren't a recursive type
668 // Prints a type definition. Returns true if it could not resolve all the
669 // types in the definition but had to use a forward reference.
670 void CppWriter::printType(const Type* Ty) {
671 assert(TypeStack.empty());
673 printTypeInternal(Ty);
674 assert(TypeStack.empty());
677 void CppWriter::printTypes(const Module* M) {
678 // Walk the symbol table and print out all its types
679 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
680 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
683 // For primitive types and types already defined, just add a name
684 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
685 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
686 TNI != TypeNames.end()) {
687 Out << "mod->addTypeName(\"";
688 printEscapedString(TI->first);
689 Out << "\", " << getCppName(TI->second) << ");";
691 // For everything else, define the type
693 printType(TI->second);
697 // Add all of the global variables to the value table...
698 for (Module::const_global_iterator I = TheModule->global_begin(),
699 E = TheModule->global_end(); I != E; ++I) {
700 if (I->hasInitializer())
701 printType(I->getInitializer()->getType());
702 printType(I->getType());
705 // Add all the functions to the table
706 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
708 printType(FI->getReturnType());
709 printType(FI->getFunctionType());
710 // Add all the function arguments
711 for (Function::const_arg_iterator AI = FI->arg_begin(),
712 AE = FI->arg_end(); AI != AE; ++AI) {
713 printType(AI->getType());
716 // Add all of the basic blocks and instructions
717 for (Function::const_iterator BB = FI->begin(),
718 E = FI->end(); BB != E; ++BB) {
719 printType(BB->getType());
720 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
722 printType(I->getType());
723 for (unsigned i = 0; i < I->getNumOperands(); ++i)
724 printType(I->getOperand(i)->getType());
731 // printConstant - Print out a constant pool entry...
732 void CppWriter::printConstant(const Constant *CV) {
733 // First, if the constant is actually a GlobalValue (variable or function)
734 // or its already in the constant list then we've printed it already and we
736 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
739 std::string constName(getCppName(CV));
740 std::string typeName(getCppName(CV->getType()));
741 if (CV->isNullValue()) {
742 Out << "Constant* " << constName << " = Constant::getNullValue("
747 if (isa<GlobalValue>(CV)) {
748 // Skip variables and functions, we emit them elsewhere
751 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
752 Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
753 << cast<IntegerType>(CI->getType())->getBitWidth() << ", "
754 << " \"" << CI->getValue().toStringSigned(10) << "\", 10));";
755 } else if (isa<ConstantAggregateZero>(CV)) {
756 Out << "ConstantAggregateZero* " << constName
757 << " = ConstantAggregateZero::get(" << typeName << ");";
758 } else if (isa<ConstantPointerNull>(CV)) {
759 Out << "ConstantPointerNull* " << constName
760 << " = ConstanPointerNull::get(" << typeName << ");";
761 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
762 Out << "ConstantFP* " << constName << " = ";
765 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
766 if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
767 Out << "Constant* " << constName << " = ConstantArray::get(\"";
768 std::string tmp = CA->getAsString();
769 bool nullTerminate = false;
770 if (tmp[tmp.length()-1] == 0) {
771 tmp.erase(tmp.length()-1);
772 nullTerminate = true;
774 printEscapedString(tmp);
775 // Determine if we want null termination or not.
777 Out << "\", true"; // Indicate that the null terminator should be
780 Out << "\", false";// No null terminator
783 Out << "std::vector<Constant*> " << constName << "_elems;";
785 unsigned N = CA->getNumOperands();
786 for (unsigned i = 0; i < N; ++i) {
787 printConstant(CA->getOperand(i)); // recurse to print operands
788 Out << constName << "_elems.push_back("
789 << getCppName(CA->getOperand(i)) << ");";
792 Out << "Constant* " << constName << " = ConstantArray::get("
793 << typeName << ", " << constName << "_elems);";
795 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
796 Out << "std::vector<Constant*> " << constName << "_fields;";
798 unsigned N = CS->getNumOperands();
799 for (unsigned i = 0; i < N; i++) {
800 printConstant(CS->getOperand(i));
801 Out << constName << "_fields.push_back("
802 << getCppName(CS->getOperand(i)) << ");";
805 Out << "Constant* " << constName << " = ConstantStruct::get("
806 << typeName << ", " << constName << "_fields);";
807 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
808 Out << "std::vector<Constant*> " << constName << "_elems;";
810 unsigned N = CP->getNumOperands();
811 for (unsigned i = 0; i < N; ++i) {
812 printConstant(CP->getOperand(i));
813 Out << constName << "_elems.push_back("
814 << getCppName(CP->getOperand(i)) << ");";
817 Out << "Constant* " << constName << " = ConstantVector::get("
818 << typeName << ", " << constName << "_elems);";
819 } else if (isa<UndefValue>(CV)) {
820 Out << "UndefValue* " << constName << " = UndefValue::get("
822 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
823 if (CE->getOpcode() == Instruction::GetElementPtr) {
824 Out << "std::vector<Constant*> " << constName << "_indices;";
826 printConstant(CE->getOperand(0));
827 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
828 printConstant(CE->getOperand(i));
829 Out << constName << "_indices.push_back("
830 << getCppName(CE->getOperand(i)) << ");";
833 Out << "Constant* " << constName
834 << " = ConstantExpr::getGetElementPtr("
835 << getCppName(CE->getOperand(0)) << ", "
836 << "&" << constName << "_indices[0], "
837 << constName << "_indices.size()"
839 } else if (CE->isCast()) {
840 printConstant(CE->getOperand(0));
841 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
842 switch (CE->getOpcode()) {
843 default: assert(0 && "Invalid cast opcode");
844 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
845 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
846 case Instruction::SExt: Out << "Instruction::SExt"; break;
847 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
848 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
849 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
850 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
851 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
852 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
853 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
854 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
855 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
857 Out << ", " << getCppName(CE->getOperand(0)) << ", "
858 << getCppName(CE->getType()) << ");";
860 unsigned N = CE->getNumOperands();
861 for (unsigned i = 0; i < N; ++i ) {
862 printConstant(CE->getOperand(i));
864 Out << "Constant* " << constName << " = ConstantExpr::";
865 switch (CE->getOpcode()) {
866 case Instruction::Add: Out << "getAdd("; break;
867 case Instruction::Sub: Out << "getSub("; break;
868 case Instruction::Mul: Out << "getMul("; break;
869 case Instruction::UDiv: Out << "getUDiv("; break;
870 case Instruction::SDiv: Out << "getSDiv("; break;
871 case Instruction::FDiv: Out << "getFDiv("; break;
872 case Instruction::URem: Out << "getURem("; break;
873 case Instruction::SRem: Out << "getSRem("; break;
874 case Instruction::FRem: Out << "getFRem("; break;
875 case Instruction::And: Out << "getAnd("; break;
876 case Instruction::Or: Out << "getOr("; break;
877 case Instruction::Xor: Out << "getXor("; break;
878 case Instruction::ICmp:
879 Out << "getICmp(ICmpInst::ICMP_";
880 switch (CE->getPredicate()) {
881 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
882 case ICmpInst::ICMP_NE: Out << "NE"; break;
883 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
884 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
885 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
886 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
887 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
888 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
889 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
890 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
891 default: error("Invalid ICmp Predicate");
894 case Instruction::FCmp:
895 Out << "getFCmp(FCmpInst::FCMP_";
896 switch (CE->getPredicate()) {
897 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
898 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
899 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
900 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
901 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
902 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
903 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
904 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
905 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
906 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
907 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
908 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
909 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
910 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
911 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
912 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
913 default: error("Invalid FCmp Predicate");
916 case Instruction::Shl: Out << "getShl("; break;
917 case Instruction::LShr: Out << "getLShr("; break;
918 case Instruction::AShr: Out << "getAShr("; break;
919 case Instruction::Select: Out << "getSelect("; break;
920 case Instruction::ExtractElement: Out << "getExtractElement("; break;
921 case Instruction::InsertElement: Out << "getInsertElement("; break;
922 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
924 error("Invalid constant expression");
927 Out << getCppName(CE->getOperand(0));
928 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
929 Out << ", " << getCppName(CE->getOperand(i));
933 error("Bad Constant");
934 Out << "Constant* " << constName << " = 0; ";
939 void CppWriter::printConstants(const Module* M) {
940 // Traverse all the global variables looking for constant initializers
941 for (Module::const_global_iterator I = TheModule->global_begin(),
942 E = TheModule->global_end(); I != E; ++I)
943 if (I->hasInitializer())
944 printConstant(I->getInitializer());
946 // Traverse the LLVM functions looking for constants
947 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
949 // Add all of the basic blocks and instructions
950 for (Function::const_iterator BB = FI->begin(),
951 E = FI->end(); BB != E; ++BB) {
952 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
954 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
955 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
964 void CppWriter::printVariableUses(const GlobalVariable *GV) {
965 nl(Out) << "// Type Definitions";
967 printType(GV->getType());
968 if (GV->hasInitializer()) {
969 Constant* Init = GV->getInitializer();
970 printType(Init->getType());
971 if (Function* F = dyn_cast<Function>(Init)) {
972 nl(Out)<< "/ Function Declarations"; nl(Out);
973 printFunctionHead(F);
974 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
975 nl(Out) << "// Global Variable Declarations"; nl(Out);
976 printVariableHead(gv);
978 nl(Out) << "// Constant Definitions"; nl(Out);
981 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
982 nl(Out) << "// Global Variable Definitions"; nl(Out);
983 printVariableBody(gv);
988 void CppWriter::printVariableHead(const GlobalVariable *GV) {
989 nl(Out) << "GlobalVariable* " << getCppName(GV);
991 Out << " = mod->getGlobalVariable(";
992 printEscapedString(GV->getName());
993 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
994 nl(Out) << "if (!" << getCppName(GV) << ") {";
995 in(); nl(Out) << getCppName(GV);
997 Out << " = new GlobalVariable(";
998 nl(Out) << "/*Type=*/";
999 printCppName(GV->getType()->getElementType());
1001 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
1003 nl(Out) << "/*Linkage=*/";
1004 printLinkageType(GV->getLinkage());
1006 nl(Out) << "/*Initializer=*/0, ";
1007 if (GV->hasInitializer()) {
1008 Out << "// has initializer, specified below";
1010 nl(Out) << "/*Name=*/\"";
1011 printEscapedString(GV->getName());
1016 if (GV->hasSection()) {
1018 Out << "->setSection(\"";
1019 printEscapedString(GV->getSection());
1023 if (GV->getAlignment()) {
1025 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1028 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1030 Out << "->setVisibility(";
1031 printVisibilityType(GV->getVisibility());
1036 out(); Out << "}"; nl(Out);
1040 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1041 if (GV->hasInitializer()) {
1043 Out << "->setInitializer(";
1044 Out << getCppName(GV->getInitializer()) << ");";
1049 std::string CppWriter::getOpName(Value* V) {
1050 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1051 return getCppName(V);
1053 // See if its alread in the map of forward references, if so just return the
1054 // name we already set up for it
1055 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1056 if (I != ForwardRefs.end())
1059 // This is a new forward reference. Generate a unique name for it
1060 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1062 // Yes, this is a hack. An Argument is the smallest instantiable value that
1063 // we can make as a placeholder for the real value. We'll replace these
1064 // Argument instances later.
1065 Out << "Argument* " << result << " = new Argument("
1066 << getCppName(V->getType()) << ");";
1068 ForwardRefs[V] = result;
1072 // printInstruction - This member is called for each Instruction in a function.
1073 void CppWriter::printInstruction(const Instruction *I,
1074 const std::string& bbname) {
1075 std::string iName(getCppName(I));
1077 // Before we emit this instruction, we need to take care of generating any
1078 // forward references. So, we get the names of all the operands in advance
1079 std::string* opNames = new std::string[I->getNumOperands()];
1080 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1081 opNames[i] = getOpName(I->getOperand(i));
1084 switch (I->getOpcode()) {
1085 case Instruction::Ret: {
1086 const ReturnInst* ret = cast<ReturnInst>(I);
1087 Out << "ReturnInst::Create("
1088 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1091 case Instruction::Br: {
1092 const BranchInst* br = cast<BranchInst>(I);
1093 Out << "BranchInst::Create(" ;
1094 if (br->getNumOperands() == 3 ) {
1095 Out << opNames[0] << ", "
1096 << opNames[1] << ", "
1097 << opNames[2] << ", ";
1099 } else if (br->getNumOperands() == 1) {
1100 Out << opNames[0] << ", ";
1102 error("Branch with 2 operands?");
1104 Out << bbname << ");";
1107 case Instruction::Switch: {
1108 const SwitchInst* sw = cast<SwitchInst>(I);
1109 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1110 << opNames[0] << ", "
1111 << opNames[1] << ", "
1112 << sw->getNumCases() << ", " << bbname << ");";
1114 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1115 Out << iName << "->addCase("
1116 << opNames[i] << ", "
1117 << opNames[i+1] << ");";
1122 case Instruction::Invoke: {
1123 const InvokeInst* inv = cast<InvokeInst>(I);
1124 Out << "std::vector<Value*> " << iName << "_params;";
1126 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1127 Out << iName << "_params.push_back("
1128 << opNames[i] << ");";
1131 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1132 << opNames[0] << ", "
1133 << opNames[1] << ", "
1134 << opNames[2] << ", "
1135 << iName << "_params.begin(), " << iName << "_params.end(), \"";
1136 printEscapedString(inv->getName());
1137 Out << "\", " << bbname << ");";
1138 nl(Out) << iName << "->setCallingConv(";
1139 printCallingConv(inv->getCallingConv());
1141 printParamAttrs(inv->getParamAttrs(), iName);
1142 Out << iName << "->setParamAttrs(" << iName << "_PAL);";
1146 case Instruction::Unwind: {
1147 Out << "new UnwindInst("
1151 case Instruction::Unreachable:{
1152 Out << "new UnreachableInst("
1156 case Instruction::Add:
1157 case Instruction::Sub:
1158 case Instruction::Mul:
1159 case Instruction::UDiv:
1160 case Instruction::SDiv:
1161 case Instruction::FDiv:
1162 case Instruction::URem:
1163 case Instruction::SRem:
1164 case Instruction::FRem:
1165 case Instruction::And:
1166 case Instruction::Or:
1167 case Instruction::Xor:
1168 case Instruction::Shl:
1169 case Instruction::LShr:
1170 case Instruction::AShr:{
1171 Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
1172 switch (I->getOpcode()) {
1173 case Instruction::Add: Out << "Instruction::Add"; break;
1174 case Instruction::Sub: Out << "Instruction::Sub"; break;
1175 case Instruction::Mul: Out << "Instruction::Mul"; break;
1176 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1177 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1178 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1179 case Instruction::URem:Out << "Instruction::URem"; break;
1180 case Instruction::SRem:Out << "Instruction::SRem"; break;
1181 case Instruction::FRem:Out << "Instruction::FRem"; break;
1182 case Instruction::And: Out << "Instruction::And"; break;
1183 case Instruction::Or: Out << "Instruction::Or"; break;
1184 case Instruction::Xor: Out << "Instruction::Xor"; break;
1185 case Instruction::Shl: Out << "Instruction::Shl"; break;
1186 case Instruction::LShr:Out << "Instruction::LShr"; break;
1187 case Instruction::AShr:Out << "Instruction::AShr"; break;
1188 default: Out << "Instruction::BadOpCode"; break;
1190 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1191 printEscapedString(I->getName());
1192 Out << "\", " << bbname << ");";
1195 case Instruction::FCmp: {
1196 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1197 switch (cast<FCmpInst>(I)->getPredicate()) {
1198 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1199 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1200 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1201 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1202 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1203 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1204 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1205 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1206 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1207 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1208 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1209 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1210 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1211 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1212 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1213 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1214 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1216 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1217 printEscapedString(I->getName());
1218 Out << "\", " << bbname << ");";
1221 case Instruction::ICmp: {
1222 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1223 switch (cast<ICmpInst>(I)->getPredicate()) {
1224 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1225 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1226 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1227 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1228 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1229 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1230 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1231 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1232 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1233 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1234 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1236 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1237 printEscapedString(I->getName());
1238 Out << "\", " << bbname << ");";
1241 case Instruction::Malloc: {
1242 const MallocInst* mallocI = cast<MallocInst>(I);
1243 Out << "MallocInst* " << iName << " = new MallocInst("
1244 << getCppName(mallocI->getAllocatedType()) << ", ";
1245 if (mallocI->isArrayAllocation())
1246 Out << opNames[0] << ", " ;
1248 printEscapedString(mallocI->getName());
1249 Out << "\", " << bbname << ");";
1250 if (mallocI->getAlignment())
1251 nl(Out) << iName << "->setAlignment("
1252 << mallocI->getAlignment() << ");";
1255 case Instruction::Free: {
1256 Out << "FreeInst* " << iName << " = new FreeInst("
1257 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1260 case Instruction::Alloca: {
1261 const AllocaInst* allocaI = cast<AllocaInst>(I);
1262 Out << "AllocaInst* " << iName << " = new AllocaInst("
1263 << getCppName(allocaI->getAllocatedType()) << ", ";
1264 if (allocaI->isArrayAllocation())
1265 Out << opNames[0] << ", ";
1267 printEscapedString(allocaI->getName());
1268 Out << "\", " << bbname << ");";
1269 if (allocaI->getAlignment())
1270 nl(Out) << iName << "->setAlignment("
1271 << allocaI->getAlignment() << ");";
1274 case Instruction::Load:{
1275 const LoadInst* load = cast<LoadInst>(I);
1276 Out << "LoadInst* " << iName << " = new LoadInst("
1277 << opNames[0] << ", \"";
1278 printEscapedString(load->getName());
1279 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1280 << ", " << bbname << ");";
1283 case Instruction::Store: {
1284 const StoreInst* store = cast<StoreInst>(I);
1285 Out << "StoreInst* " << iName << " = new StoreInst("
1286 << opNames[0] << ", "
1287 << opNames[1] << ", "
1288 << (store->isVolatile() ? "true" : "false")
1289 << ", " << bbname << ");";
1292 case Instruction::GetElementPtr: {
1293 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1294 if (gep->getNumOperands() <= 2) {
1295 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1297 if (gep->getNumOperands() == 2)
1298 Out << ", " << opNames[1];
1300 Out << "std::vector<Value*> " << iName << "_indices;";
1302 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1303 Out << iName << "_indices.push_back("
1304 << opNames[i] << ");";
1307 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1308 << opNames[0] << ", " << iName << "_indices.begin(), "
1309 << iName << "_indices.end()";
1312 printEscapedString(gep->getName());
1313 Out << "\", " << bbname << ");";
1316 case Instruction::PHI: {
1317 const PHINode* phi = cast<PHINode>(I);
1319 Out << "PHINode* " << iName << " = PHINode::Create("
1320 << getCppName(phi->getType()) << ", \"";
1321 printEscapedString(phi->getName());
1322 Out << "\", " << bbname << ");";
1323 nl(Out) << iName << "->reserveOperandSpace("
1324 << phi->getNumIncomingValues()
1327 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1328 Out << iName << "->addIncoming("
1329 << opNames[i] << ", " << opNames[i+1] << ");";
1334 case Instruction::Trunc:
1335 case Instruction::ZExt:
1336 case Instruction::SExt:
1337 case Instruction::FPTrunc:
1338 case Instruction::FPExt:
1339 case Instruction::FPToUI:
1340 case Instruction::FPToSI:
1341 case Instruction::UIToFP:
1342 case Instruction::SIToFP:
1343 case Instruction::PtrToInt:
1344 case Instruction::IntToPtr:
1345 case Instruction::BitCast: {
1346 const CastInst* cst = cast<CastInst>(I);
1347 Out << "CastInst* " << iName << " = new ";
1348 switch (I->getOpcode()) {
1349 case Instruction::Trunc: Out << "TruncInst"; break;
1350 case Instruction::ZExt: Out << "ZExtInst"; break;
1351 case Instruction::SExt: Out << "SExtInst"; break;
1352 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1353 case Instruction::FPExt: Out << "FPExtInst"; break;
1354 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1355 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1356 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1357 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1358 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1359 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1360 case Instruction::BitCast: Out << "BitCastInst"; break;
1361 default: assert(!"Unreachable"); break;
1363 Out << "(" << opNames[0] << ", "
1364 << getCppName(cst->getType()) << ", \"";
1365 printEscapedString(cst->getName());
1366 Out << "\", " << bbname << ");";
1369 case Instruction::Call:{
1370 const CallInst* call = cast<CallInst>(I);
1371 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1372 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1373 << getCppName(ila->getFunctionType()) << ", \""
1374 << ila->getAsmString() << "\", \""
1375 << ila->getConstraintString() << "\","
1376 << (ila->hasSideEffects() ? "true" : "false") << ");";
1379 if (call->getNumOperands() > 2) {
1380 Out << "std::vector<Value*> " << iName << "_params;";
1382 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1383 Out << iName << "_params.push_back(" << opNames[i] << ");";
1386 Out << "CallInst* " << iName << " = CallInst::Create("
1387 << opNames[0] << ", " << iName << "_params.begin(), "
1388 << iName << "_params.end(), \"";
1389 } else if (call->getNumOperands() == 2) {
1390 Out << "CallInst* " << iName << " = CallInst::Create("
1391 << opNames[0] << ", " << opNames[1] << ", \"";
1393 Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
1396 printEscapedString(call->getName());
1397 Out << "\", " << bbname << ");";
1398 nl(Out) << iName << "->setCallingConv(";
1399 printCallingConv(call->getCallingConv());
1401 nl(Out) << iName << "->setTailCall("
1402 << (call->isTailCall() ? "true":"false");
1404 printParamAttrs(call->getParamAttrs(), iName);
1405 Out << iName << "->setParamAttrs(" << iName << "_PAL);";
1409 case Instruction::Select: {
1410 const SelectInst* sel = cast<SelectInst>(I);
1411 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1412 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1413 printEscapedString(sel->getName());
1414 Out << "\", " << bbname << ");";
1417 case Instruction::UserOp1:
1419 case Instruction::UserOp2: {
1420 /// FIXME: What should be done here?
1423 case Instruction::VAArg: {
1424 const VAArgInst* va = cast<VAArgInst>(I);
1425 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1426 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1427 printEscapedString(va->getName());
1428 Out << "\", " << bbname << ");";
1431 case Instruction::ExtractElement: {
1432 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1433 Out << "ExtractElementInst* " << getCppName(eei)
1434 << " = new ExtractElementInst(" << opNames[0]
1435 << ", " << opNames[1] << ", \"";
1436 printEscapedString(eei->getName());
1437 Out << "\", " << bbname << ");";
1440 case Instruction::InsertElement: {
1441 const InsertElementInst* iei = cast<InsertElementInst>(I);
1442 Out << "InsertElementInst* " << getCppName(iei)
1443 << " = InsertElementInst::Create(" << opNames[0]
1444 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1445 printEscapedString(iei->getName());
1446 Out << "\", " << bbname << ");";
1449 case Instruction::ShuffleVector: {
1450 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1451 Out << "ShuffleVectorInst* " << getCppName(svi)
1452 << " = new ShuffleVectorInst(" << opNames[0]
1453 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1454 printEscapedString(svi->getName());
1455 Out << "\", " << bbname << ");";
1459 DefinedValues.insert(I);
1464 // Print out the types, constants and declarations needed by one function
1465 void CppWriter::printFunctionUses(const Function* F) {
1466 nl(Out) << "// Type Definitions"; nl(Out);
1468 // Print the function's return type
1469 printType(F->getReturnType());
1471 // Print the function's function type
1472 printType(F->getFunctionType());
1474 // Print the types of each of the function's arguments
1475 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1477 printType(AI->getType());
1481 // Print type definitions for every type referenced by an instruction and
1482 // make a note of any global values or constants that are referenced
1483 SmallPtrSet<GlobalValue*,64> gvs;
1484 SmallPtrSet<Constant*,64> consts;
1485 for (Function::const_iterator BB = F->begin(), BE = F->end();
1487 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1489 // Print the type of the instruction itself
1490 printType(I->getType());
1492 // Print the type of each of the instruction's operands
1493 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1494 Value* operand = I->getOperand(i);
1495 printType(operand->getType());
1497 // If the operand references a GVal or Constant, make a note of it
1498 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1500 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1501 if (GVar->hasInitializer())
1502 consts.insert(GVar->getInitializer());
1503 } else if (Constant* C = dyn_cast<Constant>(operand))
1509 // Print the function declarations for any functions encountered
1510 nl(Out) << "// Function Declarations"; nl(Out);
1511 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1513 if (Function* Fun = dyn_cast<Function>(*I)) {
1514 if (!is_inline || Fun != F)
1515 printFunctionHead(Fun);
1519 // Print the global variable declarations for any variables encountered
1520 nl(Out) << "// Global Variable Declarations"; nl(Out);
1521 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1523 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1524 printVariableHead(F);
1527 // Print the constants found
1528 nl(Out) << "// Constant Definitions"; nl(Out);
1529 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1530 E = consts.end(); I != E; ++I) {
1534 // Process the global variables definitions now that all the constants have
1535 // been emitted. These definitions just couple the gvars with their constant
1537 nl(Out) << "// Global Variable Definitions"; nl(Out);
1538 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1540 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1541 printVariableBody(GV);
1545 void CppWriter::printFunctionHead(const Function* F) {
1546 nl(Out) << "Function* " << getCppName(F);
1548 Out << " = mod->getFunction(\"";
1549 printEscapedString(F->getName());
1550 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1551 nl(Out) << "if (!" << getCppName(F) << ") {";
1552 nl(Out) << getCppName(F);
1554 Out<< " = Function::Create(";
1555 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1556 nl(Out) << "/*Linkage=*/";
1557 printLinkageType(F->getLinkage());
1559 nl(Out) << "/*Name=*/\"";
1560 printEscapedString(F->getName());
1561 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1564 Out << "->setCallingConv(";
1565 printCallingConv(F->getCallingConv());
1568 if (F->hasSection()) {
1570 Out << "->setSection(\"" << F->getSection() << "\");";
1573 if (F->getAlignment()) {
1575 Out << "->setAlignment(" << F->getAlignment() << ");";
1578 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1580 Out << "->setVisibility(";
1581 printVisibilityType(F->getVisibility());
1585 if (F->hasCollector()) {
1587 Out << "->setCollector(\"" << F->getCollector() << "\");";
1594 printParamAttrs(F->getParamAttrs(), getCppName(F));
1596 Out << "->setParamAttrs(" << getCppName(F) << "_PAL);";
1600 void CppWriter::printFunctionBody(const Function *F) {
1601 if (F->isDeclaration())
1602 return; // external functions have no bodies.
1604 // Clear the DefinedValues and ForwardRefs maps because we can't have
1605 // cross-function forward refs
1606 ForwardRefs.clear();
1607 DefinedValues.clear();
1609 // Create all the argument values
1611 if (!F->arg_empty()) {
1612 Out << "Function::arg_iterator args = " << getCppName(F)
1613 << "->arg_begin();";
1616 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1618 Out << "Value* " << getCppName(AI) << " = args++;";
1620 if (AI->hasName()) {
1621 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1627 // Create all the basic blocks
1629 for (Function::const_iterator BI = F->begin(), BE = F->end();
1631 std::string bbname(getCppName(BI));
1632 Out << "BasicBlock* " << bbname << " = BasicBlock::Create(\"";
1634 printEscapedString(BI->getName());
1635 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1639 // Output all of its basic blocks... for the function
1640 for (Function::const_iterator BI = F->begin(), BE = F->end();
1642 std::string bbname(getCppName(BI));
1643 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1646 // Output all of the instructions in the basic block...
1647 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1649 printInstruction(I,bbname);
1653 // Loop over the ForwardRefs and resolve them now that all instructions
1655 if (!ForwardRefs.empty()) {
1656 nl(Out) << "// Resolve Forward References";
1660 while (!ForwardRefs.empty()) {
1661 ForwardRefMap::iterator I = ForwardRefs.begin();
1662 Out << I->second << "->replaceAllUsesWith("
1663 << getCppName(I->first) << "); delete " << I->second << ";";
1665 ForwardRefs.erase(I);
1669 void CppWriter::printInline(const std::string& fname,
1670 const std::string& func) {
1671 const Function* F = TheModule->getFunction(func);
1673 error(std::string("Function '") + func + "' not found in input module");
1676 if (F->isDeclaration()) {
1677 error(std::string("Function '") + func + "' is external!");
1680 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1682 unsigned arg_count = 1;
1683 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1685 Out << ", Value* arg_" << arg_count;
1690 printFunctionUses(F);
1691 printFunctionBody(F);
1693 Out << "return " << getCppName(F->begin()) << ";";
1698 void CppWriter::printModuleBody() {
1699 // Print out all the type definitions
1700 nl(Out) << "// Type Definitions"; nl(Out);
1701 printTypes(TheModule);
1703 // Functions can call each other and global variables can reference them so
1704 // define all the functions first before emitting their function bodies.
1705 nl(Out) << "// Function Declarations"; nl(Out);
1706 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1708 printFunctionHead(I);
1710 // Process the global variables declarations. We can't initialze them until
1711 // after the constants are printed so just print a header for each global
1712 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1713 for (Module::const_global_iterator I = TheModule->global_begin(),
1714 E = TheModule->global_end(); I != E; ++I) {
1715 printVariableHead(I);
1718 // Print out all the constants definitions. Constants don't recurse except
1719 // through GlobalValues. All GlobalValues have been declared at this point
1720 // so we can proceed to generate the constants.
1721 nl(Out) << "// Constant Definitions"; nl(Out);
1722 printConstants(TheModule);
1724 // Process the global variables definitions now that all the constants have
1725 // been emitted. These definitions just couple the gvars with their constant
1727 nl(Out) << "// Global Variable Definitions"; nl(Out);
1728 for (Module::const_global_iterator I = TheModule->global_begin(),
1729 E = TheModule->global_end(); I != E; ++I) {
1730 printVariableBody(I);
1733 // Finally, we can safely put out all of the function bodies.
1734 nl(Out) << "// Function Definitions"; nl(Out);
1735 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1737 if (!I->isDeclaration()) {
1738 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1742 printFunctionBody(I);
1749 void CppWriter::printProgram(const std::string& fname,
1750 const std::string& mName) {
1751 Out << "#include <llvm/Module.h>\n";
1752 Out << "#include <llvm/DerivedTypes.h>\n";
1753 Out << "#include <llvm/Constants.h>\n";
1754 Out << "#include <llvm/GlobalVariable.h>\n";
1755 Out << "#include <llvm/Function.h>\n";
1756 Out << "#include <llvm/CallingConv.h>\n";
1757 Out << "#include <llvm/BasicBlock.h>\n";
1758 Out << "#include <llvm/Instructions.h>\n";
1759 Out << "#include <llvm/InlineAsm.h>\n";
1760 Out << "#include <llvm/Support/MathExtras.h>\n";
1761 Out << "#include <llvm/Pass.h>\n";
1762 Out << "#include <llvm/PassManager.h>\n";
1763 Out << "#include <llvm/Analysis/Verifier.h>\n";
1764 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1765 Out << "#include <algorithm>\n";
1766 Out << "#include <iostream>\n\n";
1767 Out << "using namespace llvm;\n\n";
1768 Out << "Module* " << fname << "();\n\n";
1769 Out << "int main(int argc, char**argv) {\n";
1770 Out << " Module* Mod = " << fname << "();\n";
1771 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1772 Out << " std::cerr.flush();\n";
1773 Out << " std::cout.flush();\n";
1774 Out << " PassManager PM;\n";
1775 Out << " PM.add(new PrintModulePass(&llvm::cout));\n";
1776 Out << " PM.run(*Mod);\n";
1777 Out << " return 0;\n";
1779 printModule(fname,mName);
1782 void CppWriter::printModule(const std::string& fname,
1783 const std::string& mName) {
1784 nl(Out) << "Module* " << fname << "() {";
1785 nl(Out,1) << "// Module Construction";
1786 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1787 if (!TheModule->getTargetTriple().empty()) {
1788 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1790 if (!TheModule->getTargetTriple().empty()) {
1791 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1795 if (!TheModule->getModuleInlineAsm().empty()) {
1796 nl(Out) << "mod->setModuleInlineAsm(\"";
1797 printEscapedString(TheModule->getModuleInlineAsm());
1802 // Loop over the dependent libraries and emit them.
1803 Module::lib_iterator LI = TheModule->lib_begin();
1804 Module::lib_iterator LE = TheModule->lib_end();
1806 Out << "mod->addLibrary(\"" << *LI << "\");";
1811 nl(Out) << "return mod;";
1816 void CppWriter::printContents(const std::string& fname,
1817 const std::string& mName) {
1818 Out << "\nModule* " << fname << "(Module *mod) {\n";
1819 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1821 Out << "\nreturn mod;\n";
1825 void CppWriter::printFunction(const std::string& fname,
1826 const std::string& funcName) {
1827 const Function* F = TheModule->getFunction(funcName);
1829 error(std::string("Function '") + funcName + "' not found in input module");
1832 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1833 printFunctionUses(F);
1834 printFunctionHead(F);
1835 printFunctionBody(F);
1836 Out << "return " << getCppName(F) << ";\n";
1840 void CppWriter::printFunctions() {
1841 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1842 Module::const_iterator I = funcs.begin();
1843 Module::const_iterator IE = funcs.end();
1845 for (; I != IE; ++I) {
1846 const Function &func = *I;
1847 if (!func.isDeclaration()) {
1848 std::string name("define_");
1849 name += func.getName();
1850 printFunction(name, func.getName());
1855 void CppWriter::printVariable(const std::string& fname,
1856 const std::string& varName) {
1857 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1860 error(std::string("Variable '") + varName + "' not found in input module");
1863 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1864 printVariableUses(GV);
1865 printVariableHead(GV);
1866 printVariableBody(GV);
1867 Out << "return " << getCppName(GV) << ";\n";
1871 void CppWriter::printType(const std::string& fname,
1872 const std::string& typeName) {
1873 const Type* Ty = TheModule->getTypeByName(typeName);
1875 error(std::string("Type '") + typeName + "' not found in input module");
1878 Out << "\nType* " << fname << "(Module *mod) {\n";
1880 Out << "return " << getCppName(Ty) << ";\n";
1884 bool CppWriter::runOnModule(Module &M) {
1888 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1890 // Get the name of the function we're supposed to generate
1891 std::string fname = FuncName.getValue();
1893 // Get the name of the thing we are to generate
1894 std::string tgtname = NameToGenerate.getValue();
1895 if (GenerationType == GenModule ||
1896 GenerationType == GenContents ||
1897 GenerationType == GenProgram ||
1898 GenerationType == GenFunctions) {
1899 if (tgtname == "!bad!") {
1900 if (M.getModuleIdentifier() == "-")
1901 tgtname = "<stdin>";
1903 tgtname = M.getModuleIdentifier();
1905 } else if (tgtname == "!bad!")
1906 error("You must use the -for option with -gen-{function,variable,type}");
1908 switch (WhatToGenerate(GenerationType)) {
1911 fname = "makeLLVMModule";
1912 printProgram(fname,tgtname);
1916 fname = "makeLLVMModule";
1917 printModule(fname,tgtname);
1921 fname = "makeLLVMModuleContents";
1922 printContents(fname,tgtname);
1926 fname = "makeLLVMFunction";
1927 printFunction(fname,tgtname);
1934 fname = "makeLLVMInline";
1935 printInline(fname,tgtname);
1939 fname = "makeLLVMVariable";
1940 printVariable(fname,tgtname);
1944 fname = "makeLLVMType";
1945 printType(fname,tgtname);
1948 error("Invalid generation option");
1955 char CppWriter::ID = 0;
1957 //===----------------------------------------------------------------------===//
1958 // External Interface declaration
1959 //===----------------------------------------------------------------------===//
1961 bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
1963 CodeGenFileType FileType,
1965 if (FileType != TargetMachine::AssemblyFile) return true;
1966 PM.add(new CppWriter(o));