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/Support/CFG.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Config/config.h"
41 static cl::opt<std::string>
42 FuncName("funcname", cl::desc("Specify the name of the generated function"),
43 cl::value_desc("function name"));
56 static cl::opt<WhatToGenerate> GenerationType(cl::Optional,
57 cl::desc("Choose what kind of output to generate"),
60 clEnumValN(GenProgram, "gen-program", "Generate a complete program"),
61 clEnumValN(GenModule, "gen-module", "Generate a module definition"),
62 clEnumValN(GenContents, "gen-contents", "Generate contents of a module"),
63 clEnumValN(GenFunction, "gen-function", "Generate a function definition"),
64 clEnumValN(GenFunctions,"gen-functions", "Generate all function definitions"),
65 clEnumValN(GenInline, "gen-inline", "Generate an inline function"),
66 clEnumValN(GenVariable, "gen-variable", "Generate a variable definition"),
67 clEnumValN(GenType, "gen-type", "Generate a type definition"),
72 static cl::opt<std::string> NameToGenerate("for", cl::Optional,
73 cl::desc("Specify the name of the thing to generate"),
77 // Register the target.
78 RegisterTarget<CPPTargetMachine> X("cpp", " C++ backend");
80 typedef std::vector<const Type*> TypeList;
81 typedef std::map<const Type*,std::string> TypeMap;
82 typedef std::map<const Value*,std::string> ValueMap;
83 typedef std::set<std::string> NameSet;
84 typedef std::set<const Type*> TypeSet;
85 typedef std::set<const Value*> ValueSet;
86 typedef std::map<const Value*,std::string> ForwardRefMap;
88 /// CppWriter - This class is the main chunk of code that converts an LLVM
89 /// module to a C++ translation unit.
90 class CppWriter : public ModulePass {
93 const Module *TheModule;
97 TypeMap UnresolvedTypes;
100 TypeSet DefinedTypes;
101 ValueSet DefinedValues;
102 ForwardRefMap ForwardRefs;
107 explicit CppWriter(std::ostream &o) : ModulePass((intptr_t)&ID), Out(o) {}
109 virtual const char *getPassName() const { return "C++ backend"; }
111 bool runOnModule(Module &M);
113 bool doInitialization(Module &M) {
119 UnresolvedTypes.clear();
122 DefinedTypes.clear();
123 DefinedValues.clear();
129 void printProgram(const std::string& fname, const std::string& modName );
130 void printModule(const std::string& fname, const std::string& modName );
131 void printContents(const std::string& fname, const std::string& modName );
132 void printFunction(const std::string& fname, const std::string& funcName );
133 void printFunctions();
134 void printInline(const std::string& fname, const std::string& funcName );
135 void printVariable(const std::string& fname, const std::string& varName );
136 void printType(const std::string& fname, const std::string& typeName );
138 void error(const std::string& msg);
141 void printLinkageType(GlobalValue::LinkageTypes LT);
142 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
143 void printCallingConv(unsigned cc);
144 void printEscapedString(const std::string& str);
145 void printCFP(const ConstantFP* CFP);
147 std::string getCppName(const Type* val);
148 inline void printCppName(const Type* val);
150 std::string getCppName(const Value* val);
151 inline void printCppName(const Value* val);
153 void printParamAttrs(const PAListPtr &PAL, const std::string &name);
154 bool printTypeInternal(const Type* Ty);
155 inline void printType(const Type* Ty);
156 void printTypes(const Module* M);
158 void printConstant(const Constant *CPV);
159 void printConstants(const Module* M);
161 void printVariableUses(const GlobalVariable *GV);
162 void printVariableHead(const GlobalVariable *GV);
163 void printVariableBody(const GlobalVariable *GV);
165 void printFunctionUses(const Function *F);
166 void printFunctionHead(const Function *F);
167 void printFunctionBody(const Function *F);
168 void printInstruction(const Instruction *I, const std::string& bbname);
169 std::string getOpName(Value*);
171 void printModuleBody();
174 static unsigned indent_level = 0;
175 inline std::ostream& nl(std::ostream& Out, int delta = 0) {
177 if (delta >= 0 || indent_level >= unsigned(-delta))
178 indent_level += delta;
179 for (unsigned i = 0; i < indent_level; ++i)
184 inline void in() { indent_level++; }
185 inline void out() { if (indent_level >0) indent_level--; }
188 sanitize(std::string& str) {
189 for (size_t i = 0; i < str.length(); ++i)
190 if (!isalnum(str[i]) && str[i] != '_')
195 getTypePrefix(const Type* Ty ) {
196 switch (Ty->getTypeID()) {
197 case Type::VoidTyID: return "void_";
198 case Type::IntegerTyID:
199 return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
201 case Type::FloatTyID: return "float_";
202 case Type::DoubleTyID: return "double_";
203 case Type::LabelTyID: return "label_";
204 case Type::FunctionTyID: return "func_";
205 case Type::StructTyID: return "struct_";
206 case Type::ArrayTyID: return "array_";
207 case Type::PointerTyID: return "ptr_";
208 case Type::VectorTyID: return "packed_";
209 case Type::OpaqueTyID: return "opaque_";
210 default: return "other_";
215 // Looks up the type in the symbol table and returns a pointer to its name or
216 // a null pointer if it wasn't found. Note that this isn't the same as the
217 // Mode::getTypeName function which will return an empty string, not a null
218 // pointer if the name is not found.
219 inline const std::string*
220 findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
221 TypeSymbolTable::const_iterator TI = ST.begin();
222 TypeSymbolTable::const_iterator TE = ST.end();
223 for (;TI != TE; ++TI)
224 if (TI->second == Ty)
229 void CppWriter::error(const std::string& msg) {
230 std::cerr << progname << ": " << msg << "\n";
234 // printCFP - Print a floating point constant .. very carefully :)
235 // This makes sure that conversion to/from floating yields the same binary
236 // result so that we don't lose precision.
237 void CppWriter::printCFP(const ConstantFP *CFP) {
238 APFloat APF = APFloat(CFP->getValueAPF()); // copy
239 if (CFP->getType() == Type::FloatTy)
240 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
241 Out << "ConstantFP::get(";
242 if (CFP->getType() == Type::DoubleTy)
243 Out << "Type::DoubleTy, ";
245 Out << "Type::FloatTy, ";
249 sprintf(Buffer, "%A", APF.convertToDouble());
250 if ((!strncmp(Buffer, "0x", 2) ||
251 !strncmp(Buffer, "-0x", 3) ||
252 !strncmp(Buffer, "+0x", 3)) &&
253 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
254 if (CFP->getType() == Type::DoubleTy)
255 Out << "BitsToDouble(" << Buffer << ")";
257 Out << "BitsToFloat((float)" << Buffer << ")";
261 std::string StrVal = ftostr(CFP->getValueAPF());
263 while (StrVal[0] == ' ')
264 StrVal.erase(StrVal.begin());
266 // Check to make sure that the stringized number is not some string like
267 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
268 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
269 ((StrVal[0] == '-' || StrVal[0] == '+') &&
270 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
271 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
272 if (CFP->getType() == Type::DoubleTy)
275 Out << StrVal << "f";
276 } else if (CFP->getType() == Type::DoubleTy)
277 Out << "BitsToDouble(0x" << std::hex
278 << CFP->getValueAPF().convertToAPInt().getZExtValue()
279 << std::dec << "ULL) /* " << StrVal << " */";
281 Out << "BitsToFloat(0x" << std::hex
282 << (uint32_t)CFP->getValueAPF().convertToAPInt().getZExtValue()
283 << std::dec << "U) /* " << StrVal << " */";
291 void CppWriter::printCallingConv(unsigned cc){
292 // Print the calling convention.
294 case CallingConv::C: Out << "CallingConv::C"; break;
295 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
296 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
297 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
298 default: Out << cc; break;
302 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
304 case GlobalValue::InternalLinkage:
305 Out << "GlobalValue::InternalLinkage"; break;
306 case GlobalValue::LinkOnceLinkage:
307 Out << "GlobalValue::LinkOnceLinkage "; break;
308 case GlobalValue::WeakLinkage:
309 Out << "GlobalValue::WeakLinkage"; break;
310 case GlobalValue::AppendingLinkage:
311 Out << "GlobalValue::AppendingLinkage"; break;
312 case GlobalValue::ExternalLinkage:
313 Out << "GlobalValue::ExternalLinkage"; break;
314 case GlobalValue::DLLImportLinkage:
315 Out << "GlobalValue::DLLImportLinkage"; break;
316 case GlobalValue::DLLExportLinkage:
317 Out << "GlobalValue::DLLExportLinkage"; break;
318 case GlobalValue::ExternalWeakLinkage:
319 Out << "GlobalValue::ExternalWeakLinkage"; break;
320 case GlobalValue::GhostLinkage:
321 Out << "GlobalValue::GhostLinkage"; break;
325 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
327 default: assert(0 && "Unknown GVar visibility");
328 case GlobalValue::DefaultVisibility:
329 Out << "GlobalValue::DefaultVisibility";
331 case GlobalValue::HiddenVisibility:
332 Out << "GlobalValue::HiddenVisibility";
334 case GlobalValue::ProtectedVisibility:
335 Out << "GlobalValue::ProtectedVisibility";
340 // printEscapedString - Print each character of the specified string, escaping
341 // it if it is not printable or if it is an escape char.
342 void CppWriter::printEscapedString(const std::string &Str) {
343 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
344 unsigned char C = Str[i];
345 if (isprint(C) && C != '"' && C != '\\') {
349 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
350 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
355 std::string CppWriter::getCppName(const Type* Ty) {
356 // First, handle the primitive types .. easy
357 if (Ty->isPrimitiveType() || Ty->isInteger()) {
358 switch (Ty->getTypeID()) {
359 case Type::VoidTyID: return "Type::VoidTy";
360 case Type::IntegerTyID: {
361 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
362 return "IntegerType::get(" + utostr(BitWidth) + ")";
364 case Type::FloatTyID: return "Type::FloatTy";
365 case Type::DoubleTyID: return "Type::DoubleTy";
366 case Type::LabelTyID: return "Type::LabelTy";
368 error("Invalid primitive type");
371 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
374 // Now, see if we've seen the type before and return that
375 TypeMap::iterator I = TypeNames.find(Ty);
376 if (I != TypeNames.end())
379 // Okay, let's build a new name for this type. Start with a prefix
380 const char* prefix = 0;
381 switch (Ty->getTypeID()) {
382 case Type::FunctionTyID: prefix = "FuncTy_"; break;
383 case Type::StructTyID: prefix = "StructTy_"; break;
384 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
385 case Type::PointerTyID: prefix = "PointerTy_"; break;
386 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
387 case Type::VectorTyID: prefix = "VectorTy_"; break;
388 default: prefix = "OtherTy_"; break; // prevent breakage
391 // See if the type has a name in the symboltable and build accordingly
392 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
395 name = std::string(prefix) + *tName;
397 name = std::string(prefix) + utostr(uniqueNum++);
401 return TypeNames[Ty] = name;
404 void CppWriter::printCppName(const Type* Ty) {
405 printEscapedString(getCppName(Ty));
408 std::string CppWriter::getCppName(const Value* val) {
410 ValueMap::iterator I = ValueNames.find(val);
411 if (I != ValueNames.end() && I->first == val)
414 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
415 name = std::string("gvar_") +
416 getTypePrefix(GV->getType()->getElementType());
417 } else if (isa<Function>(val)) {
418 name = std::string("func_");
419 } else if (const Constant* C = dyn_cast<Constant>(val)) {
420 name = std::string("const_") + getTypePrefix(C->getType());
421 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
423 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
424 Function::const_arg_iterator(Arg)) + 1;
425 name = std::string("arg_") + utostr(argNum);
426 NameSet::iterator NI = UsedNames.find(name);
427 if (NI != UsedNames.end())
428 name += std::string("_") + utostr(uniqueNum++);
429 UsedNames.insert(name);
430 return ValueNames[val] = name;
432 name = getTypePrefix(val->getType());
435 name = getTypePrefix(val->getType());
437 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
439 NameSet::iterator NI = UsedNames.find(name);
440 if (NI != UsedNames.end())
441 name += std::string("_") + utostr(uniqueNum++);
442 UsedNames.insert(name);
443 return ValueNames[val] = name;
446 void CppWriter::printCppName(const Value* val) {
447 printEscapedString(getCppName(val));
450 void CppWriter::printParamAttrs(const PAListPtr &PAL,
451 const std::string &name) {
452 Out << "PAListPtr " << name << "_PAL = 0;";
454 if (!PAL.isEmpty()) {
455 Out << '{'; in(); nl(Out);
456 Out << "SmallVector<ParamAttrsWithIndex, 4> Attrs;"; nl(Out);
457 Out << "ParamAttrsWithIndex PAWI;"; nl(Out);
458 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
459 uint16_t index = PAL.getSlot(i).Index;
460 ParameterAttributes attrs = PAL.getSlot(i).Attrs;
461 Out << "PAWI.index = " << index << "; PAWI.attrs = 0 ";
462 if (attrs & ParamAttr::SExt)
463 Out << " | ParamAttr::SExt";
464 if (attrs & ParamAttr::ZExt)
465 Out << " | ParamAttr::ZExt";
466 if (attrs & ParamAttr::StructRet)
467 Out << " | ParamAttr::StructRet";
468 if (attrs & ParamAttr::InReg)
469 Out << " | ParamAttr::InReg";
470 if (attrs & ParamAttr::NoReturn)
471 Out << " | ParamAttr::NoReturn";
472 if (attrs & ParamAttr::NoUnwind)
473 Out << " | ParamAttr::NoUnwind";
474 if (attrs & ParamAttr::ByVal)
475 Out << " | ParamAttr::ByVal";
476 if (attrs & ParamAttr::NoAlias)
477 Out << " | ParamAttr::NoAlias";
478 if (attrs & ParamAttr::Nest)
479 Out << " | ParamAttr::Nest";
480 if (attrs & ParamAttr::ReadNone)
481 Out << " | ParamAttr::ReadNone";
482 if (attrs & ParamAttr::ReadOnly)
483 Out << " | ParamAttr::ReadOnly";
486 Out << "Attrs.push_back(PAWI);";
489 Out << name << "_PAL = PAListPtr::get(Attrs.begin(), Attrs.end());";
496 bool CppWriter::printTypeInternal(const Type* Ty) {
497 // We don't print definitions for primitive types
498 if (Ty->isPrimitiveType() || Ty->isInteger())
501 // If we already defined this type, we don't need to define it again.
502 if (DefinedTypes.find(Ty) != DefinedTypes.end())
505 // Everything below needs the name for the type so get it now.
506 std::string typeName(getCppName(Ty));
508 // Search the type stack for recursion. If we find it, then generate this
509 // as an OpaqueType, but make sure not to do this multiple times because
510 // the type could appear in multiple places on the stack. Once the opaque
511 // definition is issued, it must not be re-issued. Consequently we have to
512 // check the UnresolvedTypes list as well.
513 TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
515 if (TI != TypeStack.end()) {
516 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
517 if (I == UnresolvedTypes.end()) {
518 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
520 UnresolvedTypes[Ty] = typeName;
525 // We're going to print a derived type which, by definition, contains other
526 // types. So, push this one we're printing onto the type stack to assist with
527 // recursive definitions.
528 TypeStack.push_back(Ty);
530 // Print the type definition
531 switch (Ty->getTypeID()) {
532 case Type::FunctionTyID: {
533 const FunctionType* FT = cast<FunctionType>(Ty);
534 Out << "std::vector<const Type*>" << typeName << "_args;";
536 FunctionType::param_iterator PI = FT->param_begin();
537 FunctionType::param_iterator PE = FT->param_end();
538 for (; PI != PE; ++PI) {
539 const Type* argTy = static_cast<const Type*>(*PI);
540 bool isForward = printTypeInternal(argTy);
541 std::string argName(getCppName(argTy));
542 Out << typeName << "_args.push_back(" << argName;
548 bool isForward = printTypeInternal(FT->getReturnType());
549 std::string retTypeName(getCppName(FT->getReturnType()));
550 Out << "FunctionType* " << typeName << " = FunctionType::get(";
551 in(); nl(Out) << "/*Result=*/" << retTypeName;
555 nl(Out) << "/*Params=*/" << typeName << "_args,";
556 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
561 case Type::StructTyID: {
562 const StructType* ST = cast<StructType>(Ty);
563 Out << "std::vector<const Type*>" << typeName << "_fields;";
565 StructType::element_iterator EI = ST->element_begin();
566 StructType::element_iterator EE = ST->element_end();
567 for (; EI != EE; ++EI) {
568 const Type* fieldTy = static_cast<const Type*>(*EI);
569 bool isForward = printTypeInternal(fieldTy);
570 std::string fieldName(getCppName(fieldTy));
571 Out << typeName << "_fields.push_back(" << fieldName;
577 Out << "StructType* " << typeName << " = StructType::get("
578 << typeName << "_fields, /*isPacked=*/"
579 << (ST->isPacked() ? "true" : "false") << ");";
583 case Type::ArrayTyID: {
584 const ArrayType* AT = cast<ArrayType>(Ty);
585 const Type* ET = AT->getElementType();
586 bool isForward = printTypeInternal(ET);
587 std::string elemName(getCppName(ET));
588 Out << "ArrayType* " << typeName << " = ArrayType::get("
589 << elemName << (isForward ? "_fwd" : "")
590 << ", " << utostr(AT->getNumElements()) << ");";
594 case Type::PointerTyID: {
595 const PointerType* PT = cast<PointerType>(Ty);
596 const Type* ET = PT->getElementType();
597 bool isForward = printTypeInternal(ET);
598 std::string elemName(getCppName(ET));
599 Out << "PointerType* " << typeName << " = PointerType::get("
600 << elemName << (isForward ? "_fwd" : "")
601 << ", " << utostr(PT->getAddressSpace()) << ");";
605 case Type::VectorTyID: {
606 const VectorType* PT = cast<VectorType>(Ty);
607 const Type* ET = PT->getElementType();
608 bool isForward = printTypeInternal(ET);
609 std::string elemName(getCppName(ET));
610 Out << "VectorType* " << typeName << " = VectorType::get("
611 << elemName << (isForward ? "_fwd" : "")
612 << ", " << utostr(PT->getNumElements()) << ");";
616 case Type::OpaqueTyID: {
617 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
622 error("Invalid TypeID");
625 // If the type had a name, make sure we recreate it.
626 const std::string* progTypeName =
627 findTypeName(TheModule->getTypeSymbolTable(),Ty);
629 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
634 // Pop us off the type stack
635 TypeStack.pop_back();
637 // Indicate that this type is now defined.
638 DefinedTypes.insert(Ty);
640 // Early resolve as many unresolved types as possible. Search the unresolved
641 // types map for the type we just printed. Now that its definition is complete
642 // we can resolve any previous references to it. This prevents a cascade of
644 TypeMap::iterator I = UnresolvedTypes.find(Ty);
645 if (I != UnresolvedTypes.end()) {
646 Out << "cast<OpaqueType>(" << I->second
647 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
649 Out << I->second << " = cast<";
650 switch (Ty->getTypeID()) {
651 case Type::FunctionTyID: Out << "FunctionType"; break;
652 case Type::ArrayTyID: Out << "ArrayType"; break;
653 case Type::StructTyID: Out << "StructType"; break;
654 case Type::VectorTyID: Out << "VectorType"; break;
655 case Type::PointerTyID: Out << "PointerType"; break;
656 case Type::OpaqueTyID: Out << "OpaqueType"; break;
657 default: Out << "NoSuchDerivedType"; break;
659 Out << ">(" << I->second << "_fwd.get());";
661 UnresolvedTypes.erase(I);
664 // Finally, separate the type definition from other with a newline.
667 // We weren't a recursive type
671 // Prints a type definition. Returns true if it could not resolve all the
672 // types in the definition but had to use a forward reference.
673 void CppWriter::printType(const Type* Ty) {
674 assert(TypeStack.empty());
676 printTypeInternal(Ty);
677 assert(TypeStack.empty());
680 void CppWriter::printTypes(const Module* M) {
681 // Walk the symbol table and print out all its types
682 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
683 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
686 // For primitive types and types already defined, just add a name
687 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
688 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
689 TNI != TypeNames.end()) {
690 Out << "mod->addTypeName(\"";
691 printEscapedString(TI->first);
692 Out << "\", " << getCppName(TI->second) << ");";
694 // For everything else, define the type
696 printType(TI->second);
700 // Add all of the global variables to the value table...
701 for (Module::const_global_iterator I = TheModule->global_begin(),
702 E = TheModule->global_end(); I != E; ++I) {
703 if (I->hasInitializer())
704 printType(I->getInitializer()->getType());
705 printType(I->getType());
708 // Add all the functions to the table
709 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
711 printType(FI->getReturnType());
712 printType(FI->getFunctionType());
713 // Add all the function arguments
714 for (Function::const_arg_iterator AI = FI->arg_begin(),
715 AE = FI->arg_end(); AI != AE; ++AI) {
716 printType(AI->getType());
719 // Add all of the basic blocks and instructions
720 for (Function::const_iterator BB = FI->begin(),
721 E = FI->end(); BB != E; ++BB) {
722 printType(BB->getType());
723 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
725 printType(I->getType());
726 for (unsigned i = 0; i < I->getNumOperands(); ++i)
727 printType(I->getOperand(i)->getType());
734 // printConstant - Print out a constant pool entry...
735 void CppWriter::printConstant(const Constant *CV) {
736 // First, if the constant is actually a GlobalValue (variable or function)
737 // or its already in the constant list then we've printed it already and we
739 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
742 std::string constName(getCppName(CV));
743 std::string typeName(getCppName(CV->getType()));
744 if (CV->isNullValue()) {
745 Out << "Constant* " << constName << " = Constant::getNullValue("
750 if (isa<GlobalValue>(CV)) {
751 // Skip variables and functions, we emit them elsewhere
754 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
755 Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
756 << cast<IntegerType>(CI->getType())->getBitWidth() << ", "
757 << " \"" << CI->getValue().toStringSigned(10) << "\", 10));";
758 } else if (isa<ConstantAggregateZero>(CV)) {
759 Out << "ConstantAggregateZero* " << constName
760 << " = ConstantAggregateZero::get(" << typeName << ");";
761 } else if (isa<ConstantPointerNull>(CV)) {
762 Out << "ConstantPointerNull* " << constName
763 << " = ConstanPointerNull::get(" << typeName << ");";
764 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
765 Out << "ConstantFP* " << constName << " = ";
768 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
769 if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
770 Out << "Constant* " << constName << " = ConstantArray::get(\"";
771 std::string tmp = CA->getAsString();
772 bool nullTerminate = false;
773 if (tmp[tmp.length()-1] == 0) {
774 tmp.erase(tmp.length()-1);
775 nullTerminate = true;
777 printEscapedString(tmp);
778 // Determine if we want null termination or not.
780 Out << "\", true"; // Indicate that the null terminator should be
783 Out << "\", false";// No null terminator
786 Out << "std::vector<Constant*> " << constName << "_elems;";
788 unsigned N = CA->getNumOperands();
789 for (unsigned i = 0; i < N; ++i) {
790 printConstant(CA->getOperand(i)); // recurse to print operands
791 Out << constName << "_elems.push_back("
792 << getCppName(CA->getOperand(i)) << ");";
795 Out << "Constant* " << constName << " = ConstantArray::get("
796 << typeName << ", " << constName << "_elems);";
798 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
799 Out << "std::vector<Constant*> " << constName << "_fields;";
801 unsigned N = CS->getNumOperands();
802 for (unsigned i = 0; i < N; i++) {
803 printConstant(CS->getOperand(i));
804 Out << constName << "_fields.push_back("
805 << getCppName(CS->getOperand(i)) << ");";
808 Out << "Constant* " << constName << " = ConstantStruct::get("
809 << typeName << ", " << constName << "_fields);";
810 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
811 Out << "std::vector<Constant*> " << constName << "_elems;";
813 unsigned N = CP->getNumOperands();
814 for (unsigned i = 0; i < N; ++i) {
815 printConstant(CP->getOperand(i));
816 Out << constName << "_elems.push_back("
817 << getCppName(CP->getOperand(i)) << ");";
820 Out << "Constant* " << constName << " = ConstantVector::get("
821 << typeName << ", " << constName << "_elems);";
822 } else if (isa<UndefValue>(CV)) {
823 Out << "UndefValue* " << constName << " = UndefValue::get("
825 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
826 if (CE->getOpcode() == Instruction::GetElementPtr) {
827 Out << "std::vector<Constant*> " << constName << "_indices;";
829 printConstant(CE->getOperand(0));
830 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
831 printConstant(CE->getOperand(i));
832 Out << constName << "_indices.push_back("
833 << getCppName(CE->getOperand(i)) << ");";
836 Out << "Constant* " << constName
837 << " = ConstantExpr::getGetElementPtr("
838 << getCppName(CE->getOperand(0)) << ", "
839 << "&" << constName << "_indices[0], "
840 << constName << "_indices.size()"
842 } else if (CE->isCast()) {
843 printConstant(CE->getOperand(0));
844 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
845 switch (CE->getOpcode()) {
846 default: assert(0 && "Invalid cast opcode");
847 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
848 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
849 case Instruction::SExt: Out << "Instruction::SExt"; break;
850 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
851 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
852 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
853 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
854 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
855 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
856 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
857 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
858 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
860 Out << ", " << getCppName(CE->getOperand(0)) << ", "
861 << getCppName(CE->getType()) << ");";
863 unsigned N = CE->getNumOperands();
864 for (unsigned i = 0; i < N; ++i ) {
865 printConstant(CE->getOperand(i));
867 Out << "Constant* " << constName << " = ConstantExpr::";
868 switch (CE->getOpcode()) {
869 case Instruction::Add: Out << "getAdd("; break;
870 case Instruction::Sub: Out << "getSub("; break;
871 case Instruction::Mul: Out << "getMul("; break;
872 case Instruction::UDiv: Out << "getUDiv("; break;
873 case Instruction::SDiv: Out << "getSDiv("; break;
874 case Instruction::FDiv: Out << "getFDiv("; break;
875 case Instruction::URem: Out << "getURem("; break;
876 case Instruction::SRem: Out << "getSRem("; break;
877 case Instruction::FRem: Out << "getFRem("; break;
878 case Instruction::And: Out << "getAnd("; break;
879 case Instruction::Or: Out << "getOr("; break;
880 case Instruction::Xor: Out << "getXor("; break;
881 case Instruction::ICmp:
882 Out << "getICmp(ICmpInst::ICMP_";
883 switch (CE->getPredicate()) {
884 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
885 case ICmpInst::ICMP_NE: Out << "NE"; break;
886 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
887 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
888 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
889 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
890 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
891 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
892 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
893 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
894 default: error("Invalid ICmp Predicate");
897 case Instruction::FCmp:
898 Out << "getFCmp(FCmpInst::FCMP_";
899 switch (CE->getPredicate()) {
900 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
901 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
902 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
903 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
904 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
905 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
906 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
907 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
908 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
909 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
910 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
911 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
912 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
913 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
914 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
915 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
916 default: error("Invalid FCmp Predicate");
919 case Instruction::Shl: Out << "getShl("; break;
920 case Instruction::LShr: Out << "getLShr("; break;
921 case Instruction::AShr: Out << "getAShr("; break;
922 case Instruction::Select: Out << "getSelect("; break;
923 case Instruction::ExtractElement: Out << "getExtractElement("; break;
924 case Instruction::InsertElement: Out << "getInsertElement("; break;
925 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
927 error("Invalid constant expression");
930 Out << getCppName(CE->getOperand(0));
931 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
932 Out << ", " << getCppName(CE->getOperand(i));
936 error("Bad Constant");
937 Out << "Constant* " << constName << " = 0; ";
942 void CppWriter::printConstants(const Module* M) {
943 // Traverse all the global variables looking for constant initializers
944 for (Module::const_global_iterator I = TheModule->global_begin(),
945 E = TheModule->global_end(); I != E; ++I)
946 if (I->hasInitializer())
947 printConstant(I->getInitializer());
949 // Traverse the LLVM functions looking for constants
950 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
952 // Add all of the basic blocks and instructions
953 for (Function::const_iterator BB = FI->begin(),
954 E = FI->end(); BB != E; ++BB) {
955 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
957 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
958 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
967 void CppWriter::printVariableUses(const GlobalVariable *GV) {
968 nl(Out) << "// Type Definitions";
970 printType(GV->getType());
971 if (GV->hasInitializer()) {
972 Constant* Init = GV->getInitializer();
973 printType(Init->getType());
974 if (Function* F = dyn_cast<Function>(Init)) {
975 nl(Out)<< "/ Function Declarations"; nl(Out);
976 printFunctionHead(F);
977 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
978 nl(Out) << "// Global Variable Declarations"; nl(Out);
979 printVariableHead(gv);
981 nl(Out) << "// Constant Definitions"; nl(Out);
984 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
985 nl(Out) << "// Global Variable Definitions"; nl(Out);
986 printVariableBody(gv);
991 void CppWriter::printVariableHead(const GlobalVariable *GV) {
992 nl(Out) << "GlobalVariable* " << getCppName(GV);
994 Out << " = mod->getGlobalVariable(";
995 printEscapedString(GV->getName());
996 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
997 nl(Out) << "if (!" << getCppName(GV) << ") {";
998 in(); nl(Out) << getCppName(GV);
1000 Out << " = new GlobalVariable(";
1001 nl(Out) << "/*Type=*/";
1002 printCppName(GV->getType()->getElementType());
1004 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
1006 nl(Out) << "/*Linkage=*/";
1007 printLinkageType(GV->getLinkage());
1009 nl(Out) << "/*Initializer=*/0, ";
1010 if (GV->hasInitializer()) {
1011 Out << "// has initializer, specified below";
1013 nl(Out) << "/*Name=*/\"";
1014 printEscapedString(GV->getName());
1019 if (GV->hasSection()) {
1021 Out << "->setSection(\"";
1022 printEscapedString(GV->getSection());
1026 if (GV->getAlignment()) {
1028 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1031 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1033 Out << "->setVisibility(";
1034 printVisibilityType(GV->getVisibility());
1039 out(); Out << "}"; nl(Out);
1043 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1044 if (GV->hasInitializer()) {
1046 Out << "->setInitializer(";
1047 Out << getCppName(GV->getInitializer()) << ");";
1052 std::string CppWriter::getOpName(Value* V) {
1053 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1054 return getCppName(V);
1056 // See if its alread in the map of forward references, if so just return the
1057 // name we already set up for it
1058 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1059 if (I != ForwardRefs.end())
1062 // This is a new forward reference. Generate a unique name for it
1063 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1065 // Yes, this is a hack. An Argument is the smallest instantiable value that
1066 // we can make as a placeholder for the real value. We'll replace these
1067 // Argument instances later.
1068 Out << "Argument* " << result << " = new Argument("
1069 << getCppName(V->getType()) << ");";
1071 ForwardRefs[V] = result;
1075 // printInstruction - This member is called for each Instruction in a function.
1076 void CppWriter::printInstruction(const Instruction *I,
1077 const std::string& bbname) {
1078 std::string iName(getCppName(I));
1080 // Before we emit this instruction, we need to take care of generating any
1081 // forward references. So, we get the names of all the operands in advance
1082 std::string* opNames = new std::string[I->getNumOperands()];
1083 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1084 opNames[i] = getOpName(I->getOperand(i));
1087 switch (I->getOpcode()) {
1088 case Instruction::Ret: {
1089 const ReturnInst* ret = cast<ReturnInst>(I);
1090 Out << "ReturnInst::Create("
1091 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1094 case Instruction::Br: {
1095 const BranchInst* br = cast<BranchInst>(I);
1096 Out << "BranchInst::Create(" ;
1097 if (br->getNumOperands() == 3 ) {
1098 Out << opNames[0] << ", "
1099 << opNames[1] << ", "
1100 << opNames[2] << ", ";
1102 } else if (br->getNumOperands() == 1) {
1103 Out << opNames[0] << ", ";
1105 error("Branch with 2 operands?");
1107 Out << bbname << ");";
1110 case Instruction::Switch: {
1111 const SwitchInst* sw = cast<SwitchInst>(I);
1112 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1113 << opNames[0] << ", "
1114 << opNames[1] << ", "
1115 << sw->getNumCases() << ", " << bbname << ");";
1117 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1118 Out << iName << "->addCase("
1119 << opNames[i] << ", "
1120 << opNames[i+1] << ");";
1125 case Instruction::Invoke: {
1126 const InvokeInst* inv = cast<InvokeInst>(I);
1127 Out << "std::vector<Value*> " << iName << "_params;";
1129 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1130 Out << iName << "_params.push_back("
1131 << opNames[i] << ");";
1134 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1135 << opNames[0] << ", "
1136 << opNames[1] << ", "
1137 << opNames[2] << ", "
1138 << iName << "_params.begin(), " << iName << "_params.end(), \"";
1139 printEscapedString(inv->getName());
1140 Out << "\", " << bbname << ");";
1141 nl(Out) << iName << "->setCallingConv(";
1142 printCallingConv(inv->getCallingConv());
1144 printParamAttrs(inv->getParamAttrs(), iName);
1145 Out << iName << "->setParamAttrs(" << iName << "_PAL);";
1149 case Instruction::Unwind: {
1150 Out << "new UnwindInst("
1154 case Instruction::Unreachable:{
1155 Out << "new UnreachableInst("
1159 case Instruction::Add:
1160 case Instruction::Sub:
1161 case Instruction::Mul:
1162 case Instruction::UDiv:
1163 case Instruction::SDiv:
1164 case Instruction::FDiv:
1165 case Instruction::URem:
1166 case Instruction::SRem:
1167 case Instruction::FRem:
1168 case Instruction::And:
1169 case Instruction::Or:
1170 case Instruction::Xor:
1171 case Instruction::Shl:
1172 case Instruction::LShr:
1173 case Instruction::AShr:{
1174 Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
1175 switch (I->getOpcode()) {
1176 case Instruction::Add: Out << "Instruction::Add"; break;
1177 case Instruction::Sub: Out << "Instruction::Sub"; break;
1178 case Instruction::Mul: Out << "Instruction::Mul"; break;
1179 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1180 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1181 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1182 case Instruction::URem:Out << "Instruction::URem"; break;
1183 case Instruction::SRem:Out << "Instruction::SRem"; break;
1184 case Instruction::FRem:Out << "Instruction::FRem"; break;
1185 case Instruction::And: Out << "Instruction::And"; break;
1186 case Instruction::Or: Out << "Instruction::Or"; break;
1187 case Instruction::Xor: Out << "Instruction::Xor"; break;
1188 case Instruction::Shl: Out << "Instruction::Shl"; break;
1189 case Instruction::LShr:Out << "Instruction::LShr"; break;
1190 case Instruction::AShr:Out << "Instruction::AShr"; break;
1191 default: Out << "Instruction::BadOpCode"; break;
1193 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1194 printEscapedString(I->getName());
1195 Out << "\", " << bbname << ");";
1198 case Instruction::FCmp: {
1199 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1200 switch (cast<FCmpInst>(I)->getPredicate()) {
1201 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1202 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1203 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1204 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1205 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1206 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1207 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1208 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1209 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1210 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1211 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1212 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1213 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1214 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1215 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1216 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1217 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1219 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1220 printEscapedString(I->getName());
1221 Out << "\", " << bbname << ");";
1224 case Instruction::ICmp: {
1225 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1226 switch (cast<ICmpInst>(I)->getPredicate()) {
1227 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1228 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1229 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1230 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1231 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1232 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1233 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1234 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1235 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1236 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1237 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1239 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1240 printEscapedString(I->getName());
1241 Out << "\", " << bbname << ");";
1244 case Instruction::Malloc: {
1245 const MallocInst* mallocI = cast<MallocInst>(I);
1246 Out << "MallocInst* " << iName << " = new MallocInst("
1247 << getCppName(mallocI->getAllocatedType()) << ", ";
1248 if (mallocI->isArrayAllocation())
1249 Out << opNames[0] << ", " ;
1251 printEscapedString(mallocI->getName());
1252 Out << "\", " << bbname << ");";
1253 if (mallocI->getAlignment())
1254 nl(Out) << iName << "->setAlignment("
1255 << mallocI->getAlignment() << ");";
1258 case Instruction::Free: {
1259 Out << "FreeInst* " << iName << " = new FreeInst("
1260 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1263 case Instruction::Alloca: {
1264 const AllocaInst* allocaI = cast<AllocaInst>(I);
1265 Out << "AllocaInst* " << iName << " = new AllocaInst("
1266 << getCppName(allocaI->getAllocatedType()) << ", ";
1267 if (allocaI->isArrayAllocation())
1268 Out << opNames[0] << ", ";
1270 printEscapedString(allocaI->getName());
1271 Out << "\", " << bbname << ");";
1272 if (allocaI->getAlignment())
1273 nl(Out) << iName << "->setAlignment("
1274 << allocaI->getAlignment() << ");";
1277 case Instruction::Load:{
1278 const LoadInst* load = cast<LoadInst>(I);
1279 Out << "LoadInst* " << iName << " = new LoadInst("
1280 << opNames[0] << ", \"";
1281 printEscapedString(load->getName());
1282 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1283 << ", " << bbname << ");";
1286 case Instruction::Store: {
1287 const StoreInst* store = cast<StoreInst>(I);
1288 Out << "StoreInst* " << iName << " = new StoreInst("
1289 << opNames[0] << ", "
1290 << opNames[1] << ", "
1291 << (store->isVolatile() ? "true" : "false")
1292 << ", " << bbname << ");";
1295 case Instruction::GetElementPtr: {
1296 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1297 if (gep->getNumOperands() <= 2) {
1298 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1300 if (gep->getNumOperands() == 2)
1301 Out << ", " << opNames[1];
1303 Out << "std::vector<Value*> " << iName << "_indices;";
1305 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1306 Out << iName << "_indices.push_back("
1307 << opNames[i] << ");";
1310 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1311 << opNames[0] << ", " << iName << "_indices.begin(), "
1312 << iName << "_indices.end()";
1315 printEscapedString(gep->getName());
1316 Out << "\", " << bbname << ");";
1319 case Instruction::PHI: {
1320 const PHINode* phi = cast<PHINode>(I);
1322 Out << "PHINode* " << iName << " = PHINode::Create("
1323 << getCppName(phi->getType()) << ", \"";
1324 printEscapedString(phi->getName());
1325 Out << "\", " << bbname << ");";
1326 nl(Out) << iName << "->reserveOperandSpace("
1327 << phi->getNumIncomingValues()
1330 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1331 Out << iName << "->addIncoming("
1332 << opNames[i] << ", " << opNames[i+1] << ");";
1337 case Instruction::Trunc:
1338 case Instruction::ZExt:
1339 case Instruction::SExt:
1340 case Instruction::FPTrunc:
1341 case Instruction::FPExt:
1342 case Instruction::FPToUI:
1343 case Instruction::FPToSI:
1344 case Instruction::UIToFP:
1345 case Instruction::SIToFP:
1346 case Instruction::PtrToInt:
1347 case Instruction::IntToPtr:
1348 case Instruction::BitCast: {
1349 const CastInst* cst = cast<CastInst>(I);
1350 Out << "CastInst* " << iName << " = new ";
1351 switch (I->getOpcode()) {
1352 case Instruction::Trunc: Out << "TruncInst"; break;
1353 case Instruction::ZExt: Out << "ZExtInst"; break;
1354 case Instruction::SExt: Out << "SExtInst"; break;
1355 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1356 case Instruction::FPExt: Out << "FPExtInst"; break;
1357 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1358 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1359 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1360 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1361 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1362 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1363 case Instruction::BitCast: Out << "BitCastInst"; break;
1364 default: assert(!"Unreachable"); break;
1366 Out << "(" << opNames[0] << ", "
1367 << getCppName(cst->getType()) << ", \"";
1368 printEscapedString(cst->getName());
1369 Out << "\", " << bbname << ");";
1372 case Instruction::Call:{
1373 const CallInst* call = cast<CallInst>(I);
1374 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1375 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1376 << getCppName(ila->getFunctionType()) << ", \""
1377 << ila->getAsmString() << "\", \""
1378 << ila->getConstraintString() << "\","
1379 << (ila->hasSideEffects() ? "true" : "false") << ");";
1382 if (call->getNumOperands() > 2) {
1383 Out << "std::vector<Value*> " << iName << "_params;";
1385 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1386 Out << iName << "_params.push_back(" << opNames[i] << ");";
1389 Out << "CallInst* " << iName << " = CallInst::Create("
1390 << opNames[0] << ", " << iName << "_params.begin(), "
1391 << iName << "_params.end(), \"";
1392 } else if (call->getNumOperands() == 2) {
1393 Out << "CallInst* " << iName << " = CallInst::Create("
1394 << opNames[0] << ", " << opNames[1] << ", \"";
1396 Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
1399 printEscapedString(call->getName());
1400 Out << "\", " << bbname << ");";
1401 nl(Out) << iName << "->setCallingConv(";
1402 printCallingConv(call->getCallingConv());
1404 nl(Out) << iName << "->setTailCall("
1405 << (call->isTailCall() ? "true":"false");
1407 printParamAttrs(call->getParamAttrs(), iName);
1408 Out << iName << "->setParamAttrs(" << iName << "_PAL);";
1412 case Instruction::Select: {
1413 const SelectInst* sel = cast<SelectInst>(I);
1414 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1415 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1416 printEscapedString(sel->getName());
1417 Out << "\", " << bbname << ");";
1420 case Instruction::UserOp1:
1422 case Instruction::UserOp2: {
1423 /// FIXME: What should be done here?
1426 case Instruction::VAArg: {
1427 const VAArgInst* va = cast<VAArgInst>(I);
1428 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1429 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1430 printEscapedString(va->getName());
1431 Out << "\", " << bbname << ");";
1434 case Instruction::ExtractElement: {
1435 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1436 Out << "ExtractElementInst* " << getCppName(eei)
1437 << " = new ExtractElementInst(" << opNames[0]
1438 << ", " << opNames[1] << ", \"";
1439 printEscapedString(eei->getName());
1440 Out << "\", " << bbname << ");";
1443 case Instruction::InsertElement: {
1444 const InsertElementInst* iei = cast<InsertElementInst>(I);
1445 Out << "InsertElementInst* " << getCppName(iei)
1446 << " = InsertElementInst::Create(" << opNames[0]
1447 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1448 printEscapedString(iei->getName());
1449 Out << "\", " << bbname << ");";
1452 case Instruction::ShuffleVector: {
1453 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1454 Out << "ShuffleVectorInst* " << getCppName(svi)
1455 << " = new ShuffleVectorInst(" << opNames[0]
1456 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1457 printEscapedString(svi->getName());
1458 Out << "\", " << bbname << ");";
1462 DefinedValues.insert(I);
1467 // Print out the types, constants and declarations needed by one function
1468 void CppWriter::printFunctionUses(const Function* F) {
1469 nl(Out) << "// Type Definitions"; nl(Out);
1471 // Print the function's return type
1472 printType(F->getReturnType());
1474 // Print the function's function type
1475 printType(F->getFunctionType());
1477 // Print the types of each of the function's arguments
1478 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1480 printType(AI->getType());
1484 // Print type definitions for every type referenced by an instruction and
1485 // make a note of any global values or constants that are referenced
1486 SmallPtrSet<GlobalValue*,64> gvs;
1487 SmallPtrSet<Constant*,64> consts;
1488 for (Function::const_iterator BB = F->begin(), BE = F->end();
1490 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1492 // Print the type of the instruction itself
1493 printType(I->getType());
1495 // Print the type of each of the instruction's operands
1496 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1497 Value* operand = I->getOperand(i);
1498 printType(operand->getType());
1500 // If the operand references a GVal or Constant, make a note of it
1501 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1503 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1504 if (GVar->hasInitializer())
1505 consts.insert(GVar->getInitializer());
1506 } else if (Constant* C = dyn_cast<Constant>(operand))
1512 // Print the function declarations for any functions encountered
1513 nl(Out) << "// Function Declarations"; nl(Out);
1514 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1516 if (Function* Fun = dyn_cast<Function>(*I)) {
1517 if (!is_inline || Fun != F)
1518 printFunctionHead(Fun);
1522 // Print the global variable declarations for any variables encountered
1523 nl(Out) << "// Global Variable Declarations"; nl(Out);
1524 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1526 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1527 printVariableHead(F);
1530 // Print the constants found
1531 nl(Out) << "// Constant Definitions"; nl(Out);
1532 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1533 E = consts.end(); I != E; ++I) {
1537 // Process the global variables definitions now that all the constants have
1538 // been emitted. These definitions just couple the gvars with their constant
1540 nl(Out) << "// Global Variable Definitions"; nl(Out);
1541 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1543 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1544 printVariableBody(GV);
1548 void CppWriter::printFunctionHead(const Function* F) {
1549 nl(Out) << "Function* " << getCppName(F);
1551 Out << " = mod->getFunction(\"";
1552 printEscapedString(F->getName());
1553 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1554 nl(Out) << "if (!" << getCppName(F) << ") {";
1555 nl(Out) << getCppName(F);
1557 Out<< " = Function::Create(";
1558 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1559 nl(Out) << "/*Linkage=*/";
1560 printLinkageType(F->getLinkage());
1562 nl(Out) << "/*Name=*/\"";
1563 printEscapedString(F->getName());
1564 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1567 Out << "->setCallingConv(";
1568 printCallingConv(F->getCallingConv());
1571 if (F->hasSection()) {
1573 Out << "->setSection(\"" << F->getSection() << "\");";
1576 if (F->getAlignment()) {
1578 Out << "->setAlignment(" << F->getAlignment() << ");";
1581 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1583 Out << "->setVisibility(";
1584 printVisibilityType(F->getVisibility());
1588 if (F->hasCollector()) {
1590 Out << "->setCollector(\"" << F->getCollector() << "\");";
1597 printParamAttrs(F->getParamAttrs(), getCppName(F));
1599 Out << "->setParamAttrs(" << getCppName(F) << "_PAL);";
1603 void CppWriter::printFunctionBody(const Function *F) {
1604 if (F->isDeclaration())
1605 return; // external functions have no bodies.
1607 // Clear the DefinedValues and ForwardRefs maps because we can't have
1608 // cross-function forward refs
1609 ForwardRefs.clear();
1610 DefinedValues.clear();
1612 // Create all the argument values
1614 if (!F->arg_empty()) {
1615 Out << "Function::arg_iterator args = " << getCppName(F)
1616 << "->arg_begin();";
1619 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1621 Out << "Value* " << getCppName(AI) << " = args++;";
1623 if (AI->hasName()) {
1624 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1630 // Create all the basic blocks
1632 for (Function::const_iterator BI = F->begin(), BE = F->end();
1634 std::string bbname(getCppName(BI));
1635 Out << "BasicBlock* " << bbname << " = BasicBlock::Create(\"";
1637 printEscapedString(BI->getName());
1638 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1642 // Output all of its basic blocks... for the function
1643 for (Function::const_iterator BI = F->begin(), BE = F->end();
1645 std::string bbname(getCppName(BI));
1646 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1649 // Output all of the instructions in the basic block...
1650 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1652 printInstruction(I,bbname);
1656 // Loop over the ForwardRefs and resolve them now that all instructions
1658 if (!ForwardRefs.empty()) {
1659 nl(Out) << "// Resolve Forward References";
1663 while (!ForwardRefs.empty()) {
1664 ForwardRefMap::iterator I = ForwardRefs.begin();
1665 Out << I->second << "->replaceAllUsesWith("
1666 << getCppName(I->first) << "); delete " << I->second << ";";
1668 ForwardRefs.erase(I);
1672 void CppWriter::printInline(const std::string& fname,
1673 const std::string& func) {
1674 const Function* F = TheModule->getFunction(func);
1676 error(std::string("Function '") + func + "' not found in input module");
1679 if (F->isDeclaration()) {
1680 error(std::string("Function '") + func + "' is external!");
1683 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1685 unsigned arg_count = 1;
1686 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1688 Out << ", Value* arg_" << arg_count;
1693 printFunctionUses(F);
1694 printFunctionBody(F);
1696 Out << "return " << getCppName(F->begin()) << ";";
1701 void CppWriter::printModuleBody() {
1702 // Print out all the type definitions
1703 nl(Out) << "// Type Definitions"; nl(Out);
1704 printTypes(TheModule);
1706 // Functions can call each other and global variables can reference them so
1707 // define all the functions first before emitting their function bodies.
1708 nl(Out) << "// Function Declarations"; nl(Out);
1709 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1711 printFunctionHead(I);
1713 // Process the global variables declarations. We can't initialze them until
1714 // after the constants are printed so just print a header for each global
1715 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1716 for (Module::const_global_iterator I = TheModule->global_begin(),
1717 E = TheModule->global_end(); I != E; ++I) {
1718 printVariableHead(I);
1721 // Print out all the constants definitions. Constants don't recurse except
1722 // through GlobalValues. All GlobalValues have been declared at this point
1723 // so we can proceed to generate the constants.
1724 nl(Out) << "// Constant Definitions"; nl(Out);
1725 printConstants(TheModule);
1727 // Process the global variables definitions now that all the constants have
1728 // been emitted. These definitions just couple the gvars with their constant
1730 nl(Out) << "// Global Variable Definitions"; nl(Out);
1731 for (Module::const_global_iterator I = TheModule->global_begin(),
1732 E = TheModule->global_end(); I != E; ++I) {
1733 printVariableBody(I);
1736 // Finally, we can safely put out all of the function bodies.
1737 nl(Out) << "// Function Definitions"; nl(Out);
1738 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1740 if (!I->isDeclaration()) {
1741 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1745 printFunctionBody(I);
1752 void CppWriter::printProgram(const std::string& fname,
1753 const std::string& mName) {
1754 Out << "#include <llvm/Module.h>\n";
1755 Out << "#include <llvm/DerivedTypes.h>\n";
1756 Out << "#include <llvm/Constants.h>\n";
1757 Out << "#include <llvm/GlobalVariable.h>\n";
1758 Out << "#include <llvm/Function.h>\n";
1759 Out << "#include <llvm/CallingConv.h>\n";
1760 Out << "#include <llvm/BasicBlock.h>\n";
1761 Out << "#include <llvm/Instructions.h>\n";
1762 Out << "#include <llvm/InlineAsm.h>\n";
1763 Out << "#include <llvm/Support/MathExtras.h>\n";
1764 Out << "#include <llvm/Pass.h>\n";
1765 Out << "#include <llvm/PassManager.h>\n";
1766 Out << "#include <llvm/Analysis/Verifier.h>\n";
1767 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1768 Out << "#include <algorithm>\n";
1769 Out << "#include <iostream>\n\n";
1770 Out << "using namespace llvm;\n\n";
1771 Out << "Module* " << fname << "();\n\n";
1772 Out << "int main(int argc, char**argv) {\n";
1773 Out << " Module* Mod = " << fname << "();\n";
1774 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1775 Out << " std::cerr.flush();\n";
1776 Out << " std::cout.flush();\n";
1777 Out << " PassManager PM;\n";
1778 Out << " PM.add(new PrintModulePass(&llvm::cout));\n";
1779 Out << " PM.run(*Mod);\n";
1780 Out << " return 0;\n";
1782 printModule(fname,mName);
1785 void CppWriter::printModule(const std::string& fname,
1786 const std::string& mName) {
1787 nl(Out) << "Module* " << fname << "() {";
1788 nl(Out,1) << "// Module Construction";
1789 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1790 if (!TheModule->getTargetTriple().empty()) {
1791 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1793 if (!TheModule->getTargetTriple().empty()) {
1794 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1798 if (!TheModule->getModuleInlineAsm().empty()) {
1799 nl(Out) << "mod->setModuleInlineAsm(\"";
1800 printEscapedString(TheModule->getModuleInlineAsm());
1805 // Loop over the dependent libraries and emit them.
1806 Module::lib_iterator LI = TheModule->lib_begin();
1807 Module::lib_iterator LE = TheModule->lib_end();
1809 Out << "mod->addLibrary(\"" << *LI << "\");";
1814 nl(Out) << "return mod;";
1819 void CppWriter::printContents(const std::string& fname,
1820 const std::string& mName) {
1821 Out << "\nModule* " << fname << "(Module *mod) {\n";
1822 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1824 Out << "\nreturn mod;\n";
1828 void CppWriter::printFunction(const std::string& fname,
1829 const std::string& funcName) {
1830 const Function* F = TheModule->getFunction(funcName);
1832 error(std::string("Function '") + funcName + "' not found in input module");
1835 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1836 printFunctionUses(F);
1837 printFunctionHead(F);
1838 printFunctionBody(F);
1839 Out << "return " << getCppName(F) << ";\n";
1843 void CppWriter::printFunctions() {
1844 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1845 Module::const_iterator I = funcs.begin();
1846 Module::const_iterator IE = funcs.end();
1848 for (; I != IE; ++I) {
1849 const Function &func = *I;
1850 if (!func.isDeclaration()) {
1851 std::string name("define_");
1852 name += func.getName();
1853 printFunction(name, func.getName());
1858 void CppWriter::printVariable(const std::string& fname,
1859 const std::string& varName) {
1860 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1863 error(std::string("Variable '") + varName + "' not found in input module");
1866 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1867 printVariableUses(GV);
1868 printVariableHead(GV);
1869 printVariableBody(GV);
1870 Out << "return " << getCppName(GV) << ";\n";
1874 void CppWriter::printType(const std::string& fname,
1875 const std::string& typeName) {
1876 const Type* Ty = TheModule->getTypeByName(typeName);
1878 error(std::string("Type '") + typeName + "' not found in input module");
1881 Out << "\nType* " << fname << "(Module *mod) {\n";
1883 Out << "return " << getCppName(Ty) << ";\n";
1887 bool CppWriter::runOnModule(Module &M) {
1891 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1893 // Get the name of the function we're supposed to generate
1894 std::string fname = FuncName.getValue();
1896 // Get the name of the thing we are to generate
1897 std::string tgtname = NameToGenerate.getValue();
1898 if (GenerationType == GenModule ||
1899 GenerationType == GenContents ||
1900 GenerationType == GenProgram ||
1901 GenerationType == GenFunctions) {
1902 if (tgtname == "!bad!") {
1903 if (M.getModuleIdentifier() == "-")
1904 tgtname = "<stdin>";
1906 tgtname = M.getModuleIdentifier();
1908 } else if (tgtname == "!bad!")
1909 error("You must use the -for option with -gen-{function,variable,type}");
1911 switch (WhatToGenerate(GenerationType)) {
1914 fname = "makeLLVMModule";
1915 printProgram(fname,tgtname);
1919 fname = "makeLLVMModule";
1920 printModule(fname,tgtname);
1924 fname = "makeLLVMModuleContents";
1925 printContents(fname,tgtname);
1929 fname = "makeLLVMFunction";
1930 printFunction(fname,tgtname);
1937 fname = "makeLLVMInline";
1938 printInline(fname,tgtname);
1942 fname = "makeLLVMVariable";
1943 printVariable(fname,tgtname);
1947 fname = "makeLLVMType";
1948 printType(fname,tgtname);
1951 error("Invalid generation option");
1958 char CppWriter::ID = 0;
1960 //===----------------------------------------------------------------------===//
1961 // External Interface declaration
1962 //===----------------------------------------------------------------------===//
1964 bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
1966 CodeGenFileType FileType,
1968 if (FileType != TargetMachine::AssemblyFile) return true;
1969 PM.add(new CppWriter(o));