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"
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);
81 typedef std::vector<Type*> TypeList;
82 typedef std::map<Type*,std::string> TypeMap;
83 typedef std::map<const Value*,std::string> ValueMap;
84 typedef std::set<std::string> NameSet;
85 typedef std::set<Type*> TypeSet;
86 typedef std::set<const Value*> ValueSet;
87 typedef std::map<const Value*,std::string> ForwardRefMap;
89 /// CppWriter - This class is the main chunk of code that converts an LLVM
90 /// module to a C++ translation unit.
91 class CppWriter : public ModulePass {
92 formatted_raw_ostream &Out;
93 const Module *TheModule;
99 ValueSet DefinedValues;
100 ForwardRefMap ForwardRefs;
102 unsigned indent_level;
106 explicit CppWriter(formatted_raw_ostream &o) :
107 ModulePass(ID), Out(o), uniqueNum(0), is_inline(false), indent_level(0){}
109 virtual const char *getPassName() const { return "C++ backend"; }
111 bool runOnModule(Module &M);
113 void printProgram(const std::string& fname, const std::string& modName );
114 void printModule(const std::string& fname, const std::string& modName );
115 void printContents(const std::string& fname, const std::string& modName );
116 void printFunction(const std::string& fname, const std::string& funcName );
117 void printFunctions();
118 void printInline(const std::string& fname, const std::string& funcName );
119 void printVariable(const std::string& fname, const std::string& varName );
120 void printType(const std::string& fname, const std::string& typeName );
122 void error(const std::string& msg);
125 formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0);
126 inline void in() { indent_level++; }
127 inline void out() { if (indent_level >0) indent_level--; }
130 void printLinkageType(GlobalValue::LinkageTypes LT);
131 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
132 void printCallingConv(CallingConv::ID cc);
133 void printEscapedString(const std::string& str);
134 void printCFP(const ConstantFP* CFP);
136 std::string getCppName(Type* val);
137 inline void printCppName(Type* val);
139 std::string getCppName(const Value* val);
140 inline void printCppName(const Value* val);
142 void printAttributes(const AttrListPtr &PAL, const std::string &name);
143 void printType(Type* Ty);
144 void printTypes(const Module* M);
146 void printConstant(const Constant *CPV);
147 void printConstants(const Module* M);
149 void printVariableUses(const GlobalVariable *GV);
150 void printVariableHead(const GlobalVariable *GV);
151 void printVariableBody(const GlobalVariable *GV);
153 void printFunctionUses(const Function *F);
154 void printFunctionHead(const Function *F);
155 void printFunctionBody(const Function *F);
156 void printInstruction(const Instruction *I, const std::string& bbname);
157 std::string getOpName(const Value*);
159 void printModuleBody();
161 } // end anonymous namespace.
163 formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
165 if (delta >= 0 || indent_level >= unsigned(-delta))
166 indent_level += delta;
167 Out.indent(indent_level);
171 static inline void sanitize(std::string &str) {
172 for (size_t i = 0; i < str.length(); ++i)
173 if (!isalnum(str[i]) && str[i] != '_')
177 static std::string getTypePrefix(Type *Ty) {
178 switch (Ty->getTypeID()) {
179 case Type::VoidTyID: return "void_";
180 case Type::IntegerTyID:
181 return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
182 case Type::FloatTyID: return "float_";
183 case Type::DoubleTyID: return "double_";
184 case Type::LabelTyID: return "label_";
185 case Type::FunctionTyID: return "func_";
186 case Type::StructTyID: return "struct_";
187 case Type::ArrayTyID: return "array_";
188 case Type::PointerTyID: return "ptr_";
189 case Type::VectorTyID: return "packed_";
190 default: return "other_";
194 void CppWriter::error(const std::string& msg) {
195 report_fatal_error(msg);
198 static inline std::string ftostr(const APFloat& V) {
200 if (&V.getSemantics() == &APFloat::IEEEdouble) {
201 raw_string_ostream(Buf) << V.convertToDouble();
203 } else if (&V.getSemantics() == &APFloat::IEEEsingle) {
204 raw_string_ostream(Buf) << (double)V.convertToFloat();
207 return "<unknown format in ftostr>"; // error
210 // printCFP - Print a floating point constant .. very carefully :)
211 // This makes sure that conversion to/from floating yields the same binary
212 // result so that we don't lose precision.
213 void CppWriter::printCFP(const ConstantFP *CFP) {
215 APFloat APF = APFloat(CFP->getValueAPF()); // copy
216 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
217 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
218 Out << "ConstantFP::get(mod->getContext(), ";
222 sprintf(Buffer, "%A", APF.convertToDouble());
223 if ((!strncmp(Buffer, "0x", 2) ||
224 !strncmp(Buffer, "-0x", 3) ||
225 !strncmp(Buffer, "+0x", 3)) &&
226 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
227 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
228 Out << "BitsToDouble(" << Buffer << ")";
230 Out << "BitsToFloat((float)" << Buffer << ")";
234 std::string StrVal = ftostr(CFP->getValueAPF());
236 while (StrVal[0] == ' ')
237 StrVal.erase(StrVal.begin());
239 // Check to make sure that the stringized number is not some string like
240 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
241 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
242 ((StrVal[0] == '-' || StrVal[0] == '+') &&
243 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
244 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
245 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
248 Out << StrVal << "f";
249 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
250 Out << "BitsToDouble(0x"
251 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
252 << "ULL) /* " << StrVal << " */";
254 Out << "BitsToFloat(0x"
255 << utohexstr((uint32_t)CFP->getValueAPF().
256 bitcastToAPInt().getZExtValue())
257 << "U) /* " << StrVal << " */";
265 void CppWriter::printCallingConv(CallingConv::ID cc){
266 // Print the calling convention.
268 case CallingConv::C: Out << "CallingConv::C"; break;
269 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
270 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
271 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
272 default: Out << cc; break;
276 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
278 case GlobalValue::InternalLinkage:
279 Out << "GlobalValue::InternalLinkage"; break;
280 case GlobalValue::PrivateLinkage:
281 Out << "GlobalValue::PrivateLinkage"; break;
282 case GlobalValue::LinkerPrivateLinkage:
283 Out << "GlobalValue::LinkerPrivateLinkage"; break;
284 case GlobalValue::LinkerPrivateWeakLinkage:
285 Out << "GlobalValue::LinkerPrivateWeakLinkage"; break;
286 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
287 Out << "GlobalValue::LinkerPrivateWeakDefAutoLinkage"; break;
288 case GlobalValue::AvailableExternallyLinkage:
289 Out << "GlobalValue::AvailableExternallyLinkage "; break;
290 case GlobalValue::LinkOnceAnyLinkage:
291 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
292 case GlobalValue::LinkOnceODRLinkage:
293 Out << "GlobalValue::LinkOnceODRLinkage "; break;
294 case GlobalValue::WeakAnyLinkage:
295 Out << "GlobalValue::WeakAnyLinkage"; break;
296 case GlobalValue::WeakODRLinkage:
297 Out << "GlobalValue::WeakODRLinkage"; break;
298 case GlobalValue::AppendingLinkage:
299 Out << "GlobalValue::AppendingLinkage"; break;
300 case GlobalValue::ExternalLinkage:
301 Out << "GlobalValue::ExternalLinkage"; break;
302 case GlobalValue::DLLImportLinkage:
303 Out << "GlobalValue::DLLImportLinkage"; break;
304 case GlobalValue::DLLExportLinkage:
305 Out << "GlobalValue::DLLExportLinkage"; break;
306 case GlobalValue::ExternalWeakLinkage:
307 Out << "GlobalValue::ExternalWeakLinkage"; break;
308 case GlobalValue::CommonLinkage:
309 Out << "GlobalValue::CommonLinkage"; break;
313 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
315 case GlobalValue::DefaultVisibility:
316 Out << "GlobalValue::DefaultVisibility";
318 case GlobalValue::HiddenVisibility:
319 Out << "GlobalValue::HiddenVisibility";
321 case GlobalValue::ProtectedVisibility:
322 Out << "GlobalValue::ProtectedVisibility";
327 // printEscapedString - Print each character of the specified string, escaping
328 // it if it is not printable or if it is an escape char.
329 void CppWriter::printEscapedString(const std::string &Str) {
330 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
331 unsigned char C = Str[i];
332 if (isprint(C) && C != '"' && C != '\\') {
336 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
337 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
342 std::string CppWriter::getCppName(Type* Ty) {
343 // First, handle the primitive types .. easy
344 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
345 switch (Ty->getTypeID()) {
346 case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())";
347 case Type::IntegerTyID: {
348 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
349 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
351 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
352 case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())";
353 case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())";
354 case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())";
355 case Type::X86_MMXTyID: return "Type::getX86_MMXTy(mod->getContext())";
357 error("Invalid primitive type");
360 // shouldn't be returned, but make it sensible
361 return "Type::getVoidTy(mod->getContext())";
364 // Now, see if we've seen the type before and return that
365 TypeMap::iterator I = TypeNames.find(Ty);
366 if (I != TypeNames.end())
369 // Okay, let's build a new name for this type. Start with a prefix
370 const char* prefix = 0;
371 switch (Ty->getTypeID()) {
372 case Type::FunctionTyID: prefix = "FuncTy_"; break;
373 case Type::StructTyID: prefix = "StructTy_"; break;
374 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
375 case Type::PointerTyID: prefix = "PointerTy_"; break;
376 case Type::VectorTyID: prefix = "VectorTy_"; break;
377 default: prefix = "OtherTy_"; break; // prevent breakage
380 // See if the type has a name in the symboltable and build accordingly
382 if (StructType *STy = dyn_cast<StructType>(Ty))
384 name = STy->getName();
387 name = utostr(uniqueNum++);
389 name = std::string(prefix) + name;
393 return TypeNames[Ty] = name;
396 void CppWriter::printCppName(Type* Ty) {
397 printEscapedString(getCppName(Ty));
400 std::string CppWriter::getCppName(const Value* val) {
402 ValueMap::iterator I = ValueNames.find(val);
403 if (I != ValueNames.end() && I->first == val)
406 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
407 name = std::string("gvar_") +
408 getTypePrefix(GV->getType()->getElementType());
409 } else if (isa<Function>(val)) {
410 name = std::string("func_");
411 } else if (const Constant* C = dyn_cast<Constant>(val)) {
412 name = std::string("const_") + getTypePrefix(C->getType());
413 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
415 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
416 Function::const_arg_iterator(Arg)) + 1;
417 name = std::string("arg_") + utostr(argNum);
418 NameSet::iterator NI = UsedNames.find(name);
419 if (NI != UsedNames.end())
420 name += std::string("_") + utostr(uniqueNum++);
421 UsedNames.insert(name);
422 return ValueNames[val] = name;
424 name = getTypePrefix(val->getType());
427 name = getTypePrefix(val->getType());
430 name += val->getName();
432 name += utostr(uniqueNum++);
434 NameSet::iterator NI = UsedNames.find(name);
435 if (NI != UsedNames.end())
436 name += std::string("_") + utostr(uniqueNum++);
437 UsedNames.insert(name);
438 return ValueNames[val] = name;
441 void CppWriter::printCppName(const Value* val) {
442 printEscapedString(getCppName(val));
445 void CppWriter::printAttributes(const AttrListPtr &PAL,
446 const std::string &name) {
447 Out << "AttrListPtr " << name << "_PAL;";
449 if (!PAL.isEmpty()) {
450 Out << '{'; in(); nl(Out);
451 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
452 Out << "AttributeWithIndex PAWI;"; nl(Out);
453 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
454 unsigned index = PAL.getSlot(i).Index;
455 Attributes attrs = PAL.getSlot(i).Attrs;
456 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = Attribute::None ";
457 #define HANDLE_ATTR(X) \
458 if (attrs & Attribute::X) \
459 Out << " | Attribute::" #X; \
460 attrs &= ~Attribute::X;
464 HANDLE_ATTR(NoReturn);
466 HANDLE_ATTR(StructRet);
467 HANDLE_ATTR(NoUnwind);
468 HANDLE_ATTR(NoAlias);
471 HANDLE_ATTR(ReadNone);
472 HANDLE_ATTR(ReadOnly);
473 HANDLE_ATTR(NoInline);
474 HANDLE_ATTR(AlwaysInline);
475 HANDLE_ATTR(OptimizeForSize);
476 HANDLE_ATTR(StackProtect);
477 HANDLE_ATTR(StackProtectReq);
478 HANDLE_ATTR(NoCapture);
479 HANDLE_ATTR(NoRedZone);
480 HANDLE_ATTR(NoImplicitFloat);
482 HANDLE_ATTR(InlineHint);
483 HANDLE_ATTR(ReturnsTwice);
484 HANDLE_ATTR(UWTable);
485 HANDLE_ATTR(NonLazyBind);
487 if (attrs & Attribute::StackAlignment)
488 Out << " | Attribute::constructStackAlignmentFromInt("
489 << Attribute::getStackAlignmentFromAttrs(attrs)
491 attrs &= ~Attribute::StackAlignment;
492 assert(attrs == 0 && "Unhandled attribute!");
495 Out << "Attrs.push_back(PAWI);";
498 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
505 void CppWriter::printType(Type* Ty) {
506 // We don't print definitions for primitive types
507 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
510 // If we already defined this type, we don't need to define it again.
511 if (DefinedTypes.find(Ty) != DefinedTypes.end())
514 // Everything below needs the name for the type so get it now.
515 std::string typeName(getCppName(Ty));
517 // Print the type definition
518 switch (Ty->getTypeID()) {
519 case Type::FunctionTyID: {
520 FunctionType* FT = cast<FunctionType>(Ty);
521 Out << "std::vector<Type*>" << typeName << "_args;";
523 FunctionType::param_iterator PI = FT->param_begin();
524 FunctionType::param_iterator PE = FT->param_end();
525 for (; PI != PE; ++PI) {
526 Type* argTy = static_cast<Type*>(*PI);
528 std::string argName(getCppName(argTy));
529 Out << typeName << "_args.push_back(" << argName;
533 printType(FT->getReturnType());
534 std::string retTypeName(getCppName(FT->getReturnType()));
535 Out << "FunctionType* " << typeName << " = FunctionType::get(";
536 in(); nl(Out) << "/*Result=*/" << retTypeName;
538 nl(Out) << "/*Params=*/" << typeName << "_args,";
539 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
544 case Type::StructTyID: {
545 StructType* ST = cast<StructType>(Ty);
546 if (!ST->isLiteral()) {
547 Out << "StructType *" << typeName << " = mod->getTypeByName(\"";
548 printEscapedString(ST->getName());
551 Out << "if (!" << typeName << ") {";
553 Out << typeName << " = ";
554 Out << "StructType::create(mod->getContext(), \"";
555 printEscapedString(ST->getName());
560 // Indicate that this type is now defined.
561 DefinedTypes.insert(Ty);
564 Out << "std::vector<Type*>" << typeName << "_fields;";
566 StructType::element_iterator EI = ST->element_begin();
567 StructType::element_iterator EE = ST->element_end();
568 for (; EI != EE; ++EI) {
569 Type* fieldTy = static_cast<Type*>(*EI);
571 std::string fieldName(getCppName(fieldTy));
572 Out << typeName << "_fields.push_back(" << fieldName;
577 if (ST->isLiteral()) {
578 Out << "StructType *" << typeName << " = ";
579 Out << "StructType::get(" << "mod->getContext(), ";
581 Out << "if (" << typeName << "->isOpaque()) {";
583 Out << typeName << "->setBody(";
586 Out << typeName << "_fields, /*isPacked=*/"
587 << (ST->isPacked() ? "true" : "false") << ");";
589 if (!ST->isLiteral()) {
595 case Type::ArrayTyID: {
596 ArrayType* AT = cast<ArrayType>(Ty);
597 Type* ET = AT->getElementType();
599 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
600 std::string elemName(getCppName(ET));
601 Out << "ArrayType* " << typeName << " = ArrayType::get("
603 << ", " << utostr(AT->getNumElements()) << ");";
608 case Type::PointerTyID: {
609 PointerType* PT = cast<PointerType>(Ty);
610 Type* ET = PT->getElementType();
612 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
613 std::string elemName(getCppName(ET));
614 Out << "PointerType* " << typeName << " = PointerType::get("
616 << ", " << utostr(PT->getAddressSpace()) << ");";
621 case Type::VectorTyID: {
622 VectorType* PT = cast<VectorType>(Ty);
623 Type* ET = PT->getElementType();
625 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
626 std::string elemName(getCppName(ET));
627 Out << "VectorType* " << typeName << " = VectorType::get("
629 << ", " << utostr(PT->getNumElements()) << ");";
635 error("Invalid TypeID");
638 // Indicate that this type is now defined.
639 DefinedTypes.insert(Ty);
641 // Finally, separate the type definition from other with a newline.
645 void CppWriter::printTypes(const Module* M) {
646 // Add all of the global variables to the value table.
647 for (Module::const_global_iterator I = TheModule->global_begin(),
648 E = TheModule->global_end(); I != E; ++I) {
649 if (I->hasInitializer())
650 printType(I->getInitializer()->getType());
651 printType(I->getType());
654 // Add all the functions to the table
655 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
657 printType(FI->getReturnType());
658 printType(FI->getFunctionType());
659 // Add all the function arguments
660 for (Function::const_arg_iterator AI = FI->arg_begin(),
661 AE = FI->arg_end(); AI != AE; ++AI) {
662 printType(AI->getType());
665 // Add all of the basic blocks and instructions
666 for (Function::const_iterator BB = FI->begin(),
667 E = FI->end(); BB != E; ++BB) {
668 printType(BB->getType());
669 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
671 printType(I->getType());
672 for (unsigned i = 0; i < I->getNumOperands(); ++i)
673 printType(I->getOperand(i)->getType());
680 // printConstant - Print out a constant pool entry...
681 void CppWriter::printConstant(const Constant *CV) {
682 // First, if the constant is actually a GlobalValue (variable or function)
683 // or its already in the constant list then we've printed it already and we
685 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
688 std::string constName(getCppName(CV));
689 std::string typeName(getCppName(CV->getType()));
691 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
692 std::string constValue = CI->getValue().toString(10, true);
693 Out << "ConstantInt* " << constName
694 << " = ConstantInt::get(mod->getContext(), APInt("
695 << cast<IntegerType>(CI->getType())->getBitWidth()
696 << ", StringRef(\"" << constValue << "\"), 10));";
697 } else if (isa<ConstantAggregateZero>(CV)) {
698 Out << "ConstantAggregateZero* " << constName
699 << " = ConstantAggregateZero::get(" << typeName << ");";
700 } else if (isa<ConstantPointerNull>(CV)) {
701 Out << "ConstantPointerNull* " << constName
702 << " = ConstantPointerNull::get(" << typeName << ");";
703 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
704 Out << "ConstantFP* " << constName << " = ";
707 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
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);";
719 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
720 Out << "std::vector<Constant*> " << constName << "_fields;";
722 unsigned N = CS->getNumOperands();
723 for (unsigned i = 0; i < N; i++) {
724 printConstant(CS->getOperand(i));
725 Out << constName << "_fields.push_back("
726 << getCppName(CS->getOperand(i)) << ");";
729 Out << "Constant* " << constName << " = ConstantStruct::get("
730 << typeName << ", " << constName << "_fields);";
731 } else if (const ConstantVector *CVec = dyn_cast<ConstantVector>(CV)) {
732 Out << "std::vector<Constant*> " << constName << "_elems;";
734 unsigned N = CVec->getNumOperands();
735 for (unsigned i = 0; i < N; ++i) {
736 printConstant(CVec->getOperand(i));
737 Out << constName << "_elems.push_back("
738 << getCppName(CVec->getOperand(i)) << ");";
741 Out << "Constant* " << constName << " = ConstantVector::get("
742 << typeName << ", " << constName << "_elems);";
743 } else if (isa<UndefValue>(CV)) {
744 Out << "UndefValue* " << constName << " = UndefValue::get("
746 } else if (const ConstantDataSequential *CDS =
747 dyn_cast<ConstantDataSequential>(CV)) {
748 if (CDS->isString()) {
749 Out << "Constant *" << constName <<
750 " = ConstantDataArray::getString(mod->getContext(), \"";
751 StringRef Str = CDS->getAsString();
752 bool nullTerminate = false;
753 if (Str.back() == 0) {
754 Str = Str.drop_back();
755 nullTerminate = true;
757 printEscapedString(Str);
758 // Determine if we want null termination or not.
762 Out << "\", false);";// No null terminator
764 // TODO: Could generate more efficient code generating CDS calls instead.
765 Out << "std::vector<Constant*> " << constName << "_elems;";
767 for (unsigned i = 0; i != CDS->getNumElements(); ++i) {
768 Constant *Elt = CDS->getElementAsConstant(i);
770 Out << constName << "_elems.push_back(" << getCppName(Elt) << ");";
773 Out << "Constant* " << constName;
775 if (isa<ArrayType>(CDS->getType()))
776 Out << " = ConstantArray::get(";
778 Out << " = ConstantVector::get(";
779 Out << typeName << ", " << constName << "_elems);";
781 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
782 if (CE->getOpcode() == Instruction::GetElementPtr) {
783 Out << "std::vector<Constant*> " << constName << "_indices;";
785 printConstant(CE->getOperand(0));
786 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
787 printConstant(CE->getOperand(i));
788 Out << constName << "_indices.push_back("
789 << getCppName(CE->getOperand(i)) << ");";
792 Out << "Constant* " << constName
793 << " = ConstantExpr::getGetElementPtr("
794 << getCppName(CE->getOperand(0)) << ", "
795 << constName << "_indices);";
796 } else if (CE->isCast()) {
797 printConstant(CE->getOperand(0));
798 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
799 switch (CE->getOpcode()) {
800 default: llvm_unreachable("Invalid cast opcode");
801 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
802 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
803 case Instruction::SExt: Out << "Instruction::SExt"; break;
804 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
805 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
806 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
807 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
808 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
809 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
810 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
811 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
812 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
814 Out << ", " << getCppName(CE->getOperand(0)) << ", "
815 << getCppName(CE->getType()) << ");";
817 unsigned N = CE->getNumOperands();
818 for (unsigned i = 0; i < N; ++i ) {
819 printConstant(CE->getOperand(i));
821 Out << "Constant* " << constName << " = ConstantExpr::";
822 switch (CE->getOpcode()) {
823 case Instruction::Add: Out << "getAdd("; break;
824 case Instruction::FAdd: Out << "getFAdd("; break;
825 case Instruction::Sub: Out << "getSub("; break;
826 case Instruction::FSub: Out << "getFSub("; break;
827 case Instruction::Mul: Out << "getMul("; break;
828 case Instruction::FMul: Out << "getFMul("; break;
829 case Instruction::UDiv: Out << "getUDiv("; break;
830 case Instruction::SDiv: Out << "getSDiv("; break;
831 case Instruction::FDiv: Out << "getFDiv("; break;
832 case Instruction::URem: Out << "getURem("; break;
833 case Instruction::SRem: Out << "getSRem("; break;
834 case Instruction::FRem: Out << "getFRem("; break;
835 case Instruction::And: Out << "getAnd("; break;
836 case Instruction::Or: Out << "getOr("; break;
837 case Instruction::Xor: Out << "getXor("; break;
838 case Instruction::ICmp:
839 Out << "getICmp(ICmpInst::ICMP_";
840 switch (CE->getPredicate()) {
841 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
842 case ICmpInst::ICMP_NE: Out << "NE"; break;
843 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
844 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
845 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
846 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
847 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
848 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
849 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
850 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
851 default: error("Invalid ICmp Predicate");
854 case Instruction::FCmp:
855 Out << "getFCmp(FCmpInst::FCMP_";
856 switch (CE->getPredicate()) {
857 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
858 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
859 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
860 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
861 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
862 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
863 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
864 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
865 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
866 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
867 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
868 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
869 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
870 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
871 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
872 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
873 default: error("Invalid FCmp Predicate");
876 case Instruction::Shl: Out << "getShl("; break;
877 case Instruction::LShr: Out << "getLShr("; break;
878 case Instruction::AShr: Out << "getAShr("; break;
879 case Instruction::Select: Out << "getSelect("; break;
880 case Instruction::ExtractElement: Out << "getExtractElement("; break;
881 case Instruction::InsertElement: Out << "getInsertElement("; break;
882 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
884 error("Invalid constant expression");
887 Out << getCppName(CE->getOperand(0));
888 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
889 Out << ", " << getCppName(CE->getOperand(i));
892 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
893 Out << "Constant* " << constName << " = ";
894 Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
896 error("Bad Constant");
897 Out << "Constant* " << constName << " = 0; ";
902 void CppWriter::printConstants(const Module* M) {
903 // Traverse all the global variables looking for constant initializers
904 for (Module::const_global_iterator I = TheModule->global_begin(),
905 E = TheModule->global_end(); I != E; ++I)
906 if (I->hasInitializer())
907 printConstant(I->getInitializer());
909 // Traverse the LLVM functions looking for constants
910 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
912 // Add all of the basic blocks and instructions
913 for (Function::const_iterator BB = FI->begin(),
914 E = FI->end(); BB != E; ++BB) {
915 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
917 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
918 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
927 void CppWriter::printVariableUses(const GlobalVariable *GV) {
928 nl(Out) << "// Type Definitions";
930 printType(GV->getType());
931 if (GV->hasInitializer()) {
932 const Constant *Init = GV->getInitializer();
933 printType(Init->getType());
934 if (const Function *F = dyn_cast<Function>(Init)) {
935 nl(Out)<< "/ Function Declarations"; nl(Out);
936 printFunctionHead(F);
937 } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
938 nl(Out) << "// Global Variable Declarations"; nl(Out);
939 printVariableHead(gv);
941 nl(Out) << "// Global Variable Definitions"; nl(Out);
942 printVariableBody(gv);
944 nl(Out) << "// Constant Definitions"; nl(Out);
950 void CppWriter::printVariableHead(const GlobalVariable *GV) {
951 nl(Out) << "GlobalVariable* " << getCppName(GV);
953 Out << " = mod->getGlobalVariable(mod->getContext(), ";
954 printEscapedString(GV->getName());
955 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
956 nl(Out) << "if (!" << getCppName(GV) << ") {";
957 in(); nl(Out) << getCppName(GV);
959 Out << " = new GlobalVariable(/*Module=*/*mod, ";
960 nl(Out) << "/*Type=*/";
961 printCppName(GV->getType()->getElementType());
963 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
965 nl(Out) << "/*Linkage=*/";
966 printLinkageType(GV->getLinkage());
968 nl(Out) << "/*Initializer=*/0, ";
969 if (GV->hasInitializer()) {
970 Out << "// has initializer, specified below";
972 nl(Out) << "/*Name=*/\"";
973 printEscapedString(GV->getName());
977 if (GV->hasSection()) {
979 Out << "->setSection(\"";
980 printEscapedString(GV->getSection());
984 if (GV->getAlignment()) {
986 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
989 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
991 Out << "->setVisibility(";
992 printVisibilityType(GV->getVisibility());
996 if (GV->isThreadLocal()) {
998 Out << "->setThreadLocal(true);";
1002 out(); Out << "}"; nl(Out);
1006 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1007 if (GV->hasInitializer()) {
1009 Out << "->setInitializer(";
1010 Out << getCppName(GV->getInitializer()) << ");";
1015 std::string CppWriter::getOpName(const Value* V) {
1016 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1017 return getCppName(V);
1019 // See if its alread in the map of forward references, if so just return the
1020 // name we already set up for it
1021 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1022 if (I != ForwardRefs.end())
1025 // This is a new forward reference. Generate a unique name for it
1026 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1028 // Yes, this is a hack. An Argument is the smallest instantiable value that
1029 // we can make as a placeholder for the real value. We'll replace these
1030 // Argument instances later.
1031 Out << "Argument* " << result << " = new Argument("
1032 << getCppName(V->getType()) << ");";
1034 ForwardRefs[V] = result;
1038 static StringRef ConvertAtomicOrdering(AtomicOrdering Ordering) {
1040 case NotAtomic: return "NotAtomic";
1041 case Unordered: return "Unordered";
1042 case Monotonic: return "Monotonic";
1043 case Acquire: return "Acquire";
1044 case Release: return "Release";
1045 case AcquireRelease: return "AcquireRelease";
1046 case SequentiallyConsistent: return "SequentiallyConsistent";
1048 llvm_unreachable("Unknown ordering");
1051 static StringRef ConvertAtomicSynchScope(SynchronizationScope SynchScope) {
1052 switch (SynchScope) {
1053 case SingleThread: return "SingleThread";
1054 case CrossThread: return "CrossThread";
1056 llvm_unreachable("Unknown synch scope");
1059 // printInstruction - This member is called for each Instruction in a function.
1060 void CppWriter::printInstruction(const Instruction *I,
1061 const std::string& bbname) {
1062 std::string iName(getCppName(I));
1064 // Before we emit this instruction, we need to take care of generating any
1065 // forward references. So, we get the names of all the operands in advance
1066 const unsigned Ops(I->getNumOperands());
1067 std::string* opNames = new std::string[Ops];
1068 for (unsigned i = 0; i < Ops; i++)
1069 opNames[i] = getOpName(I->getOperand(i));
1071 switch (I->getOpcode()) {
1073 error("Invalid instruction");
1076 case Instruction::Ret: {
1077 const ReturnInst* ret = cast<ReturnInst>(I);
1078 Out << "ReturnInst::Create(mod->getContext(), "
1079 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1082 case Instruction::Br: {
1083 const BranchInst* br = cast<BranchInst>(I);
1084 Out << "BranchInst::Create(" ;
1085 if (br->getNumOperands() == 3) {
1086 Out << opNames[2] << ", "
1087 << opNames[1] << ", "
1088 << opNames[0] << ", ";
1090 } else if (br->getNumOperands() == 1) {
1091 Out << opNames[0] << ", ";
1093 error("Branch with 2 operands?");
1095 Out << bbname << ");";
1098 case Instruction::Switch: {
1099 const SwitchInst *SI = cast<SwitchInst>(I);
1100 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1101 << getOpName(SI->getCondition()) << ", "
1102 << getOpName(SI->getDefaultDest()) << ", "
1103 << SI->getNumCases() << ", " << bbname << ");";
1105 for (SwitchInst::ConstCaseIt i = SI->case_begin(), e = SI->case_end();
1107 const ConstantInt* CaseVal = i.getCaseValue();
1108 const BasicBlock *BB = i.getCaseSuccessor();
1109 Out << iName << "->addCase("
1110 << getOpName(CaseVal) << ", "
1111 << getOpName(BB) << ");";
1116 case Instruction::IndirectBr: {
1117 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1118 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1119 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1121 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1122 Out << iName << "->addDestination(" << opNames[i] << ");";
1127 case Instruction::Resume: {
1128 Out << "ResumeInst::Create(mod->getContext(), " << opNames[0]
1129 << ", " << bbname << ");";
1132 case Instruction::Invoke: {
1133 const InvokeInst* inv = cast<InvokeInst>(I);
1134 Out << "std::vector<Value*> " << iName << "_params;";
1136 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1137 Out << iName << "_params.push_back("
1138 << getOpName(inv->getArgOperand(i)) << ");";
1141 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1142 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1143 << getOpName(inv->getCalledFunction()) << ", "
1144 << getOpName(inv->getNormalDest()) << ", "
1145 << getOpName(inv->getUnwindDest()) << ", "
1146 << iName << "_params, \"";
1147 printEscapedString(inv->getName());
1148 Out << "\", " << bbname << ");";
1149 nl(Out) << iName << "->setCallingConv(";
1150 printCallingConv(inv->getCallingConv());
1152 printAttributes(inv->getAttributes(), iName);
1153 Out << iName << "->setAttributes(" << iName << "_PAL);";
1157 case Instruction::Unreachable: {
1158 Out << "new UnreachableInst("
1159 << "mod->getContext(), "
1163 case Instruction::Add:
1164 case Instruction::FAdd:
1165 case Instruction::Sub:
1166 case Instruction::FSub:
1167 case Instruction::Mul:
1168 case Instruction::FMul:
1169 case Instruction::UDiv:
1170 case Instruction::SDiv:
1171 case Instruction::FDiv:
1172 case Instruction::URem:
1173 case Instruction::SRem:
1174 case Instruction::FRem:
1175 case Instruction::And:
1176 case Instruction::Or:
1177 case Instruction::Xor:
1178 case Instruction::Shl:
1179 case Instruction::LShr:
1180 case Instruction::AShr:{
1181 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1182 switch (I->getOpcode()) {
1183 case Instruction::Add: Out << "Instruction::Add"; break;
1184 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1185 case Instruction::Sub: Out << "Instruction::Sub"; break;
1186 case Instruction::FSub: Out << "Instruction::FSub"; break;
1187 case Instruction::Mul: Out << "Instruction::Mul"; break;
1188 case Instruction::FMul: Out << "Instruction::FMul"; break;
1189 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1190 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1191 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1192 case Instruction::URem:Out << "Instruction::URem"; break;
1193 case Instruction::SRem:Out << "Instruction::SRem"; break;
1194 case Instruction::FRem:Out << "Instruction::FRem"; break;
1195 case Instruction::And: Out << "Instruction::And"; break;
1196 case Instruction::Or: Out << "Instruction::Or"; break;
1197 case Instruction::Xor: Out << "Instruction::Xor"; break;
1198 case Instruction::Shl: Out << "Instruction::Shl"; break;
1199 case Instruction::LShr:Out << "Instruction::LShr"; break;
1200 case Instruction::AShr:Out << "Instruction::AShr"; break;
1201 default: Out << "Instruction::BadOpCode"; break;
1203 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1204 printEscapedString(I->getName());
1205 Out << "\", " << bbname << ");";
1208 case Instruction::FCmp: {
1209 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1210 switch (cast<FCmpInst>(I)->getPredicate()) {
1211 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1212 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1213 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1214 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1215 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1216 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1217 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1218 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1219 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1220 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1221 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1222 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1223 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1224 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1225 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1226 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1227 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1229 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1230 printEscapedString(I->getName());
1234 case Instruction::ICmp: {
1235 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1236 switch (cast<ICmpInst>(I)->getPredicate()) {
1237 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1238 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1239 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1240 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1241 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1242 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1243 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1244 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1245 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1246 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1247 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1249 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1250 printEscapedString(I->getName());
1254 case Instruction::Alloca: {
1255 const AllocaInst* allocaI = cast<AllocaInst>(I);
1256 Out << "AllocaInst* " << iName << " = new AllocaInst("
1257 << getCppName(allocaI->getAllocatedType()) << ", ";
1258 if (allocaI->isArrayAllocation())
1259 Out << opNames[0] << ", ";
1261 printEscapedString(allocaI->getName());
1262 Out << "\", " << bbname << ");";
1263 if (allocaI->getAlignment())
1264 nl(Out) << iName << "->setAlignment("
1265 << allocaI->getAlignment() << ");";
1268 case Instruction::Load: {
1269 const LoadInst* load = cast<LoadInst>(I);
1270 Out << "LoadInst* " << iName << " = new LoadInst("
1271 << opNames[0] << ", \"";
1272 printEscapedString(load->getName());
1273 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1274 << ", " << bbname << ");";
1275 if (load->getAlignment())
1276 nl(Out) << iName << "->setAlignment("
1277 << load->getAlignment() << ");";
1278 if (load->isAtomic()) {
1279 StringRef Ordering = ConvertAtomicOrdering(load->getOrdering());
1280 StringRef CrossThread = ConvertAtomicSynchScope(load->getSynchScope());
1281 nl(Out) << iName << "->setAtomic("
1282 << Ordering << ", " << CrossThread << ");";
1286 case Instruction::Store: {
1287 const StoreInst* store = cast<StoreInst>(I);
1288 Out << "StoreInst* " << iName << " = new StoreInst("
1289 << opNames[0] << ", "
1290 << opNames[1] << ", "
1291 << (store->isVolatile() ? "true" : "false")
1292 << ", " << bbname << ");";
1293 if (store->getAlignment())
1294 nl(Out) << iName << "->setAlignment("
1295 << store->getAlignment() << ");";
1296 if (store->isAtomic()) {
1297 StringRef Ordering = ConvertAtomicOrdering(store->getOrdering());
1298 StringRef CrossThread = ConvertAtomicSynchScope(store->getSynchScope());
1299 nl(Out) << iName << "->setAtomic("
1300 << Ordering << ", " << CrossThread << ");";
1304 case Instruction::GetElementPtr: {
1305 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1306 if (gep->getNumOperands() <= 2) {
1307 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1309 if (gep->getNumOperands() == 2)
1310 Out << ", " << opNames[1];
1312 Out << "std::vector<Value*> " << iName << "_indices;";
1314 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1315 Out << iName << "_indices.push_back("
1316 << opNames[i] << ");";
1319 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1320 << opNames[0] << ", " << iName << "_indices";
1323 printEscapedString(gep->getName());
1324 Out << "\", " << bbname << ");";
1327 case Instruction::PHI: {
1328 const PHINode* phi = cast<PHINode>(I);
1330 Out << "PHINode* " << iName << " = PHINode::Create("
1331 << getCppName(phi->getType()) << ", "
1332 << phi->getNumIncomingValues() << ", \"";
1333 printEscapedString(phi->getName());
1334 Out << "\", " << bbname << ");";
1336 for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
1337 Out << iName << "->addIncoming("
1338 << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
1339 << getOpName(phi->getIncomingBlock(i)) << ");";
1344 case Instruction::Trunc:
1345 case Instruction::ZExt:
1346 case Instruction::SExt:
1347 case Instruction::FPTrunc:
1348 case Instruction::FPExt:
1349 case Instruction::FPToUI:
1350 case Instruction::FPToSI:
1351 case Instruction::UIToFP:
1352 case Instruction::SIToFP:
1353 case Instruction::PtrToInt:
1354 case Instruction::IntToPtr:
1355 case Instruction::BitCast: {
1356 const CastInst* cst = cast<CastInst>(I);
1357 Out << "CastInst* " << iName << " = new ";
1358 switch (I->getOpcode()) {
1359 case Instruction::Trunc: Out << "TruncInst"; break;
1360 case Instruction::ZExt: Out << "ZExtInst"; break;
1361 case Instruction::SExt: Out << "SExtInst"; break;
1362 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1363 case Instruction::FPExt: Out << "FPExtInst"; break;
1364 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1365 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1366 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1367 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1368 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1369 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1370 case Instruction::BitCast: Out << "BitCastInst"; break;
1371 default: llvm_unreachable("Unreachable");
1373 Out << "(" << opNames[0] << ", "
1374 << getCppName(cst->getType()) << ", \"";
1375 printEscapedString(cst->getName());
1376 Out << "\", " << bbname << ");";
1379 case Instruction::Call: {
1380 const CallInst* call = cast<CallInst>(I);
1381 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1382 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1383 << getCppName(ila->getFunctionType()) << ", \""
1384 << ila->getAsmString() << "\", \""
1385 << ila->getConstraintString() << "\","
1386 << (ila->hasSideEffects() ? "true" : "false") << ");";
1389 if (call->getNumArgOperands() > 1) {
1390 Out << "std::vector<Value*> " << iName << "_params;";
1392 for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
1393 Out << iName << "_params.push_back(" << opNames[i] << ");";
1396 Out << "CallInst* " << iName << " = CallInst::Create("
1397 << opNames[call->getNumArgOperands()] << ", "
1398 << iName << "_params, \"";
1399 } else if (call->getNumArgOperands() == 1) {
1400 Out << "CallInst* " << iName << " = CallInst::Create("
1401 << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
1403 Out << "CallInst* " << iName << " = CallInst::Create("
1404 << opNames[call->getNumArgOperands()] << ", \"";
1406 printEscapedString(call->getName());
1407 Out << "\", " << bbname << ");";
1408 nl(Out) << iName << "->setCallingConv(";
1409 printCallingConv(call->getCallingConv());
1411 nl(Out) << iName << "->setTailCall("
1412 << (call->isTailCall() ? "true" : "false");
1415 printAttributes(call->getAttributes(), iName);
1416 Out << iName << "->setAttributes(" << iName << "_PAL);";
1420 case Instruction::Select: {
1421 const SelectInst* sel = cast<SelectInst>(I);
1422 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1423 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1424 printEscapedString(sel->getName());
1425 Out << "\", " << bbname << ");";
1428 case Instruction::UserOp1:
1430 case Instruction::UserOp2: {
1431 /// FIXME: What should be done here?
1434 case Instruction::VAArg: {
1435 const VAArgInst* va = cast<VAArgInst>(I);
1436 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1437 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1438 printEscapedString(va->getName());
1439 Out << "\", " << bbname << ");";
1442 case Instruction::ExtractElement: {
1443 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1444 Out << "ExtractElementInst* " << getCppName(eei)
1445 << " = new ExtractElementInst(" << opNames[0]
1446 << ", " << opNames[1] << ", \"";
1447 printEscapedString(eei->getName());
1448 Out << "\", " << bbname << ");";
1451 case Instruction::InsertElement: {
1452 const InsertElementInst* iei = cast<InsertElementInst>(I);
1453 Out << "InsertElementInst* " << getCppName(iei)
1454 << " = InsertElementInst::Create(" << opNames[0]
1455 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1456 printEscapedString(iei->getName());
1457 Out << "\", " << bbname << ");";
1460 case Instruction::ShuffleVector: {
1461 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1462 Out << "ShuffleVectorInst* " << getCppName(svi)
1463 << " = new ShuffleVectorInst(" << opNames[0]
1464 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1465 printEscapedString(svi->getName());
1466 Out << "\", " << bbname << ");";
1469 case Instruction::ExtractValue: {
1470 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1471 Out << "std::vector<unsigned> " << iName << "_indices;";
1473 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1474 Out << iName << "_indices.push_back("
1475 << evi->idx_begin()[i] << ");";
1478 Out << "ExtractValueInst* " << getCppName(evi)
1479 << " = ExtractValueInst::Create(" << opNames[0]
1481 << iName << "_indices, \"";
1482 printEscapedString(evi->getName());
1483 Out << "\", " << bbname << ");";
1486 case Instruction::InsertValue: {
1487 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1488 Out << "std::vector<unsigned> " << iName << "_indices;";
1490 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1491 Out << iName << "_indices.push_back("
1492 << ivi->idx_begin()[i] << ");";
1495 Out << "InsertValueInst* " << getCppName(ivi)
1496 << " = InsertValueInst::Create(" << opNames[0]
1497 << ", " << opNames[1] << ", "
1498 << iName << "_indices, \"";
1499 printEscapedString(ivi->getName());
1500 Out << "\", " << bbname << ");";
1503 case Instruction::Fence: {
1504 const FenceInst *fi = cast<FenceInst>(I);
1505 StringRef Ordering = ConvertAtomicOrdering(fi->getOrdering());
1506 StringRef CrossThread = ConvertAtomicSynchScope(fi->getSynchScope());
1507 Out << "FenceInst* " << iName
1508 << " = new FenceInst(mod->getContext(), "
1509 << Ordering << ", " << CrossThread << ", " << bbname
1513 case Instruction::AtomicCmpXchg: {
1514 const AtomicCmpXchgInst *cxi = cast<AtomicCmpXchgInst>(I);
1515 StringRef Ordering = ConvertAtomicOrdering(cxi->getOrdering());
1516 StringRef CrossThread = ConvertAtomicSynchScope(cxi->getSynchScope());
1517 Out << "AtomicCmpXchgInst* " << iName
1518 << " = new AtomicCmpXchgInst("
1519 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", "
1520 << Ordering << ", " << CrossThread << ", " << bbname
1522 nl(Out) << iName << "->setName(\"";
1523 printEscapedString(cxi->getName());
1527 case Instruction::AtomicRMW: {
1528 const AtomicRMWInst *rmwi = cast<AtomicRMWInst>(I);
1529 StringRef Ordering = ConvertAtomicOrdering(rmwi->getOrdering());
1530 StringRef CrossThread = ConvertAtomicSynchScope(rmwi->getSynchScope());
1531 StringRef Operation;
1532 switch (rmwi->getOperation()) {
1533 case AtomicRMWInst::Xchg: Operation = "AtomicRMWInst::Xchg"; break;
1534 case AtomicRMWInst::Add: Operation = "AtomicRMWInst::Add"; break;
1535 case AtomicRMWInst::Sub: Operation = "AtomicRMWInst::Sub"; break;
1536 case AtomicRMWInst::And: Operation = "AtomicRMWInst::And"; break;
1537 case AtomicRMWInst::Nand: Operation = "AtomicRMWInst::Nand"; break;
1538 case AtomicRMWInst::Or: Operation = "AtomicRMWInst::Or"; break;
1539 case AtomicRMWInst::Xor: Operation = "AtomicRMWInst::Xor"; break;
1540 case AtomicRMWInst::Max: Operation = "AtomicRMWInst::Max"; break;
1541 case AtomicRMWInst::Min: Operation = "AtomicRMWInst::Min"; break;
1542 case AtomicRMWInst::UMax: Operation = "AtomicRMWInst::UMax"; break;
1543 case AtomicRMWInst::UMin: Operation = "AtomicRMWInst::UMin"; break;
1544 case AtomicRMWInst::BAD_BINOP: llvm_unreachable("Bad atomic operation");
1546 Out << "AtomicRMWInst* " << iName
1547 << " = new AtomicRMWInst("
1548 << Operation << ", "
1549 << opNames[0] << ", " << opNames[1] << ", "
1550 << Ordering << ", " << CrossThread << ", " << bbname
1552 nl(Out) << iName << "->setName(\"";
1553 printEscapedString(rmwi->getName());
1558 DefinedValues.insert(I);
1563 // Print out the types, constants and declarations needed by one function
1564 void CppWriter::printFunctionUses(const Function* F) {
1565 nl(Out) << "// Type Definitions"; nl(Out);
1567 // Print the function's return type
1568 printType(F->getReturnType());
1570 // Print the function's function type
1571 printType(F->getFunctionType());
1573 // Print the types of each of the function's arguments
1574 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1576 printType(AI->getType());
1580 // Print type definitions for every type referenced by an instruction and
1581 // make a note of any global values or constants that are referenced
1582 SmallPtrSet<GlobalValue*,64> gvs;
1583 SmallPtrSet<Constant*,64> consts;
1584 for (Function::const_iterator BB = F->begin(), BE = F->end();
1586 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1588 // Print the type of the instruction itself
1589 printType(I->getType());
1591 // Print the type of each of the instruction's operands
1592 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1593 Value* operand = I->getOperand(i);
1594 printType(operand->getType());
1596 // If the operand references a GVal or Constant, make a note of it
1597 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1599 if (GenerationType != GenFunction)
1600 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1601 if (GVar->hasInitializer())
1602 consts.insert(GVar->getInitializer());
1603 } else if (Constant* C = dyn_cast<Constant>(operand)) {
1605 for (unsigned j = 0; j < C->getNumOperands(); ++j) {
1606 // If the operand references a GVal or Constant, make a note of it
1607 Value* operand = C->getOperand(j);
1608 printType(operand->getType());
1609 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1611 if (GenerationType != GenFunction)
1612 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1613 if (GVar->hasInitializer())
1614 consts.insert(GVar->getInitializer());
1622 // Print the function declarations for any functions encountered
1623 nl(Out) << "// Function Declarations"; nl(Out);
1624 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1626 if (Function* Fun = dyn_cast<Function>(*I)) {
1627 if (!is_inline || Fun != F)
1628 printFunctionHead(Fun);
1632 // Print the global variable declarations for any variables encountered
1633 nl(Out) << "// Global Variable Declarations"; nl(Out);
1634 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1636 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1637 printVariableHead(F);
1640 // Print the constants found
1641 nl(Out) << "// Constant Definitions"; nl(Out);
1642 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1643 E = consts.end(); I != E; ++I) {
1647 // Process the global variables definitions now that all the constants have
1648 // been emitted. These definitions just couple the gvars with their constant
1650 if (GenerationType != GenFunction) {
1651 nl(Out) << "// Global Variable Definitions"; nl(Out);
1652 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1654 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1655 printVariableBody(GV);
1660 void CppWriter::printFunctionHead(const Function* F) {
1661 nl(Out) << "Function* " << getCppName(F);
1662 Out << " = mod->getFunction(\"";
1663 printEscapedString(F->getName());
1665 nl(Out) << "if (!" << getCppName(F) << ") {";
1666 nl(Out) << getCppName(F);
1668 Out<< " = Function::Create(";
1669 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1670 nl(Out) << "/*Linkage=*/";
1671 printLinkageType(F->getLinkage());
1673 nl(Out) << "/*Name=*/\"";
1674 printEscapedString(F->getName());
1675 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1678 Out << "->setCallingConv(";
1679 printCallingConv(F->getCallingConv());
1682 if (F->hasSection()) {
1684 Out << "->setSection(\"" << F->getSection() << "\");";
1687 if (F->getAlignment()) {
1689 Out << "->setAlignment(" << F->getAlignment() << ");";
1692 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1694 Out << "->setVisibility(";
1695 printVisibilityType(F->getVisibility());
1701 Out << "->setGC(\"" << F->getGC() << "\");";
1706 printAttributes(F->getAttributes(), getCppName(F));
1708 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1712 void CppWriter::printFunctionBody(const Function *F) {
1713 if (F->isDeclaration())
1714 return; // external functions have no bodies.
1716 // Clear the DefinedValues and ForwardRefs maps because we can't have
1717 // cross-function forward refs
1718 ForwardRefs.clear();
1719 DefinedValues.clear();
1721 // Create all the argument values
1723 if (!F->arg_empty()) {
1724 Out << "Function::arg_iterator args = " << getCppName(F)
1725 << "->arg_begin();";
1728 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1730 Out << "Value* " << getCppName(AI) << " = args++;";
1732 if (AI->hasName()) {
1733 Out << getCppName(AI) << "->setName(\"";
1734 printEscapedString(AI->getName());
1741 // Create all the basic blocks
1743 for (Function::const_iterator BI = F->begin(), BE = F->end();
1745 std::string bbname(getCppName(BI));
1746 Out << "BasicBlock* " << bbname <<
1747 " = BasicBlock::Create(mod->getContext(), \"";
1749 printEscapedString(BI->getName());
1750 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1754 // Output all of its basic blocks... for the function
1755 for (Function::const_iterator BI = F->begin(), BE = F->end();
1757 std::string bbname(getCppName(BI));
1758 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1761 // Output all of the instructions in the basic block...
1762 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1764 printInstruction(I,bbname);
1768 // Loop over the ForwardRefs and resolve them now that all instructions
1770 if (!ForwardRefs.empty()) {
1771 nl(Out) << "// Resolve Forward References";
1775 while (!ForwardRefs.empty()) {
1776 ForwardRefMap::iterator I = ForwardRefs.begin();
1777 Out << I->second << "->replaceAllUsesWith("
1778 << getCppName(I->first) << "); delete " << I->second << ";";
1780 ForwardRefs.erase(I);
1784 void CppWriter::printInline(const std::string& fname,
1785 const std::string& func) {
1786 const Function* F = TheModule->getFunction(func);
1788 error(std::string("Function '") + func + "' not found in input module");
1791 if (F->isDeclaration()) {
1792 error(std::string("Function '") + func + "' is external!");
1795 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1797 unsigned arg_count = 1;
1798 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1800 Out << ", Value* arg_" << arg_count;
1805 printFunctionUses(F);
1806 printFunctionBody(F);
1808 Out << "return " << getCppName(F->begin()) << ";";
1813 void CppWriter::printModuleBody() {
1814 // Print out all the type definitions
1815 nl(Out) << "// Type Definitions"; nl(Out);
1816 printTypes(TheModule);
1818 // Functions can call each other and global variables can reference them so
1819 // define all the functions first before emitting their function bodies.
1820 nl(Out) << "// Function Declarations"; nl(Out);
1821 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1823 printFunctionHead(I);
1825 // Process the global variables declarations. We can't initialze them until
1826 // after the constants are printed so just print a header for each global
1827 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1828 for (Module::const_global_iterator I = TheModule->global_begin(),
1829 E = TheModule->global_end(); I != E; ++I) {
1830 printVariableHead(I);
1833 // Print out all the constants definitions. Constants don't recurse except
1834 // through GlobalValues. All GlobalValues have been declared at this point
1835 // so we can proceed to generate the constants.
1836 nl(Out) << "// Constant Definitions"; nl(Out);
1837 printConstants(TheModule);
1839 // Process the global variables definitions now that all the constants have
1840 // been emitted. These definitions just couple the gvars with their constant
1842 nl(Out) << "// Global Variable Definitions"; nl(Out);
1843 for (Module::const_global_iterator I = TheModule->global_begin(),
1844 E = TheModule->global_end(); I != E; ++I) {
1845 printVariableBody(I);
1848 // Finally, we can safely put out all of the function bodies.
1849 nl(Out) << "// Function Definitions"; nl(Out);
1850 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1852 if (!I->isDeclaration()) {
1853 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1857 printFunctionBody(I);
1864 void CppWriter::printProgram(const std::string& fname,
1865 const std::string& mName) {
1866 Out << "#include <llvm/LLVMContext.h>\n";
1867 Out << "#include <llvm/Module.h>\n";
1868 Out << "#include <llvm/DerivedTypes.h>\n";
1869 Out << "#include <llvm/Constants.h>\n";
1870 Out << "#include <llvm/GlobalVariable.h>\n";
1871 Out << "#include <llvm/Function.h>\n";
1872 Out << "#include <llvm/CallingConv.h>\n";
1873 Out << "#include <llvm/BasicBlock.h>\n";
1874 Out << "#include <llvm/Instructions.h>\n";
1875 Out << "#include <llvm/InlineAsm.h>\n";
1876 Out << "#include <llvm/Support/FormattedStream.h>\n";
1877 Out << "#include <llvm/Support/MathExtras.h>\n";
1878 Out << "#include <llvm/Pass.h>\n";
1879 Out << "#include <llvm/PassManager.h>\n";
1880 Out << "#include <llvm/ADT/SmallVector.h>\n";
1881 Out << "#include <llvm/Analysis/Verifier.h>\n";
1882 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1883 Out << "#include <algorithm>\n";
1884 Out << "using namespace llvm;\n\n";
1885 Out << "Module* " << fname << "();\n\n";
1886 Out << "int main(int argc, char**argv) {\n";
1887 Out << " Module* Mod = " << fname << "();\n";
1888 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1889 Out << " PassManager PM;\n";
1890 Out << " PM.add(createPrintModulePass(&outs()));\n";
1891 Out << " PM.run(*Mod);\n";
1892 Out << " return 0;\n";
1894 printModule(fname,mName);
1897 void CppWriter::printModule(const std::string& fname,
1898 const std::string& mName) {
1899 nl(Out) << "Module* " << fname << "() {";
1900 nl(Out,1) << "// Module Construction";
1901 nl(Out) << "Module* mod = new Module(\"";
1902 printEscapedString(mName);
1903 Out << "\", getGlobalContext());";
1904 if (!TheModule->getTargetTriple().empty()) {
1905 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1907 if (!TheModule->getTargetTriple().empty()) {
1908 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1912 if (!TheModule->getModuleInlineAsm().empty()) {
1913 nl(Out) << "mod->setModuleInlineAsm(\"";
1914 printEscapedString(TheModule->getModuleInlineAsm());
1919 // Loop over the dependent libraries and emit them.
1920 Module::lib_iterator LI = TheModule->lib_begin();
1921 Module::lib_iterator LE = TheModule->lib_end();
1923 Out << "mod->addLibrary(\"" << *LI << "\");";
1928 nl(Out) << "return mod;";
1933 void CppWriter::printContents(const std::string& fname,
1934 const std::string& mName) {
1935 Out << "\nModule* " << fname << "(Module *mod) {\n";
1936 Out << "\nmod->setModuleIdentifier(\"";
1937 printEscapedString(mName);
1940 Out << "\nreturn mod;\n";
1944 void CppWriter::printFunction(const std::string& fname,
1945 const std::string& funcName) {
1946 const Function* F = TheModule->getFunction(funcName);
1948 error(std::string("Function '") + funcName + "' not found in input module");
1951 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1952 printFunctionUses(F);
1953 printFunctionHead(F);
1954 printFunctionBody(F);
1955 Out << "return " << getCppName(F) << ";\n";
1959 void CppWriter::printFunctions() {
1960 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1961 Module::const_iterator I = funcs.begin();
1962 Module::const_iterator IE = funcs.end();
1964 for (; I != IE; ++I) {
1965 const Function &func = *I;
1966 if (!func.isDeclaration()) {
1967 std::string name("define_");
1968 name += func.getName();
1969 printFunction(name, func.getName());
1974 void CppWriter::printVariable(const std::string& fname,
1975 const std::string& varName) {
1976 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1979 error(std::string("Variable '") + varName + "' not found in input module");
1982 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1983 printVariableUses(GV);
1984 printVariableHead(GV);
1985 printVariableBody(GV);
1986 Out << "return " << getCppName(GV) << ";\n";
1990 void CppWriter::printType(const std::string &fname,
1991 const std::string &typeName) {
1992 Type* Ty = TheModule->getTypeByName(typeName);
1994 error(std::string("Type '") + typeName + "' not found in input module");
1997 Out << "\nType* " << fname << "(Module *mod) {\n";
1999 Out << "return " << getCppName(Ty) << ";\n";
2003 bool CppWriter::runOnModule(Module &M) {
2007 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
2009 // Get the name of the function we're supposed to generate
2010 std::string fname = FuncName.getValue();
2012 // Get the name of the thing we are to generate
2013 std::string tgtname = NameToGenerate.getValue();
2014 if (GenerationType == GenModule ||
2015 GenerationType == GenContents ||
2016 GenerationType == GenProgram ||
2017 GenerationType == GenFunctions) {
2018 if (tgtname == "!bad!") {
2019 if (M.getModuleIdentifier() == "-")
2020 tgtname = "<stdin>";
2022 tgtname = M.getModuleIdentifier();
2024 } else if (tgtname == "!bad!")
2025 error("You must use the -for option with -gen-{function,variable,type}");
2027 switch (WhatToGenerate(GenerationType)) {
2030 fname = "makeLLVMModule";
2031 printProgram(fname,tgtname);
2035 fname = "makeLLVMModule";
2036 printModule(fname,tgtname);
2040 fname = "makeLLVMModuleContents";
2041 printContents(fname,tgtname);
2045 fname = "makeLLVMFunction";
2046 printFunction(fname,tgtname);
2053 fname = "makeLLVMInline";
2054 printInline(fname,tgtname);
2058 fname = "makeLLVMVariable";
2059 printVariable(fname,tgtname);
2063 fname = "makeLLVMType";
2064 printType(fname,tgtname);
2071 char CppWriter::ID = 0;
2073 //===----------------------------------------------------------------------===//
2074 // External Interface declaration
2075 //===----------------------------------------------------------------------===//
2077 bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
2078 formatted_raw_ostream &o,
2079 CodeGenFileType FileType,
2080 bool DisableVerify) {
2081 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
2082 PM.add(new CppWriter(o));