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/Streams.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Config/config.h"
39 static cl::opt<std::string>
40 FuncName("cppfname", cl::desc("Specify the name of the generated function"),
41 cl::value_desc("function name"));
54 static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
55 cl::desc("Choose what kind of output to generate"),
58 clEnumValN(GenProgram, "program", "Generate a complete program"),
59 clEnumValN(GenModule, "module", "Generate a module definition"),
60 clEnumValN(GenContents, "contents", "Generate contents of a module"),
61 clEnumValN(GenFunction, "function", "Generate a function definition"),
62 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
63 clEnumValN(GenInline, "inline", "Generate an inline function"),
64 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
65 clEnumValN(GenType, "type", "Generate a type definition"),
70 static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
71 cl::desc("Specify the name of the thing to generate"),
74 /// CppBackendTargetMachineModule - Note that this is used on hosts
75 /// that cannot link in a library unless there are references into the
76 /// library. In particular, it seems that it is not possible to get
77 /// things to work on Win32 without this. Though it is unused, do not
79 extern "C" int CppBackendTargetMachineModule;
80 int CppBackendTargetMachineModule = 0;
82 // Register the target.
83 static RegisterTarget<CPPTargetMachine> X("cpp", "C++ backend");
86 typedef std::vector<const Type*> TypeList;
87 typedef std::map<const Type*,std::string> TypeMap;
88 typedef std::map<const Value*,std::string> ValueMap;
89 typedef std::set<std::string> NameSet;
90 typedef std::set<const Type*> TypeSet;
91 typedef std::set<const Value*> ValueSet;
92 typedef std::map<const Value*,std::string> ForwardRefMap;
94 /// CppWriter - This class is the main chunk of code that converts an LLVM
95 /// module to a C++ translation unit.
96 class CppWriter : public ModulePass {
99 const Module *TheModule;
103 TypeMap UnresolvedTypes;
106 TypeSet DefinedTypes;
107 ValueSet DefinedValues;
108 ForwardRefMap ForwardRefs;
113 explicit CppWriter(raw_ostream &o) :
114 ModulePass(&ID), Out(o), uniqueNum(0), is_inline(false) {}
116 virtual const char *getPassName() const { return "C++ backend"; }
118 bool runOnModule(Module &M);
120 void printProgram(const std::string& fname, const std::string& modName );
121 void printModule(const std::string& fname, const std::string& modName );
122 void printContents(const std::string& fname, const std::string& modName );
123 void printFunction(const std::string& fname, const std::string& funcName );
124 void printFunctions();
125 void printInline(const std::string& fname, const std::string& funcName );
126 void printVariable(const std::string& fname, const std::string& varName );
127 void printType(const std::string& fname, const std::string& typeName );
129 void error(const std::string& msg);
132 void printLinkageType(GlobalValue::LinkageTypes LT);
133 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
134 void printCallingConv(unsigned cc);
135 void printEscapedString(const std::string& str);
136 void printCFP(const ConstantFP* CFP);
138 std::string getCppName(const Type* val);
139 inline void printCppName(const Type* val);
141 std::string getCppName(const Value* val);
142 inline void printCppName(const Value* val);
144 void printAttributes(const AttrListPtr &PAL, const std::string &name);
145 bool printTypeInternal(const Type* Ty);
146 inline void printType(const Type* Ty);
147 void printTypes(const Module* M);
149 void printConstant(const Constant *CPV);
150 void printConstants(const Module* M);
152 void printVariableUses(const GlobalVariable *GV);
153 void printVariableHead(const GlobalVariable *GV);
154 void printVariableBody(const GlobalVariable *GV);
156 void printFunctionUses(const Function *F);
157 void printFunctionHead(const Function *F);
158 void printFunctionBody(const Function *F);
159 void printInstruction(const Instruction *I, const std::string& bbname);
160 std::string getOpName(Value*);
162 void printModuleBody();
165 static unsigned indent_level = 0;
166 inline raw_ostream& nl(raw_ostream& Out, int delta = 0) {
168 if (delta >= 0 || indent_level >= unsigned(-delta))
169 indent_level += delta;
170 for (unsigned i = 0; i < indent_level; ++i)
175 inline void in() { indent_level++; }
176 inline void out() { if (indent_level >0) indent_level--; }
179 sanitize(std::string& str) {
180 for (size_t i = 0; i < str.length(); ++i)
181 if (!isalnum(str[i]) && str[i] != '_')
186 getTypePrefix(const Type* Ty ) {
187 switch (Ty->getTypeID()) {
188 case Type::VoidTyID: return "void_";
189 case Type::IntegerTyID:
190 return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
192 case Type::FloatTyID: return "float_";
193 case Type::DoubleTyID: return "double_";
194 case Type::LabelTyID: return "label_";
195 case Type::FunctionTyID: return "func_";
196 case Type::StructTyID: return "struct_";
197 case Type::ArrayTyID: return "array_";
198 case Type::PointerTyID: return "ptr_";
199 case Type::VectorTyID: return "packed_";
200 case Type::OpaqueTyID: return "opaque_";
201 default: return "other_";
206 // Looks up the type in the symbol table and returns a pointer to its name or
207 // a null pointer if it wasn't found. Note that this isn't the same as the
208 // Mode::getTypeName function which will return an empty string, not a null
209 // pointer if the name is not found.
210 inline const std::string*
211 findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
212 TypeSymbolTable::const_iterator TI = ST.begin();
213 TypeSymbolTable::const_iterator TE = ST.end();
214 for (;TI != TE; ++TI)
215 if (TI->second == Ty)
220 void CppWriter::error(const std::string& msg) {
221 cerr << progname << ": " << msg << "\n";
225 // printCFP - Print a floating point constant .. very carefully :)
226 // This makes sure that conversion to/from floating yields the same binary
227 // result so that we don't lose precision.
228 void CppWriter::printCFP(const ConstantFP *CFP) {
230 APFloat APF = APFloat(CFP->getValueAPF()); // copy
231 if (CFP->getType() == Type::FloatTy)
232 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
233 Out << "ConstantFP::get(";
237 sprintf(Buffer, "%A", APF.convertToDouble());
238 if ((!strncmp(Buffer, "0x", 2) ||
239 !strncmp(Buffer, "-0x", 3) ||
240 !strncmp(Buffer, "+0x", 3)) &&
241 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
242 if (CFP->getType() == Type::DoubleTy)
243 Out << "BitsToDouble(" << Buffer << ")";
245 Out << "BitsToFloat((float)" << Buffer << ")";
249 std::string StrVal = ftostr(CFP->getValueAPF());
251 while (StrVal[0] == ' ')
252 StrVal.erase(StrVal.begin());
254 // Check to make sure that the stringized number is not some string like
255 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
256 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
257 ((StrVal[0] == '-' || StrVal[0] == '+') &&
258 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
259 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
260 if (CFP->getType() == Type::DoubleTy)
263 Out << StrVal << "f";
264 } else if (CFP->getType() == Type::DoubleTy)
265 Out << "BitsToDouble(0x"
266 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
267 << "ULL) /* " << StrVal << " */";
269 Out << "BitsToFloat(0x"
270 << utohexstr((uint32_t)CFP->getValueAPF().
271 bitcastToAPInt().getZExtValue())
272 << "U) /* " << StrVal << " */";
280 void CppWriter::printCallingConv(unsigned cc){
281 // Print the calling convention.
283 case CallingConv::C: Out << "CallingConv::C"; break;
284 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
285 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
286 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
287 default: Out << cc; break;
291 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
293 case GlobalValue::InternalLinkage:
294 Out << "GlobalValue::InternalLinkage"; break;
295 case GlobalValue::PrivateLinkage:
296 Out << "GlobalValue::PrivateLinkage"; break;
297 case GlobalValue::LinkOnceLinkage:
298 Out << "GlobalValue::LinkOnceLinkage "; break;
299 case GlobalValue::WeakLinkage:
300 Out << "GlobalValue::WeakLinkage"; break;
301 case GlobalValue::AppendingLinkage:
302 Out << "GlobalValue::AppendingLinkage"; break;
303 case GlobalValue::ExternalLinkage:
304 Out << "GlobalValue::ExternalLinkage"; break;
305 case GlobalValue::DLLImportLinkage:
306 Out << "GlobalValue::DLLImportLinkage"; break;
307 case GlobalValue::DLLExportLinkage:
308 Out << "GlobalValue::DLLExportLinkage"; break;
309 case GlobalValue::ExternalWeakLinkage:
310 Out << "GlobalValue::ExternalWeakLinkage"; break;
311 case GlobalValue::GhostLinkage:
312 Out << "GlobalValue::GhostLinkage"; break;
313 case GlobalValue::CommonLinkage:
314 Out << "GlobalValue::CommonLinkage"; break;
318 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
320 default: assert(0 && "Unknown GVar visibility");
321 case GlobalValue::DefaultVisibility:
322 Out << "GlobalValue::DefaultVisibility";
324 case GlobalValue::HiddenVisibility:
325 Out << "GlobalValue::HiddenVisibility";
327 case GlobalValue::ProtectedVisibility:
328 Out << "GlobalValue::ProtectedVisibility";
333 // printEscapedString - Print each character of the specified string, escaping
334 // it if it is not printable or if it is an escape char.
335 void CppWriter::printEscapedString(const std::string &Str) {
336 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
337 unsigned char C = Str[i];
338 if (isprint(C) && C != '"' && C != '\\') {
342 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
343 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
348 std::string CppWriter::getCppName(const Type* Ty) {
349 // First, handle the primitive types .. easy
350 if (Ty->isPrimitiveType() || Ty->isInteger()) {
351 switch (Ty->getTypeID()) {
352 case Type::VoidTyID: return "Type::VoidTy";
353 case Type::IntegerTyID: {
354 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
355 return "IntegerType::get(" + utostr(BitWidth) + ")";
357 case Type::FloatTyID: return "Type::FloatTy";
358 case Type::DoubleTyID: return "Type::DoubleTy";
359 case Type::LabelTyID: return "Type::LabelTy";
361 error("Invalid primitive type");
364 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
367 // Now, see if we've seen the type before and return that
368 TypeMap::iterator I = TypeNames.find(Ty);
369 if (I != TypeNames.end())
372 // Okay, let's build a new name for this type. Start with a prefix
373 const char* prefix = 0;
374 switch (Ty->getTypeID()) {
375 case Type::FunctionTyID: prefix = "FuncTy_"; break;
376 case Type::StructTyID: prefix = "StructTy_"; break;
377 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
378 case Type::PointerTyID: prefix = "PointerTy_"; break;
379 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
380 case Type::VectorTyID: prefix = "VectorTy_"; break;
381 default: prefix = "OtherTy_"; break; // prevent breakage
384 // See if the type has a name in the symboltable and build accordingly
385 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
388 name = std::string(prefix) + *tName;
390 name = std::string(prefix) + utostr(uniqueNum++);
394 return TypeNames[Ty] = name;
397 void CppWriter::printCppName(const Type* Ty) {
398 printEscapedString(getCppName(Ty));
401 std::string CppWriter::getCppName(const Value* val) {
403 ValueMap::iterator I = ValueNames.find(val);
404 if (I != ValueNames.end() && I->first == val)
407 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
408 name = std::string("gvar_") +
409 getTypePrefix(GV->getType()->getElementType());
410 } else if (isa<Function>(val)) {
411 name = std::string("func_");
412 } else if (const Constant* C = dyn_cast<Constant>(val)) {
413 name = std::string("const_") + getTypePrefix(C->getType());
414 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
416 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
417 Function::const_arg_iterator(Arg)) + 1;
418 name = std::string("arg_") + utostr(argNum);
419 NameSet::iterator NI = UsedNames.find(name);
420 if (NI != UsedNames.end())
421 name += std::string("_") + utostr(uniqueNum++);
422 UsedNames.insert(name);
423 return ValueNames[val] = name;
425 name = getTypePrefix(val->getType());
428 name = getTypePrefix(val->getType());
430 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
432 NameSet::iterator NI = UsedNames.find(name);
433 if (NI != UsedNames.end())
434 name += std::string("_") + utostr(uniqueNum++);
435 UsedNames.insert(name);
436 return ValueNames[val] = name;
439 void CppWriter::printCppName(const Value* val) {
440 printEscapedString(getCppName(val));
443 void CppWriter::printAttributes(const AttrListPtr &PAL,
444 const std::string &name) {
445 Out << "AttrListPtr " << name << "_PAL;";
447 if (!PAL.isEmpty()) {
448 Out << '{'; in(); nl(Out);
449 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
450 Out << "AttributeWithIndex PAWI;"; nl(Out);
451 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
452 unsigned index = PAL.getSlot(i).Index;
453 Attributes attrs = PAL.getSlot(i).Attrs;
454 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
455 #define HANDLE_ATTR(X) \
456 if (attrs & Attribute::X) \
457 Out << " | Attribute::" #X; \
458 attrs &= ~Attribute::X;
462 HANDLE_ATTR(StructRet);
464 HANDLE_ATTR(NoReturn);
465 HANDLE_ATTR(NoUnwind);
467 HANDLE_ATTR(NoAlias);
469 HANDLE_ATTR(ReadNone);
470 HANDLE_ATTR(ReadOnly);
471 HANDLE_ATTR(NoCapture);
473 assert(attrs == 0 && "Unhandled attribute!");
476 Out << "Attrs.push_back(PAWI);";
479 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
486 bool CppWriter::printTypeInternal(const Type* Ty) {
487 // We don't print definitions for primitive types
488 if (Ty->isPrimitiveType() || Ty->isInteger())
491 // If we already defined this type, we don't need to define it again.
492 if (DefinedTypes.find(Ty) != DefinedTypes.end())
495 // Everything below needs the name for the type so get it now.
496 std::string typeName(getCppName(Ty));
498 // Search the type stack for recursion. If we find it, then generate this
499 // as an OpaqueType, but make sure not to do this multiple times because
500 // the type could appear in multiple places on the stack. Once the opaque
501 // definition is issued, it must not be re-issued. Consequently we have to
502 // check the UnresolvedTypes list as well.
503 TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
505 if (TI != TypeStack.end()) {
506 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
507 if (I == UnresolvedTypes.end()) {
508 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
510 UnresolvedTypes[Ty] = typeName;
515 // We're going to print a derived type which, by definition, contains other
516 // types. So, push this one we're printing onto the type stack to assist with
517 // recursive definitions.
518 TypeStack.push_back(Ty);
520 // Print the type definition
521 switch (Ty->getTypeID()) {
522 case Type::FunctionTyID: {
523 const FunctionType* FT = cast<FunctionType>(Ty);
524 Out << "std::vector<const Type*>" << typeName << "_args;";
526 FunctionType::param_iterator PI = FT->param_begin();
527 FunctionType::param_iterator PE = FT->param_end();
528 for (; PI != PE; ++PI) {
529 const Type* argTy = static_cast<const Type*>(*PI);
530 bool isForward = printTypeInternal(argTy);
531 std::string argName(getCppName(argTy));
532 Out << typeName << "_args.push_back(" << argName;
538 bool isForward = printTypeInternal(FT->getReturnType());
539 std::string retTypeName(getCppName(FT->getReturnType()));
540 Out << "FunctionType* " << typeName << " = FunctionType::get(";
541 in(); nl(Out) << "/*Result=*/" << retTypeName;
545 nl(Out) << "/*Params=*/" << typeName << "_args,";
546 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
551 case Type::StructTyID: {
552 const StructType* ST = cast<StructType>(Ty);
553 Out << "std::vector<const Type*>" << typeName << "_fields;";
555 StructType::element_iterator EI = ST->element_begin();
556 StructType::element_iterator EE = ST->element_end();
557 for (; EI != EE; ++EI) {
558 const Type* fieldTy = static_cast<const Type*>(*EI);
559 bool isForward = printTypeInternal(fieldTy);
560 std::string fieldName(getCppName(fieldTy));
561 Out << typeName << "_fields.push_back(" << fieldName;
567 Out << "StructType* " << typeName << " = StructType::get("
568 << typeName << "_fields, /*isPacked=*/"
569 << (ST->isPacked() ? "true" : "false") << ");";
573 case Type::ArrayTyID: {
574 const ArrayType* AT = cast<ArrayType>(Ty);
575 const Type* ET = AT->getElementType();
576 bool isForward = printTypeInternal(ET);
577 std::string elemName(getCppName(ET));
578 Out << "ArrayType* " << typeName << " = ArrayType::get("
579 << elemName << (isForward ? "_fwd" : "")
580 << ", " << utostr(AT->getNumElements()) << ");";
584 case Type::PointerTyID: {
585 const PointerType* PT = cast<PointerType>(Ty);
586 const Type* ET = PT->getElementType();
587 bool isForward = printTypeInternal(ET);
588 std::string elemName(getCppName(ET));
589 Out << "PointerType* " << typeName << " = PointerType::get("
590 << elemName << (isForward ? "_fwd" : "")
591 << ", " << utostr(PT->getAddressSpace()) << ");";
595 case Type::VectorTyID: {
596 const VectorType* PT = cast<VectorType>(Ty);
597 const Type* ET = PT->getElementType();
598 bool isForward = printTypeInternal(ET);
599 std::string elemName(getCppName(ET));
600 Out << "VectorType* " << typeName << " = VectorType::get("
601 << elemName << (isForward ? "_fwd" : "")
602 << ", " << utostr(PT->getNumElements()) << ");";
606 case Type::OpaqueTyID: {
607 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
612 error("Invalid TypeID");
615 // If the type had a name, make sure we recreate it.
616 const std::string* progTypeName =
617 findTypeName(TheModule->getTypeSymbolTable(),Ty);
619 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
624 // Pop us off the type stack
625 TypeStack.pop_back();
627 // Indicate that this type is now defined.
628 DefinedTypes.insert(Ty);
630 // Early resolve as many unresolved types as possible. Search the unresolved
631 // types map for the type we just printed. Now that its definition is complete
632 // we can resolve any previous references to it. This prevents a cascade of
634 TypeMap::iterator I = UnresolvedTypes.find(Ty);
635 if (I != UnresolvedTypes.end()) {
636 Out << "cast<OpaqueType>(" << I->second
637 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
639 Out << I->second << " = cast<";
640 switch (Ty->getTypeID()) {
641 case Type::FunctionTyID: Out << "FunctionType"; break;
642 case Type::ArrayTyID: Out << "ArrayType"; break;
643 case Type::StructTyID: Out << "StructType"; break;
644 case Type::VectorTyID: Out << "VectorType"; break;
645 case Type::PointerTyID: Out << "PointerType"; break;
646 case Type::OpaqueTyID: Out << "OpaqueType"; break;
647 default: Out << "NoSuchDerivedType"; break;
649 Out << ">(" << I->second << "_fwd.get());";
651 UnresolvedTypes.erase(I);
654 // Finally, separate the type definition from other with a newline.
657 // We weren't a recursive type
661 // Prints a type definition. Returns true if it could not resolve all the
662 // types in the definition but had to use a forward reference.
663 void CppWriter::printType(const Type* Ty) {
664 assert(TypeStack.empty());
666 printTypeInternal(Ty);
667 assert(TypeStack.empty());
670 void CppWriter::printTypes(const Module* M) {
671 // Walk the symbol table and print out all its types
672 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
673 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
676 // For primitive types and types already defined, just add a name
677 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
678 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
679 TNI != TypeNames.end()) {
680 Out << "mod->addTypeName(\"";
681 printEscapedString(TI->first);
682 Out << "\", " << getCppName(TI->second) << ");";
684 // For everything else, define the type
686 printType(TI->second);
690 // Add all of the global variables to the value table...
691 for (Module::const_global_iterator I = TheModule->global_begin(),
692 E = TheModule->global_end(); I != E; ++I) {
693 if (I->hasInitializer())
694 printType(I->getInitializer()->getType());
695 printType(I->getType());
698 // Add all the functions to the table
699 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
701 printType(FI->getReturnType());
702 printType(FI->getFunctionType());
703 // Add all the function arguments
704 for (Function::const_arg_iterator AI = FI->arg_begin(),
705 AE = FI->arg_end(); AI != AE; ++AI) {
706 printType(AI->getType());
709 // Add all of the basic blocks and instructions
710 for (Function::const_iterator BB = FI->begin(),
711 E = FI->end(); BB != E; ++BB) {
712 printType(BB->getType());
713 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
715 printType(I->getType());
716 for (unsigned i = 0; i < I->getNumOperands(); ++i)
717 printType(I->getOperand(i)->getType());
724 // printConstant - Print out a constant pool entry...
725 void CppWriter::printConstant(const Constant *CV) {
726 // First, if the constant is actually a GlobalValue (variable or function)
727 // or its already in the constant list then we've printed it already and we
729 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
732 std::string constName(getCppName(CV));
733 std::string typeName(getCppName(CV->getType()));
735 if (isa<GlobalValue>(CV)) {
736 // Skip variables and functions, we emit them elsewhere
740 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
741 std::string constValue = CI->getValue().toString(10, true);
742 Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
743 << cast<IntegerType>(CI->getType())->getBitWidth() << ", \""
744 << constValue << "\", " << constValue.length() << ", 10));";
745 } else if (isa<ConstantAggregateZero>(CV)) {
746 Out << "ConstantAggregateZero* " << constName
747 << " = ConstantAggregateZero::get(" << typeName << ");";
748 } else if (isa<ConstantPointerNull>(CV)) {
749 Out << "ConstantPointerNull* " << constName
750 << " = ConstantPointerNull::get(" << typeName << ");";
751 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
752 Out << "ConstantFP* " << constName << " = ";
755 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
756 if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
757 Out << "Constant* " << constName << " = ConstantArray::get(\"";
758 std::string tmp = CA->getAsString();
759 bool nullTerminate = false;
760 if (tmp[tmp.length()-1] == 0) {
761 tmp.erase(tmp.length()-1);
762 nullTerminate = true;
764 printEscapedString(tmp);
765 // Determine if we want null termination or not.
767 Out << "\", true"; // Indicate that the null terminator should be
770 Out << "\", false";// No null terminator
773 Out << "std::vector<Constant*> " << constName << "_elems;";
775 unsigned N = CA->getNumOperands();
776 for (unsigned i = 0; i < N; ++i) {
777 printConstant(CA->getOperand(i)); // recurse to print operands
778 Out << constName << "_elems.push_back("
779 << getCppName(CA->getOperand(i)) << ");";
782 Out << "Constant* " << constName << " = ConstantArray::get("
783 << typeName << ", " << constName << "_elems);";
785 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
786 Out << "std::vector<Constant*> " << constName << "_fields;";
788 unsigned N = CS->getNumOperands();
789 for (unsigned i = 0; i < N; i++) {
790 printConstant(CS->getOperand(i));
791 Out << constName << "_fields.push_back("
792 << getCppName(CS->getOperand(i)) << ");";
795 Out << "Constant* " << constName << " = ConstantStruct::get("
796 << typeName << ", " << constName << "_fields);";
797 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
798 Out << "std::vector<Constant*> " << constName << "_elems;";
800 unsigned N = CP->getNumOperands();
801 for (unsigned i = 0; i < N; ++i) {
802 printConstant(CP->getOperand(i));
803 Out << constName << "_elems.push_back("
804 << getCppName(CP->getOperand(i)) << ");";
807 Out << "Constant* " << constName << " = ConstantVector::get("
808 << typeName << ", " << constName << "_elems);";
809 } else if (isa<UndefValue>(CV)) {
810 Out << "UndefValue* " << constName << " = UndefValue::get("
812 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
813 if (CE->getOpcode() == Instruction::GetElementPtr) {
814 Out << "std::vector<Constant*> " << constName << "_indices;";
816 printConstant(CE->getOperand(0));
817 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
818 printConstant(CE->getOperand(i));
819 Out << constName << "_indices.push_back("
820 << getCppName(CE->getOperand(i)) << ");";
823 Out << "Constant* " << constName
824 << " = ConstantExpr::getGetElementPtr("
825 << getCppName(CE->getOperand(0)) << ", "
826 << "&" << constName << "_indices[0], "
827 << constName << "_indices.size()"
829 } else if (CE->isCast()) {
830 printConstant(CE->getOperand(0));
831 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
832 switch (CE->getOpcode()) {
833 default: assert(0 && "Invalid cast opcode");
834 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
835 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
836 case Instruction::SExt: Out << "Instruction::SExt"; break;
837 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
838 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
839 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
840 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
841 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
842 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
843 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
844 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
845 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
847 Out << ", " << getCppName(CE->getOperand(0)) << ", "
848 << getCppName(CE->getType()) << ");";
850 unsigned N = CE->getNumOperands();
851 for (unsigned i = 0; i < N; ++i ) {
852 printConstant(CE->getOperand(i));
854 Out << "Constant* " << constName << " = ConstantExpr::";
855 switch (CE->getOpcode()) {
856 case Instruction::Add: Out << "getAdd("; break;
857 case Instruction::Sub: Out << "getSub("; break;
858 case Instruction::Mul: Out << "getMul("; break;
859 case Instruction::UDiv: Out << "getUDiv("; break;
860 case Instruction::SDiv: Out << "getSDiv("; break;
861 case Instruction::FDiv: Out << "getFDiv("; break;
862 case Instruction::URem: Out << "getURem("; break;
863 case Instruction::SRem: Out << "getSRem("; break;
864 case Instruction::FRem: Out << "getFRem("; break;
865 case Instruction::And: Out << "getAnd("; break;
866 case Instruction::Or: Out << "getOr("; break;
867 case Instruction::Xor: Out << "getXor("; break;
868 case Instruction::ICmp:
869 Out << "getICmp(ICmpInst::ICMP_";
870 switch (CE->getPredicate()) {
871 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
872 case ICmpInst::ICMP_NE: Out << "NE"; break;
873 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
874 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
875 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
876 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
877 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
878 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
879 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
880 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
881 default: error("Invalid ICmp Predicate");
884 case Instruction::FCmp:
885 Out << "getFCmp(FCmpInst::FCMP_";
886 switch (CE->getPredicate()) {
887 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
888 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
889 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
890 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
891 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
892 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
893 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
894 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
895 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
896 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
897 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
898 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
899 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
900 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
901 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
902 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
903 default: error("Invalid FCmp Predicate");
906 case Instruction::Shl: Out << "getShl("; break;
907 case Instruction::LShr: Out << "getLShr("; break;
908 case Instruction::AShr: Out << "getAShr("; break;
909 case Instruction::Select: Out << "getSelect("; break;
910 case Instruction::ExtractElement: Out << "getExtractElement("; break;
911 case Instruction::InsertElement: Out << "getInsertElement("; break;
912 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
914 error("Invalid constant expression");
917 Out << getCppName(CE->getOperand(0));
918 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
919 Out << ", " << getCppName(CE->getOperand(i));
923 error("Bad Constant");
924 Out << "Constant* " << constName << " = 0; ";
929 void CppWriter::printConstants(const Module* M) {
930 // Traverse all the global variables looking for constant initializers
931 for (Module::const_global_iterator I = TheModule->global_begin(),
932 E = TheModule->global_end(); I != E; ++I)
933 if (I->hasInitializer())
934 printConstant(I->getInitializer());
936 // Traverse the LLVM functions looking for constants
937 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
939 // Add all of the basic blocks and instructions
940 for (Function::const_iterator BB = FI->begin(),
941 E = FI->end(); BB != E; ++BB) {
942 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
944 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
945 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
954 void CppWriter::printVariableUses(const GlobalVariable *GV) {
955 nl(Out) << "// Type Definitions";
957 printType(GV->getType());
958 if (GV->hasInitializer()) {
959 Constant* Init = GV->getInitializer();
960 printType(Init->getType());
961 if (Function* F = dyn_cast<Function>(Init)) {
962 nl(Out)<< "/ Function Declarations"; nl(Out);
963 printFunctionHead(F);
964 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
965 nl(Out) << "// Global Variable Declarations"; nl(Out);
966 printVariableHead(gv);
968 nl(Out) << "// Constant Definitions"; nl(Out);
971 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
972 nl(Out) << "// Global Variable Definitions"; nl(Out);
973 printVariableBody(gv);
978 void CppWriter::printVariableHead(const GlobalVariable *GV) {
979 nl(Out) << "GlobalVariable* " << getCppName(GV);
981 Out << " = mod->getGlobalVariable(";
982 printEscapedString(GV->getName());
983 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
984 nl(Out) << "if (!" << getCppName(GV) << ") {";
985 in(); nl(Out) << getCppName(GV);
987 Out << " = new GlobalVariable(";
988 nl(Out) << "/*Type=*/";
989 printCppName(GV->getType()->getElementType());
991 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
993 nl(Out) << "/*Linkage=*/";
994 printLinkageType(GV->getLinkage());
996 nl(Out) << "/*Initializer=*/0, ";
997 if (GV->hasInitializer()) {
998 Out << "// has initializer, specified below";
1000 nl(Out) << "/*Name=*/\"";
1001 printEscapedString(GV->getName());
1006 if (GV->hasSection()) {
1008 Out << "->setSection(\"";
1009 printEscapedString(GV->getSection());
1013 if (GV->getAlignment()) {
1015 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1018 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1020 Out << "->setVisibility(";
1021 printVisibilityType(GV->getVisibility());
1026 out(); Out << "}"; nl(Out);
1030 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1031 if (GV->hasInitializer()) {
1033 Out << "->setInitializer(";
1034 Out << getCppName(GV->getInitializer()) << ");";
1039 std::string CppWriter::getOpName(Value* V) {
1040 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1041 return getCppName(V);
1043 // See if its alread in the map of forward references, if so just return the
1044 // name we already set up for it
1045 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1046 if (I != ForwardRefs.end())
1049 // This is a new forward reference. Generate a unique name for it
1050 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1052 // Yes, this is a hack. An Argument is the smallest instantiable value that
1053 // we can make as a placeholder for the real value. We'll replace these
1054 // Argument instances later.
1055 Out << "Argument* " << result << " = new Argument("
1056 << getCppName(V->getType()) << ");";
1058 ForwardRefs[V] = result;
1062 // printInstruction - This member is called for each Instruction in a function.
1063 void CppWriter::printInstruction(const Instruction *I,
1064 const std::string& bbname) {
1065 std::string iName(getCppName(I));
1067 // Before we emit this instruction, we need to take care of generating any
1068 // forward references. So, we get the names of all the operands in advance
1069 std::string* opNames = new std::string[I->getNumOperands()];
1070 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1071 opNames[i] = getOpName(I->getOperand(i));
1074 switch (I->getOpcode()) {
1076 error("Invalid instruction");
1079 case Instruction::Ret: {
1080 const ReturnInst* ret = cast<ReturnInst>(I);
1081 Out << "ReturnInst::Create("
1082 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1085 case Instruction::Br: {
1086 const BranchInst* br = cast<BranchInst>(I);
1087 Out << "BranchInst::Create(" ;
1088 if (br->getNumOperands() == 3 ) {
1089 Out << opNames[0] << ", "
1090 << opNames[1] << ", "
1091 << opNames[2] << ", ";
1093 } else if (br->getNumOperands() == 1) {
1094 Out << opNames[0] << ", ";
1096 error("Branch with 2 operands?");
1098 Out << bbname << ");";
1101 case Instruction::Switch: {
1102 const SwitchInst* sw = cast<SwitchInst>(I);
1103 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1104 << opNames[0] << ", "
1105 << opNames[1] << ", "
1106 << sw->getNumCases() << ", " << bbname << ");";
1108 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1109 Out << iName << "->addCase("
1110 << opNames[i] << ", "
1111 << opNames[i+1] << ");";
1116 case Instruction::Invoke: {
1117 const InvokeInst* inv = cast<InvokeInst>(I);
1118 Out << "std::vector<Value*> " << iName << "_params;";
1120 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1121 Out << iName << "_params.push_back("
1122 << opNames[i] << ");";
1125 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1126 << opNames[0] << ", "
1127 << opNames[1] << ", "
1128 << opNames[2] << ", "
1129 << iName << "_params.begin(), " << iName << "_params.end(), \"";
1130 printEscapedString(inv->getName());
1131 Out << "\", " << bbname << ");";
1132 nl(Out) << iName << "->setCallingConv(";
1133 printCallingConv(inv->getCallingConv());
1135 printAttributes(inv->getAttributes(), iName);
1136 Out << iName << "->setAttributes(" << iName << "_PAL);";
1140 case Instruction::Unwind: {
1141 Out << "new UnwindInst("
1145 case Instruction::Unreachable:{
1146 Out << "new UnreachableInst("
1150 case Instruction::Add:
1151 case Instruction::Sub:
1152 case Instruction::Mul:
1153 case Instruction::UDiv:
1154 case Instruction::SDiv:
1155 case Instruction::FDiv:
1156 case Instruction::URem:
1157 case Instruction::SRem:
1158 case Instruction::FRem:
1159 case Instruction::And:
1160 case Instruction::Or:
1161 case Instruction::Xor:
1162 case Instruction::Shl:
1163 case Instruction::LShr:
1164 case Instruction::AShr:{
1165 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1166 switch (I->getOpcode()) {
1167 case Instruction::Add: Out << "Instruction::Add"; break;
1168 case Instruction::Sub: Out << "Instruction::Sub"; break;
1169 case Instruction::Mul: Out << "Instruction::Mul"; break;
1170 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1171 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1172 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1173 case Instruction::URem:Out << "Instruction::URem"; break;
1174 case Instruction::SRem:Out << "Instruction::SRem"; break;
1175 case Instruction::FRem:Out << "Instruction::FRem"; break;
1176 case Instruction::And: Out << "Instruction::And"; break;
1177 case Instruction::Or: Out << "Instruction::Or"; break;
1178 case Instruction::Xor: Out << "Instruction::Xor"; break;
1179 case Instruction::Shl: Out << "Instruction::Shl"; break;
1180 case Instruction::LShr:Out << "Instruction::LShr"; break;
1181 case Instruction::AShr:Out << "Instruction::AShr"; break;
1182 default: Out << "Instruction::BadOpCode"; break;
1184 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1185 printEscapedString(I->getName());
1186 Out << "\", " << bbname << ");";
1189 case Instruction::FCmp: {
1190 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1191 switch (cast<FCmpInst>(I)->getPredicate()) {
1192 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1193 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1194 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1195 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1196 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1197 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1198 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1199 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1200 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1201 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1202 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1203 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1204 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1205 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1206 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1207 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1208 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1210 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1211 printEscapedString(I->getName());
1212 Out << "\", " << bbname << ");";
1215 case Instruction::ICmp: {
1216 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1217 switch (cast<ICmpInst>(I)->getPredicate()) {
1218 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1219 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1220 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1221 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1222 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1223 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1224 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1225 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1226 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1227 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1228 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1230 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1231 printEscapedString(I->getName());
1232 Out << "\", " << bbname << ");";
1235 case Instruction::Malloc: {
1236 const MallocInst* mallocI = cast<MallocInst>(I);
1237 Out << "MallocInst* " << iName << " = new MallocInst("
1238 << getCppName(mallocI->getAllocatedType()) << ", ";
1239 if (mallocI->isArrayAllocation())
1240 Out << opNames[0] << ", " ;
1242 printEscapedString(mallocI->getName());
1243 Out << "\", " << bbname << ");";
1244 if (mallocI->getAlignment())
1245 nl(Out) << iName << "->setAlignment("
1246 << mallocI->getAlignment() << ");";
1249 case Instruction::Free: {
1250 Out << "FreeInst* " << iName << " = new FreeInst("
1251 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1254 case Instruction::Alloca: {
1255 const AllocaInst* allocaI = cast<AllocaInst>(I);
1256 Out << "AllocaInst* " << iName << " = new AllocaInst("
1257 << getCppName(allocaI->getAllocatedType()) << ", ";
1258 if (allocaI->isArrayAllocation())
1259 Out << opNames[0] << ", ";
1261 printEscapedString(allocaI->getName());
1262 Out << "\", " << bbname << ");";
1263 if (allocaI->getAlignment())
1264 nl(Out) << iName << "->setAlignment("
1265 << allocaI->getAlignment() << ");";
1268 case Instruction::Load:{
1269 const LoadInst* load = cast<LoadInst>(I);
1270 Out << "LoadInst* " << iName << " = new LoadInst("
1271 << opNames[0] << ", \"";
1272 printEscapedString(load->getName());
1273 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1274 << ", " << bbname << ");";
1277 case Instruction::Store: {
1278 const StoreInst* store = cast<StoreInst>(I);
1279 Out << " new StoreInst("
1280 << opNames[0] << ", "
1281 << opNames[1] << ", "
1282 << (store->isVolatile() ? "true" : "false")
1283 << ", " << bbname << ");";
1286 case Instruction::GetElementPtr: {
1287 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1288 if (gep->getNumOperands() <= 2) {
1289 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1291 if (gep->getNumOperands() == 2)
1292 Out << ", " << opNames[1];
1294 Out << "std::vector<Value*> " << iName << "_indices;";
1296 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1297 Out << iName << "_indices.push_back("
1298 << opNames[i] << ");";
1301 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1302 << opNames[0] << ", " << iName << "_indices.begin(), "
1303 << iName << "_indices.end()";
1306 printEscapedString(gep->getName());
1307 Out << "\", " << bbname << ");";
1310 case Instruction::PHI: {
1311 const PHINode* phi = cast<PHINode>(I);
1313 Out << "PHINode* " << iName << " = PHINode::Create("
1314 << getCppName(phi->getType()) << ", \"";
1315 printEscapedString(phi->getName());
1316 Out << "\", " << bbname << ");";
1317 nl(Out) << iName << "->reserveOperandSpace("
1318 << phi->getNumIncomingValues()
1321 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1322 Out << iName << "->addIncoming("
1323 << opNames[i] << ", " << opNames[i+1] << ");";
1328 case Instruction::Trunc:
1329 case Instruction::ZExt:
1330 case Instruction::SExt:
1331 case Instruction::FPTrunc:
1332 case Instruction::FPExt:
1333 case Instruction::FPToUI:
1334 case Instruction::FPToSI:
1335 case Instruction::UIToFP:
1336 case Instruction::SIToFP:
1337 case Instruction::PtrToInt:
1338 case Instruction::IntToPtr:
1339 case Instruction::BitCast: {
1340 const CastInst* cst = cast<CastInst>(I);
1341 Out << "CastInst* " << iName << " = new ";
1342 switch (I->getOpcode()) {
1343 case Instruction::Trunc: Out << "TruncInst"; break;
1344 case Instruction::ZExt: Out << "ZExtInst"; break;
1345 case Instruction::SExt: Out << "SExtInst"; break;
1346 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1347 case Instruction::FPExt: Out << "FPExtInst"; break;
1348 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1349 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1350 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1351 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1352 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1353 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1354 case Instruction::BitCast: Out << "BitCastInst"; break;
1355 default: assert(!"Unreachable"); break;
1357 Out << "(" << opNames[0] << ", "
1358 << getCppName(cst->getType()) << ", \"";
1359 printEscapedString(cst->getName());
1360 Out << "\", " << bbname << ");";
1363 case Instruction::Call:{
1364 const CallInst* call = cast<CallInst>(I);
1365 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1366 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1367 << getCppName(ila->getFunctionType()) << ", \""
1368 << ila->getAsmString() << "\", \""
1369 << ila->getConstraintString() << "\","
1370 << (ila->hasSideEffects() ? "true" : "false") << ");";
1373 if (call->getNumOperands() > 2) {
1374 Out << "std::vector<Value*> " << iName << "_params;";
1376 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1377 Out << iName << "_params.push_back(" << opNames[i] << ");";
1380 Out << "CallInst* " << iName << " = CallInst::Create("
1381 << opNames[0] << ", " << iName << "_params.begin(), "
1382 << iName << "_params.end(), \"";
1383 } else if (call->getNumOperands() == 2) {
1384 Out << "CallInst* " << iName << " = CallInst::Create("
1385 << opNames[0] << ", " << opNames[1] << ", \"";
1387 Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
1390 printEscapedString(call->getName());
1391 Out << "\", " << bbname << ");";
1392 nl(Out) << iName << "->setCallingConv(";
1393 printCallingConv(call->getCallingConv());
1395 nl(Out) << iName << "->setTailCall("
1396 << (call->isTailCall() ? "true":"false");
1398 printAttributes(call->getAttributes(), iName);
1399 Out << iName << "->setAttributes(" << iName << "_PAL);";
1403 case Instruction::Select: {
1404 const SelectInst* sel = cast<SelectInst>(I);
1405 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1406 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1407 printEscapedString(sel->getName());
1408 Out << "\", " << bbname << ");";
1411 case Instruction::UserOp1:
1413 case Instruction::UserOp2: {
1414 /// FIXME: What should be done here?
1417 case Instruction::VAArg: {
1418 const VAArgInst* va = cast<VAArgInst>(I);
1419 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1420 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1421 printEscapedString(va->getName());
1422 Out << "\", " << bbname << ");";
1425 case Instruction::ExtractElement: {
1426 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1427 Out << "ExtractElementInst* " << getCppName(eei)
1428 << " = new ExtractElementInst(" << opNames[0]
1429 << ", " << opNames[1] << ", \"";
1430 printEscapedString(eei->getName());
1431 Out << "\", " << bbname << ");";
1434 case Instruction::InsertElement: {
1435 const InsertElementInst* iei = cast<InsertElementInst>(I);
1436 Out << "InsertElementInst* " << getCppName(iei)
1437 << " = InsertElementInst::Create(" << opNames[0]
1438 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1439 printEscapedString(iei->getName());
1440 Out << "\", " << bbname << ");";
1443 case Instruction::ShuffleVector: {
1444 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1445 Out << "ShuffleVectorInst* " << getCppName(svi)
1446 << " = new ShuffleVectorInst(" << opNames[0]
1447 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1448 printEscapedString(svi->getName());
1449 Out << "\", " << bbname << ");";
1452 case Instruction::ExtractValue: {
1453 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1454 Out << "std::vector<unsigned> " << iName << "_indices;";
1456 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1457 Out << iName << "_indices.push_back("
1458 << evi->idx_begin()[i] << ");";
1461 Out << "ExtractValueInst* " << getCppName(evi)
1462 << " = ExtractValueInst::Create(" << opNames[0]
1464 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1465 printEscapedString(evi->getName());
1466 Out << "\", " << bbname << ");";
1469 case Instruction::InsertValue: {
1470 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1471 Out << "std::vector<unsigned> " << iName << "_indices;";
1473 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1474 Out << iName << "_indices.push_back("
1475 << ivi->idx_begin()[i] << ");";
1478 Out << "InsertValueInst* " << getCppName(ivi)
1479 << " = InsertValueInst::Create(" << opNames[0]
1480 << ", " << opNames[1] << ", "
1481 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1482 printEscapedString(ivi->getName());
1483 Out << "\", " << bbname << ");";
1487 DefinedValues.insert(I);
1492 // Print out the types, constants and declarations needed by one function
1493 void CppWriter::printFunctionUses(const Function* F) {
1494 nl(Out) << "// Type Definitions"; nl(Out);
1496 // Print the function's return type
1497 printType(F->getReturnType());
1499 // Print the function's function type
1500 printType(F->getFunctionType());
1502 // Print the types of each of the function's arguments
1503 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1505 printType(AI->getType());
1509 // Print type definitions for every type referenced by an instruction and
1510 // make a note of any global values or constants that are referenced
1511 SmallPtrSet<GlobalValue*,64> gvs;
1512 SmallPtrSet<Constant*,64> consts;
1513 for (Function::const_iterator BB = F->begin(), BE = F->end();
1515 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1517 // Print the type of the instruction itself
1518 printType(I->getType());
1520 // Print the type of each of the instruction's operands
1521 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1522 Value* operand = I->getOperand(i);
1523 printType(operand->getType());
1525 // If the operand references a GVal or Constant, make a note of it
1526 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1528 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1529 if (GVar->hasInitializer())
1530 consts.insert(GVar->getInitializer());
1531 } else if (Constant* C = dyn_cast<Constant>(operand))
1537 // Print the function declarations for any functions encountered
1538 nl(Out) << "// Function Declarations"; nl(Out);
1539 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1541 if (Function* Fun = dyn_cast<Function>(*I)) {
1542 if (!is_inline || Fun != F)
1543 printFunctionHead(Fun);
1547 // Print the global variable declarations for any variables encountered
1548 nl(Out) << "// Global Variable Declarations"; nl(Out);
1549 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1551 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1552 printVariableHead(F);
1555 // Print the constants found
1556 nl(Out) << "// Constant Definitions"; nl(Out);
1557 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1558 E = consts.end(); I != E; ++I) {
1562 // Process the global variables definitions now that all the constants have
1563 // been emitted. These definitions just couple the gvars with their constant
1565 nl(Out) << "// Global Variable Definitions"; nl(Out);
1566 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1568 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1569 printVariableBody(GV);
1573 void CppWriter::printFunctionHead(const Function* F) {
1574 nl(Out) << "Function* " << getCppName(F);
1576 Out << " = mod->getFunction(\"";
1577 printEscapedString(F->getName());
1578 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1579 nl(Out) << "if (!" << getCppName(F) << ") {";
1580 nl(Out) << getCppName(F);
1582 Out<< " = Function::Create(";
1583 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1584 nl(Out) << "/*Linkage=*/";
1585 printLinkageType(F->getLinkage());
1587 nl(Out) << "/*Name=*/\"";
1588 printEscapedString(F->getName());
1589 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1592 Out << "->setCallingConv(";
1593 printCallingConv(F->getCallingConv());
1596 if (F->hasSection()) {
1598 Out << "->setSection(\"" << F->getSection() << "\");";
1601 if (F->getAlignment()) {
1603 Out << "->setAlignment(" << F->getAlignment() << ");";
1606 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1608 Out << "->setVisibility(";
1609 printVisibilityType(F->getVisibility());
1615 Out << "->setGC(\"" << F->getGC() << "\");";
1622 printAttributes(F->getAttributes(), getCppName(F));
1624 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1628 void CppWriter::printFunctionBody(const Function *F) {
1629 if (F->isDeclaration())
1630 return; // external functions have no bodies.
1632 // Clear the DefinedValues and ForwardRefs maps because we can't have
1633 // cross-function forward refs
1634 ForwardRefs.clear();
1635 DefinedValues.clear();
1637 // Create all the argument values
1639 if (!F->arg_empty()) {
1640 Out << "Function::arg_iterator args = " << getCppName(F)
1641 << "->arg_begin();";
1644 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1646 Out << "Value* " << getCppName(AI) << " = args++;";
1648 if (AI->hasName()) {
1649 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1655 // Create all the basic blocks
1657 for (Function::const_iterator BI = F->begin(), BE = F->end();
1659 std::string bbname(getCppName(BI));
1660 Out << "BasicBlock* " << bbname << " = BasicBlock::Create(\"";
1662 printEscapedString(BI->getName());
1663 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1667 // Output all of its basic blocks... for the function
1668 for (Function::const_iterator BI = F->begin(), BE = F->end();
1670 std::string bbname(getCppName(BI));
1671 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1674 // Output all of the instructions in the basic block...
1675 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1677 printInstruction(I,bbname);
1681 // Loop over the ForwardRefs and resolve them now that all instructions
1683 if (!ForwardRefs.empty()) {
1684 nl(Out) << "// Resolve Forward References";
1688 while (!ForwardRefs.empty()) {
1689 ForwardRefMap::iterator I = ForwardRefs.begin();
1690 Out << I->second << "->replaceAllUsesWith("
1691 << getCppName(I->first) << "); delete " << I->second << ";";
1693 ForwardRefs.erase(I);
1697 void CppWriter::printInline(const std::string& fname,
1698 const std::string& func) {
1699 const Function* F = TheModule->getFunction(func);
1701 error(std::string("Function '") + func + "' not found in input module");
1704 if (F->isDeclaration()) {
1705 error(std::string("Function '") + func + "' is external!");
1708 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1710 unsigned arg_count = 1;
1711 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1713 Out << ", Value* arg_" << arg_count;
1718 printFunctionUses(F);
1719 printFunctionBody(F);
1721 Out << "return " << getCppName(F->begin()) << ";";
1726 void CppWriter::printModuleBody() {
1727 // Print out all the type definitions
1728 nl(Out) << "// Type Definitions"; nl(Out);
1729 printTypes(TheModule);
1731 // Functions can call each other and global variables can reference them so
1732 // define all the functions first before emitting their function bodies.
1733 nl(Out) << "// Function Declarations"; nl(Out);
1734 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1736 printFunctionHead(I);
1738 // Process the global variables declarations. We can't initialze them until
1739 // after the constants are printed so just print a header for each global
1740 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1741 for (Module::const_global_iterator I = TheModule->global_begin(),
1742 E = TheModule->global_end(); I != E; ++I) {
1743 printVariableHead(I);
1746 // Print out all the constants definitions. Constants don't recurse except
1747 // through GlobalValues. All GlobalValues have been declared at this point
1748 // so we can proceed to generate the constants.
1749 nl(Out) << "// Constant Definitions"; nl(Out);
1750 printConstants(TheModule);
1752 // Process the global variables definitions now that all the constants have
1753 // been emitted. These definitions just couple the gvars with their constant
1755 nl(Out) << "// Global Variable Definitions"; nl(Out);
1756 for (Module::const_global_iterator I = TheModule->global_begin(),
1757 E = TheModule->global_end(); I != E; ++I) {
1758 printVariableBody(I);
1761 // Finally, we can safely put out all of the function bodies.
1762 nl(Out) << "// Function Definitions"; nl(Out);
1763 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1765 if (!I->isDeclaration()) {
1766 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1770 printFunctionBody(I);
1777 void CppWriter::printProgram(const std::string& fname,
1778 const std::string& mName) {
1779 Out << "#include <llvm/Module.h>\n";
1780 Out << "#include <llvm/DerivedTypes.h>\n";
1781 Out << "#include <llvm/Constants.h>\n";
1782 Out << "#include <llvm/GlobalVariable.h>\n";
1783 Out << "#include <llvm/Function.h>\n";
1784 Out << "#include <llvm/CallingConv.h>\n";
1785 Out << "#include <llvm/BasicBlock.h>\n";
1786 Out << "#include <llvm/Instructions.h>\n";
1787 Out << "#include <llvm/InlineAsm.h>\n";
1788 Out << "#include <llvm/Support/MathExtras.h>\n";
1789 Out << "#include <llvm/Support/raw_ostream.h>\n";
1790 Out << "#include <llvm/Pass.h>\n";
1791 Out << "#include <llvm/PassManager.h>\n";
1792 Out << "#include <llvm/ADT/SmallVector.h>\n";
1793 Out << "#include <llvm/Analysis/Verifier.h>\n";
1794 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1795 Out << "#include <algorithm>\n";
1796 Out << "using namespace llvm;\n\n";
1797 Out << "Module* " << fname << "();\n\n";
1798 Out << "int main(int argc, char**argv) {\n";
1799 Out << " Module* Mod = " << fname << "();\n";
1800 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1801 Out << " errs().flush();\n";
1802 Out << " outs().flush();\n";
1803 Out << " PassManager PM;\n";
1804 Out << " PM.add(createPrintModulePass(&outs()));\n";
1805 Out << " PM.run(*Mod);\n";
1806 Out << " return 0;\n";
1808 printModule(fname,mName);
1811 void CppWriter::printModule(const std::string& fname,
1812 const std::string& mName) {
1813 nl(Out) << "Module* " << fname << "() {";
1814 nl(Out,1) << "// Module Construction";
1815 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1816 if (!TheModule->getTargetTriple().empty()) {
1817 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1819 if (!TheModule->getTargetTriple().empty()) {
1820 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1824 if (!TheModule->getModuleInlineAsm().empty()) {
1825 nl(Out) << "mod->setModuleInlineAsm(\"";
1826 printEscapedString(TheModule->getModuleInlineAsm());
1831 // Loop over the dependent libraries and emit them.
1832 Module::lib_iterator LI = TheModule->lib_begin();
1833 Module::lib_iterator LE = TheModule->lib_end();
1835 Out << "mod->addLibrary(\"" << *LI << "\");";
1840 nl(Out) << "return mod;";
1845 void CppWriter::printContents(const std::string& fname,
1846 const std::string& mName) {
1847 Out << "\nModule* " << fname << "(Module *mod) {\n";
1848 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1850 Out << "\nreturn mod;\n";
1854 void CppWriter::printFunction(const std::string& fname,
1855 const std::string& funcName) {
1856 const Function* F = TheModule->getFunction(funcName);
1858 error(std::string("Function '") + funcName + "' not found in input module");
1861 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1862 printFunctionUses(F);
1863 printFunctionHead(F);
1864 printFunctionBody(F);
1865 Out << "return " << getCppName(F) << ";\n";
1869 void CppWriter::printFunctions() {
1870 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1871 Module::const_iterator I = funcs.begin();
1872 Module::const_iterator IE = funcs.end();
1874 for (; I != IE; ++I) {
1875 const Function &func = *I;
1876 if (!func.isDeclaration()) {
1877 std::string name("define_");
1878 name += func.getName();
1879 printFunction(name, func.getName());
1884 void CppWriter::printVariable(const std::string& fname,
1885 const std::string& varName) {
1886 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1889 error(std::string("Variable '") + varName + "' not found in input module");
1892 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1893 printVariableUses(GV);
1894 printVariableHead(GV);
1895 printVariableBody(GV);
1896 Out << "return " << getCppName(GV) << ";\n";
1900 void CppWriter::printType(const std::string& fname,
1901 const std::string& typeName) {
1902 const Type* Ty = TheModule->getTypeByName(typeName);
1904 error(std::string("Type '") + typeName + "' not found in input module");
1907 Out << "\nType* " << fname << "(Module *mod) {\n";
1909 Out << "return " << getCppName(Ty) << ";\n";
1913 bool CppWriter::runOnModule(Module &M) {
1917 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1919 // Get the name of the function we're supposed to generate
1920 std::string fname = FuncName.getValue();
1922 // Get the name of the thing we are to generate
1923 std::string tgtname = NameToGenerate.getValue();
1924 if (GenerationType == GenModule ||
1925 GenerationType == GenContents ||
1926 GenerationType == GenProgram ||
1927 GenerationType == GenFunctions) {
1928 if (tgtname == "!bad!") {
1929 if (M.getModuleIdentifier() == "-")
1930 tgtname = "<stdin>";
1932 tgtname = M.getModuleIdentifier();
1934 } else if (tgtname == "!bad!")
1935 error("You must use the -for option with -gen-{function,variable,type}");
1937 switch (WhatToGenerate(GenerationType)) {
1940 fname = "makeLLVMModule";
1941 printProgram(fname,tgtname);
1945 fname = "makeLLVMModule";
1946 printModule(fname,tgtname);
1950 fname = "makeLLVMModuleContents";
1951 printContents(fname,tgtname);
1955 fname = "makeLLVMFunction";
1956 printFunction(fname,tgtname);
1963 fname = "makeLLVMInline";
1964 printInline(fname,tgtname);
1968 fname = "makeLLVMVariable";
1969 printVariable(fname,tgtname);
1973 fname = "makeLLVMType";
1974 printType(fname,tgtname);
1977 error("Invalid generation option");
1984 char CppWriter::ID = 0;
1986 //===----------------------------------------------------------------------===//
1987 // External Interface declaration
1988 //===----------------------------------------------------------------------===//
1990 bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
1992 CodeGenFileType FileType,
1994 if (FileType != TargetMachine::AssemblyFile) return true;
1995 PM.add(new CppWriter(o));