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/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCInstrInfo.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Target/TargetRegistry.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/Config/config.h"
40 static cl::opt<std::string>
41 FuncName("cppfname", cl::desc("Specify the name of the generated function"),
42 cl::value_desc("function name"));
55 static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
56 cl::desc("Choose what kind of output to generate"),
59 clEnumValN(GenProgram, "program", "Generate a complete program"),
60 clEnumValN(GenModule, "module", "Generate a module definition"),
61 clEnumValN(GenContents, "contents", "Generate contents of a module"),
62 clEnumValN(GenFunction, "function", "Generate a function definition"),
63 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
64 clEnumValN(GenInline, "inline", "Generate an inline function"),
65 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
66 clEnumValN(GenType, "type", "Generate a type definition"),
71 static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
72 cl::desc("Specify the name of the thing to generate"),
75 extern "C" void LLVMInitializeCppBackendTarget() {
76 // Register the target.
77 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
80 extern "C" void LLVMInitializeCppBackendTargetMC() {}
83 typedef std::vector<Type*> TypeList;
84 typedef std::map<Type*,std::string> TypeMap;
85 typedef std::map<const Value*,std::string> ValueMap;
86 typedef std::set<std::string> NameSet;
87 typedef std::set<Type*> TypeSet;
88 typedef std::set<const Value*> ValueSet;
89 typedef std::map<const Value*,std::string> ForwardRefMap;
91 /// CppWriter - This class is the main chunk of code that converts an LLVM
92 /// module to a C++ translation unit.
93 class CppWriter : public ModulePass {
94 formatted_raw_ostream &Out;
95 const Module *TheModule;
100 TypeSet DefinedTypes;
101 ValueSet DefinedValues;
102 ForwardRefMap ForwardRefs;
104 unsigned indent_level;
108 explicit CppWriter(formatted_raw_ostream &o) :
109 ModulePass(ID), Out(o), uniqueNum(0), is_inline(false), indent_level(0){}
111 virtual const char *getPassName() const { return "C++ backend"; }
113 bool runOnModule(Module &M);
115 void printProgram(const std::string& fname, const std::string& modName );
116 void printModule(const std::string& fname, const std::string& modName );
117 void printContents(const std::string& fname, const std::string& modName );
118 void printFunction(const std::string& fname, const std::string& funcName );
119 void printFunctions();
120 void printInline(const std::string& fname, const std::string& funcName );
121 void printVariable(const std::string& fname, const std::string& varName );
122 void printType(const std::string& fname, const std::string& typeName );
124 void error(const std::string& msg);
127 formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0);
128 inline void in() { indent_level++; }
129 inline void out() { if (indent_level >0) indent_level--; }
132 void printLinkageType(GlobalValue::LinkageTypes LT);
133 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
134 void printCallingConv(CallingConv::ID cc);
135 void printEscapedString(const std::string& str);
136 void printCFP(const ConstantFP* CFP);
138 std::string getCppName(Type* val);
139 inline void printCppName(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 void printType(Type* Ty);
146 void printTypes(const Module* M);
148 void printConstant(const Constant *CPV);
149 void printConstants(const Module* M);
151 void printVariableUses(const GlobalVariable *GV);
152 void printVariableHead(const GlobalVariable *GV);
153 void printVariableBody(const GlobalVariable *GV);
155 void printFunctionUses(const Function *F);
156 void printFunctionHead(const Function *F);
157 void printFunctionBody(const Function *F);
158 void printInstruction(const Instruction *I, const std::string& bbname);
159 std::string getOpName(Value*);
161 void printModuleBody();
163 } // end anonymous namespace.
165 formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
167 if (delta >= 0 || indent_level >= unsigned(-delta))
168 indent_level += delta;
169 Out.indent(indent_level);
173 static inline void sanitize(std::string &str) {
174 for (size_t i = 0; i < str.length(); ++i)
175 if (!isalnum(str[i]) && str[i] != '_')
179 static std::string getTypePrefix(Type *Ty) {
180 switch (Ty->getTypeID()) {
181 case Type::VoidTyID: return "void_";
182 case Type::IntegerTyID:
183 return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
184 case Type::FloatTyID: return "float_";
185 case Type::DoubleTyID: return "double_";
186 case Type::LabelTyID: return "label_";
187 case Type::FunctionTyID: return "func_";
188 case Type::StructTyID: return "struct_";
189 case Type::ArrayTyID: return "array_";
190 case Type::PointerTyID: return "ptr_";
191 case Type::VectorTyID: return "packed_";
192 default: return "other_";
197 void CppWriter::error(const std::string& msg) {
198 report_fatal_error(msg);
201 // printCFP - Print a floating point constant .. very carefully :)
202 // This makes sure that conversion to/from floating yields the same binary
203 // result so that we don't lose precision.
204 void CppWriter::printCFP(const ConstantFP *CFP) {
206 APFloat APF = APFloat(CFP->getValueAPF()); // copy
207 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
208 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
209 Out << "ConstantFP::get(mod->getContext(), ";
213 sprintf(Buffer, "%A", APF.convertToDouble());
214 if ((!strncmp(Buffer, "0x", 2) ||
215 !strncmp(Buffer, "-0x", 3) ||
216 !strncmp(Buffer, "+0x", 3)) &&
217 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
218 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
219 Out << "BitsToDouble(" << Buffer << ")";
221 Out << "BitsToFloat((float)" << Buffer << ")";
225 std::string StrVal = ftostr(CFP->getValueAPF());
227 while (StrVal[0] == ' ')
228 StrVal.erase(StrVal.begin());
230 // Check to make sure that the stringized number is not some string like
231 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
232 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
233 ((StrVal[0] == '-' || StrVal[0] == '+') &&
234 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
235 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
236 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
239 Out << StrVal << "f";
240 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
241 Out << "BitsToDouble(0x"
242 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
243 << "ULL) /* " << StrVal << " */";
245 Out << "BitsToFloat(0x"
246 << utohexstr((uint32_t)CFP->getValueAPF().
247 bitcastToAPInt().getZExtValue())
248 << "U) /* " << StrVal << " */";
256 void CppWriter::printCallingConv(CallingConv::ID cc){
257 // Print the calling convention.
259 case CallingConv::C: Out << "CallingConv::C"; break;
260 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
261 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
262 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
263 default: Out << cc; break;
267 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
269 case GlobalValue::InternalLinkage:
270 Out << "GlobalValue::InternalLinkage"; break;
271 case GlobalValue::PrivateLinkage:
272 Out << "GlobalValue::PrivateLinkage"; break;
273 case GlobalValue::LinkerPrivateLinkage:
274 Out << "GlobalValue::LinkerPrivateLinkage"; break;
275 case GlobalValue::LinkerPrivateWeakLinkage:
276 Out << "GlobalValue::LinkerPrivateWeakLinkage"; break;
277 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
278 Out << "GlobalValue::LinkerPrivateWeakDefAutoLinkage"; break;
279 case GlobalValue::AvailableExternallyLinkage:
280 Out << "GlobalValue::AvailableExternallyLinkage "; break;
281 case GlobalValue::LinkOnceAnyLinkage:
282 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
283 case GlobalValue::LinkOnceODRLinkage:
284 Out << "GlobalValue::LinkOnceODRLinkage "; break;
285 case GlobalValue::WeakAnyLinkage:
286 Out << "GlobalValue::WeakAnyLinkage"; break;
287 case GlobalValue::WeakODRLinkage:
288 Out << "GlobalValue::WeakODRLinkage"; break;
289 case GlobalValue::AppendingLinkage:
290 Out << "GlobalValue::AppendingLinkage"; break;
291 case GlobalValue::ExternalLinkage:
292 Out << "GlobalValue::ExternalLinkage"; break;
293 case GlobalValue::DLLImportLinkage:
294 Out << "GlobalValue::DLLImportLinkage"; break;
295 case GlobalValue::DLLExportLinkage:
296 Out << "GlobalValue::DLLExportLinkage"; break;
297 case GlobalValue::ExternalWeakLinkage:
298 Out << "GlobalValue::ExternalWeakLinkage"; break;
299 case GlobalValue::CommonLinkage:
300 Out << "GlobalValue::CommonLinkage"; break;
304 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
306 default: llvm_unreachable("Unknown GVar visibility");
307 case GlobalValue::DefaultVisibility:
308 Out << "GlobalValue::DefaultVisibility";
310 case GlobalValue::HiddenVisibility:
311 Out << "GlobalValue::HiddenVisibility";
313 case GlobalValue::ProtectedVisibility:
314 Out << "GlobalValue::ProtectedVisibility";
319 // printEscapedString - Print each character of the specified string, escaping
320 // it if it is not printable or if it is an escape char.
321 void CppWriter::printEscapedString(const std::string &Str) {
322 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
323 unsigned char C = Str[i];
324 if (isprint(C) && C != '"' && C != '\\') {
328 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
329 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
334 std::string CppWriter::getCppName(Type* Ty) {
335 // First, handle the primitive types .. easy
336 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
337 switch (Ty->getTypeID()) {
338 case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())";
339 case Type::IntegerTyID: {
340 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
341 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
343 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
344 case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())";
345 case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())";
346 case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())";
347 case Type::X86_MMXTyID: return "Type::getX86_MMXTy(mod->getContext())";
349 error("Invalid primitive type");
352 // shouldn't be returned, but make it sensible
353 return "Type::getVoidTy(mod->getContext())";
356 // Now, see if we've seen the type before and return that
357 TypeMap::iterator I = TypeNames.find(Ty);
358 if (I != TypeNames.end())
361 // Okay, let's build a new name for this type. Start with a prefix
362 const char* prefix = 0;
363 switch (Ty->getTypeID()) {
364 case Type::FunctionTyID: prefix = "FuncTy_"; break;
365 case Type::StructTyID: prefix = "StructTy_"; break;
366 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
367 case Type::PointerTyID: prefix = "PointerTy_"; break;
368 case Type::VectorTyID: prefix = "VectorTy_"; break;
369 default: prefix = "OtherTy_"; break; // prevent breakage
372 // See if the type has a name in the symboltable and build accordingly
374 if (StructType *STy = dyn_cast<StructType>(Ty))
376 name = STy->getName();
379 name = utostr(uniqueNum++);
381 name = std::string(prefix) + name;
385 return TypeNames[Ty] = name;
388 void CppWriter::printCppName(Type* Ty) {
389 printEscapedString(getCppName(Ty));
392 std::string CppWriter::getCppName(const Value* val) {
394 ValueMap::iterator I = ValueNames.find(val);
395 if (I != ValueNames.end() && I->first == val)
398 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
399 name = std::string("gvar_") +
400 getTypePrefix(GV->getType()->getElementType());
401 } else if (isa<Function>(val)) {
402 name = std::string("func_");
403 } else if (const Constant* C = dyn_cast<Constant>(val)) {
404 name = std::string("const_") + getTypePrefix(C->getType());
405 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
407 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
408 Function::const_arg_iterator(Arg)) + 1;
409 name = std::string("arg_") + utostr(argNum);
410 NameSet::iterator NI = UsedNames.find(name);
411 if (NI != UsedNames.end())
412 name += std::string("_") + utostr(uniqueNum++);
413 UsedNames.insert(name);
414 return ValueNames[val] = name;
416 name = getTypePrefix(val->getType());
419 name = getTypePrefix(val->getType());
422 name += val->getName();
424 name += utostr(uniqueNum++);
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;
433 void CppWriter::printCppName(const Value* val) {
434 printEscapedString(getCppName(val));
437 void CppWriter::printAttributes(const AttrListPtr &PAL,
438 const std::string &name) {
439 Out << "AttrListPtr " << name << "_PAL;";
441 if (!PAL.isEmpty()) {
442 Out << '{'; in(); nl(Out);
443 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
444 Out << "AttributeWithIndex PAWI;"; nl(Out);
445 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
446 unsigned index = PAL.getSlot(i).Index;
447 Attributes attrs = PAL.getSlot(i).Attrs;
448 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
449 #define HANDLE_ATTR(X) \
450 if (attrs & Attribute::X) \
451 Out << " | Attribute::" #X; \
452 attrs &= ~Attribute::X;
456 HANDLE_ATTR(NoReturn);
458 HANDLE_ATTR(StructRet);
459 HANDLE_ATTR(NoUnwind);
460 HANDLE_ATTR(NoAlias);
463 HANDLE_ATTR(ReadNone);
464 HANDLE_ATTR(ReadOnly);
465 HANDLE_ATTR(NoInline);
466 HANDLE_ATTR(AlwaysInline);
467 HANDLE_ATTR(OptimizeForSize);
468 HANDLE_ATTR(StackProtect);
469 HANDLE_ATTR(StackProtectReq);
470 HANDLE_ATTR(NoCapture);
471 HANDLE_ATTR(NoRedZone);
472 HANDLE_ATTR(NoImplicitFloat);
474 HANDLE_ATTR(InlineHint);
476 if (attrs & Attribute::StackAlignment)
477 Out << " | Attribute::constructStackAlignmentFromInt("
478 << Attribute::getStackAlignmentFromAttrs(attrs)
480 attrs &= ~Attribute::StackAlignment;
481 assert(attrs == 0 && "Unhandled attribute!");
484 Out << "Attrs.push_back(PAWI);";
487 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
494 void CppWriter::printType(Type* Ty) {
495 // We don't print definitions for primitive types
496 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
499 // If we already defined this type, we don't need to define it again.
500 if (DefinedTypes.find(Ty) != DefinedTypes.end())
503 // Everything below needs the name for the type so get it now.
504 std::string typeName(getCppName(Ty));
506 // Print the type definition
507 switch (Ty->getTypeID()) {
508 case Type::FunctionTyID: {
509 FunctionType* FT = cast<FunctionType>(Ty);
510 Out << "std::vector<Type*>" << typeName << "_args;";
512 FunctionType::param_iterator PI = FT->param_begin();
513 FunctionType::param_iterator PE = FT->param_end();
514 for (; PI != PE; ++PI) {
515 Type* argTy = static_cast<Type*>(*PI);
517 std::string argName(getCppName(argTy));
518 Out << typeName << "_args.push_back(" << argName;
522 printType(FT->getReturnType());
523 std::string retTypeName(getCppName(FT->getReturnType()));
524 Out << "FunctionType* " << typeName << " = FunctionType::get(";
525 in(); nl(Out) << "/*Result=*/" << retTypeName;
527 nl(Out) << "/*Params=*/" << typeName << "_args,";
528 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
533 case Type::StructTyID: {
534 StructType* ST = cast<StructType>(Ty);
535 if (!ST->isAnonymous()) {
536 Out << "StructType *" << typeName << " = ";
537 Out << "StructType::createNamed(mod->getContext(), \"";
538 printEscapedString(ST->getName());
541 // Indicate that this type is now defined.
542 DefinedTypes.insert(Ty);
545 Out << "std::vector<Type*>" << typeName << "_fields;";
547 StructType::element_iterator EI = ST->element_begin();
548 StructType::element_iterator EE = ST->element_end();
549 for (; EI != EE; ++EI) {
550 Type* fieldTy = static_cast<Type*>(*EI);
552 std::string fieldName(getCppName(fieldTy));
553 Out << typeName << "_fields.push_back(" << fieldName;
558 if (ST->isAnonymous()) {
559 Out << "StructType *" << typeName << " = ";
560 Out << "StructType::get(" << "mod->getContext(), ";
562 Out << typeName << "->setBody(";
565 Out << typeName << "_fields, /*isPacked=*/"
566 << (ST->isPacked() ? "true" : "false") << ");";
570 case Type::ArrayTyID: {
571 ArrayType* AT = cast<ArrayType>(Ty);
572 Type* ET = AT->getElementType();
574 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
575 std::string elemName(getCppName(ET));
576 Out << "ArrayType* " << typeName << " = ArrayType::get("
578 << ", " << utostr(AT->getNumElements()) << ");";
583 case Type::PointerTyID: {
584 PointerType* PT = cast<PointerType>(Ty);
585 Type* ET = PT->getElementType();
587 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
588 std::string elemName(getCppName(ET));
589 Out << "PointerType* " << typeName << " = PointerType::get("
591 << ", " << utostr(PT->getAddressSpace()) << ");";
596 case Type::VectorTyID: {
597 VectorType* PT = cast<VectorType>(Ty);
598 Type* ET = PT->getElementType();
600 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
601 std::string elemName(getCppName(ET));
602 Out << "VectorType* " << typeName << " = VectorType::get("
604 << ", " << utostr(PT->getNumElements()) << ");";
610 error("Invalid TypeID");
613 // Indicate that this type is now defined.
614 DefinedTypes.insert(Ty);
616 // Finally, separate the type definition from other with a newline.
620 void CppWriter::printTypes(const Module* M) {
621 // Add all of the global variables to the value table.
622 for (Module::const_global_iterator I = TheModule->global_begin(),
623 E = TheModule->global_end(); I != E; ++I) {
624 if (I->hasInitializer())
625 printType(I->getInitializer()->getType());
626 printType(I->getType());
629 // Add all the functions to the table
630 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
632 printType(FI->getReturnType());
633 printType(FI->getFunctionType());
634 // Add all the function arguments
635 for (Function::const_arg_iterator AI = FI->arg_begin(),
636 AE = FI->arg_end(); AI != AE; ++AI) {
637 printType(AI->getType());
640 // Add all of the basic blocks and instructions
641 for (Function::const_iterator BB = FI->begin(),
642 E = FI->end(); BB != E; ++BB) {
643 printType(BB->getType());
644 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
646 printType(I->getType());
647 for (unsigned i = 0; i < I->getNumOperands(); ++i)
648 printType(I->getOperand(i)->getType());
655 // printConstant - Print out a constant pool entry...
656 void CppWriter::printConstant(const Constant *CV) {
657 // First, if the constant is actually a GlobalValue (variable or function)
658 // or its already in the constant list then we've printed it already and we
660 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
663 std::string constName(getCppName(CV));
664 std::string typeName(getCppName(CV->getType()));
666 if (isa<GlobalValue>(CV)) {
667 // Skip variables and functions, we emit them elsewhere
671 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
672 std::string constValue = CI->getValue().toString(10, true);
673 Out << "ConstantInt* " << constName
674 << " = ConstantInt::get(mod->getContext(), APInt("
675 << cast<IntegerType>(CI->getType())->getBitWidth()
676 << ", StringRef(\"" << constValue << "\"), 10));";
677 } else if (isa<ConstantAggregateZero>(CV)) {
678 Out << "ConstantAggregateZero* " << constName
679 << " = ConstantAggregateZero::get(" << typeName << ");";
680 } else if (isa<ConstantPointerNull>(CV)) {
681 Out << "ConstantPointerNull* " << constName
682 << " = ConstantPointerNull::get(" << typeName << ");";
683 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
684 Out << "ConstantFP* " << constName << " = ";
687 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
688 if (CA->isString() &&
689 CA->getType()->getElementType() ==
690 Type::getInt8Ty(CA->getContext())) {
691 Out << "Constant* " << constName <<
692 " = ConstantArray::get(mod->getContext(), \"";
693 std::string tmp = CA->getAsString();
694 bool nullTerminate = false;
695 if (tmp[tmp.length()-1] == 0) {
696 tmp.erase(tmp.length()-1);
697 nullTerminate = true;
699 printEscapedString(tmp);
700 // Determine if we want null termination or not.
702 Out << "\", true"; // Indicate that the null terminator should be
705 Out << "\", false";// No null terminator
708 Out << "std::vector<Constant*> " << constName << "_elems;";
710 unsigned N = CA->getNumOperands();
711 for (unsigned i = 0; i < N; ++i) {
712 printConstant(CA->getOperand(i)); // recurse to print operands
713 Out << constName << "_elems.push_back("
714 << getCppName(CA->getOperand(i)) << ");";
717 Out << "Constant* " << constName << " = ConstantArray::get("
718 << typeName << ", " << constName << "_elems);";
720 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
721 Out << "std::vector<Constant*> " << constName << "_fields;";
723 unsigned N = CS->getNumOperands();
724 for (unsigned i = 0; i < N; i++) {
725 printConstant(CS->getOperand(i));
726 Out << constName << "_fields.push_back("
727 << getCppName(CS->getOperand(i)) << ");";
730 Out << "Constant* " << constName << " = ConstantStruct::get("
731 << typeName << ", " << constName << "_fields);";
732 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
733 Out << "std::vector<Constant*> " << constName << "_elems;";
735 unsigned N = CP->getNumOperands();
736 for (unsigned i = 0; i < N; ++i) {
737 printConstant(CP->getOperand(i));
738 Out << constName << "_elems.push_back("
739 << getCppName(CP->getOperand(i)) << ");";
742 Out << "Constant* " << constName << " = ConstantVector::get("
743 << typeName << ", " << constName << "_elems);";
744 } else if (isa<UndefValue>(CV)) {
745 Out << "UndefValue* " << constName << " = UndefValue::get("
747 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
748 if (CE->getOpcode() == Instruction::GetElementPtr) {
749 Out << "std::vector<Constant*> " << constName << "_indices;";
751 printConstant(CE->getOperand(0));
752 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
753 printConstant(CE->getOperand(i));
754 Out << constName << "_indices.push_back("
755 << getCppName(CE->getOperand(i)) << ");";
758 Out << "Constant* " << constName
759 << " = ConstantExpr::getGetElementPtr("
760 << getCppName(CE->getOperand(0)) << ", "
761 << constName << "_indices);";
762 } else if (CE->isCast()) {
763 printConstant(CE->getOperand(0));
764 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
765 switch (CE->getOpcode()) {
766 default: llvm_unreachable("Invalid cast opcode");
767 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
768 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
769 case Instruction::SExt: Out << "Instruction::SExt"; break;
770 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
771 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
772 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
773 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
774 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
775 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
776 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
777 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
778 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
780 Out << ", " << getCppName(CE->getOperand(0)) << ", "
781 << getCppName(CE->getType()) << ");";
783 unsigned N = CE->getNumOperands();
784 for (unsigned i = 0; i < N; ++i ) {
785 printConstant(CE->getOperand(i));
787 Out << "Constant* " << constName << " = ConstantExpr::";
788 switch (CE->getOpcode()) {
789 case Instruction::Add: Out << "getAdd("; break;
790 case Instruction::FAdd: Out << "getFAdd("; break;
791 case Instruction::Sub: Out << "getSub("; break;
792 case Instruction::FSub: Out << "getFSub("; break;
793 case Instruction::Mul: Out << "getMul("; break;
794 case Instruction::FMul: Out << "getFMul("; break;
795 case Instruction::UDiv: Out << "getUDiv("; break;
796 case Instruction::SDiv: Out << "getSDiv("; break;
797 case Instruction::FDiv: Out << "getFDiv("; break;
798 case Instruction::URem: Out << "getURem("; break;
799 case Instruction::SRem: Out << "getSRem("; break;
800 case Instruction::FRem: Out << "getFRem("; break;
801 case Instruction::And: Out << "getAnd("; break;
802 case Instruction::Or: Out << "getOr("; break;
803 case Instruction::Xor: Out << "getXor("; break;
804 case Instruction::ICmp:
805 Out << "getICmp(ICmpInst::ICMP_";
806 switch (CE->getPredicate()) {
807 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
808 case ICmpInst::ICMP_NE: Out << "NE"; break;
809 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
810 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
811 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
812 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
813 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
814 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
815 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
816 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
817 default: error("Invalid ICmp Predicate");
820 case Instruction::FCmp:
821 Out << "getFCmp(FCmpInst::FCMP_";
822 switch (CE->getPredicate()) {
823 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
824 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
825 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
826 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
827 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
828 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
829 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
830 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
831 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
832 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
833 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
834 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
835 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
836 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
837 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
838 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
839 default: error("Invalid FCmp Predicate");
842 case Instruction::Shl: Out << "getShl("; break;
843 case Instruction::LShr: Out << "getLShr("; break;
844 case Instruction::AShr: Out << "getAShr("; break;
845 case Instruction::Select: Out << "getSelect("; break;
846 case Instruction::ExtractElement: Out << "getExtractElement("; break;
847 case Instruction::InsertElement: Out << "getInsertElement("; break;
848 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
850 error("Invalid constant expression");
853 Out << getCppName(CE->getOperand(0));
854 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
855 Out << ", " << getCppName(CE->getOperand(i));
858 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
859 Out << "Constant* " << constName << " = ";
860 Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
862 error("Bad Constant");
863 Out << "Constant* " << constName << " = 0; ";
868 void CppWriter::printConstants(const Module* M) {
869 // Traverse all the global variables looking for constant initializers
870 for (Module::const_global_iterator I = TheModule->global_begin(),
871 E = TheModule->global_end(); I != E; ++I)
872 if (I->hasInitializer())
873 printConstant(I->getInitializer());
875 // Traverse the LLVM functions looking for constants
876 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
878 // Add all of the basic blocks and instructions
879 for (Function::const_iterator BB = FI->begin(),
880 E = FI->end(); BB != E; ++BB) {
881 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
883 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
884 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
893 void CppWriter::printVariableUses(const GlobalVariable *GV) {
894 nl(Out) << "// Type Definitions";
896 printType(GV->getType());
897 if (GV->hasInitializer()) {
898 const Constant *Init = GV->getInitializer();
899 printType(Init->getType());
900 if (const Function *F = dyn_cast<Function>(Init)) {
901 nl(Out)<< "/ Function Declarations"; nl(Out);
902 printFunctionHead(F);
903 } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
904 nl(Out) << "// Global Variable Declarations"; nl(Out);
905 printVariableHead(gv);
907 nl(Out) << "// Global Variable Definitions"; nl(Out);
908 printVariableBody(gv);
910 nl(Out) << "// Constant Definitions"; nl(Out);
916 void CppWriter::printVariableHead(const GlobalVariable *GV) {
917 nl(Out) << "GlobalVariable* " << getCppName(GV);
919 Out << " = mod->getGlobalVariable(mod->getContext(), ";
920 printEscapedString(GV->getName());
921 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
922 nl(Out) << "if (!" << getCppName(GV) << ") {";
923 in(); nl(Out) << getCppName(GV);
925 Out << " = new GlobalVariable(/*Module=*/*mod, ";
926 nl(Out) << "/*Type=*/";
927 printCppName(GV->getType()->getElementType());
929 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
931 nl(Out) << "/*Linkage=*/";
932 printLinkageType(GV->getLinkage());
934 nl(Out) << "/*Initializer=*/0, ";
935 if (GV->hasInitializer()) {
936 Out << "// has initializer, specified below";
938 nl(Out) << "/*Name=*/\"";
939 printEscapedString(GV->getName());
943 if (GV->hasSection()) {
945 Out << "->setSection(\"";
946 printEscapedString(GV->getSection());
950 if (GV->getAlignment()) {
952 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
955 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
957 Out << "->setVisibility(";
958 printVisibilityType(GV->getVisibility());
962 if (GV->isThreadLocal()) {
964 Out << "->setThreadLocal(true);";
968 out(); Out << "}"; nl(Out);
972 void CppWriter::printVariableBody(const GlobalVariable *GV) {
973 if (GV->hasInitializer()) {
975 Out << "->setInitializer(";
976 Out << getCppName(GV->getInitializer()) << ");";
981 std::string CppWriter::getOpName(Value* V) {
982 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
983 return getCppName(V);
985 // See if its alread in the map of forward references, if so just return the
986 // name we already set up for it
987 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
988 if (I != ForwardRefs.end())
991 // This is a new forward reference. Generate a unique name for it
992 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
994 // Yes, this is a hack. An Argument is the smallest instantiable value that
995 // we can make as a placeholder for the real value. We'll replace these
996 // Argument instances later.
997 Out << "Argument* " << result << " = new Argument("
998 << getCppName(V->getType()) << ");";
1000 ForwardRefs[V] = result;
1004 // printInstruction - This member is called for each Instruction in a function.
1005 void CppWriter::printInstruction(const Instruction *I,
1006 const std::string& bbname) {
1007 std::string iName(getCppName(I));
1009 // Before we emit this instruction, we need to take care of generating any
1010 // forward references. So, we get the names of all the operands in advance
1011 const unsigned Ops(I->getNumOperands());
1012 std::string* opNames = new std::string[Ops];
1013 for (unsigned i = 0; i < Ops; i++)
1014 opNames[i] = getOpName(I->getOperand(i));
1016 switch (I->getOpcode()) {
1018 error("Invalid instruction");
1021 case Instruction::Ret: {
1022 const ReturnInst* ret = cast<ReturnInst>(I);
1023 Out << "ReturnInst::Create(mod->getContext(), "
1024 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1027 case Instruction::Br: {
1028 const BranchInst* br = cast<BranchInst>(I);
1029 Out << "BranchInst::Create(" ;
1030 if (br->getNumOperands() == 3) {
1031 Out << opNames[2] << ", "
1032 << opNames[1] << ", "
1033 << opNames[0] << ", ";
1035 } else if (br->getNumOperands() == 1) {
1036 Out << opNames[0] << ", ";
1038 error("Branch with 2 operands?");
1040 Out << bbname << ");";
1043 case Instruction::Switch: {
1044 const SwitchInst *SI = cast<SwitchInst>(I);
1045 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1046 << opNames[0] << ", "
1047 << opNames[1] << ", "
1048 << SI->getNumCases() << ", " << bbname << ");";
1050 for (unsigned i = 2; i != SI->getNumOperands(); i += 2) {
1051 Out << iName << "->addCase("
1052 << opNames[i] << ", "
1053 << opNames[i+1] << ");";
1058 case Instruction::IndirectBr: {
1059 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1060 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1061 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1063 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1064 Out << iName << "->addDestination(" << opNames[i] << ");";
1069 case Instruction::Invoke: {
1070 const InvokeInst* inv = cast<InvokeInst>(I);
1071 Out << "std::vector<Value*> " << iName << "_params;";
1073 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1074 Out << iName << "_params.push_back("
1075 << getOpName(inv->getArgOperand(i)) << ");";
1078 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1079 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1080 << getOpName(inv->getCalledFunction()) << ", "
1081 << getOpName(inv->getNormalDest()) << ", "
1082 << getOpName(inv->getUnwindDest()) << ", "
1083 << iName << "_params.begin(), "
1084 << iName << "_params.end(), \"";
1085 printEscapedString(inv->getName());
1086 Out << "\", " << bbname << ");";
1087 nl(Out) << iName << "->setCallingConv(";
1088 printCallingConv(inv->getCallingConv());
1090 printAttributes(inv->getAttributes(), iName);
1091 Out << iName << "->setAttributes(" << iName << "_PAL);";
1095 case Instruction::Unwind: {
1096 Out << "new UnwindInst("
1100 case Instruction::Unreachable: {
1101 Out << "new UnreachableInst("
1102 << "mod->getContext(), "
1106 case Instruction::Add:
1107 case Instruction::FAdd:
1108 case Instruction::Sub:
1109 case Instruction::FSub:
1110 case Instruction::Mul:
1111 case Instruction::FMul:
1112 case Instruction::UDiv:
1113 case Instruction::SDiv:
1114 case Instruction::FDiv:
1115 case Instruction::URem:
1116 case Instruction::SRem:
1117 case Instruction::FRem:
1118 case Instruction::And:
1119 case Instruction::Or:
1120 case Instruction::Xor:
1121 case Instruction::Shl:
1122 case Instruction::LShr:
1123 case Instruction::AShr:{
1124 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1125 switch (I->getOpcode()) {
1126 case Instruction::Add: Out << "Instruction::Add"; break;
1127 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1128 case Instruction::Sub: Out << "Instruction::Sub"; break;
1129 case Instruction::FSub: Out << "Instruction::FSub"; break;
1130 case Instruction::Mul: Out << "Instruction::Mul"; break;
1131 case Instruction::FMul: Out << "Instruction::FMul"; break;
1132 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1133 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1134 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1135 case Instruction::URem:Out << "Instruction::URem"; break;
1136 case Instruction::SRem:Out << "Instruction::SRem"; break;
1137 case Instruction::FRem:Out << "Instruction::FRem"; break;
1138 case Instruction::And: Out << "Instruction::And"; break;
1139 case Instruction::Or: Out << "Instruction::Or"; break;
1140 case Instruction::Xor: Out << "Instruction::Xor"; break;
1141 case Instruction::Shl: Out << "Instruction::Shl"; break;
1142 case Instruction::LShr:Out << "Instruction::LShr"; break;
1143 case Instruction::AShr:Out << "Instruction::AShr"; break;
1144 default: Out << "Instruction::BadOpCode"; break;
1146 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1147 printEscapedString(I->getName());
1148 Out << "\", " << bbname << ");";
1151 case Instruction::FCmp: {
1152 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1153 switch (cast<FCmpInst>(I)->getPredicate()) {
1154 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1155 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1156 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1157 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1158 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1159 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1160 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1161 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1162 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1163 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1164 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1165 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1166 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1167 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1168 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1169 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1170 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1172 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1173 printEscapedString(I->getName());
1177 case Instruction::ICmp: {
1178 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1179 switch (cast<ICmpInst>(I)->getPredicate()) {
1180 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1181 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1182 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1183 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1184 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1185 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1186 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1187 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1188 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1189 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1190 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1192 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1193 printEscapedString(I->getName());
1197 case Instruction::Alloca: {
1198 const AllocaInst* allocaI = cast<AllocaInst>(I);
1199 Out << "AllocaInst* " << iName << " = new AllocaInst("
1200 << getCppName(allocaI->getAllocatedType()) << ", ";
1201 if (allocaI->isArrayAllocation())
1202 Out << opNames[0] << ", ";
1204 printEscapedString(allocaI->getName());
1205 Out << "\", " << bbname << ");";
1206 if (allocaI->getAlignment())
1207 nl(Out) << iName << "->setAlignment("
1208 << allocaI->getAlignment() << ");";
1211 case Instruction::Load: {
1212 const LoadInst* load = cast<LoadInst>(I);
1213 Out << "LoadInst* " << iName << " = new LoadInst("
1214 << opNames[0] << ", \"";
1215 printEscapedString(load->getName());
1216 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1217 << ", " << bbname << ");";
1220 case Instruction::Store: {
1221 const StoreInst* store = cast<StoreInst>(I);
1222 Out << " new StoreInst("
1223 << opNames[0] << ", "
1224 << opNames[1] << ", "
1225 << (store->isVolatile() ? "true" : "false")
1226 << ", " << bbname << ");";
1229 case Instruction::GetElementPtr: {
1230 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1231 if (gep->getNumOperands() <= 2) {
1232 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1234 if (gep->getNumOperands() == 2)
1235 Out << ", " << opNames[1];
1237 Out << "std::vector<Value*> " << iName << "_indices;";
1239 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1240 Out << iName << "_indices.push_back("
1241 << opNames[i] << ");";
1244 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1245 << opNames[0] << ", " << iName << "_indices.begin(), "
1246 << iName << "_indices.end()";
1249 printEscapedString(gep->getName());
1250 Out << "\", " << bbname << ");";
1253 case Instruction::PHI: {
1254 const PHINode* phi = cast<PHINode>(I);
1256 Out << "PHINode* " << iName << " = PHINode::Create("
1257 << getCppName(phi->getType()) << ", "
1258 << phi->getNumIncomingValues() << ", \"";
1259 printEscapedString(phi->getName());
1260 Out << "\", " << bbname << ");";
1262 for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
1263 Out << iName << "->addIncoming("
1264 << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
1265 << getOpName(phi->getIncomingBlock(i)) << ");";
1270 case Instruction::Trunc:
1271 case Instruction::ZExt:
1272 case Instruction::SExt:
1273 case Instruction::FPTrunc:
1274 case Instruction::FPExt:
1275 case Instruction::FPToUI:
1276 case Instruction::FPToSI:
1277 case Instruction::UIToFP:
1278 case Instruction::SIToFP:
1279 case Instruction::PtrToInt:
1280 case Instruction::IntToPtr:
1281 case Instruction::BitCast: {
1282 const CastInst* cst = cast<CastInst>(I);
1283 Out << "CastInst* " << iName << " = new ";
1284 switch (I->getOpcode()) {
1285 case Instruction::Trunc: Out << "TruncInst"; break;
1286 case Instruction::ZExt: Out << "ZExtInst"; break;
1287 case Instruction::SExt: Out << "SExtInst"; break;
1288 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1289 case Instruction::FPExt: Out << "FPExtInst"; break;
1290 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1291 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1292 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1293 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1294 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1295 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1296 case Instruction::BitCast: Out << "BitCastInst"; break;
1297 default: assert(!"Unreachable"); break;
1299 Out << "(" << opNames[0] << ", "
1300 << getCppName(cst->getType()) << ", \"";
1301 printEscapedString(cst->getName());
1302 Out << "\", " << bbname << ");";
1305 case Instruction::Call: {
1306 const CallInst* call = cast<CallInst>(I);
1307 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1308 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1309 << getCppName(ila->getFunctionType()) << ", \""
1310 << ila->getAsmString() << "\", \""
1311 << ila->getConstraintString() << "\","
1312 << (ila->hasSideEffects() ? "true" : "false") << ");";
1315 if (call->getNumArgOperands() > 1) {
1316 Out << "std::vector<Value*> " << iName << "_params;";
1318 for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
1319 Out << iName << "_params.push_back(" << opNames[i] << ");";
1322 Out << "CallInst* " << iName << " = CallInst::Create("
1323 << opNames[call->getNumArgOperands()] << ", "
1324 << iName << "_params, \"";
1325 } else if (call->getNumArgOperands() == 1) {
1326 Out << "CallInst* " << iName << " = CallInst::Create("
1327 << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
1329 Out << "CallInst* " << iName << " = CallInst::Create("
1330 << opNames[call->getNumArgOperands()] << ", \"";
1332 printEscapedString(call->getName());
1333 Out << "\", " << bbname << ");";
1334 nl(Out) << iName << "->setCallingConv(";
1335 printCallingConv(call->getCallingConv());
1337 nl(Out) << iName << "->setTailCall("
1338 << (call->isTailCall() ? "true" : "false");
1341 printAttributes(call->getAttributes(), iName);
1342 Out << iName << "->setAttributes(" << iName << "_PAL);";
1346 case Instruction::Select: {
1347 const SelectInst* sel = cast<SelectInst>(I);
1348 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1349 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1350 printEscapedString(sel->getName());
1351 Out << "\", " << bbname << ");";
1354 case Instruction::UserOp1:
1356 case Instruction::UserOp2: {
1357 /// FIXME: What should be done here?
1360 case Instruction::VAArg: {
1361 const VAArgInst* va = cast<VAArgInst>(I);
1362 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1363 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1364 printEscapedString(va->getName());
1365 Out << "\", " << bbname << ");";
1368 case Instruction::ExtractElement: {
1369 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1370 Out << "ExtractElementInst* " << getCppName(eei)
1371 << " = new ExtractElementInst(" << opNames[0]
1372 << ", " << opNames[1] << ", \"";
1373 printEscapedString(eei->getName());
1374 Out << "\", " << bbname << ");";
1377 case Instruction::InsertElement: {
1378 const InsertElementInst* iei = cast<InsertElementInst>(I);
1379 Out << "InsertElementInst* " << getCppName(iei)
1380 << " = InsertElementInst::Create(" << opNames[0]
1381 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1382 printEscapedString(iei->getName());
1383 Out << "\", " << bbname << ");";
1386 case Instruction::ShuffleVector: {
1387 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1388 Out << "ShuffleVectorInst* " << getCppName(svi)
1389 << " = new ShuffleVectorInst(" << opNames[0]
1390 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1391 printEscapedString(svi->getName());
1392 Out << "\", " << bbname << ");";
1395 case Instruction::ExtractValue: {
1396 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1397 Out << "std::vector<unsigned> " << iName << "_indices;";
1399 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1400 Out << iName << "_indices.push_back("
1401 << evi->idx_begin()[i] << ");";
1404 Out << "ExtractValueInst* " << getCppName(evi)
1405 << " = ExtractValueInst::Create(" << opNames[0]
1407 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1408 printEscapedString(evi->getName());
1409 Out << "\", " << bbname << ");";
1412 case Instruction::InsertValue: {
1413 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1414 Out << "std::vector<unsigned> " << iName << "_indices;";
1416 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1417 Out << iName << "_indices.push_back("
1418 << ivi->idx_begin()[i] << ");";
1421 Out << "InsertValueInst* " << getCppName(ivi)
1422 << " = InsertValueInst::Create(" << opNames[0]
1423 << ", " << opNames[1] << ", "
1424 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1425 printEscapedString(ivi->getName());
1426 Out << "\", " << bbname << ");";
1430 DefinedValues.insert(I);
1435 // Print out the types, constants and declarations needed by one function
1436 void CppWriter::printFunctionUses(const Function* F) {
1437 nl(Out) << "// Type Definitions"; nl(Out);
1439 // Print the function's return type
1440 printType(F->getReturnType());
1442 // Print the function's function type
1443 printType(F->getFunctionType());
1445 // Print the types of each of the function's arguments
1446 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1448 printType(AI->getType());
1452 // Print type definitions for every type referenced by an instruction and
1453 // make a note of any global values or constants that are referenced
1454 SmallPtrSet<GlobalValue*,64> gvs;
1455 SmallPtrSet<Constant*,64> consts;
1456 for (Function::const_iterator BB = F->begin(), BE = F->end();
1458 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1460 // Print the type of the instruction itself
1461 printType(I->getType());
1463 // Print the type of each of the instruction's operands
1464 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1465 Value* operand = I->getOperand(i);
1466 printType(operand->getType());
1468 // If the operand references a GVal or Constant, make a note of it
1469 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1471 if (GenerationType != GenFunction)
1472 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1473 if (GVar->hasInitializer())
1474 consts.insert(GVar->getInitializer());
1475 } else if (Constant* C = dyn_cast<Constant>(operand)) {
1477 for (unsigned j = 0; j < C->getNumOperands(); ++j) {
1478 // If the operand references a GVal or Constant, make a note of it
1479 Value* operand = C->getOperand(j);
1480 printType(operand->getType());
1481 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1483 if (GenerationType != GenFunction)
1484 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1485 if (GVar->hasInitializer())
1486 consts.insert(GVar->getInitializer());
1494 // Print the function declarations for any functions encountered
1495 nl(Out) << "// Function Declarations"; nl(Out);
1496 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1498 if (Function* Fun = dyn_cast<Function>(*I)) {
1499 if (!is_inline || Fun != F)
1500 printFunctionHead(Fun);
1504 // Print the global variable declarations for any variables encountered
1505 nl(Out) << "// Global Variable Declarations"; nl(Out);
1506 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1508 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1509 printVariableHead(F);
1512 // Print the constants found
1513 nl(Out) << "// Constant Definitions"; nl(Out);
1514 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1515 E = consts.end(); I != E; ++I) {
1519 // Process the global variables definitions now that all the constants have
1520 // been emitted. These definitions just couple the gvars with their constant
1522 if (GenerationType != GenFunction) {
1523 nl(Out) << "// Global Variable Definitions"; nl(Out);
1524 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1526 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1527 printVariableBody(GV);
1532 void CppWriter::printFunctionHead(const Function* F) {
1533 nl(Out) << "Function* " << getCppName(F);
1535 Out << " = mod->getFunction(\"";
1536 printEscapedString(F->getName());
1537 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1538 nl(Out) << "if (!" << getCppName(F) << ") {";
1539 nl(Out) << getCppName(F);
1541 Out<< " = Function::Create(";
1542 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1543 nl(Out) << "/*Linkage=*/";
1544 printLinkageType(F->getLinkage());
1546 nl(Out) << "/*Name=*/\"";
1547 printEscapedString(F->getName());
1548 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1551 Out << "->setCallingConv(";
1552 printCallingConv(F->getCallingConv());
1555 if (F->hasSection()) {
1557 Out << "->setSection(\"" << F->getSection() << "\");";
1560 if (F->getAlignment()) {
1562 Out << "->setAlignment(" << F->getAlignment() << ");";
1565 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1567 Out << "->setVisibility(";
1568 printVisibilityType(F->getVisibility());
1574 Out << "->setGC(\"" << F->getGC() << "\");";
1581 printAttributes(F->getAttributes(), getCppName(F));
1583 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1587 void CppWriter::printFunctionBody(const Function *F) {
1588 if (F->isDeclaration())
1589 return; // external functions have no bodies.
1591 // Clear the DefinedValues and ForwardRefs maps because we can't have
1592 // cross-function forward refs
1593 ForwardRefs.clear();
1594 DefinedValues.clear();
1596 // Create all the argument values
1598 if (!F->arg_empty()) {
1599 Out << "Function::arg_iterator args = " << getCppName(F)
1600 << "->arg_begin();";
1603 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1605 Out << "Value* " << getCppName(AI) << " = args++;";
1607 if (AI->hasName()) {
1608 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1614 // Create all the basic blocks
1616 for (Function::const_iterator BI = F->begin(), BE = F->end();
1618 std::string bbname(getCppName(BI));
1619 Out << "BasicBlock* " << bbname <<
1620 " = BasicBlock::Create(mod->getContext(), \"";
1622 printEscapedString(BI->getName());
1623 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1627 // Output all of its basic blocks... for the function
1628 for (Function::const_iterator BI = F->begin(), BE = F->end();
1630 std::string bbname(getCppName(BI));
1631 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1634 // Output all of the instructions in the basic block...
1635 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1637 printInstruction(I,bbname);
1641 // Loop over the ForwardRefs and resolve them now that all instructions
1643 if (!ForwardRefs.empty()) {
1644 nl(Out) << "// Resolve Forward References";
1648 while (!ForwardRefs.empty()) {
1649 ForwardRefMap::iterator I = ForwardRefs.begin();
1650 Out << I->second << "->replaceAllUsesWith("
1651 << getCppName(I->first) << "); delete " << I->second << ";";
1653 ForwardRefs.erase(I);
1657 void CppWriter::printInline(const std::string& fname,
1658 const std::string& func) {
1659 const Function* F = TheModule->getFunction(func);
1661 error(std::string("Function '") + func + "' not found in input module");
1664 if (F->isDeclaration()) {
1665 error(std::string("Function '") + func + "' is external!");
1668 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1670 unsigned arg_count = 1;
1671 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1673 Out << ", Value* arg_" << arg_count;
1678 printFunctionUses(F);
1679 printFunctionBody(F);
1681 Out << "return " << getCppName(F->begin()) << ";";
1686 void CppWriter::printModuleBody() {
1687 // Print out all the type definitions
1688 nl(Out) << "// Type Definitions"; nl(Out);
1689 printTypes(TheModule);
1691 // Functions can call each other and global variables can reference them so
1692 // define all the functions first before emitting their function bodies.
1693 nl(Out) << "// Function Declarations"; nl(Out);
1694 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1696 printFunctionHead(I);
1698 // Process the global variables declarations. We can't initialze them until
1699 // after the constants are printed so just print a header for each global
1700 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1701 for (Module::const_global_iterator I = TheModule->global_begin(),
1702 E = TheModule->global_end(); I != E; ++I) {
1703 printVariableHead(I);
1706 // Print out all the constants definitions. Constants don't recurse except
1707 // through GlobalValues. All GlobalValues have been declared at this point
1708 // so we can proceed to generate the constants.
1709 nl(Out) << "// Constant Definitions"; nl(Out);
1710 printConstants(TheModule);
1712 // Process the global variables definitions now that all the constants have
1713 // been emitted. These definitions just couple the gvars with their constant
1715 nl(Out) << "// Global Variable Definitions"; nl(Out);
1716 for (Module::const_global_iterator I = TheModule->global_begin(),
1717 E = TheModule->global_end(); I != E; ++I) {
1718 printVariableBody(I);
1721 // Finally, we can safely put out all of the function bodies.
1722 nl(Out) << "// Function Definitions"; nl(Out);
1723 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1725 if (!I->isDeclaration()) {
1726 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1730 printFunctionBody(I);
1737 void CppWriter::printProgram(const std::string& fname,
1738 const std::string& mName) {
1739 Out << "#include <llvm/LLVMContext.h>\n";
1740 Out << "#include <llvm/Module.h>\n";
1741 Out << "#include <llvm/DerivedTypes.h>\n";
1742 Out << "#include <llvm/Constants.h>\n";
1743 Out << "#include <llvm/GlobalVariable.h>\n";
1744 Out << "#include <llvm/Function.h>\n";
1745 Out << "#include <llvm/CallingConv.h>\n";
1746 Out << "#include <llvm/BasicBlock.h>\n";
1747 Out << "#include <llvm/Instructions.h>\n";
1748 Out << "#include <llvm/InlineAsm.h>\n";
1749 Out << "#include <llvm/Support/FormattedStream.h>\n";
1750 Out << "#include <llvm/Support/MathExtras.h>\n";
1751 Out << "#include <llvm/Pass.h>\n";
1752 Out << "#include <llvm/PassManager.h>\n";
1753 Out << "#include <llvm/ADT/SmallVector.h>\n";
1754 Out << "#include <llvm/Analysis/Verifier.h>\n";
1755 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1756 Out << "#include <algorithm>\n";
1757 Out << "using namespace llvm;\n\n";
1758 Out << "Module* " << fname << "();\n\n";
1759 Out << "int main(int argc, char**argv) {\n";
1760 Out << " Module* Mod = " << fname << "();\n";
1761 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1762 Out << " PassManager PM;\n";
1763 Out << " PM.add(createPrintModulePass(&outs()));\n";
1764 Out << " PM.run(*Mod);\n";
1765 Out << " return 0;\n";
1767 printModule(fname,mName);
1770 void CppWriter::printModule(const std::string& fname,
1771 const std::string& mName) {
1772 nl(Out) << "Module* " << fname << "() {";
1773 nl(Out,1) << "// Module Construction";
1774 nl(Out) << "Module* mod = new Module(\"";
1775 printEscapedString(mName);
1776 Out << "\", getGlobalContext());";
1777 if (!TheModule->getTargetTriple().empty()) {
1778 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1780 if (!TheModule->getTargetTriple().empty()) {
1781 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1785 if (!TheModule->getModuleInlineAsm().empty()) {
1786 nl(Out) << "mod->setModuleInlineAsm(\"";
1787 printEscapedString(TheModule->getModuleInlineAsm());
1792 // Loop over the dependent libraries and emit them.
1793 Module::lib_iterator LI = TheModule->lib_begin();
1794 Module::lib_iterator LE = TheModule->lib_end();
1796 Out << "mod->addLibrary(\"" << *LI << "\");";
1801 nl(Out) << "return mod;";
1806 void CppWriter::printContents(const std::string& fname,
1807 const std::string& mName) {
1808 Out << "\nModule* " << fname << "(Module *mod) {\n";
1809 Out << "\nmod->setModuleIdentifier(\"";
1810 printEscapedString(mName);
1813 Out << "\nreturn mod;\n";
1817 void CppWriter::printFunction(const std::string& fname,
1818 const std::string& funcName) {
1819 const Function* F = TheModule->getFunction(funcName);
1821 error(std::string("Function '") + funcName + "' not found in input module");
1824 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1825 printFunctionUses(F);
1826 printFunctionHead(F);
1827 printFunctionBody(F);
1828 Out << "return " << getCppName(F) << ";\n";
1832 void CppWriter::printFunctions() {
1833 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1834 Module::const_iterator I = funcs.begin();
1835 Module::const_iterator IE = funcs.end();
1837 for (; I != IE; ++I) {
1838 const Function &func = *I;
1839 if (!func.isDeclaration()) {
1840 std::string name("define_");
1841 name += func.getName();
1842 printFunction(name, func.getName());
1847 void CppWriter::printVariable(const std::string& fname,
1848 const std::string& varName) {
1849 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1852 error(std::string("Variable '") + varName + "' not found in input module");
1855 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1856 printVariableUses(GV);
1857 printVariableHead(GV);
1858 printVariableBody(GV);
1859 Out << "return " << getCppName(GV) << ";\n";
1863 void CppWriter::printType(const std::string &fname,
1864 const std::string &typeName) {
1865 Type* Ty = TheModule->getTypeByName(typeName);
1867 error(std::string("Type '") + typeName + "' not found in input module");
1870 Out << "\nType* " << fname << "(Module *mod) {\n";
1872 Out << "return " << getCppName(Ty) << ";\n";
1876 bool CppWriter::runOnModule(Module &M) {
1880 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1882 // Get the name of the function we're supposed to generate
1883 std::string fname = FuncName.getValue();
1885 // Get the name of the thing we are to generate
1886 std::string tgtname = NameToGenerate.getValue();
1887 if (GenerationType == GenModule ||
1888 GenerationType == GenContents ||
1889 GenerationType == GenProgram ||
1890 GenerationType == GenFunctions) {
1891 if (tgtname == "!bad!") {
1892 if (M.getModuleIdentifier() == "-")
1893 tgtname = "<stdin>";
1895 tgtname = M.getModuleIdentifier();
1897 } else if (tgtname == "!bad!")
1898 error("You must use the -for option with -gen-{function,variable,type}");
1900 switch (WhatToGenerate(GenerationType)) {
1903 fname = "makeLLVMModule";
1904 printProgram(fname,tgtname);
1908 fname = "makeLLVMModule";
1909 printModule(fname,tgtname);
1913 fname = "makeLLVMModuleContents";
1914 printContents(fname,tgtname);
1918 fname = "makeLLVMFunction";
1919 printFunction(fname,tgtname);
1926 fname = "makeLLVMInline";
1927 printInline(fname,tgtname);
1931 fname = "makeLLVMVariable";
1932 printVariable(fname,tgtname);
1936 fname = "makeLLVMType";
1937 printType(fname,tgtname);
1940 error("Invalid generation option");
1946 char CppWriter::ID = 0;
1948 //===----------------------------------------------------------------------===//
1949 // External Interface declaration
1950 //===----------------------------------------------------------------------===//
1952 bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
1953 formatted_raw_ostream &o,
1954 CodeGenFileType FileType,
1955 CodeGenOpt::Level OptLevel,
1956 bool DisableVerify) {
1957 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
1958 PM.add(new CppWriter(o));