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/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Config/config.h"
19 #include "llvm/IR/CallingConv.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/InlineAsm.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/Pass.h"
30 #include "llvm/PassManager.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/TargetRegistry.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 AttributeSet &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::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::LinkOnceODRAutoHideLinkage:
295 Out << "GlobalValue::LinkOnceODRAutoHideLinkage"; 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 AttributeSet &PAL,
468 const std::string &name) {
469 Out << "AttributeSet " << 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.getSlotIndex(i);
477 AttrBuilder attrs(PAL.getSlot(i).Attrs);
478 Out << "PAWI.Index = " << index << "U;\n";
479 Out << " {\n AttrBuilder B;\n";
481 #define HANDLE_ATTR(X) \
482 if (attrs.contains(Attribute::X)) \
483 Out << " B.addAttribute(Attribute::" #X ");\n"; \
484 attrs.removeAttribute(Attribute::X);
488 HANDLE_ATTR(NoReturn);
490 HANDLE_ATTR(StructRet);
491 HANDLE_ATTR(NoUnwind);
492 HANDLE_ATTR(NoAlias);
495 HANDLE_ATTR(ReadNone);
496 HANDLE_ATTR(ReadOnly);
497 HANDLE_ATTR(NoInline);
498 HANDLE_ATTR(AlwaysInline);
499 HANDLE_ATTR(OptimizeForSize);
500 HANDLE_ATTR(StackProtect);
501 HANDLE_ATTR(StackProtectReq);
502 HANDLE_ATTR(StackProtectStrong);
503 HANDLE_ATTR(NoCapture);
504 HANDLE_ATTR(NoRedZone);
505 HANDLE_ATTR(NoImplicitFloat);
507 HANDLE_ATTR(InlineHint);
508 HANDLE_ATTR(ReturnsTwice);
509 HANDLE_ATTR(UWTable);
510 HANDLE_ATTR(NonLazyBind);
511 HANDLE_ATTR(MinSize);
513 if (attrs.contains(Attribute::StackAlignment))
514 Out << " B.addStackAlignmentAttr(" << attrs.getStackAlignment() << ")\n";
515 attrs.removeAttribute(Attribute::StackAlignment);
516 assert(!attrs.hasAttributes() && "Unhandled attribute!");
517 Out << " PAWI.Attrs = Attribute::get(mod->getContext(), B);\n }";
519 Out << "Attrs.push_back(PAWI);";
522 Out << name << "_PAL = AttributeSet::get(mod->getContext(), Attrs);";
529 void CppWriter::printType(Type* Ty) {
530 // We don't print definitions for primitive types
531 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
534 // If we already defined this type, we don't need to define it again.
535 if (DefinedTypes.find(Ty) != DefinedTypes.end())
538 // Everything below needs the name for the type so get it now.
539 std::string typeName(getCppName(Ty));
541 // Print the type definition
542 switch (Ty->getTypeID()) {
543 case Type::FunctionTyID: {
544 FunctionType* FT = cast<FunctionType>(Ty);
545 Out << "std::vector<Type*>" << typeName << "_args;";
547 FunctionType::param_iterator PI = FT->param_begin();
548 FunctionType::param_iterator PE = FT->param_end();
549 for (; PI != PE; ++PI) {
550 Type* argTy = static_cast<Type*>(*PI);
552 std::string argName(getCppName(argTy));
553 Out << typeName << "_args.push_back(" << argName;
557 printType(FT->getReturnType());
558 std::string retTypeName(getCppName(FT->getReturnType()));
559 Out << "FunctionType* " << typeName << " = FunctionType::get(";
560 in(); nl(Out) << "/*Result=*/" << retTypeName;
562 nl(Out) << "/*Params=*/" << typeName << "_args,";
563 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
568 case Type::StructTyID: {
569 StructType* ST = cast<StructType>(Ty);
570 if (!ST->isLiteral()) {
571 Out << "StructType *" << typeName << " = mod->getTypeByName(\"";
572 printEscapedString(ST->getName());
575 Out << "if (!" << typeName << ") {";
577 Out << typeName << " = ";
578 Out << "StructType::create(mod->getContext(), \"";
579 printEscapedString(ST->getName());
584 // Indicate that this type is now defined.
585 DefinedTypes.insert(Ty);
588 Out << "std::vector<Type*>" << typeName << "_fields;";
590 StructType::element_iterator EI = ST->element_begin();
591 StructType::element_iterator EE = ST->element_end();
592 for (; EI != EE; ++EI) {
593 Type* fieldTy = static_cast<Type*>(*EI);
595 std::string fieldName(getCppName(fieldTy));
596 Out << typeName << "_fields.push_back(" << fieldName;
601 if (ST->isLiteral()) {
602 Out << "StructType *" << typeName << " = ";
603 Out << "StructType::get(" << "mod->getContext(), ";
605 Out << "if (" << typeName << "->isOpaque()) {";
607 Out << typeName << "->setBody(";
610 Out << typeName << "_fields, /*isPacked=*/"
611 << (ST->isPacked() ? "true" : "false") << ");";
613 if (!ST->isLiteral()) {
619 case Type::ArrayTyID: {
620 ArrayType* AT = cast<ArrayType>(Ty);
621 Type* ET = AT->getElementType();
623 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
624 std::string elemName(getCppName(ET));
625 Out << "ArrayType* " << typeName << " = ArrayType::get("
627 << ", " << utostr(AT->getNumElements()) << ");";
632 case Type::PointerTyID: {
633 PointerType* PT = cast<PointerType>(Ty);
634 Type* ET = PT->getElementType();
636 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
637 std::string elemName(getCppName(ET));
638 Out << "PointerType* " << typeName << " = PointerType::get("
640 << ", " << utostr(PT->getAddressSpace()) << ");";
645 case Type::VectorTyID: {
646 VectorType* PT = cast<VectorType>(Ty);
647 Type* ET = PT->getElementType();
649 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
650 std::string elemName(getCppName(ET));
651 Out << "VectorType* " << typeName << " = VectorType::get("
653 << ", " << utostr(PT->getNumElements()) << ");";
659 error("Invalid TypeID");
662 // Indicate that this type is now defined.
663 DefinedTypes.insert(Ty);
665 // Finally, separate the type definition from other with a newline.
669 void CppWriter::printTypes(const Module* M) {
670 // Add all of the global variables to the value table.
671 for (Module::const_global_iterator I = TheModule->global_begin(),
672 E = TheModule->global_end(); I != E; ++I) {
673 if (I->hasInitializer())
674 printType(I->getInitializer()->getType());
675 printType(I->getType());
678 // Add all the functions to the table
679 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
681 printType(FI->getReturnType());
682 printType(FI->getFunctionType());
683 // Add all the function arguments
684 for (Function::const_arg_iterator AI = FI->arg_begin(),
685 AE = FI->arg_end(); AI != AE; ++AI) {
686 printType(AI->getType());
689 // Add all of the basic blocks and instructions
690 for (Function::const_iterator BB = FI->begin(),
691 E = FI->end(); BB != E; ++BB) {
692 printType(BB->getType());
693 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
695 printType(I->getType());
696 for (unsigned i = 0; i < I->getNumOperands(); ++i)
697 printType(I->getOperand(i)->getType());
704 // printConstant - Print out a constant pool entry...
705 void CppWriter::printConstant(const Constant *CV) {
706 // First, if the constant is actually a GlobalValue (variable or function)
707 // or its already in the constant list then we've printed it already and we
709 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
712 std::string constName(getCppName(CV));
713 std::string typeName(getCppName(CV->getType()));
715 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
716 std::string constValue = CI->getValue().toString(10, true);
717 Out << "ConstantInt* " << constName
718 << " = ConstantInt::get(mod->getContext(), APInt("
719 << cast<IntegerType>(CI->getType())->getBitWidth()
720 << ", StringRef(\"" << constValue << "\"), 10));";
721 } else if (isa<ConstantAggregateZero>(CV)) {
722 Out << "ConstantAggregateZero* " << constName
723 << " = ConstantAggregateZero::get(" << typeName << ");";
724 } else if (isa<ConstantPointerNull>(CV)) {
725 Out << "ConstantPointerNull* " << constName
726 << " = ConstantPointerNull::get(" << typeName << ");";
727 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
728 Out << "ConstantFP* " << constName << " = ";
731 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
732 Out << "std::vector<Constant*> " << constName << "_elems;";
734 unsigned N = CA->getNumOperands();
735 for (unsigned i = 0; i < N; ++i) {
736 printConstant(CA->getOperand(i)); // recurse to print operands
737 Out << constName << "_elems.push_back("
738 << getCppName(CA->getOperand(i)) << ");";
741 Out << "Constant* " << constName << " = ConstantArray::get("
742 << typeName << ", " << constName << "_elems);";
743 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
744 Out << "std::vector<Constant*> " << constName << "_fields;";
746 unsigned N = CS->getNumOperands();
747 for (unsigned i = 0; i < N; i++) {
748 printConstant(CS->getOperand(i));
749 Out << constName << "_fields.push_back("
750 << getCppName(CS->getOperand(i)) << ");";
753 Out << "Constant* " << constName << " = ConstantStruct::get("
754 << typeName << ", " << constName << "_fields);";
755 } else if (const ConstantVector *CVec = dyn_cast<ConstantVector>(CV)) {
756 Out << "std::vector<Constant*> " << constName << "_elems;";
758 unsigned N = CVec->getNumOperands();
759 for (unsigned i = 0; i < N; ++i) {
760 printConstant(CVec->getOperand(i));
761 Out << constName << "_elems.push_back("
762 << getCppName(CVec->getOperand(i)) << ");";
765 Out << "Constant* " << constName << " = ConstantVector::get("
766 << typeName << ", " << constName << "_elems);";
767 } else if (isa<UndefValue>(CV)) {
768 Out << "UndefValue* " << constName << " = UndefValue::get("
770 } else if (const ConstantDataSequential *CDS =
771 dyn_cast<ConstantDataSequential>(CV)) {
772 if (CDS->isString()) {
773 Out << "Constant *" << constName <<
774 " = ConstantDataArray::getString(mod->getContext(), \"";
775 StringRef Str = CDS->getAsString();
776 bool nullTerminate = false;
777 if (Str.back() == 0) {
778 Str = Str.drop_back();
779 nullTerminate = true;
781 printEscapedString(Str);
782 // Determine if we want null termination or not.
786 Out << "\", false);";// No null terminator
788 // TODO: Could generate more efficient code generating CDS calls instead.
789 Out << "std::vector<Constant*> " << constName << "_elems;";
791 for (unsigned i = 0; i != CDS->getNumElements(); ++i) {
792 Constant *Elt = CDS->getElementAsConstant(i);
794 Out << constName << "_elems.push_back(" << getCppName(Elt) << ");";
797 Out << "Constant* " << constName;
799 if (isa<ArrayType>(CDS->getType()))
800 Out << " = ConstantArray::get(";
802 Out << " = ConstantVector::get(";
803 Out << typeName << ", " << constName << "_elems);";
805 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
806 if (CE->getOpcode() == Instruction::GetElementPtr) {
807 Out << "std::vector<Constant*> " << constName << "_indices;";
809 printConstant(CE->getOperand(0));
810 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
811 printConstant(CE->getOperand(i));
812 Out << constName << "_indices.push_back("
813 << getCppName(CE->getOperand(i)) << ");";
816 Out << "Constant* " << constName
817 << " = ConstantExpr::getGetElementPtr("
818 << getCppName(CE->getOperand(0)) << ", "
819 << constName << "_indices);";
820 } else if (CE->isCast()) {
821 printConstant(CE->getOperand(0));
822 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
823 switch (CE->getOpcode()) {
824 default: llvm_unreachable("Invalid cast opcode");
825 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
826 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
827 case Instruction::SExt: Out << "Instruction::SExt"; break;
828 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
829 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
830 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
831 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
832 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
833 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
834 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
835 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
836 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
838 Out << ", " << getCppName(CE->getOperand(0)) << ", "
839 << getCppName(CE->getType()) << ");";
841 unsigned N = CE->getNumOperands();
842 for (unsigned i = 0; i < N; ++i ) {
843 printConstant(CE->getOperand(i));
845 Out << "Constant* " << constName << " = ConstantExpr::";
846 switch (CE->getOpcode()) {
847 case Instruction::Add: Out << "getAdd("; break;
848 case Instruction::FAdd: Out << "getFAdd("; break;
849 case Instruction::Sub: Out << "getSub("; break;
850 case Instruction::FSub: Out << "getFSub("; break;
851 case Instruction::Mul: Out << "getMul("; break;
852 case Instruction::FMul: Out << "getFMul("; break;
853 case Instruction::UDiv: Out << "getUDiv("; break;
854 case Instruction::SDiv: Out << "getSDiv("; break;
855 case Instruction::FDiv: Out << "getFDiv("; break;
856 case Instruction::URem: Out << "getURem("; break;
857 case Instruction::SRem: Out << "getSRem("; break;
858 case Instruction::FRem: Out << "getFRem("; break;
859 case Instruction::And: Out << "getAnd("; break;
860 case Instruction::Or: Out << "getOr("; break;
861 case Instruction::Xor: Out << "getXor("; break;
862 case Instruction::ICmp:
863 Out << "getICmp(ICmpInst::ICMP_";
864 switch (CE->getPredicate()) {
865 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
866 case ICmpInst::ICMP_NE: Out << "NE"; break;
867 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
868 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
869 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
870 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
871 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
872 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
873 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
874 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
875 default: error("Invalid ICmp Predicate");
878 case Instruction::FCmp:
879 Out << "getFCmp(FCmpInst::FCMP_";
880 switch (CE->getPredicate()) {
881 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
882 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
883 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
884 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
885 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
886 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
887 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
888 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
889 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
890 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
891 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
892 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
893 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
894 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
895 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
896 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
897 default: error("Invalid FCmp Predicate");
900 case Instruction::Shl: Out << "getShl("; break;
901 case Instruction::LShr: Out << "getLShr("; break;
902 case Instruction::AShr: Out << "getAShr("; break;
903 case Instruction::Select: Out << "getSelect("; break;
904 case Instruction::ExtractElement: Out << "getExtractElement("; break;
905 case Instruction::InsertElement: Out << "getInsertElement("; break;
906 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
908 error("Invalid constant expression");
911 Out << getCppName(CE->getOperand(0));
912 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
913 Out << ", " << getCppName(CE->getOperand(i));
916 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
917 Out << "Constant* " << constName << " = ";
918 Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
920 error("Bad Constant");
921 Out << "Constant* " << constName << " = 0; ";
926 void CppWriter::printConstants(const Module* M) {
927 // Traverse all the global variables looking for constant initializers
928 for (Module::const_global_iterator I = TheModule->global_begin(),
929 E = TheModule->global_end(); I != E; ++I)
930 if (I->hasInitializer())
931 printConstant(I->getInitializer());
933 // Traverse the LLVM functions looking for constants
934 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
936 // Add all of the basic blocks and instructions
937 for (Function::const_iterator BB = FI->begin(),
938 E = FI->end(); BB != E; ++BB) {
939 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
941 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
942 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
951 void CppWriter::printVariableUses(const GlobalVariable *GV) {
952 nl(Out) << "// Type Definitions";
954 printType(GV->getType());
955 if (GV->hasInitializer()) {
956 const Constant *Init = GV->getInitializer();
957 printType(Init->getType());
958 if (const Function *F = dyn_cast<Function>(Init)) {
959 nl(Out)<< "/ Function Declarations"; nl(Out);
960 printFunctionHead(F);
961 } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
962 nl(Out) << "// Global Variable Declarations"; nl(Out);
963 printVariableHead(gv);
965 nl(Out) << "// Global Variable Definitions"; nl(Out);
966 printVariableBody(gv);
968 nl(Out) << "// Constant Definitions"; nl(Out);
974 void CppWriter::printVariableHead(const GlobalVariable *GV) {
975 nl(Out) << "GlobalVariable* " << getCppName(GV);
977 Out << " = mod->getGlobalVariable(mod->getContext(), ";
978 printEscapedString(GV->getName());
979 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
980 nl(Out) << "if (!" << getCppName(GV) << ") {";
981 in(); nl(Out) << getCppName(GV);
983 Out << " = new GlobalVariable(/*Module=*/*mod, ";
984 nl(Out) << "/*Type=*/";
985 printCppName(GV->getType()->getElementType());
987 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
989 nl(Out) << "/*Linkage=*/";
990 printLinkageType(GV->getLinkage());
992 nl(Out) << "/*Initializer=*/0, ";
993 if (GV->hasInitializer()) {
994 Out << "// has initializer, specified below";
996 nl(Out) << "/*Name=*/\"";
997 printEscapedString(GV->getName());
1001 if (GV->hasSection()) {
1003 Out << "->setSection(\"";
1004 printEscapedString(GV->getSection());
1008 if (GV->getAlignment()) {
1010 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1013 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1015 Out << "->setVisibility(";
1016 printVisibilityType(GV->getVisibility());
1020 if (GV->isThreadLocal()) {
1022 Out << "->setThreadLocalMode(";
1023 printThreadLocalMode(GV->getThreadLocalMode());
1028 out(); Out << "}"; nl(Out);
1032 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1033 if (GV->hasInitializer()) {
1035 Out << "->setInitializer(";
1036 Out << getCppName(GV->getInitializer()) << ");";
1041 std::string CppWriter::getOpName(const Value* V) {
1042 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1043 return getCppName(V);
1045 // See if its alread in the map of forward references, if so just return the
1046 // name we already set up for it
1047 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1048 if (I != ForwardRefs.end())
1051 // This is a new forward reference. Generate a unique name for it
1052 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1054 // Yes, this is a hack. An Argument is the smallest instantiable value that
1055 // we can make as a placeholder for the real value. We'll replace these
1056 // Argument instances later.
1057 Out << "Argument* " << result << " = new Argument("
1058 << getCppName(V->getType()) << ");";
1060 ForwardRefs[V] = result;
1064 static StringRef ConvertAtomicOrdering(AtomicOrdering Ordering) {
1066 case NotAtomic: return "NotAtomic";
1067 case Unordered: return "Unordered";
1068 case Monotonic: return "Monotonic";
1069 case Acquire: return "Acquire";
1070 case Release: return "Release";
1071 case AcquireRelease: return "AcquireRelease";
1072 case SequentiallyConsistent: return "SequentiallyConsistent";
1074 llvm_unreachable("Unknown ordering");
1077 static StringRef ConvertAtomicSynchScope(SynchronizationScope SynchScope) {
1078 switch (SynchScope) {
1079 case SingleThread: return "SingleThread";
1080 case CrossThread: return "CrossThread";
1082 llvm_unreachable("Unknown synch scope");
1085 // printInstruction - This member is called for each Instruction in a function.
1086 void CppWriter::printInstruction(const Instruction *I,
1087 const std::string& bbname) {
1088 std::string iName(getCppName(I));
1090 // Before we emit this instruction, we need to take care of generating any
1091 // forward references. So, we get the names of all the operands in advance
1092 const unsigned Ops(I->getNumOperands());
1093 std::string* opNames = new std::string[Ops];
1094 for (unsigned i = 0; i < Ops; i++)
1095 opNames[i] = getOpName(I->getOperand(i));
1097 switch (I->getOpcode()) {
1099 error("Invalid instruction");
1102 case Instruction::Ret: {
1103 const ReturnInst* ret = cast<ReturnInst>(I);
1104 Out << "ReturnInst::Create(mod->getContext(), "
1105 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1108 case Instruction::Br: {
1109 const BranchInst* br = cast<BranchInst>(I);
1110 Out << "BranchInst::Create(" ;
1111 if (br->getNumOperands() == 3) {
1112 Out << opNames[2] << ", "
1113 << opNames[1] << ", "
1114 << opNames[0] << ", ";
1116 } else if (br->getNumOperands() == 1) {
1117 Out << opNames[0] << ", ";
1119 error("Branch with 2 operands?");
1121 Out << bbname << ");";
1124 case Instruction::Switch: {
1125 const SwitchInst *SI = cast<SwitchInst>(I);
1126 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1127 << getOpName(SI->getCondition()) << ", "
1128 << getOpName(SI->getDefaultDest()) << ", "
1129 << SI->getNumCases() << ", " << bbname << ");";
1131 for (SwitchInst::ConstCaseIt i = SI->case_begin(), e = SI->case_end();
1133 const IntegersSubset CaseVal = i.getCaseValueEx();
1134 const BasicBlock *BB = i.getCaseSuccessor();
1135 Out << iName << "->addCase("
1136 << getOpName(CaseVal) << ", "
1137 << getOpName(BB) << ");";
1142 case Instruction::IndirectBr: {
1143 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1144 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1145 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1147 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1148 Out << iName << "->addDestination(" << opNames[i] << ");";
1153 case Instruction::Resume: {
1154 Out << "ResumeInst::Create(mod->getContext(), " << opNames[0]
1155 << ", " << bbname << ");";
1158 case Instruction::Invoke: {
1159 const InvokeInst* inv = cast<InvokeInst>(I);
1160 Out << "std::vector<Value*> " << iName << "_params;";
1162 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1163 Out << iName << "_params.push_back("
1164 << getOpName(inv->getArgOperand(i)) << ");";
1167 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1168 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1169 << getOpName(inv->getCalledFunction()) << ", "
1170 << getOpName(inv->getNormalDest()) << ", "
1171 << getOpName(inv->getUnwindDest()) << ", "
1172 << iName << "_params, \"";
1173 printEscapedString(inv->getName());
1174 Out << "\", " << bbname << ");";
1175 nl(Out) << iName << "->setCallingConv(";
1176 printCallingConv(inv->getCallingConv());
1178 printAttributes(inv->getAttributes(), iName);
1179 Out << iName << "->setAttributes(" << iName << "_PAL);";
1183 case Instruction::Unreachable: {
1184 Out << "new UnreachableInst("
1185 << "mod->getContext(), "
1189 case Instruction::Add:
1190 case Instruction::FAdd:
1191 case Instruction::Sub:
1192 case Instruction::FSub:
1193 case Instruction::Mul:
1194 case Instruction::FMul:
1195 case Instruction::UDiv:
1196 case Instruction::SDiv:
1197 case Instruction::FDiv:
1198 case Instruction::URem:
1199 case Instruction::SRem:
1200 case Instruction::FRem:
1201 case Instruction::And:
1202 case Instruction::Or:
1203 case Instruction::Xor:
1204 case Instruction::Shl:
1205 case Instruction::LShr:
1206 case Instruction::AShr:{
1207 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1208 switch (I->getOpcode()) {
1209 case Instruction::Add: Out << "Instruction::Add"; break;
1210 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1211 case Instruction::Sub: Out << "Instruction::Sub"; break;
1212 case Instruction::FSub: Out << "Instruction::FSub"; break;
1213 case Instruction::Mul: Out << "Instruction::Mul"; break;
1214 case Instruction::FMul: Out << "Instruction::FMul"; break;
1215 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1216 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1217 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1218 case Instruction::URem:Out << "Instruction::URem"; break;
1219 case Instruction::SRem:Out << "Instruction::SRem"; break;
1220 case Instruction::FRem:Out << "Instruction::FRem"; break;
1221 case Instruction::And: Out << "Instruction::And"; break;
1222 case Instruction::Or: Out << "Instruction::Or"; break;
1223 case Instruction::Xor: Out << "Instruction::Xor"; break;
1224 case Instruction::Shl: Out << "Instruction::Shl"; break;
1225 case Instruction::LShr:Out << "Instruction::LShr"; break;
1226 case Instruction::AShr:Out << "Instruction::AShr"; break;
1227 default: Out << "Instruction::BadOpCode"; break;
1229 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1230 printEscapedString(I->getName());
1231 Out << "\", " << bbname << ");";
1234 case Instruction::FCmp: {
1235 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1236 switch (cast<FCmpInst>(I)->getPredicate()) {
1237 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1238 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1239 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1240 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1241 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1242 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1243 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1244 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1245 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1246 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1247 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1248 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1249 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1250 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1251 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1252 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1253 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1255 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1256 printEscapedString(I->getName());
1260 case Instruction::ICmp: {
1261 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1262 switch (cast<ICmpInst>(I)->getPredicate()) {
1263 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1264 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1265 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1266 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1267 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1268 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1269 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1270 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1271 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1272 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1273 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1275 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1276 printEscapedString(I->getName());
1280 case Instruction::Alloca: {
1281 const AllocaInst* allocaI = cast<AllocaInst>(I);
1282 Out << "AllocaInst* " << iName << " = new AllocaInst("
1283 << getCppName(allocaI->getAllocatedType()) << ", ";
1284 if (allocaI->isArrayAllocation())
1285 Out << opNames[0] << ", ";
1287 printEscapedString(allocaI->getName());
1288 Out << "\", " << bbname << ");";
1289 if (allocaI->getAlignment())
1290 nl(Out) << iName << "->setAlignment("
1291 << allocaI->getAlignment() << ");";
1294 case Instruction::Load: {
1295 const LoadInst* load = cast<LoadInst>(I);
1296 Out << "LoadInst* " << iName << " = new LoadInst("
1297 << opNames[0] << ", \"";
1298 printEscapedString(load->getName());
1299 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1300 << ", " << bbname << ");";
1301 if (load->getAlignment())
1302 nl(Out) << iName << "->setAlignment("
1303 << load->getAlignment() << ");";
1304 if (load->isAtomic()) {
1305 StringRef Ordering = ConvertAtomicOrdering(load->getOrdering());
1306 StringRef CrossThread = ConvertAtomicSynchScope(load->getSynchScope());
1307 nl(Out) << iName << "->setAtomic("
1308 << Ordering << ", " << CrossThread << ");";
1312 case Instruction::Store: {
1313 const StoreInst* store = cast<StoreInst>(I);
1314 Out << "StoreInst* " << iName << " = new StoreInst("
1315 << opNames[0] << ", "
1316 << opNames[1] << ", "
1317 << (store->isVolatile() ? "true" : "false")
1318 << ", " << bbname << ");";
1319 if (store->getAlignment())
1320 nl(Out) << iName << "->setAlignment("
1321 << store->getAlignment() << ");";
1322 if (store->isAtomic()) {
1323 StringRef Ordering = ConvertAtomicOrdering(store->getOrdering());
1324 StringRef CrossThread = ConvertAtomicSynchScope(store->getSynchScope());
1325 nl(Out) << iName << "->setAtomic("
1326 << Ordering << ", " << CrossThread << ");";
1330 case Instruction::GetElementPtr: {
1331 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1332 if (gep->getNumOperands() <= 2) {
1333 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1335 if (gep->getNumOperands() == 2)
1336 Out << ", " << opNames[1];
1338 Out << "std::vector<Value*> " << iName << "_indices;";
1340 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1341 Out << iName << "_indices.push_back("
1342 << opNames[i] << ");";
1345 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1346 << opNames[0] << ", " << iName << "_indices";
1349 printEscapedString(gep->getName());
1350 Out << "\", " << bbname << ");";
1353 case Instruction::PHI: {
1354 const PHINode* phi = cast<PHINode>(I);
1356 Out << "PHINode* " << iName << " = PHINode::Create("
1357 << getCppName(phi->getType()) << ", "
1358 << phi->getNumIncomingValues() << ", \"";
1359 printEscapedString(phi->getName());
1360 Out << "\", " << bbname << ");";
1362 for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
1363 Out << iName << "->addIncoming("
1364 << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
1365 << getOpName(phi->getIncomingBlock(i)) << ");";
1370 case Instruction::Trunc:
1371 case Instruction::ZExt:
1372 case Instruction::SExt:
1373 case Instruction::FPTrunc:
1374 case Instruction::FPExt:
1375 case Instruction::FPToUI:
1376 case Instruction::FPToSI:
1377 case Instruction::UIToFP:
1378 case Instruction::SIToFP:
1379 case Instruction::PtrToInt:
1380 case Instruction::IntToPtr:
1381 case Instruction::BitCast: {
1382 const CastInst* cst = cast<CastInst>(I);
1383 Out << "CastInst* " << iName << " = new ";
1384 switch (I->getOpcode()) {
1385 case Instruction::Trunc: Out << "TruncInst"; break;
1386 case Instruction::ZExt: Out << "ZExtInst"; break;
1387 case Instruction::SExt: Out << "SExtInst"; break;
1388 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1389 case Instruction::FPExt: Out << "FPExtInst"; break;
1390 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1391 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1392 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1393 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1394 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1395 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1396 case Instruction::BitCast: Out << "BitCastInst"; break;
1397 default: llvm_unreachable("Unreachable");
1399 Out << "(" << opNames[0] << ", "
1400 << getCppName(cst->getType()) << ", \"";
1401 printEscapedString(cst->getName());
1402 Out << "\", " << bbname << ");";
1405 case Instruction::Call: {
1406 const CallInst* call = cast<CallInst>(I);
1407 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1408 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1409 << getCppName(ila->getFunctionType()) << ", \""
1410 << ila->getAsmString() << "\", \""
1411 << ila->getConstraintString() << "\","
1412 << (ila->hasSideEffects() ? "true" : "false") << ");";
1415 if (call->getNumArgOperands() > 1) {
1416 Out << "std::vector<Value*> " << iName << "_params;";
1418 for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
1419 Out << iName << "_params.push_back(" << opNames[i] << ");";
1422 Out << "CallInst* " << iName << " = CallInst::Create("
1423 << opNames[call->getNumArgOperands()] << ", "
1424 << iName << "_params, \"";
1425 } else if (call->getNumArgOperands() == 1) {
1426 Out << "CallInst* " << iName << " = CallInst::Create("
1427 << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
1429 Out << "CallInst* " << iName << " = CallInst::Create("
1430 << opNames[call->getNumArgOperands()] << ", \"";
1432 printEscapedString(call->getName());
1433 Out << "\", " << bbname << ");";
1434 nl(Out) << iName << "->setCallingConv(";
1435 printCallingConv(call->getCallingConv());
1437 nl(Out) << iName << "->setTailCall("
1438 << (call->isTailCall() ? "true" : "false");
1441 printAttributes(call->getAttributes(), iName);
1442 Out << iName << "->setAttributes(" << iName << "_PAL);";
1446 case Instruction::Select: {
1447 const SelectInst* sel = cast<SelectInst>(I);
1448 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1449 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1450 printEscapedString(sel->getName());
1451 Out << "\", " << bbname << ");";
1454 case Instruction::UserOp1:
1456 case Instruction::UserOp2: {
1457 /// FIXME: What should be done here?
1460 case Instruction::VAArg: {
1461 const VAArgInst* va = cast<VAArgInst>(I);
1462 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1463 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1464 printEscapedString(va->getName());
1465 Out << "\", " << bbname << ");";
1468 case Instruction::ExtractElement: {
1469 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1470 Out << "ExtractElementInst* " << getCppName(eei)
1471 << " = new ExtractElementInst(" << opNames[0]
1472 << ", " << opNames[1] << ", \"";
1473 printEscapedString(eei->getName());
1474 Out << "\", " << bbname << ");";
1477 case Instruction::InsertElement: {
1478 const InsertElementInst* iei = cast<InsertElementInst>(I);
1479 Out << "InsertElementInst* " << getCppName(iei)
1480 << " = InsertElementInst::Create(" << opNames[0]
1481 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1482 printEscapedString(iei->getName());
1483 Out << "\", " << bbname << ");";
1486 case Instruction::ShuffleVector: {
1487 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1488 Out << "ShuffleVectorInst* " << getCppName(svi)
1489 << " = new ShuffleVectorInst(" << opNames[0]
1490 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1491 printEscapedString(svi->getName());
1492 Out << "\", " << bbname << ");";
1495 case Instruction::ExtractValue: {
1496 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1497 Out << "std::vector<unsigned> " << iName << "_indices;";
1499 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1500 Out << iName << "_indices.push_back("
1501 << evi->idx_begin()[i] << ");";
1504 Out << "ExtractValueInst* " << getCppName(evi)
1505 << " = ExtractValueInst::Create(" << opNames[0]
1507 << iName << "_indices, \"";
1508 printEscapedString(evi->getName());
1509 Out << "\", " << bbname << ");";
1512 case Instruction::InsertValue: {
1513 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1514 Out << "std::vector<unsigned> " << iName << "_indices;";
1516 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1517 Out << iName << "_indices.push_back("
1518 << ivi->idx_begin()[i] << ");";
1521 Out << "InsertValueInst* " << getCppName(ivi)
1522 << " = InsertValueInst::Create(" << opNames[0]
1523 << ", " << opNames[1] << ", "
1524 << iName << "_indices, \"";
1525 printEscapedString(ivi->getName());
1526 Out << "\", " << bbname << ");";
1529 case Instruction::Fence: {
1530 const FenceInst *fi = cast<FenceInst>(I);
1531 StringRef Ordering = ConvertAtomicOrdering(fi->getOrdering());
1532 StringRef CrossThread = ConvertAtomicSynchScope(fi->getSynchScope());
1533 Out << "FenceInst* " << iName
1534 << " = new FenceInst(mod->getContext(), "
1535 << Ordering << ", " << CrossThread << ", " << bbname
1539 case Instruction::AtomicCmpXchg: {
1540 const AtomicCmpXchgInst *cxi = cast<AtomicCmpXchgInst>(I);
1541 StringRef Ordering = ConvertAtomicOrdering(cxi->getOrdering());
1542 StringRef CrossThread = ConvertAtomicSynchScope(cxi->getSynchScope());
1543 Out << "AtomicCmpXchgInst* " << iName
1544 << " = new AtomicCmpXchgInst("
1545 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", "
1546 << Ordering << ", " << CrossThread << ", " << bbname
1548 nl(Out) << iName << "->setName(\"";
1549 printEscapedString(cxi->getName());
1553 case Instruction::AtomicRMW: {
1554 const AtomicRMWInst *rmwi = cast<AtomicRMWInst>(I);
1555 StringRef Ordering = ConvertAtomicOrdering(rmwi->getOrdering());
1556 StringRef CrossThread = ConvertAtomicSynchScope(rmwi->getSynchScope());
1557 StringRef Operation;
1558 switch (rmwi->getOperation()) {
1559 case AtomicRMWInst::Xchg: Operation = "AtomicRMWInst::Xchg"; break;
1560 case AtomicRMWInst::Add: Operation = "AtomicRMWInst::Add"; break;
1561 case AtomicRMWInst::Sub: Operation = "AtomicRMWInst::Sub"; break;
1562 case AtomicRMWInst::And: Operation = "AtomicRMWInst::And"; break;
1563 case AtomicRMWInst::Nand: Operation = "AtomicRMWInst::Nand"; break;
1564 case AtomicRMWInst::Or: Operation = "AtomicRMWInst::Or"; break;
1565 case AtomicRMWInst::Xor: Operation = "AtomicRMWInst::Xor"; break;
1566 case AtomicRMWInst::Max: Operation = "AtomicRMWInst::Max"; break;
1567 case AtomicRMWInst::Min: Operation = "AtomicRMWInst::Min"; break;
1568 case AtomicRMWInst::UMax: Operation = "AtomicRMWInst::UMax"; break;
1569 case AtomicRMWInst::UMin: Operation = "AtomicRMWInst::UMin"; break;
1570 case AtomicRMWInst::BAD_BINOP: llvm_unreachable("Bad atomic operation");
1572 Out << "AtomicRMWInst* " << iName
1573 << " = new AtomicRMWInst("
1574 << Operation << ", "
1575 << opNames[0] << ", " << opNames[1] << ", "
1576 << Ordering << ", " << CrossThread << ", " << bbname
1578 nl(Out) << iName << "->setName(\"";
1579 printEscapedString(rmwi->getName());
1584 DefinedValues.insert(I);
1589 // Print out the types, constants and declarations needed by one function
1590 void CppWriter::printFunctionUses(const Function* F) {
1591 nl(Out) << "// Type Definitions"; nl(Out);
1593 // Print the function's return type
1594 printType(F->getReturnType());
1596 // Print the function's function type
1597 printType(F->getFunctionType());
1599 // Print the types of each of the function's arguments
1600 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1602 printType(AI->getType());
1606 // Print type definitions for every type referenced by an instruction and
1607 // make a note of any global values or constants that are referenced
1608 SmallPtrSet<GlobalValue*,64> gvs;
1609 SmallPtrSet<Constant*,64> consts;
1610 for (Function::const_iterator BB = F->begin(), BE = F->end();
1612 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1614 // Print the type of the instruction itself
1615 printType(I->getType());
1617 // Print the type of each of the instruction's operands
1618 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1619 Value* operand = I->getOperand(i);
1620 printType(operand->getType());
1622 // If the operand references a GVal or Constant, make a note of it
1623 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1625 if (GenerationType != GenFunction)
1626 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1627 if (GVar->hasInitializer())
1628 consts.insert(GVar->getInitializer());
1629 } else if (Constant* C = dyn_cast<Constant>(operand)) {
1631 for (unsigned j = 0; j < C->getNumOperands(); ++j) {
1632 // If the operand references a GVal or Constant, make a note of it
1633 Value* operand = C->getOperand(j);
1634 printType(operand->getType());
1635 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1637 if (GenerationType != GenFunction)
1638 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1639 if (GVar->hasInitializer())
1640 consts.insert(GVar->getInitializer());
1648 // Print the function declarations for any functions encountered
1649 nl(Out) << "// Function Declarations"; nl(Out);
1650 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1652 if (Function* Fun = dyn_cast<Function>(*I)) {
1653 if (!is_inline || Fun != F)
1654 printFunctionHead(Fun);
1658 // Print the global variable declarations for any variables encountered
1659 nl(Out) << "// Global Variable Declarations"; nl(Out);
1660 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1662 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1663 printVariableHead(F);
1666 // Print the constants found
1667 nl(Out) << "// Constant Definitions"; nl(Out);
1668 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1669 E = consts.end(); I != E; ++I) {
1673 // Process the global variables definitions now that all the constants have
1674 // been emitted. These definitions just couple the gvars with their constant
1676 if (GenerationType != GenFunction) {
1677 nl(Out) << "// Global Variable Definitions"; nl(Out);
1678 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1680 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1681 printVariableBody(GV);
1686 void CppWriter::printFunctionHead(const Function* F) {
1687 nl(Out) << "Function* " << getCppName(F);
1688 Out << " = mod->getFunction(\"";
1689 printEscapedString(F->getName());
1691 nl(Out) << "if (!" << getCppName(F) << ") {";
1692 nl(Out) << getCppName(F);
1694 Out<< " = Function::Create(";
1695 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1696 nl(Out) << "/*Linkage=*/";
1697 printLinkageType(F->getLinkage());
1699 nl(Out) << "/*Name=*/\"";
1700 printEscapedString(F->getName());
1701 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1704 Out << "->setCallingConv(";
1705 printCallingConv(F->getCallingConv());
1708 if (F->hasSection()) {
1710 Out << "->setSection(\"" << F->getSection() << "\");";
1713 if (F->getAlignment()) {
1715 Out << "->setAlignment(" << F->getAlignment() << ");";
1718 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1720 Out << "->setVisibility(";
1721 printVisibilityType(F->getVisibility());
1727 Out << "->setGC(\"" << F->getGC() << "\");";
1732 printAttributes(F->getAttributes(), getCppName(F));
1734 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1738 void CppWriter::printFunctionBody(const Function *F) {
1739 if (F->isDeclaration())
1740 return; // external functions have no bodies.
1742 // Clear the DefinedValues and ForwardRefs maps because we can't have
1743 // cross-function forward refs
1744 ForwardRefs.clear();
1745 DefinedValues.clear();
1747 // Create all the argument values
1749 if (!F->arg_empty()) {
1750 Out << "Function::arg_iterator args = " << getCppName(F)
1751 << "->arg_begin();";
1754 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1756 Out << "Value* " << getCppName(AI) << " = args++;";
1758 if (AI->hasName()) {
1759 Out << getCppName(AI) << "->setName(\"";
1760 printEscapedString(AI->getName());
1767 // Create all the basic blocks
1769 for (Function::const_iterator BI = F->begin(), BE = F->end();
1771 std::string bbname(getCppName(BI));
1772 Out << "BasicBlock* " << bbname <<
1773 " = BasicBlock::Create(mod->getContext(), \"";
1775 printEscapedString(BI->getName());
1776 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1780 // Output all of its basic blocks... for the function
1781 for (Function::const_iterator BI = F->begin(), BE = F->end();
1783 std::string bbname(getCppName(BI));
1784 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1787 // Output all of the instructions in the basic block...
1788 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1790 printInstruction(I,bbname);
1794 // Loop over the ForwardRefs and resolve them now that all instructions
1796 if (!ForwardRefs.empty()) {
1797 nl(Out) << "// Resolve Forward References";
1801 while (!ForwardRefs.empty()) {
1802 ForwardRefMap::iterator I = ForwardRefs.begin();
1803 Out << I->second << "->replaceAllUsesWith("
1804 << getCppName(I->first) << "); delete " << I->second << ";";
1806 ForwardRefs.erase(I);
1810 void CppWriter::printInline(const std::string& fname,
1811 const std::string& func) {
1812 const Function* F = TheModule->getFunction(func);
1814 error(std::string("Function '") + func + "' not found in input module");
1817 if (F->isDeclaration()) {
1818 error(std::string("Function '") + func + "' is external!");
1821 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1823 unsigned arg_count = 1;
1824 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1826 Out << ", Value* arg_" << arg_count;
1831 printFunctionUses(F);
1832 printFunctionBody(F);
1834 Out << "return " << getCppName(F->begin()) << ";";
1839 void CppWriter::printModuleBody() {
1840 // Print out all the type definitions
1841 nl(Out) << "// Type Definitions"; nl(Out);
1842 printTypes(TheModule);
1844 // Functions can call each other and global variables can reference them so
1845 // define all the functions first before emitting their function bodies.
1846 nl(Out) << "// Function Declarations"; nl(Out);
1847 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1849 printFunctionHead(I);
1851 // Process the global variables declarations. We can't initialze them until
1852 // after the constants are printed so just print a header for each global
1853 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1854 for (Module::const_global_iterator I = TheModule->global_begin(),
1855 E = TheModule->global_end(); I != E; ++I) {
1856 printVariableHead(I);
1859 // Print out all the constants definitions. Constants don't recurse except
1860 // through GlobalValues. All GlobalValues have been declared at this point
1861 // so we can proceed to generate the constants.
1862 nl(Out) << "// Constant Definitions"; nl(Out);
1863 printConstants(TheModule);
1865 // Process the global variables definitions now that all the constants have
1866 // been emitted. These definitions just couple the gvars with their constant
1868 nl(Out) << "// Global Variable Definitions"; nl(Out);
1869 for (Module::const_global_iterator I = TheModule->global_begin(),
1870 E = TheModule->global_end(); I != E; ++I) {
1871 printVariableBody(I);
1874 // Finally, we can safely put out all of the function bodies.
1875 nl(Out) << "// Function Definitions"; nl(Out);
1876 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1878 if (!I->isDeclaration()) {
1879 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1883 printFunctionBody(I);
1890 void CppWriter::printProgram(const std::string& fname,
1891 const std::string& mName) {
1892 Out << "#include <llvm/LLVMContext.h>\n";
1893 Out << "#include <llvm/Module.h>\n";
1894 Out << "#include <llvm/DerivedTypes.h>\n";
1895 Out << "#include <llvm/Constants.h>\n";
1896 Out << "#include <llvm/GlobalVariable.h>\n";
1897 Out << "#include <llvm/Function.h>\n";
1898 Out << "#include <llvm/CallingConv.h>\n";
1899 Out << "#include <llvm/BasicBlock.h>\n";
1900 Out << "#include <llvm/Instructions.h>\n";
1901 Out << "#include <llvm/InlineAsm.h>\n";
1902 Out << "#include <llvm/Support/FormattedStream.h>\n";
1903 Out << "#include <llvm/Support/MathExtras.h>\n";
1904 Out << "#include <llvm/Pass.h>\n";
1905 Out << "#include <llvm/PassManager.h>\n";
1906 Out << "#include <llvm/ADT/SmallVector.h>\n";
1907 Out << "#include <llvm/Analysis/Verifier.h>\n";
1908 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1909 Out << "#include <algorithm>\n";
1910 Out << "using namespace llvm;\n\n";
1911 Out << "Module* " << fname << "();\n\n";
1912 Out << "int main(int argc, char**argv) {\n";
1913 Out << " Module* Mod = " << fname << "();\n";
1914 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1915 Out << " PassManager PM;\n";
1916 Out << " PM.add(createPrintModulePass(&outs()));\n";
1917 Out << " PM.run(*Mod);\n";
1918 Out << " return 0;\n";
1920 printModule(fname,mName);
1923 void CppWriter::printModule(const std::string& fname,
1924 const std::string& mName) {
1925 nl(Out) << "Module* " << fname << "() {";
1926 nl(Out,1) << "// Module Construction";
1927 nl(Out) << "Module* mod = new Module(\"";
1928 printEscapedString(mName);
1929 Out << "\", getGlobalContext());";
1930 if (!TheModule->getTargetTriple().empty()) {
1931 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1933 if (!TheModule->getTargetTriple().empty()) {
1934 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1938 if (!TheModule->getModuleInlineAsm().empty()) {
1939 nl(Out) << "mod->setModuleInlineAsm(\"";
1940 printEscapedString(TheModule->getModuleInlineAsm());
1946 nl(Out) << "return mod;";
1951 void CppWriter::printContents(const std::string& fname,
1952 const std::string& mName) {
1953 Out << "\nModule* " << fname << "(Module *mod) {\n";
1954 Out << "\nmod->setModuleIdentifier(\"";
1955 printEscapedString(mName);
1958 Out << "\nreturn mod;\n";
1962 void CppWriter::printFunction(const std::string& fname,
1963 const std::string& funcName) {
1964 const Function* F = TheModule->getFunction(funcName);
1966 error(std::string("Function '") + funcName + "' not found in input module");
1969 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1970 printFunctionUses(F);
1971 printFunctionHead(F);
1972 printFunctionBody(F);
1973 Out << "return " << getCppName(F) << ";\n";
1977 void CppWriter::printFunctions() {
1978 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1979 Module::const_iterator I = funcs.begin();
1980 Module::const_iterator IE = funcs.end();
1982 for (; I != IE; ++I) {
1983 const Function &func = *I;
1984 if (!func.isDeclaration()) {
1985 std::string name("define_");
1986 name += func.getName();
1987 printFunction(name, func.getName());
1992 void CppWriter::printVariable(const std::string& fname,
1993 const std::string& varName) {
1994 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1997 error(std::string("Variable '") + varName + "' not found in input module");
2000 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
2001 printVariableUses(GV);
2002 printVariableHead(GV);
2003 printVariableBody(GV);
2004 Out << "return " << getCppName(GV) << ";\n";
2008 void CppWriter::printType(const std::string &fname,
2009 const std::string &typeName) {
2010 Type* Ty = TheModule->getTypeByName(typeName);
2012 error(std::string("Type '") + typeName + "' not found in input module");
2015 Out << "\nType* " << fname << "(Module *mod) {\n";
2017 Out << "return " << getCppName(Ty) << ";\n";
2021 bool CppWriter::runOnModule(Module &M) {
2025 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
2027 // Get the name of the function we're supposed to generate
2028 std::string fname = FuncName.getValue();
2030 // Get the name of the thing we are to generate
2031 std::string tgtname = NameToGenerate.getValue();
2032 if (GenerationType == GenModule ||
2033 GenerationType == GenContents ||
2034 GenerationType == GenProgram ||
2035 GenerationType == GenFunctions) {
2036 if (tgtname == "!bad!") {
2037 if (M.getModuleIdentifier() == "-")
2038 tgtname = "<stdin>";
2040 tgtname = M.getModuleIdentifier();
2042 } else if (tgtname == "!bad!")
2043 error("You must use the -for option with -gen-{function,variable,type}");
2045 switch (WhatToGenerate(GenerationType)) {
2048 fname = "makeLLVMModule";
2049 printProgram(fname,tgtname);
2053 fname = "makeLLVMModule";
2054 printModule(fname,tgtname);
2058 fname = "makeLLVMModuleContents";
2059 printContents(fname,tgtname);
2063 fname = "makeLLVMFunction";
2064 printFunction(fname,tgtname);
2071 fname = "makeLLVMInline";
2072 printInline(fname,tgtname);
2076 fname = "makeLLVMVariable";
2077 printVariable(fname,tgtname);
2081 fname = "makeLLVMType";
2082 printType(fname,tgtname);
2089 char CppWriter::ID = 0;
2091 //===----------------------------------------------------------------------===//
2092 // External Interface declaration
2093 //===----------------------------------------------------------------------===//
2095 bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
2096 formatted_raw_ostream &o,
2097 CodeGenFileType FileType,
2099 AnalysisID StartAfter,
2100 AnalysisID StopAfter) {
2101 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
2102 PM.add(new CppWriter(o));