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/Support/TargetRegistry.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/Config/config.h"
41 static cl::opt<std::string>
42 FuncName("cppfname", cl::desc("Specify the name of the generated function"),
43 cl::value_desc("function name"));
56 static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
57 cl::desc("Choose what kind of output to generate"),
60 clEnumValN(GenProgram, "program", "Generate a complete program"),
61 clEnumValN(GenModule, "module", "Generate a module definition"),
62 clEnumValN(GenContents, "contents", "Generate contents of a module"),
63 clEnumValN(GenFunction, "function", "Generate a function definition"),
64 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
65 clEnumValN(GenInline, "inline", "Generate an inline function"),
66 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
67 clEnumValN(GenType, "type", "Generate a type definition"),
72 static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
73 cl::desc("Specify the name of the thing to generate"),
76 extern "C" void LLVMInitializeCppBackendTarget() {
77 // Register the target.
78 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
82 typedef std::vector<Type*> TypeList;
83 typedef std::map<Type*,std::string> TypeMap;
84 typedef std::map<const Value*,std::string> ValueMap;
85 typedef std::set<std::string> NameSet;
86 typedef std::set<Type*> TypeSet;
87 typedef std::set<const Value*> ValueSet;
88 typedef std::map<const Value*,std::string> ForwardRefMap;
90 /// CppWriter - This class is the main chunk of code that converts an LLVM
91 /// module to a C++ translation unit.
92 class CppWriter : public ModulePass {
93 formatted_raw_ostream &Out;
94 const Module *TheModule;
100 ValueSet DefinedValues;
101 ForwardRefMap ForwardRefs;
103 unsigned indent_level;
107 explicit CppWriter(formatted_raw_ostream &o) :
108 ModulePass(ID), Out(o), uniqueNum(0), is_inline(false), indent_level(0){}
110 virtual const char *getPassName() const { return "C++ backend"; }
112 bool runOnModule(Module &M);
114 void printProgram(const std::string& fname, const std::string& modName );
115 void printModule(const std::string& fname, const std::string& modName );
116 void printContents(const std::string& fname, const std::string& modName );
117 void printFunction(const std::string& fname, const std::string& funcName );
118 void printFunctions();
119 void printInline(const std::string& fname, const std::string& funcName );
120 void printVariable(const std::string& fname, const std::string& varName );
121 void printType(const std::string& fname, const std::string& typeName );
123 void error(const std::string& msg);
126 formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0);
127 inline void in() { indent_level++; }
128 inline void out() { if (indent_level >0) indent_level--; }
131 void printLinkageType(GlobalValue::LinkageTypes LT);
132 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
133 void printThreadLocalMode(GlobalVariable::ThreadLocalMode TLM);
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(const 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_";
196 void CppWriter::error(const std::string& msg) {
197 report_fatal_error(msg);
200 static inline std::string ftostr(const APFloat& V) {
202 if (&V.getSemantics() == &APFloat::IEEEdouble) {
203 raw_string_ostream(Buf) << V.convertToDouble();
205 } else if (&V.getSemantics() == &APFloat::IEEEsingle) {
206 raw_string_ostream(Buf) << (double)V.convertToFloat();
209 return "<unknown format in ftostr>"; // error
212 // printCFP - Print a floating point constant .. very carefully :)
213 // This makes sure that conversion to/from floating yields the same binary
214 // result so that we don't lose precision.
215 void CppWriter::printCFP(const ConstantFP *CFP) {
217 APFloat APF = APFloat(CFP->getValueAPF()); // copy
218 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
219 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
220 Out << "ConstantFP::get(mod->getContext(), ";
224 sprintf(Buffer, "%A", APF.convertToDouble());
225 if ((!strncmp(Buffer, "0x", 2) ||
226 !strncmp(Buffer, "-0x", 3) ||
227 !strncmp(Buffer, "+0x", 3)) &&
228 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
229 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
230 Out << "BitsToDouble(" << Buffer << ")";
232 Out << "BitsToFloat((float)" << Buffer << ")";
236 std::string StrVal = ftostr(CFP->getValueAPF());
238 while (StrVal[0] == ' ')
239 StrVal.erase(StrVal.begin());
241 // Check to make sure that the stringized number is not some string like
242 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
243 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
244 ((StrVal[0] == '-' || StrVal[0] == '+') &&
245 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
246 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
247 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
250 Out << StrVal << "f";
251 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
252 Out << "BitsToDouble(0x"
253 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
254 << "ULL) /* " << StrVal << " */";
256 Out << "BitsToFloat(0x"
257 << utohexstr((uint32_t)CFP->getValueAPF().
258 bitcastToAPInt().getZExtValue())
259 << "U) /* " << StrVal << " */";
267 void CppWriter::printCallingConv(CallingConv::ID cc){
268 // Print the calling convention.
270 case CallingConv::C: Out << "CallingConv::C"; break;
271 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
272 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
273 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
274 default: Out << cc; break;
278 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
280 case GlobalValue::InternalLinkage:
281 Out << "GlobalValue::InternalLinkage"; break;
282 case GlobalValue::PrivateLinkage:
283 Out << "GlobalValue::PrivateLinkage"; break;
284 case GlobalValue::LinkerPrivateLinkage:
285 Out << "GlobalValue::LinkerPrivateLinkage"; break;
286 case GlobalValue::LinkerPrivateWeakLinkage:
287 Out << "GlobalValue::LinkerPrivateWeakLinkage"; break;
288 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
289 Out << "GlobalValue::LinkerPrivateWeakDefAutoLinkage"; break;
290 case GlobalValue::AvailableExternallyLinkage:
291 Out << "GlobalValue::AvailableExternallyLinkage "; break;
292 case GlobalValue::LinkOnceAnyLinkage:
293 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
294 case GlobalValue::LinkOnceODRLinkage:
295 Out << "GlobalValue::LinkOnceODRLinkage "; break;
296 case GlobalValue::WeakAnyLinkage:
297 Out << "GlobalValue::WeakAnyLinkage"; break;
298 case GlobalValue::WeakODRLinkage:
299 Out << "GlobalValue::WeakODRLinkage"; break;
300 case GlobalValue::AppendingLinkage:
301 Out << "GlobalValue::AppendingLinkage"; break;
302 case GlobalValue::ExternalLinkage:
303 Out << "GlobalValue::ExternalLinkage"; break;
304 case GlobalValue::DLLImportLinkage:
305 Out << "GlobalValue::DLLImportLinkage"; break;
306 case GlobalValue::DLLExportLinkage:
307 Out << "GlobalValue::DLLExportLinkage"; break;
308 case GlobalValue::ExternalWeakLinkage:
309 Out << "GlobalValue::ExternalWeakLinkage"; break;
310 case GlobalValue::CommonLinkage:
311 Out << "GlobalValue::CommonLinkage"; break;
315 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
317 case GlobalValue::DefaultVisibility:
318 Out << "GlobalValue::DefaultVisibility";
320 case GlobalValue::HiddenVisibility:
321 Out << "GlobalValue::HiddenVisibility";
323 case GlobalValue::ProtectedVisibility:
324 Out << "GlobalValue::ProtectedVisibility";
329 void CppWriter::printThreadLocalMode(GlobalVariable::ThreadLocalMode TLM) {
331 case GlobalVariable::NotThreadLocal:
332 Out << "GlobalVariable::NotThreadLocal";
334 case GlobalVariable::GeneralDynamicTLSModel:
335 Out << "GlobalVariable::GeneralDynamicTLSModel";
337 case GlobalVariable::LocalDynamicTLSModel:
338 Out << "GlobalVariable::LocalDynamicTLSModel";
340 case GlobalVariable::InitialExecTLSModel:
341 Out << "GlobalVariable::InitialExecTLSModel";
343 case GlobalVariable::LocalExecTLSModel:
344 Out << "GlobalVariable::LocalExecTLSModel";
349 // printEscapedString - Print each character of the specified string, escaping
350 // it if it is not printable or if it is an escape char.
351 void CppWriter::printEscapedString(const std::string &Str) {
352 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
353 unsigned char C = Str[i];
354 if (isprint(C) && C != '"' && C != '\\') {
358 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
359 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
364 std::string CppWriter::getCppName(Type* Ty) {
365 // First, handle the primitive types .. easy
366 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
367 switch (Ty->getTypeID()) {
368 case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())";
369 case Type::IntegerTyID: {
370 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
371 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
373 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
374 case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())";
375 case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())";
376 case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())";
377 case Type::X86_MMXTyID: return "Type::getX86_MMXTy(mod->getContext())";
379 error("Invalid primitive type");
382 // shouldn't be returned, but make it sensible
383 return "Type::getVoidTy(mod->getContext())";
386 // Now, see if we've seen the type before and return that
387 TypeMap::iterator I = TypeNames.find(Ty);
388 if (I != TypeNames.end())
391 // Okay, let's build a new name for this type. Start with a prefix
392 const char* prefix = 0;
393 switch (Ty->getTypeID()) {
394 case Type::FunctionTyID: prefix = "FuncTy_"; break;
395 case Type::StructTyID: prefix = "StructTy_"; break;
396 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
397 case Type::PointerTyID: prefix = "PointerTy_"; break;
398 case Type::VectorTyID: prefix = "VectorTy_"; break;
399 default: prefix = "OtherTy_"; break; // prevent breakage
402 // See if the type has a name in the symboltable and build accordingly
404 if (StructType *STy = dyn_cast<StructType>(Ty))
406 name = STy->getName();
409 name = utostr(uniqueNum++);
411 name = std::string(prefix) + name;
415 return TypeNames[Ty] = name;
418 void CppWriter::printCppName(Type* Ty) {
419 printEscapedString(getCppName(Ty));
422 std::string CppWriter::getCppName(const Value* val) {
424 ValueMap::iterator I = ValueNames.find(val);
425 if (I != ValueNames.end() && I->first == val)
428 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
429 name = std::string("gvar_") +
430 getTypePrefix(GV->getType()->getElementType());
431 } else if (isa<Function>(val)) {
432 name = std::string("func_");
433 } else if (const Constant* C = dyn_cast<Constant>(val)) {
434 name = std::string("const_") + getTypePrefix(C->getType());
435 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
437 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
438 Function::const_arg_iterator(Arg)) + 1;
439 name = std::string("arg_") + utostr(argNum);
440 NameSet::iterator NI = UsedNames.find(name);
441 if (NI != UsedNames.end())
442 name += std::string("_") + utostr(uniqueNum++);
443 UsedNames.insert(name);
444 return ValueNames[val] = name;
446 name = getTypePrefix(val->getType());
449 name = getTypePrefix(val->getType());
452 name += val->getName();
454 name += utostr(uniqueNum++);
456 NameSet::iterator NI = UsedNames.find(name);
457 if (NI != UsedNames.end())
458 name += std::string("_") + utostr(uniqueNum++);
459 UsedNames.insert(name);
460 return ValueNames[val] = name;
463 void CppWriter::printCppName(const Value* val) {
464 printEscapedString(getCppName(val));
467 void CppWriter::printAttributes(const AttrListPtr &PAL,
468 const std::string &name) {
469 Out << "AttrListPtr " << name << "_PAL;";
471 if (!PAL.isEmpty()) {
472 Out << '{'; in(); nl(Out);
473 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
474 Out << "AttributeWithIndex PAWI;"; nl(Out);
475 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
476 unsigned index = PAL.getSlot(i).Index;
477 Attributes attrs = PAL.getSlot(i).Attrs;
478 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = Attribute::None ";
479 #define HANDLE_ATTR(X) \
480 if (attrs & Attribute::X) \
481 Out << " | Attribute::" #X; \
482 attrs &= ~Attribute::X;
486 HANDLE_ATTR(NoReturn);
488 HANDLE_ATTR(StructRet);
489 HANDLE_ATTR(NoUnwind);
490 HANDLE_ATTR(NoAlias);
493 HANDLE_ATTR(ReadNone);
494 HANDLE_ATTR(ReadOnly);
495 HANDLE_ATTR(NoInline);
496 HANDLE_ATTR(AlwaysInline);
497 HANDLE_ATTR(OptimizeForSize);
498 HANDLE_ATTR(StackProtect);
499 HANDLE_ATTR(StackProtectReq);
500 HANDLE_ATTR(NoCapture);
501 HANDLE_ATTR(NoRedZone);
502 HANDLE_ATTR(NoImplicitFloat);
504 HANDLE_ATTR(InlineHint);
505 HANDLE_ATTR(ReturnsTwice);
506 HANDLE_ATTR(UWTable);
507 HANDLE_ATTR(NonLazyBind);
509 if (attrs & Attribute::StackAlignment)
510 Out << " | Attribute::constructStackAlignmentFromInt("
511 << Attribute::getStackAlignmentFromAttrs(attrs)
513 attrs &= ~Attribute::StackAlignment;
514 assert(attrs == 0 && "Unhandled attribute!");
517 Out << "Attrs.push_back(PAWI);";
520 Out << name << "_PAL = AttrListPtr::get(Attrs);";
527 void CppWriter::printType(Type* Ty) {
528 // We don't print definitions for primitive types
529 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
532 // If we already defined this type, we don't need to define it again.
533 if (DefinedTypes.find(Ty) != DefinedTypes.end())
536 // Everything below needs the name for the type so get it now.
537 std::string typeName(getCppName(Ty));
539 // Print the type definition
540 switch (Ty->getTypeID()) {
541 case Type::FunctionTyID: {
542 FunctionType* FT = cast<FunctionType>(Ty);
543 Out << "std::vector<Type*>" << typeName << "_args;";
545 FunctionType::param_iterator PI = FT->param_begin();
546 FunctionType::param_iterator PE = FT->param_end();
547 for (; PI != PE; ++PI) {
548 Type* argTy = static_cast<Type*>(*PI);
550 std::string argName(getCppName(argTy));
551 Out << typeName << "_args.push_back(" << argName;
555 printType(FT->getReturnType());
556 std::string retTypeName(getCppName(FT->getReturnType()));
557 Out << "FunctionType* " << typeName << " = FunctionType::get(";
558 in(); nl(Out) << "/*Result=*/" << retTypeName;
560 nl(Out) << "/*Params=*/" << typeName << "_args,";
561 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
566 case Type::StructTyID: {
567 StructType* ST = cast<StructType>(Ty);
568 if (!ST->isLiteral()) {
569 Out << "StructType *" << typeName << " = mod->getTypeByName(\"";
570 printEscapedString(ST->getName());
573 Out << "if (!" << typeName << ") {";
575 Out << typeName << " = ";
576 Out << "StructType::create(mod->getContext(), \"";
577 printEscapedString(ST->getName());
582 // Indicate that this type is now defined.
583 DefinedTypes.insert(Ty);
586 Out << "std::vector<Type*>" << typeName << "_fields;";
588 StructType::element_iterator EI = ST->element_begin();
589 StructType::element_iterator EE = ST->element_end();
590 for (; EI != EE; ++EI) {
591 Type* fieldTy = static_cast<Type*>(*EI);
593 std::string fieldName(getCppName(fieldTy));
594 Out << typeName << "_fields.push_back(" << fieldName;
599 if (ST->isLiteral()) {
600 Out << "StructType *" << typeName << " = ";
601 Out << "StructType::get(" << "mod->getContext(), ";
603 Out << "if (" << typeName << "->isOpaque()) {";
605 Out << typeName << "->setBody(";
608 Out << typeName << "_fields, /*isPacked=*/"
609 << (ST->isPacked() ? "true" : "false") << ");";
611 if (!ST->isLiteral()) {
617 case Type::ArrayTyID: {
618 ArrayType* AT = cast<ArrayType>(Ty);
619 Type* ET = AT->getElementType();
621 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
622 std::string elemName(getCppName(ET));
623 Out << "ArrayType* " << typeName << " = ArrayType::get("
625 << ", " << utostr(AT->getNumElements()) << ");";
630 case Type::PointerTyID: {
631 PointerType* PT = cast<PointerType>(Ty);
632 Type* ET = PT->getElementType();
634 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
635 std::string elemName(getCppName(ET));
636 Out << "PointerType* " << typeName << " = PointerType::get("
638 << ", " << utostr(PT->getAddressSpace()) << ");";
643 case Type::VectorTyID: {
644 VectorType* PT = cast<VectorType>(Ty);
645 Type* ET = PT->getElementType();
647 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
648 std::string elemName(getCppName(ET));
649 Out << "VectorType* " << typeName << " = VectorType::get("
651 << ", " << utostr(PT->getNumElements()) << ");";
657 error("Invalid TypeID");
660 // Indicate that this type is now defined.
661 DefinedTypes.insert(Ty);
663 // Finally, separate the type definition from other with a newline.
667 void CppWriter::printTypes(const Module* M) {
668 // Add all of the global variables to the value table.
669 for (Module::const_global_iterator I = TheModule->global_begin(),
670 E = TheModule->global_end(); I != E; ++I) {
671 if (I->hasInitializer())
672 printType(I->getInitializer()->getType());
673 printType(I->getType());
676 // Add all the functions to the table
677 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
679 printType(FI->getReturnType());
680 printType(FI->getFunctionType());
681 // Add all the function arguments
682 for (Function::const_arg_iterator AI = FI->arg_begin(),
683 AE = FI->arg_end(); AI != AE; ++AI) {
684 printType(AI->getType());
687 // Add all of the basic blocks and instructions
688 for (Function::const_iterator BB = FI->begin(),
689 E = FI->end(); BB != E; ++BB) {
690 printType(BB->getType());
691 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
693 printType(I->getType());
694 for (unsigned i = 0; i < I->getNumOperands(); ++i)
695 printType(I->getOperand(i)->getType());
702 // printConstant - Print out a constant pool entry...
703 void CppWriter::printConstant(const Constant *CV) {
704 // First, if the constant is actually a GlobalValue (variable or function)
705 // or its already in the constant list then we've printed it already and we
707 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
710 std::string constName(getCppName(CV));
711 std::string typeName(getCppName(CV->getType()));
713 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
714 std::string constValue = CI->getValue().toString(10, true);
715 Out << "ConstantInt* " << constName
716 << " = ConstantInt::get(mod->getContext(), APInt("
717 << cast<IntegerType>(CI->getType())->getBitWidth()
718 << ", StringRef(\"" << constValue << "\"), 10));";
719 } else if (isa<ConstantAggregateZero>(CV)) {
720 Out << "ConstantAggregateZero* " << constName
721 << " = ConstantAggregateZero::get(" << typeName << ");";
722 } else if (isa<ConstantPointerNull>(CV)) {
723 Out << "ConstantPointerNull* " << constName
724 << " = ConstantPointerNull::get(" << typeName << ");";
725 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
726 Out << "ConstantFP* " << constName << " = ";
729 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
730 Out << "std::vector<Constant*> " << constName << "_elems;";
732 unsigned N = CA->getNumOperands();
733 for (unsigned i = 0; i < N; ++i) {
734 printConstant(CA->getOperand(i)); // recurse to print operands
735 Out << constName << "_elems.push_back("
736 << getCppName(CA->getOperand(i)) << ");";
739 Out << "Constant* " << constName << " = ConstantArray::get("
740 << typeName << ", " << constName << "_elems);";
741 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
742 Out << "std::vector<Constant*> " << constName << "_fields;";
744 unsigned N = CS->getNumOperands();
745 for (unsigned i = 0; i < N; i++) {
746 printConstant(CS->getOperand(i));
747 Out << constName << "_fields.push_back("
748 << getCppName(CS->getOperand(i)) << ");";
751 Out << "Constant* " << constName << " = ConstantStruct::get("
752 << typeName << ", " << constName << "_fields);";
753 } else if (const ConstantVector *CVec = dyn_cast<ConstantVector>(CV)) {
754 Out << "std::vector<Constant*> " << constName << "_elems;";
756 unsigned N = CVec->getNumOperands();
757 for (unsigned i = 0; i < N; ++i) {
758 printConstant(CVec->getOperand(i));
759 Out << constName << "_elems.push_back("
760 << getCppName(CVec->getOperand(i)) << ");";
763 Out << "Constant* " << constName << " = ConstantVector::get("
764 << typeName << ", " << constName << "_elems);";
765 } else if (isa<UndefValue>(CV)) {
766 Out << "UndefValue* " << constName << " = UndefValue::get("
768 } else if (const ConstantDataSequential *CDS =
769 dyn_cast<ConstantDataSequential>(CV)) {
770 if (CDS->isString()) {
771 Out << "Constant *" << constName <<
772 " = ConstantDataArray::getString(mod->getContext(), \"";
773 StringRef Str = CDS->getAsString();
774 bool nullTerminate = false;
775 if (Str.back() == 0) {
776 Str = Str.drop_back();
777 nullTerminate = true;
779 printEscapedString(Str);
780 // Determine if we want null termination or not.
784 Out << "\", false);";// No null terminator
786 // TODO: Could generate more efficient code generating CDS calls instead.
787 Out << "std::vector<Constant*> " << constName << "_elems;";
789 for (unsigned i = 0; i != CDS->getNumElements(); ++i) {
790 Constant *Elt = CDS->getElementAsConstant(i);
792 Out << constName << "_elems.push_back(" << getCppName(Elt) << ");";
795 Out << "Constant* " << constName;
797 if (isa<ArrayType>(CDS->getType()))
798 Out << " = ConstantArray::get(";
800 Out << " = ConstantVector::get(";
801 Out << typeName << ", " << constName << "_elems);";
803 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
804 if (CE->getOpcode() == Instruction::GetElementPtr) {
805 Out << "std::vector<Constant*> " << constName << "_indices;";
807 printConstant(CE->getOperand(0));
808 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
809 printConstant(CE->getOperand(i));
810 Out << constName << "_indices.push_back("
811 << getCppName(CE->getOperand(i)) << ");";
814 Out << "Constant* " << constName
815 << " = ConstantExpr::getGetElementPtr("
816 << getCppName(CE->getOperand(0)) << ", "
817 << constName << "_indices);";
818 } else if (CE->isCast()) {
819 printConstant(CE->getOperand(0));
820 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
821 switch (CE->getOpcode()) {
822 default: llvm_unreachable("Invalid cast opcode");
823 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
824 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
825 case Instruction::SExt: Out << "Instruction::SExt"; break;
826 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
827 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
828 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
829 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
830 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
831 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
832 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
833 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
834 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
836 Out << ", " << getCppName(CE->getOperand(0)) << ", "
837 << getCppName(CE->getType()) << ");";
839 unsigned N = CE->getNumOperands();
840 for (unsigned i = 0; i < N; ++i ) {
841 printConstant(CE->getOperand(i));
843 Out << "Constant* " << constName << " = ConstantExpr::";
844 switch (CE->getOpcode()) {
845 case Instruction::Add: Out << "getAdd("; break;
846 case Instruction::FAdd: Out << "getFAdd("; break;
847 case Instruction::Sub: Out << "getSub("; break;
848 case Instruction::FSub: Out << "getFSub("; break;
849 case Instruction::Mul: Out << "getMul("; break;
850 case Instruction::FMul: Out << "getFMul("; break;
851 case Instruction::UDiv: Out << "getUDiv("; break;
852 case Instruction::SDiv: Out << "getSDiv("; break;
853 case Instruction::FDiv: Out << "getFDiv("; break;
854 case Instruction::URem: Out << "getURem("; break;
855 case Instruction::SRem: Out << "getSRem("; break;
856 case Instruction::FRem: Out << "getFRem("; break;
857 case Instruction::And: Out << "getAnd("; break;
858 case Instruction::Or: Out << "getOr("; break;
859 case Instruction::Xor: Out << "getXor("; break;
860 case Instruction::ICmp:
861 Out << "getICmp(ICmpInst::ICMP_";
862 switch (CE->getPredicate()) {
863 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
864 case ICmpInst::ICMP_NE: Out << "NE"; break;
865 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
866 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
867 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
868 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
869 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
870 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
871 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
872 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
873 default: error("Invalid ICmp Predicate");
876 case Instruction::FCmp:
877 Out << "getFCmp(FCmpInst::FCMP_";
878 switch (CE->getPredicate()) {
879 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
880 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
881 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
882 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
883 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
884 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
885 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
886 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
887 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
888 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
889 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
890 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
891 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
892 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
893 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
894 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
895 default: error("Invalid FCmp Predicate");
898 case Instruction::Shl: Out << "getShl("; break;
899 case Instruction::LShr: Out << "getLShr("; break;
900 case Instruction::AShr: Out << "getAShr("; break;
901 case Instruction::Select: Out << "getSelect("; break;
902 case Instruction::ExtractElement: Out << "getExtractElement("; break;
903 case Instruction::InsertElement: Out << "getInsertElement("; break;
904 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
906 error("Invalid constant expression");
909 Out << getCppName(CE->getOperand(0));
910 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
911 Out << ", " << getCppName(CE->getOperand(i));
914 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
915 Out << "Constant* " << constName << " = ";
916 Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
918 error("Bad Constant");
919 Out << "Constant* " << constName << " = 0; ";
924 void CppWriter::printConstants(const Module* M) {
925 // Traverse all the global variables looking for constant initializers
926 for (Module::const_global_iterator I = TheModule->global_begin(),
927 E = TheModule->global_end(); I != E; ++I)
928 if (I->hasInitializer())
929 printConstant(I->getInitializer());
931 // Traverse the LLVM functions looking for constants
932 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
934 // Add all of the basic blocks and instructions
935 for (Function::const_iterator BB = FI->begin(),
936 E = FI->end(); BB != E; ++BB) {
937 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
939 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
940 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
949 void CppWriter::printVariableUses(const GlobalVariable *GV) {
950 nl(Out) << "// Type Definitions";
952 printType(GV->getType());
953 if (GV->hasInitializer()) {
954 const Constant *Init = GV->getInitializer();
955 printType(Init->getType());
956 if (const Function *F = dyn_cast<Function>(Init)) {
957 nl(Out)<< "/ Function Declarations"; nl(Out);
958 printFunctionHead(F);
959 } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
960 nl(Out) << "// Global Variable Declarations"; nl(Out);
961 printVariableHead(gv);
963 nl(Out) << "// Global Variable Definitions"; nl(Out);
964 printVariableBody(gv);
966 nl(Out) << "// Constant Definitions"; nl(Out);
972 void CppWriter::printVariableHead(const GlobalVariable *GV) {
973 nl(Out) << "GlobalVariable* " << getCppName(GV);
975 Out << " = mod->getGlobalVariable(mod->getContext(), ";
976 printEscapedString(GV->getName());
977 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
978 nl(Out) << "if (!" << getCppName(GV) << ") {";
979 in(); nl(Out) << getCppName(GV);
981 Out << " = new GlobalVariable(/*Module=*/*mod, ";
982 nl(Out) << "/*Type=*/";
983 printCppName(GV->getType()->getElementType());
985 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
987 nl(Out) << "/*Linkage=*/";
988 printLinkageType(GV->getLinkage());
990 nl(Out) << "/*Initializer=*/0, ";
991 if (GV->hasInitializer()) {
992 Out << "// has initializer, specified below";
994 nl(Out) << "/*Name=*/\"";
995 printEscapedString(GV->getName());
999 if (GV->hasSection()) {
1001 Out << "->setSection(\"";
1002 printEscapedString(GV->getSection());
1006 if (GV->getAlignment()) {
1008 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1011 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1013 Out << "->setVisibility(";
1014 printVisibilityType(GV->getVisibility());
1018 if (GV->isThreadLocal()) {
1020 Out << "->setThreadLocalMode(";
1021 printThreadLocalMode(GV->getThreadLocalMode());
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(const 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 static StringRef ConvertAtomicOrdering(AtomicOrdering Ordering) {
1064 case NotAtomic: return "NotAtomic";
1065 case Unordered: return "Unordered";
1066 case Monotonic: return "Monotonic";
1067 case Acquire: return "Acquire";
1068 case Release: return "Release";
1069 case AcquireRelease: return "AcquireRelease";
1070 case SequentiallyConsistent: return "SequentiallyConsistent";
1072 llvm_unreachable("Unknown ordering");
1075 static StringRef ConvertAtomicSynchScope(SynchronizationScope SynchScope) {
1076 switch (SynchScope) {
1077 case SingleThread: return "SingleThread";
1078 case CrossThread: return "CrossThread";
1080 llvm_unreachable("Unknown synch scope");
1083 // printInstruction - This member is called for each Instruction in a function.
1084 void CppWriter::printInstruction(const Instruction *I,
1085 const std::string& bbname) {
1086 std::string iName(getCppName(I));
1088 // Before we emit this instruction, we need to take care of generating any
1089 // forward references. So, we get the names of all the operands in advance
1090 const unsigned Ops(I->getNumOperands());
1091 std::string* opNames = new std::string[Ops];
1092 for (unsigned i = 0; i < Ops; i++)
1093 opNames[i] = getOpName(I->getOperand(i));
1095 switch (I->getOpcode()) {
1097 error("Invalid instruction");
1100 case Instruction::Ret: {
1101 const ReturnInst* ret = cast<ReturnInst>(I);
1102 Out << "ReturnInst::Create(mod->getContext(), "
1103 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1106 case Instruction::Br: {
1107 const BranchInst* br = cast<BranchInst>(I);
1108 Out << "BranchInst::Create(" ;
1109 if (br->getNumOperands() == 3) {
1110 Out << opNames[2] << ", "
1111 << opNames[1] << ", "
1112 << opNames[0] << ", ";
1114 } else if (br->getNumOperands() == 1) {
1115 Out << opNames[0] << ", ";
1117 error("Branch with 2 operands?");
1119 Out << bbname << ");";
1122 case Instruction::Switch: {
1123 const SwitchInst *SI = cast<SwitchInst>(I);
1124 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1125 << getOpName(SI->getCondition()) << ", "
1126 << getOpName(SI->getDefaultDest()) << ", "
1127 << SI->getNumCases() << ", " << bbname << ");";
1129 for (SwitchInst::ConstCaseIt i = SI->case_begin(), e = SI->case_end();
1131 const IntegersSubset CaseVal = i.getCaseValueEx();
1132 const BasicBlock *BB = i.getCaseSuccessor();
1133 Out << iName << "->addCase("
1134 << getOpName(CaseVal) << ", "
1135 << getOpName(BB) << ");";
1140 case Instruction::IndirectBr: {
1141 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1142 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1143 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1145 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1146 Out << iName << "->addDestination(" << opNames[i] << ");";
1151 case Instruction::Resume: {
1152 Out << "ResumeInst::Create(mod->getContext(), " << opNames[0]
1153 << ", " << bbname << ");";
1156 case Instruction::Invoke: {
1157 const InvokeInst* inv = cast<InvokeInst>(I);
1158 Out << "std::vector<Value*> " << iName << "_params;";
1160 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1161 Out << iName << "_params.push_back("
1162 << getOpName(inv->getArgOperand(i)) << ");";
1165 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1166 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1167 << getOpName(inv->getCalledFunction()) << ", "
1168 << getOpName(inv->getNormalDest()) << ", "
1169 << getOpName(inv->getUnwindDest()) << ", "
1170 << iName << "_params, \"";
1171 printEscapedString(inv->getName());
1172 Out << "\", " << bbname << ");";
1173 nl(Out) << iName << "->setCallingConv(";
1174 printCallingConv(inv->getCallingConv());
1176 printAttributes(inv->getAttributes(), iName);
1177 Out << iName << "->setAttributes(" << iName << "_PAL);";
1181 case Instruction::Unreachable: {
1182 Out << "new UnreachableInst("
1183 << "mod->getContext(), "
1187 case Instruction::Add:
1188 case Instruction::FAdd:
1189 case Instruction::Sub:
1190 case Instruction::FSub:
1191 case Instruction::Mul:
1192 case Instruction::FMul:
1193 case Instruction::UDiv:
1194 case Instruction::SDiv:
1195 case Instruction::FDiv:
1196 case Instruction::URem:
1197 case Instruction::SRem:
1198 case Instruction::FRem:
1199 case Instruction::And:
1200 case Instruction::Or:
1201 case Instruction::Xor:
1202 case Instruction::Shl:
1203 case Instruction::LShr:
1204 case Instruction::AShr:{
1205 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1206 switch (I->getOpcode()) {
1207 case Instruction::Add: Out << "Instruction::Add"; break;
1208 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1209 case Instruction::Sub: Out << "Instruction::Sub"; break;
1210 case Instruction::FSub: Out << "Instruction::FSub"; break;
1211 case Instruction::Mul: Out << "Instruction::Mul"; break;
1212 case Instruction::FMul: Out << "Instruction::FMul"; break;
1213 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1214 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1215 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1216 case Instruction::URem:Out << "Instruction::URem"; break;
1217 case Instruction::SRem:Out << "Instruction::SRem"; break;
1218 case Instruction::FRem:Out << "Instruction::FRem"; break;
1219 case Instruction::And: Out << "Instruction::And"; break;
1220 case Instruction::Or: Out << "Instruction::Or"; break;
1221 case Instruction::Xor: Out << "Instruction::Xor"; break;
1222 case Instruction::Shl: Out << "Instruction::Shl"; break;
1223 case Instruction::LShr:Out << "Instruction::LShr"; break;
1224 case Instruction::AShr:Out << "Instruction::AShr"; break;
1225 default: Out << "Instruction::BadOpCode"; break;
1227 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1228 printEscapedString(I->getName());
1229 Out << "\", " << bbname << ");";
1232 case Instruction::FCmp: {
1233 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1234 switch (cast<FCmpInst>(I)->getPredicate()) {
1235 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1236 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1237 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1238 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1239 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1240 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1241 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1242 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1243 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1244 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1245 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1246 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1247 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1248 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1249 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1250 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1251 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1253 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1254 printEscapedString(I->getName());
1258 case Instruction::ICmp: {
1259 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1260 switch (cast<ICmpInst>(I)->getPredicate()) {
1261 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1262 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1263 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1264 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1265 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1266 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1267 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1268 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1269 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1270 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1271 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1273 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1274 printEscapedString(I->getName());
1278 case Instruction::Alloca: {
1279 const AllocaInst* allocaI = cast<AllocaInst>(I);
1280 Out << "AllocaInst* " << iName << " = new AllocaInst("
1281 << getCppName(allocaI->getAllocatedType()) << ", ";
1282 if (allocaI->isArrayAllocation())
1283 Out << opNames[0] << ", ";
1285 printEscapedString(allocaI->getName());
1286 Out << "\", " << bbname << ");";
1287 if (allocaI->getAlignment())
1288 nl(Out) << iName << "->setAlignment("
1289 << allocaI->getAlignment() << ");";
1292 case Instruction::Load: {
1293 const LoadInst* load = cast<LoadInst>(I);
1294 Out << "LoadInst* " << iName << " = new LoadInst("
1295 << opNames[0] << ", \"";
1296 printEscapedString(load->getName());
1297 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1298 << ", " << bbname << ");";
1299 if (load->getAlignment())
1300 nl(Out) << iName << "->setAlignment("
1301 << load->getAlignment() << ");";
1302 if (load->isAtomic()) {
1303 StringRef Ordering = ConvertAtomicOrdering(load->getOrdering());
1304 StringRef CrossThread = ConvertAtomicSynchScope(load->getSynchScope());
1305 nl(Out) << iName << "->setAtomic("
1306 << Ordering << ", " << CrossThread << ");";
1310 case Instruction::Store: {
1311 const StoreInst* store = cast<StoreInst>(I);
1312 Out << "StoreInst* " << iName << " = new StoreInst("
1313 << opNames[0] << ", "
1314 << opNames[1] << ", "
1315 << (store->isVolatile() ? "true" : "false")
1316 << ", " << bbname << ");";
1317 if (store->getAlignment())
1318 nl(Out) << iName << "->setAlignment("
1319 << store->getAlignment() << ");";
1320 if (store->isAtomic()) {
1321 StringRef Ordering = ConvertAtomicOrdering(store->getOrdering());
1322 StringRef CrossThread = ConvertAtomicSynchScope(store->getSynchScope());
1323 nl(Out) << iName << "->setAtomic("
1324 << Ordering << ", " << CrossThread << ");";
1328 case Instruction::GetElementPtr: {
1329 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1330 if (gep->getNumOperands() <= 2) {
1331 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1333 if (gep->getNumOperands() == 2)
1334 Out << ", " << opNames[1];
1336 Out << "std::vector<Value*> " << iName << "_indices;";
1338 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1339 Out << iName << "_indices.push_back("
1340 << opNames[i] << ");";
1343 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1344 << opNames[0] << ", " << iName << "_indices";
1347 printEscapedString(gep->getName());
1348 Out << "\", " << bbname << ");";
1351 case Instruction::PHI: {
1352 const PHINode* phi = cast<PHINode>(I);
1354 Out << "PHINode* " << iName << " = PHINode::Create("
1355 << getCppName(phi->getType()) << ", "
1356 << phi->getNumIncomingValues() << ", \"";
1357 printEscapedString(phi->getName());
1358 Out << "\", " << bbname << ");";
1360 for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
1361 Out << iName << "->addIncoming("
1362 << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
1363 << getOpName(phi->getIncomingBlock(i)) << ");";
1368 case Instruction::Trunc:
1369 case Instruction::ZExt:
1370 case Instruction::SExt:
1371 case Instruction::FPTrunc:
1372 case Instruction::FPExt:
1373 case Instruction::FPToUI:
1374 case Instruction::FPToSI:
1375 case Instruction::UIToFP:
1376 case Instruction::SIToFP:
1377 case Instruction::PtrToInt:
1378 case Instruction::IntToPtr:
1379 case Instruction::BitCast: {
1380 const CastInst* cst = cast<CastInst>(I);
1381 Out << "CastInst* " << iName << " = new ";
1382 switch (I->getOpcode()) {
1383 case Instruction::Trunc: Out << "TruncInst"; break;
1384 case Instruction::ZExt: Out << "ZExtInst"; break;
1385 case Instruction::SExt: Out << "SExtInst"; break;
1386 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1387 case Instruction::FPExt: Out << "FPExtInst"; break;
1388 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1389 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1390 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1391 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1392 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1393 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1394 case Instruction::BitCast: Out << "BitCastInst"; break;
1395 default: llvm_unreachable("Unreachable");
1397 Out << "(" << opNames[0] << ", "
1398 << getCppName(cst->getType()) << ", \"";
1399 printEscapedString(cst->getName());
1400 Out << "\", " << bbname << ");";
1403 case Instruction::Call: {
1404 const CallInst* call = cast<CallInst>(I);
1405 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1406 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1407 << getCppName(ila->getFunctionType()) << ", \""
1408 << ila->getAsmString() << "\", \""
1409 << ila->getConstraintString() << "\","
1410 << (ila->hasSideEffects() ? "true" : "false") << ");";
1413 if (call->getNumArgOperands() > 1) {
1414 Out << "std::vector<Value*> " << iName << "_params;";
1416 for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
1417 Out << iName << "_params.push_back(" << opNames[i] << ");";
1420 Out << "CallInst* " << iName << " = CallInst::Create("
1421 << opNames[call->getNumArgOperands()] << ", "
1422 << iName << "_params, \"";
1423 } else if (call->getNumArgOperands() == 1) {
1424 Out << "CallInst* " << iName << " = CallInst::Create("
1425 << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
1427 Out << "CallInst* " << iName << " = CallInst::Create("
1428 << opNames[call->getNumArgOperands()] << ", \"";
1430 printEscapedString(call->getName());
1431 Out << "\", " << bbname << ");";
1432 nl(Out) << iName << "->setCallingConv(";
1433 printCallingConv(call->getCallingConv());
1435 nl(Out) << iName << "->setTailCall("
1436 << (call->isTailCall() ? "true" : "false");
1439 printAttributes(call->getAttributes(), iName);
1440 Out << iName << "->setAttributes(" << iName << "_PAL);";
1444 case Instruction::Select: {
1445 const SelectInst* sel = cast<SelectInst>(I);
1446 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1447 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1448 printEscapedString(sel->getName());
1449 Out << "\", " << bbname << ");";
1452 case Instruction::UserOp1:
1454 case Instruction::UserOp2: {
1455 /// FIXME: What should be done here?
1458 case Instruction::VAArg: {
1459 const VAArgInst* va = cast<VAArgInst>(I);
1460 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1461 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1462 printEscapedString(va->getName());
1463 Out << "\", " << bbname << ");";
1466 case Instruction::ExtractElement: {
1467 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1468 Out << "ExtractElementInst* " << getCppName(eei)
1469 << " = new ExtractElementInst(" << opNames[0]
1470 << ", " << opNames[1] << ", \"";
1471 printEscapedString(eei->getName());
1472 Out << "\", " << bbname << ");";
1475 case Instruction::InsertElement: {
1476 const InsertElementInst* iei = cast<InsertElementInst>(I);
1477 Out << "InsertElementInst* " << getCppName(iei)
1478 << " = InsertElementInst::Create(" << opNames[0]
1479 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1480 printEscapedString(iei->getName());
1481 Out << "\", " << bbname << ");";
1484 case Instruction::ShuffleVector: {
1485 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1486 Out << "ShuffleVectorInst* " << getCppName(svi)
1487 << " = new ShuffleVectorInst(" << opNames[0]
1488 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1489 printEscapedString(svi->getName());
1490 Out << "\", " << bbname << ");";
1493 case Instruction::ExtractValue: {
1494 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1495 Out << "std::vector<unsigned> " << iName << "_indices;";
1497 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1498 Out << iName << "_indices.push_back("
1499 << evi->idx_begin()[i] << ");";
1502 Out << "ExtractValueInst* " << getCppName(evi)
1503 << " = ExtractValueInst::Create(" << opNames[0]
1505 << iName << "_indices, \"";
1506 printEscapedString(evi->getName());
1507 Out << "\", " << bbname << ");";
1510 case Instruction::InsertValue: {
1511 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1512 Out << "std::vector<unsigned> " << iName << "_indices;";
1514 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1515 Out << iName << "_indices.push_back("
1516 << ivi->idx_begin()[i] << ");";
1519 Out << "InsertValueInst* " << getCppName(ivi)
1520 << " = InsertValueInst::Create(" << opNames[0]
1521 << ", " << opNames[1] << ", "
1522 << iName << "_indices, \"";
1523 printEscapedString(ivi->getName());
1524 Out << "\", " << bbname << ");";
1527 case Instruction::Fence: {
1528 const FenceInst *fi = cast<FenceInst>(I);
1529 StringRef Ordering = ConvertAtomicOrdering(fi->getOrdering());
1530 StringRef CrossThread = ConvertAtomicSynchScope(fi->getSynchScope());
1531 Out << "FenceInst* " << iName
1532 << " = new FenceInst(mod->getContext(), "
1533 << Ordering << ", " << CrossThread << ", " << bbname
1537 case Instruction::AtomicCmpXchg: {
1538 const AtomicCmpXchgInst *cxi = cast<AtomicCmpXchgInst>(I);
1539 StringRef Ordering = ConvertAtomicOrdering(cxi->getOrdering());
1540 StringRef CrossThread = ConvertAtomicSynchScope(cxi->getSynchScope());
1541 Out << "AtomicCmpXchgInst* " << iName
1542 << " = new AtomicCmpXchgInst("
1543 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", "
1544 << Ordering << ", " << CrossThread << ", " << bbname
1546 nl(Out) << iName << "->setName(\"";
1547 printEscapedString(cxi->getName());
1551 case Instruction::AtomicRMW: {
1552 const AtomicRMWInst *rmwi = cast<AtomicRMWInst>(I);
1553 StringRef Ordering = ConvertAtomicOrdering(rmwi->getOrdering());
1554 StringRef CrossThread = ConvertAtomicSynchScope(rmwi->getSynchScope());
1555 StringRef Operation;
1556 switch (rmwi->getOperation()) {
1557 case AtomicRMWInst::Xchg: Operation = "AtomicRMWInst::Xchg"; break;
1558 case AtomicRMWInst::Add: Operation = "AtomicRMWInst::Add"; break;
1559 case AtomicRMWInst::Sub: Operation = "AtomicRMWInst::Sub"; break;
1560 case AtomicRMWInst::And: Operation = "AtomicRMWInst::And"; break;
1561 case AtomicRMWInst::Nand: Operation = "AtomicRMWInst::Nand"; break;
1562 case AtomicRMWInst::Or: Operation = "AtomicRMWInst::Or"; break;
1563 case AtomicRMWInst::Xor: Operation = "AtomicRMWInst::Xor"; break;
1564 case AtomicRMWInst::Max: Operation = "AtomicRMWInst::Max"; break;
1565 case AtomicRMWInst::Min: Operation = "AtomicRMWInst::Min"; break;
1566 case AtomicRMWInst::UMax: Operation = "AtomicRMWInst::UMax"; break;
1567 case AtomicRMWInst::UMin: Operation = "AtomicRMWInst::UMin"; break;
1568 case AtomicRMWInst::BAD_BINOP: llvm_unreachable("Bad atomic operation");
1570 Out << "AtomicRMWInst* " << iName
1571 << " = new AtomicRMWInst("
1572 << Operation << ", "
1573 << opNames[0] << ", " << opNames[1] << ", "
1574 << Ordering << ", " << CrossThread << ", " << bbname
1576 nl(Out) << iName << "->setName(\"";
1577 printEscapedString(rmwi->getName());
1582 DefinedValues.insert(I);
1587 // Print out the types, constants and declarations needed by one function
1588 void CppWriter::printFunctionUses(const Function* F) {
1589 nl(Out) << "// Type Definitions"; nl(Out);
1591 // Print the function's return type
1592 printType(F->getReturnType());
1594 // Print the function's function type
1595 printType(F->getFunctionType());
1597 // Print the types of each of the function's arguments
1598 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1600 printType(AI->getType());
1604 // Print type definitions for every type referenced by an instruction and
1605 // make a note of any global values or constants that are referenced
1606 SmallPtrSet<GlobalValue*,64> gvs;
1607 SmallPtrSet<Constant*,64> consts;
1608 for (Function::const_iterator BB = F->begin(), BE = F->end();
1610 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1612 // Print the type of the instruction itself
1613 printType(I->getType());
1615 // Print the type of each of the instruction's operands
1616 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1617 Value* operand = I->getOperand(i);
1618 printType(operand->getType());
1620 // If the operand references a GVal or Constant, make a note of it
1621 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1623 if (GenerationType != GenFunction)
1624 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1625 if (GVar->hasInitializer())
1626 consts.insert(GVar->getInitializer());
1627 } else if (Constant* C = dyn_cast<Constant>(operand)) {
1629 for (unsigned j = 0; j < C->getNumOperands(); ++j) {
1630 // If the operand references a GVal or Constant, make a note of it
1631 Value* operand = C->getOperand(j);
1632 printType(operand->getType());
1633 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1635 if (GenerationType != GenFunction)
1636 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1637 if (GVar->hasInitializer())
1638 consts.insert(GVar->getInitializer());
1646 // Print the function declarations for any functions encountered
1647 nl(Out) << "// Function Declarations"; nl(Out);
1648 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1650 if (Function* Fun = dyn_cast<Function>(*I)) {
1651 if (!is_inline || Fun != F)
1652 printFunctionHead(Fun);
1656 // Print the global variable declarations for any variables encountered
1657 nl(Out) << "// Global Variable Declarations"; nl(Out);
1658 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1660 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1661 printVariableHead(F);
1664 // Print the constants found
1665 nl(Out) << "// Constant Definitions"; nl(Out);
1666 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1667 E = consts.end(); I != E; ++I) {
1671 // Process the global variables definitions now that all the constants have
1672 // been emitted. These definitions just couple the gvars with their constant
1674 if (GenerationType != GenFunction) {
1675 nl(Out) << "// Global Variable Definitions"; nl(Out);
1676 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1678 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1679 printVariableBody(GV);
1684 void CppWriter::printFunctionHead(const Function* F) {
1685 nl(Out) << "Function* " << getCppName(F);
1686 Out << " = mod->getFunction(\"";
1687 printEscapedString(F->getName());
1689 nl(Out) << "if (!" << getCppName(F) << ") {";
1690 nl(Out) << getCppName(F);
1692 Out<< " = Function::Create(";
1693 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1694 nl(Out) << "/*Linkage=*/";
1695 printLinkageType(F->getLinkage());
1697 nl(Out) << "/*Name=*/\"";
1698 printEscapedString(F->getName());
1699 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1702 Out << "->setCallingConv(";
1703 printCallingConv(F->getCallingConv());
1706 if (F->hasSection()) {
1708 Out << "->setSection(\"" << F->getSection() << "\");";
1711 if (F->getAlignment()) {
1713 Out << "->setAlignment(" << F->getAlignment() << ");";
1716 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1718 Out << "->setVisibility(";
1719 printVisibilityType(F->getVisibility());
1725 Out << "->setGC(\"" << F->getGC() << "\");";
1730 printAttributes(F->getAttributes(), getCppName(F));
1732 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1736 void CppWriter::printFunctionBody(const Function *F) {
1737 if (F->isDeclaration())
1738 return; // external functions have no bodies.
1740 // Clear the DefinedValues and ForwardRefs maps because we can't have
1741 // cross-function forward refs
1742 ForwardRefs.clear();
1743 DefinedValues.clear();
1745 // Create all the argument values
1747 if (!F->arg_empty()) {
1748 Out << "Function::arg_iterator args = " << getCppName(F)
1749 << "->arg_begin();";
1752 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1754 Out << "Value* " << getCppName(AI) << " = args++;";
1756 if (AI->hasName()) {
1757 Out << getCppName(AI) << "->setName(\"";
1758 printEscapedString(AI->getName());
1765 // Create all the basic blocks
1767 for (Function::const_iterator BI = F->begin(), BE = F->end();
1769 std::string bbname(getCppName(BI));
1770 Out << "BasicBlock* " << bbname <<
1771 " = BasicBlock::Create(mod->getContext(), \"";
1773 printEscapedString(BI->getName());
1774 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1778 // Output all of its basic blocks... for the function
1779 for (Function::const_iterator BI = F->begin(), BE = F->end();
1781 std::string bbname(getCppName(BI));
1782 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1785 // Output all of the instructions in the basic block...
1786 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1788 printInstruction(I,bbname);
1792 // Loop over the ForwardRefs and resolve them now that all instructions
1794 if (!ForwardRefs.empty()) {
1795 nl(Out) << "// Resolve Forward References";
1799 while (!ForwardRefs.empty()) {
1800 ForwardRefMap::iterator I = ForwardRefs.begin();
1801 Out << I->second << "->replaceAllUsesWith("
1802 << getCppName(I->first) << "); delete " << I->second << ";";
1804 ForwardRefs.erase(I);
1808 void CppWriter::printInline(const std::string& fname,
1809 const std::string& func) {
1810 const Function* F = TheModule->getFunction(func);
1812 error(std::string("Function '") + func + "' not found in input module");
1815 if (F->isDeclaration()) {
1816 error(std::string("Function '") + func + "' is external!");
1819 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1821 unsigned arg_count = 1;
1822 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1824 Out << ", Value* arg_" << arg_count;
1829 printFunctionUses(F);
1830 printFunctionBody(F);
1832 Out << "return " << getCppName(F->begin()) << ";";
1837 void CppWriter::printModuleBody() {
1838 // Print out all the type definitions
1839 nl(Out) << "// Type Definitions"; nl(Out);
1840 printTypes(TheModule);
1842 // Functions can call each other and global variables can reference them so
1843 // define all the functions first before emitting their function bodies.
1844 nl(Out) << "// Function Declarations"; nl(Out);
1845 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1847 printFunctionHead(I);
1849 // Process the global variables declarations. We can't initialze them until
1850 // after the constants are printed so just print a header for each global
1851 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1852 for (Module::const_global_iterator I = TheModule->global_begin(),
1853 E = TheModule->global_end(); I != E; ++I) {
1854 printVariableHead(I);
1857 // Print out all the constants definitions. Constants don't recurse except
1858 // through GlobalValues. All GlobalValues have been declared at this point
1859 // so we can proceed to generate the constants.
1860 nl(Out) << "// Constant Definitions"; nl(Out);
1861 printConstants(TheModule);
1863 // Process the global variables definitions now that all the constants have
1864 // been emitted. These definitions just couple the gvars with their constant
1866 nl(Out) << "// Global Variable Definitions"; nl(Out);
1867 for (Module::const_global_iterator I = TheModule->global_begin(),
1868 E = TheModule->global_end(); I != E; ++I) {
1869 printVariableBody(I);
1872 // Finally, we can safely put out all of the function bodies.
1873 nl(Out) << "// Function Definitions"; nl(Out);
1874 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1876 if (!I->isDeclaration()) {
1877 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1881 printFunctionBody(I);
1888 void CppWriter::printProgram(const std::string& fname,
1889 const std::string& mName) {
1890 Out << "#include <llvm/LLVMContext.h>\n";
1891 Out << "#include <llvm/Module.h>\n";
1892 Out << "#include <llvm/DerivedTypes.h>\n";
1893 Out << "#include <llvm/Constants.h>\n";
1894 Out << "#include <llvm/GlobalVariable.h>\n";
1895 Out << "#include <llvm/Function.h>\n";
1896 Out << "#include <llvm/CallingConv.h>\n";
1897 Out << "#include <llvm/BasicBlock.h>\n";
1898 Out << "#include <llvm/Instructions.h>\n";
1899 Out << "#include <llvm/InlineAsm.h>\n";
1900 Out << "#include <llvm/Support/FormattedStream.h>\n";
1901 Out << "#include <llvm/Support/MathExtras.h>\n";
1902 Out << "#include <llvm/Pass.h>\n";
1903 Out << "#include <llvm/PassManager.h>\n";
1904 Out << "#include <llvm/ADT/SmallVector.h>\n";
1905 Out << "#include <llvm/Analysis/Verifier.h>\n";
1906 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1907 Out << "#include <algorithm>\n";
1908 Out << "using namespace llvm;\n\n";
1909 Out << "Module* " << fname << "();\n\n";
1910 Out << "int main(int argc, char**argv) {\n";
1911 Out << " Module* Mod = " << fname << "();\n";
1912 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1913 Out << " PassManager PM;\n";
1914 Out << " PM.add(createPrintModulePass(&outs()));\n";
1915 Out << " PM.run(*Mod);\n";
1916 Out << " return 0;\n";
1918 printModule(fname,mName);
1921 void CppWriter::printModule(const std::string& fname,
1922 const std::string& mName) {
1923 nl(Out) << "Module* " << fname << "() {";
1924 nl(Out,1) << "// Module Construction";
1925 nl(Out) << "Module* mod = new Module(\"";
1926 printEscapedString(mName);
1927 Out << "\", getGlobalContext());";
1928 if (!TheModule->getTargetTriple().empty()) {
1929 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1931 if (!TheModule->getTargetTriple().empty()) {
1932 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1936 if (!TheModule->getModuleInlineAsm().empty()) {
1937 nl(Out) << "mod->setModuleInlineAsm(\"";
1938 printEscapedString(TheModule->getModuleInlineAsm());
1943 // Loop over the dependent libraries and emit them.
1944 Module::lib_iterator LI = TheModule->lib_begin();
1945 Module::lib_iterator LE = TheModule->lib_end();
1947 Out << "mod->addLibrary(\"" << *LI << "\");";
1952 nl(Out) << "return mod;";
1957 void CppWriter::printContents(const std::string& fname,
1958 const std::string& mName) {
1959 Out << "\nModule* " << fname << "(Module *mod) {\n";
1960 Out << "\nmod->setModuleIdentifier(\"";
1961 printEscapedString(mName);
1964 Out << "\nreturn mod;\n";
1968 void CppWriter::printFunction(const std::string& fname,
1969 const std::string& funcName) {
1970 const Function* F = TheModule->getFunction(funcName);
1972 error(std::string("Function '") + funcName + "' not found in input module");
1975 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1976 printFunctionUses(F);
1977 printFunctionHead(F);
1978 printFunctionBody(F);
1979 Out << "return " << getCppName(F) << ";\n";
1983 void CppWriter::printFunctions() {
1984 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1985 Module::const_iterator I = funcs.begin();
1986 Module::const_iterator IE = funcs.end();
1988 for (; I != IE; ++I) {
1989 const Function &func = *I;
1990 if (!func.isDeclaration()) {
1991 std::string name("define_");
1992 name += func.getName();
1993 printFunction(name, func.getName());
1998 void CppWriter::printVariable(const std::string& fname,
1999 const std::string& varName) {
2000 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
2003 error(std::string("Variable '") + varName + "' not found in input module");
2006 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
2007 printVariableUses(GV);
2008 printVariableHead(GV);
2009 printVariableBody(GV);
2010 Out << "return " << getCppName(GV) << ";\n";
2014 void CppWriter::printType(const std::string &fname,
2015 const std::string &typeName) {
2016 Type* Ty = TheModule->getTypeByName(typeName);
2018 error(std::string("Type '") + typeName + "' not found in input module");
2021 Out << "\nType* " << fname << "(Module *mod) {\n";
2023 Out << "return " << getCppName(Ty) << ";\n";
2027 bool CppWriter::runOnModule(Module &M) {
2031 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
2033 // Get the name of the function we're supposed to generate
2034 std::string fname = FuncName.getValue();
2036 // Get the name of the thing we are to generate
2037 std::string tgtname = NameToGenerate.getValue();
2038 if (GenerationType == GenModule ||
2039 GenerationType == GenContents ||
2040 GenerationType == GenProgram ||
2041 GenerationType == GenFunctions) {
2042 if (tgtname == "!bad!") {
2043 if (M.getModuleIdentifier() == "-")
2044 tgtname = "<stdin>";
2046 tgtname = M.getModuleIdentifier();
2048 } else if (tgtname == "!bad!")
2049 error("You must use the -for option with -gen-{function,variable,type}");
2051 switch (WhatToGenerate(GenerationType)) {
2054 fname = "makeLLVMModule";
2055 printProgram(fname,tgtname);
2059 fname = "makeLLVMModule";
2060 printModule(fname,tgtname);
2064 fname = "makeLLVMModuleContents";
2065 printContents(fname,tgtname);
2069 fname = "makeLLVMFunction";
2070 printFunction(fname,tgtname);
2077 fname = "makeLLVMInline";
2078 printInline(fname,tgtname);
2082 fname = "makeLLVMVariable";
2083 printVariable(fname,tgtname);
2087 fname = "makeLLVMType";
2088 printType(fname,tgtname);
2095 char CppWriter::ID = 0;
2097 //===----------------------------------------------------------------------===//
2098 // External Interface declaration
2099 //===----------------------------------------------------------------------===//
2101 bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
2102 formatted_raw_ostream &o,
2103 CodeGenFileType FileType,
2105 AnalysisID StartAfter,
2106 AnalysisID StopAfter) {
2107 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
2108 PM.add(new CppWriter(o));