1 //===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the writing of the LLVM IR as a set of C++ calls to the
11 // LLVM IR interface. The input module is assumed to be verified.
13 //===----------------------------------------------------------------------===//
15 #include "CPPTargetMachine.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instruction.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/PassManager.h"
25 #include "llvm/TypeSymbolTable.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/FormattedStream.h"
30 #include "llvm/Target/TargetRegistry.h"
31 #include "llvm/Config/config.h"
37 static cl::opt<std::string>
38 FuncName("cppfname", cl::desc("Specify the name of the generated function"),
39 cl::value_desc("function name"));
52 static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
53 cl::desc("Choose what kind of output to generate"),
56 clEnumValN(GenProgram, "program", "Generate a complete program"),
57 clEnumValN(GenModule, "module", "Generate a module definition"),
58 clEnumValN(GenContents, "contents", "Generate contents of a module"),
59 clEnumValN(GenFunction, "function", "Generate a function definition"),
60 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
61 clEnumValN(GenInline, "inline", "Generate an inline function"),
62 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
63 clEnumValN(GenType, "type", "Generate a type definition"),
68 static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
69 cl::desc("Specify the name of the thing to generate"),
72 extern "C" void LLVMInitializeCppBackendTarget() {
73 // Register the target.
74 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
78 typedef std::vector<const Type*> TypeList;
79 typedef std::map<const Type*,std::string> TypeMap;
80 typedef std::map<const Value*,std::string> ValueMap;
81 typedef std::set<std::string> NameSet;
82 typedef std::set<const Type*> TypeSet;
83 typedef std::set<const Value*> ValueSet;
84 typedef std::map<const Value*,std::string> ForwardRefMap;
86 /// CppWriter - This class is the main chunk of code that converts an LLVM
87 /// module to a C++ translation unit.
88 class CppWriter : public ModulePass {
89 formatted_raw_ostream &Out;
90 const Module *TheModule;
94 TypeMap UnresolvedTypes;
98 ValueSet DefinedValues;
99 ForwardRefMap ForwardRefs;
104 explicit CppWriter(formatted_raw_ostream &o) :
105 ModulePass(&ID), Out(o), uniqueNum(0), is_inline(false) {}
107 virtual const char *getPassName() const { return "C++ backend"; }
109 bool runOnModule(Module &M);
111 void printProgram(const std::string& fname, const std::string& modName );
112 void printModule(const std::string& fname, const std::string& modName );
113 void printContents(const std::string& fname, const std::string& modName );
114 void printFunction(const std::string& fname, const std::string& funcName );
115 void printFunctions();
116 void printInline(const std::string& fname, const std::string& funcName );
117 void printVariable(const std::string& fname, const std::string& varName );
118 void printType(const std::string& fname, const std::string& typeName );
120 void error(const std::string& msg);
123 void printLinkageType(GlobalValue::LinkageTypes LT);
124 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
125 void printCallingConv(unsigned cc);
126 void printEscapedString(const std::string& str);
127 void printCFP(const ConstantFP* CFP);
129 std::string getCppName(const Type* val);
130 inline void printCppName(const Type* val);
132 std::string getCppName(const Value* val);
133 inline void printCppName(const Value* val);
135 void printAttributes(const AttrListPtr &PAL, const std::string &name);
136 bool printTypeInternal(const Type* Ty);
137 inline void printType(const Type* Ty);
138 void printTypes(const Module* M);
140 void printConstant(const Constant *CPV);
141 void printConstants(const Module* M);
143 void printVariableUses(const GlobalVariable *GV);
144 void printVariableHead(const GlobalVariable *GV);
145 void printVariableBody(const GlobalVariable *GV);
147 void printFunctionUses(const Function *F);
148 void printFunctionHead(const Function *F);
149 void printFunctionBody(const Function *F);
150 void printInstruction(const Instruction *I, const std::string& bbname);
151 std::string getOpName(Value*);
153 void printModuleBody();
156 static unsigned indent_level = 0;
157 inline formatted_raw_ostream& nl(formatted_raw_ostream& Out, int delta = 0) {
159 if (delta >= 0 || indent_level >= unsigned(-delta))
160 indent_level += delta;
161 for (unsigned i = 0; i < indent_level; ++i)
166 inline void in() { indent_level++; }
167 inline void out() { if (indent_level >0) indent_level--; }
170 sanitize(std::string& str) {
171 for (size_t i = 0; i < str.length(); ++i)
172 if (!isalnum(str[i]) && str[i] != '_')
177 getTypePrefix(const Type* Ty ) {
178 switch (Ty->getTypeID()) {
179 case Type::VoidTyID: return "void_";
180 case Type::IntegerTyID:
181 return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
183 case Type::FloatTyID: return "float_";
184 case Type::DoubleTyID: return "double_";
185 case Type::LabelTyID: return "label_";
186 case Type::FunctionTyID: return "func_";
187 case Type::StructTyID: return "struct_";
188 case Type::ArrayTyID: return "array_";
189 case Type::PointerTyID: return "ptr_";
190 case Type::VectorTyID: return "packed_";
191 case Type::OpaqueTyID: return "opaque_";
192 default: return "other_";
197 // Looks up the type in the symbol table and returns a pointer to its name or
198 // a null pointer if it wasn't found. Note that this isn't the same as the
199 // Mode::getTypeName function which will return an empty string, not a null
200 // pointer if the name is not found.
201 inline const std::string*
202 findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
203 TypeSymbolTable::const_iterator TI = ST.begin();
204 TypeSymbolTable::const_iterator TE = ST.end();
205 for (;TI != TE; ++TI)
206 if (TI->second == Ty)
211 void CppWriter::error(const std::string& msg) {
212 llvm_report_error(msg);
215 // printCFP - Print a floating point constant .. very carefully :)
216 // This makes sure that conversion to/from floating yields the same binary
217 // result so that we don't lose precision.
218 void CppWriter::printCFP(const ConstantFP *CFP) {
220 APFloat APF = APFloat(CFP->getValueAPF()); // copy
221 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
222 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
223 Out << "ConstantFP::get(getGlobalContext(), ";
227 sprintf(Buffer, "%A", APF.convertToDouble());
228 if ((!strncmp(Buffer, "0x", 2) ||
229 !strncmp(Buffer, "-0x", 3) ||
230 !strncmp(Buffer, "+0x", 3)) &&
231 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
232 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
233 Out << "BitsToDouble(" << Buffer << ")";
235 Out << "BitsToFloat((float)" << Buffer << ")";
239 std::string StrVal = ftostr(CFP->getValueAPF());
241 while (StrVal[0] == ' ')
242 StrVal.erase(StrVal.begin());
244 // Check to make sure that the stringized number is not some string like
245 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
246 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
247 ((StrVal[0] == '-' || StrVal[0] == '+') &&
248 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
249 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
250 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
253 Out << StrVal << "f";
254 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
255 Out << "BitsToDouble(0x"
256 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
257 << "ULL) /* " << StrVal << " */";
259 Out << "BitsToFloat(0x"
260 << utohexstr((uint32_t)CFP->getValueAPF().
261 bitcastToAPInt().getZExtValue())
262 << "U) /* " << StrVal << " */";
270 void CppWriter::printCallingConv(unsigned cc){
271 // Print the calling convention.
273 case CallingConv::C: Out << "CallingConv::C"; break;
274 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
275 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
276 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
277 default: Out << cc; break;
281 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
283 case GlobalValue::InternalLinkage:
284 Out << "GlobalValue::InternalLinkage"; break;
285 case GlobalValue::PrivateLinkage:
286 Out << "GlobalValue::PrivateLinkage"; break;
287 case GlobalValue::LinkerPrivateLinkage:
288 Out << "GlobalValue::LinkerPrivateLinkage"; break;
289 case GlobalValue::AvailableExternallyLinkage:
290 Out << "GlobalValue::AvailableExternallyLinkage "; break;
291 case GlobalValue::LinkOnceAnyLinkage:
292 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
293 case GlobalValue::LinkOnceODRLinkage:
294 Out << "GlobalValue::LinkOnceODRLinkage "; break;
295 case GlobalValue::WeakAnyLinkage:
296 Out << "GlobalValue::WeakAnyLinkage"; break;
297 case GlobalValue::WeakODRLinkage:
298 Out << "GlobalValue::WeakODRLinkage"; break;
299 case GlobalValue::AppendingLinkage:
300 Out << "GlobalValue::AppendingLinkage"; break;
301 case GlobalValue::ExternalLinkage:
302 Out << "GlobalValue::ExternalLinkage"; break;
303 case GlobalValue::DLLImportLinkage:
304 Out << "GlobalValue::DLLImportLinkage"; break;
305 case GlobalValue::DLLExportLinkage:
306 Out << "GlobalValue::DLLExportLinkage"; break;
307 case GlobalValue::ExternalWeakLinkage:
308 Out << "GlobalValue::ExternalWeakLinkage"; break;
309 case GlobalValue::GhostLinkage:
310 Out << "GlobalValue::GhostLinkage"; break;
311 case GlobalValue::CommonLinkage:
312 Out << "GlobalValue::CommonLinkage"; break;
316 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
318 default: llvm_unreachable("Unknown GVar visibility");
319 case GlobalValue::DefaultVisibility:
320 Out << "GlobalValue::DefaultVisibility";
322 case GlobalValue::HiddenVisibility:
323 Out << "GlobalValue::HiddenVisibility";
325 case GlobalValue::ProtectedVisibility:
326 Out << "GlobalValue::ProtectedVisibility";
331 // printEscapedString - Print each character of the specified string, escaping
332 // it if it is not printable or if it is an escape char.
333 void CppWriter::printEscapedString(const std::string &Str) {
334 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
335 unsigned char C = Str[i];
336 if (isprint(C) && C != '"' && C != '\\') {
340 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
341 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
346 std::string CppWriter::getCppName(const Type* Ty) {
347 // First, handle the primitive types .. easy
348 if (Ty->isPrimitiveType() || Ty->isInteger()) {
349 switch (Ty->getTypeID()) {
350 case Type::VoidTyID: return "Type::getVoidTy(getGlobalContext())";
351 case Type::IntegerTyID: {
352 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
353 return "IntegerType::get(getGlobalContext(), " + utostr(BitWidth) + ")";
355 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(getGlobalContext())";
356 case Type::FloatTyID: return "Type::getFloatTy(getGlobalContext())";
357 case Type::DoubleTyID: return "Type::getDoubleTy(getGlobalContext())";
358 case Type::LabelTyID: return "Type::getLabelTy(getGlobalContext())";
360 error("Invalid primitive type");
363 // shouldn't be returned, but make it sensible
364 return "Type::getVoidTy(getGlobalContext())";
367 // Now, see if we've seen the type before and return that
368 TypeMap::iterator I = TypeNames.find(Ty);
369 if (I != TypeNames.end())
372 // Okay, let's build a new name for this type. Start with a prefix
373 const char* prefix = 0;
374 switch (Ty->getTypeID()) {
375 case Type::FunctionTyID: prefix = "FuncTy_"; break;
376 case Type::StructTyID: prefix = "StructTy_"; break;
377 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
378 case Type::PointerTyID: prefix = "PointerTy_"; break;
379 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
380 case Type::VectorTyID: prefix = "VectorTy_"; break;
381 default: prefix = "OtherTy_"; break; // prevent breakage
384 // See if the type has a name in the symboltable and build accordingly
385 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
388 name = std::string(prefix) + *tName;
390 name = std::string(prefix) + utostr(uniqueNum++);
394 return TypeNames[Ty] = name;
397 void CppWriter::printCppName(const Type* Ty) {
398 printEscapedString(getCppName(Ty));
401 std::string CppWriter::getCppName(const Value* val) {
403 ValueMap::iterator I = ValueNames.find(val);
404 if (I != ValueNames.end() && I->first == val)
407 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
408 name = std::string("gvar_") +
409 getTypePrefix(GV->getType()->getElementType());
410 } else if (isa<Function>(val)) {
411 name = std::string("func_");
412 } else if (const Constant* C = dyn_cast<Constant>(val)) {
413 name = std::string("const_") + getTypePrefix(C->getType());
414 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
416 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
417 Function::const_arg_iterator(Arg)) + 1;
418 name = std::string("arg_") + utostr(argNum);
419 NameSet::iterator NI = UsedNames.find(name);
420 if (NI != UsedNames.end())
421 name += std::string("_") + utostr(uniqueNum++);
422 UsedNames.insert(name);
423 return ValueNames[val] = name;
425 name = getTypePrefix(val->getType());
428 name = getTypePrefix(val->getType());
431 name += val->getName();
433 name += utostr(uniqueNum++);
435 NameSet::iterator NI = UsedNames.find(name);
436 if (NI != UsedNames.end())
437 name += std::string("_") + utostr(uniqueNum++);
438 UsedNames.insert(name);
439 return ValueNames[val] = name;
442 void CppWriter::printCppName(const Value* val) {
443 printEscapedString(getCppName(val));
446 void CppWriter::printAttributes(const AttrListPtr &PAL,
447 const std::string &name) {
448 Out << "AttrListPtr " << name << "_PAL;";
450 if (!PAL.isEmpty()) {
451 Out << '{'; in(); nl(Out);
452 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
453 Out << "AttributeWithIndex PAWI;"; nl(Out);
454 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
455 unsigned index = PAL.getSlot(i).Index;
456 Attributes attrs = PAL.getSlot(i).Attrs;
457 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
458 #define HANDLE_ATTR(X) \
459 if (attrs & Attribute::X) \
460 Out << " | Attribute::" #X; \
461 attrs &= ~Attribute::X;
465 HANDLE_ATTR(NoReturn);
467 HANDLE_ATTR(StructRet);
468 HANDLE_ATTR(NoUnwind);
469 HANDLE_ATTR(NoAlias);
472 HANDLE_ATTR(ReadNone);
473 HANDLE_ATTR(ReadOnly);
474 HANDLE_ATTR(NoInline);
475 HANDLE_ATTR(AlwaysInline);
476 HANDLE_ATTR(OptimizeForSize);
477 HANDLE_ATTR(StackProtect);
478 HANDLE_ATTR(StackProtectReq);
479 HANDLE_ATTR(NoCapture);
481 assert(attrs == 0 && "Unhandled attribute!");
484 Out << "Attrs.push_back(PAWI);";
487 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
494 bool CppWriter::printTypeInternal(const Type* Ty) {
495 // We don't print definitions for primitive types
496 if (Ty->isPrimitiveType() || Ty->isInteger())
499 // If we already defined this type, we don't need to define it again.
500 if (DefinedTypes.find(Ty) != DefinedTypes.end())
503 // Everything below needs the name for the type so get it now.
504 std::string typeName(getCppName(Ty));
506 // Search the type stack for recursion. If we find it, then generate this
507 // as an OpaqueType, but make sure not to do this multiple times because
508 // the type could appear in multiple places on the stack. Once the opaque
509 // definition is issued, it must not be re-issued. Consequently we have to
510 // check the UnresolvedTypes list as well.
511 TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
513 if (TI != TypeStack.end()) {
514 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
515 if (I == UnresolvedTypes.end()) {
516 Out << "PATypeHolder " << typeName;
517 Out << "_fwd = OpaqueType::get(getGlobalContext());";
519 UnresolvedTypes[Ty] = typeName;
524 // We're going to print a derived type which, by definition, contains other
525 // types. So, push this one we're printing onto the type stack to assist with
526 // recursive definitions.
527 TypeStack.push_back(Ty);
529 // Print the type definition
530 switch (Ty->getTypeID()) {
531 case Type::FunctionTyID: {
532 const FunctionType* FT = cast<FunctionType>(Ty);
533 Out << "std::vector<const Type*>" << typeName << "_args;";
535 FunctionType::param_iterator PI = FT->param_begin();
536 FunctionType::param_iterator PE = FT->param_end();
537 for (; PI != PE; ++PI) {
538 const Type* argTy = static_cast<const Type*>(*PI);
539 bool isForward = printTypeInternal(argTy);
540 std::string argName(getCppName(argTy));
541 Out << typeName << "_args.push_back(" << argName;
547 bool isForward = printTypeInternal(FT->getReturnType());
548 std::string retTypeName(getCppName(FT->getReturnType()));
549 Out << "FunctionType* " << typeName << " = FunctionType::get(";
550 in(); nl(Out) << "/*Result=*/" << retTypeName;
554 nl(Out) << "/*Params=*/" << typeName << "_args,";
555 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
560 case Type::StructTyID: {
561 const StructType* ST = cast<StructType>(Ty);
562 Out << "std::vector<const Type*>" << typeName << "_fields;";
564 StructType::element_iterator EI = ST->element_begin();
565 StructType::element_iterator EE = ST->element_end();
566 for (; EI != EE; ++EI) {
567 const Type* fieldTy = static_cast<const Type*>(*EI);
568 bool isForward = printTypeInternal(fieldTy);
569 std::string fieldName(getCppName(fieldTy));
570 Out << typeName << "_fields.push_back(" << fieldName;
576 Out << "StructType* " << typeName << " = StructType::get("
577 << "mod->getContext(), "
578 << typeName << "_fields, /*isPacked=*/"
579 << (ST->isPacked() ? "true" : "false") << ");";
583 case Type::ArrayTyID: {
584 const ArrayType* AT = cast<ArrayType>(Ty);
585 const Type* ET = AT->getElementType();
586 bool isForward = printTypeInternal(ET);
587 std::string elemName(getCppName(ET));
588 Out << "ArrayType* " << typeName << " = ArrayType::get("
589 << elemName << (isForward ? "_fwd" : "")
590 << ", " << utostr(AT->getNumElements()) << ");";
594 case Type::PointerTyID: {
595 const PointerType* PT = cast<PointerType>(Ty);
596 const Type* ET = PT->getElementType();
597 bool isForward = printTypeInternal(ET);
598 std::string elemName(getCppName(ET));
599 Out << "PointerType* " << typeName << " = PointerType::get("
600 << elemName << (isForward ? "_fwd" : "")
601 << ", " << utostr(PT->getAddressSpace()) << ");";
605 case Type::VectorTyID: {
606 const VectorType* PT = cast<VectorType>(Ty);
607 const Type* ET = PT->getElementType();
608 bool isForward = printTypeInternal(ET);
609 std::string elemName(getCppName(ET));
610 Out << "VectorType* " << typeName << " = VectorType::get("
611 << elemName << (isForward ? "_fwd" : "")
612 << ", " << utostr(PT->getNumElements()) << ");";
616 case Type::OpaqueTyID: {
617 Out << "OpaqueType* " << typeName;
618 Out << " = OpaqueType::get(getGlobalContext());";
623 error("Invalid TypeID");
626 // If the type had a name, make sure we recreate it.
627 const std::string* progTypeName =
628 findTypeName(TheModule->getTypeSymbolTable(),Ty);
630 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
635 // Pop us off the type stack
636 TypeStack.pop_back();
638 // Indicate that this type is now defined.
639 DefinedTypes.insert(Ty);
641 // Early resolve as many unresolved types as possible. Search the unresolved
642 // types map for the type we just printed. Now that its definition is complete
643 // we can resolve any previous references to it. This prevents a cascade of
645 TypeMap::iterator I = UnresolvedTypes.find(Ty);
646 if (I != UnresolvedTypes.end()) {
647 Out << "cast<OpaqueType>(" << I->second
648 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
650 Out << I->second << " = cast<";
651 switch (Ty->getTypeID()) {
652 case Type::FunctionTyID: Out << "FunctionType"; break;
653 case Type::ArrayTyID: Out << "ArrayType"; break;
654 case Type::StructTyID: Out << "StructType"; break;
655 case Type::VectorTyID: Out << "VectorType"; break;
656 case Type::PointerTyID: Out << "PointerType"; break;
657 case Type::OpaqueTyID: Out << "OpaqueType"; break;
658 default: Out << "NoSuchDerivedType"; break;
660 Out << ">(" << I->second << "_fwd.get());";
662 UnresolvedTypes.erase(I);
665 // Finally, separate the type definition from other with a newline.
668 // We weren't a recursive type
672 // Prints a type definition. Returns true if it could not resolve all the
673 // types in the definition but had to use a forward reference.
674 void CppWriter::printType(const Type* Ty) {
675 assert(TypeStack.empty());
677 printTypeInternal(Ty);
678 assert(TypeStack.empty());
681 void CppWriter::printTypes(const Module* M) {
682 // Walk the symbol table and print out all its types
683 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
684 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
687 // For primitive types and types already defined, just add a name
688 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
689 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
690 TNI != TypeNames.end()) {
691 Out << "mod->addTypeName(\"";
692 printEscapedString(TI->first);
693 Out << "\", " << getCppName(TI->second) << ");";
695 // For everything else, define the type
697 printType(TI->second);
701 // Add all of the global variables to the value table...
702 for (Module::const_global_iterator I = TheModule->global_begin(),
703 E = TheModule->global_end(); I != E; ++I) {
704 if (I->hasInitializer())
705 printType(I->getInitializer()->getType());
706 printType(I->getType());
709 // Add all the functions to the table
710 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
712 printType(FI->getReturnType());
713 printType(FI->getFunctionType());
714 // Add all the function arguments
715 for (Function::const_arg_iterator AI = FI->arg_begin(),
716 AE = FI->arg_end(); AI != AE; ++AI) {
717 printType(AI->getType());
720 // Add all of the basic blocks and instructions
721 for (Function::const_iterator BB = FI->begin(),
722 E = FI->end(); BB != E; ++BB) {
723 printType(BB->getType());
724 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
726 printType(I->getType());
727 for (unsigned i = 0; i < I->getNumOperands(); ++i)
728 printType(I->getOperand(i)->getType());
735 // printConstant - Print out a constant pool entry...
736 void CppWriter::printConstant(const Constant *CV) {
737 // First, if the constant is actually a GlobalValue (variable or function)
738 // or its already in the constant list then we've printed it already and we
740 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
743 std::string constName(getCppName(CV));
744 std::string typeName(getCppName(CV->getType()));
746 if (isa<GlobalValue>(CV)) {
747 // Skip variables and functions, we emit them elsewhere
751 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
752 std::string constValue = CI->getValue().toString(10, true);
753 Out << "ConstantInt* " << constName
754 << " = ConstantInt::get(getGlobalContext(), APInt("
755 << cast<IntegerType>(CI->getType())->getBitWidth()
756 << ", StringRef(\"" << constValue << "\"), 10));";
757 } else if (isa<ConstantAggregateZero>(CV)) {
758 Out << "ConstantAggregateZero* " << constName
759 << " = ConstantAggregateZero::get(" << typeName << ");";
760 } else if (isa<ConstantPointerNull>(CV)) {
761 Out << "ConstantPointerNull* " << constName
762 << " = ConstantPointerNull::get(" << typeName << ");";
763 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
764 Out << "ConstantFP* " << constName << " = ";
767 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
768 if (CA->isString() &&
769 CA->getType()->getElementType() ==
770 Type::getInt8Ty(CA->getContext())) {
771 Out << "Constant* " << constName <<
772 " = ConstantArray::get(getGlobalContext(), \"";
773 std::string tmp = CA->getAsString();
774 bool nullTerminate = false;
775 if (tmp[tmp.length()-1] == 0) {
776 tmp.erase(tmp.length()-1);
777 nullTerminate = true;
779 printEscapedString(tmp);
780 // Determine if we want null termination or not.
782 Out << "\", true"; // Indicate that the null terminator should be
785 Out << "\", false";// No null terminator
788 Out << "std::vector<Constant*> " << constName << "_elems;";
790 unsigned N = CA->getNumOperands();
791 for (unsigned i = 0; i < N; ++i) {
792 printConstant(CA->getOperand(i)); // recurse to print operands
793 Out << constName << "_elems.push_back("
794 << getCppName(CA->getOperand(i)) << ");";
797 Out << "Constant* " << constName << " = ConstantArray::get("
798 << typeName << ", " << constName << "_elems);";
800 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
801 Out << "std::vector<Constant*> " << constName << "_fields;";
803 unsigned N = CS->getNumOperands();
804 for (unsigned i = 0; i < N; i++) {
805 printConstant(CS->getOperand(i));
806 Out << constName << "_fields.push_back("
807 << getCppName(CS->getOperand(i)) << ");";
810 Out << "Constant* " << constName << " = ConstantStruct::get("
811 << typeName << ", " << constName << "_fields);";
812 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
813 Out << "std::vector<Constant*> " << constName << "_elems;";
815 unsigned N = CP->getNumOperands();
816 for (unsigned i = 0; i < N; ++i) {
817 printConstant(CP->getOperand(i));
818 Out << constName << "_elems.push_back("
819 << getCppName(CP->getOperand(i)) << ");";
822 Out << "Constant* " << constName << " = ConstantVector::get("
823 << typeName << ", " << constName << "_elems);";
824 } else if (isa<UndefValue>(CV)) {
825 Out << "UndefValue* " << constName << " = UndefValue::get("
827 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
828 if (CE->getOpcode() == Instruction::GetElementPtr) {
829 Out << "std::vector<Constant*> " << constName << "_indices;";
831 printConstant(CE->getOperand(0));
832 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
833 printConstant(CE->getOperand(i));
834 Out << constName << "_indices.push_back("
835 << getCppName(CE->getOperand(i)) << ");";
838 Out << "Constant* " << constName
839 << " = ConstantExpr::getGetElementPtr("
840 << getCppName(CE->getOperand(0)) << ", "
841 << "&" << constName << "_indices[0], "
842 << constName << "_indices.size()"
844 } else if (CE->isCast()) {
845 printConstant(CE->getOperand(0));
846 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
847 switch (CE->getOpcode()) {
848 default: llvm_unreachable("Invalid cast opcode");
849 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
850 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
851 case Instruction::SExt: Out << "Instruction::SExt"; break;
852 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
853 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
854 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
855 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
856 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
857 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
858 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
859 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
860 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
862 Out << ", " << getCppName(CE->getOperand(0)) << ", "
863 << getCppName(CE->getType()) << ");";
865 unsigned N = CE->getNumOperands();
866 for (unsigned i = 0; i < N; ++i ) {
867 printConstant(CE->getOperand(i));
869 Out << "Constant* " << constName << " = ConstantExpr::";
870 switch (CE->getOpcode()) {
871 case Instruction::Add: Out << "getAdd("; break;
872 case Instruction::FAdd: Out << "getFAdd("; break;
873 case Instruction::Sub: Out << "getSub("; break;
874 case Instruction::FSub: Out << "getFSub("; break;
875 case Instruction::Mul: Out << "getMul("; break;
876 case Instruction::FMul: Out << "getFMul("; break;
877 case Instruction::UDiv: Out << "getUDiv("; break;
878 case Instruction::SDiv: Out << "getSDiv("; break;
879 case Instruction::FDiv: Out << "getFDiv("; break;
880 case Instruction::URem: Out << "getURem("; break;
881 case Instruction::SRem: Out << "getSRem("; break;
882 case Instruction::FRem: Out << "getFRem("; break;
883 case Instruction::And: Out << "getAnd("; break;
884 case Instruction::Or: Out << "getOr("; break;
885 case Instruction::Xor: Out << "getXor("; break;
886 case Instruction::ICmp:
887 Out << "getICmp(ICmpInst::ICMP_";
888 switch (CE->getPredicate()) {
889 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
890 case ICmpInst::ICMP_NE: Out << "NE"; break;
891 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
892 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
893 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
894 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
895 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
896 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
897 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
898 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
899 default: error("Invalid ICmp Predicate");
902 case Instruction::FCmp:
903 Out << "getFCmp(FCmpInst::FCMP_";
904 switch (CE->getPredicate()) {
905 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
906 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
907 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
908 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
909 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
910 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
911 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
912 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
913 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
914 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
915 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
916 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
917 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
918 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
919 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
920 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
921 default: error("Invalid FCmp Predicate");
924 case Instruction::Shl: Out << "getShl("; break;
925 case Instruction::LShr: Out << "getLShr("; break;
926 case Instruction::AShr: Out << "getAShr("; break;
927 case Instruction::Select: Out << "getSelect("; break;
928 case Instruction::ExtractElement: Out << "getExtractElement("; break;
929 case Instruction::InsertElement: Out << "getInsertElement("; break;
930 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
932 error("Invalid constant expression");
935 Out << getCppName(CE->getOperand(0));
936 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
937 Out << ", " << getCppName(CE->getOperand(i));
941 error("Bad Constant");
942 Out << "Constant* " << constName << " = 0; ";
947 void CppWriter::printConstants(const Module* M) {
948 // Traverse all the global variables looking for constant initializers
949 for (Module::const_global_iterator I = TheModule->global_begin(),
950 E = TheModule->global_end(); I != E; ++I)
951 if (I->hasInitializer())
952 printConstant(I->getInitializer());
954 // Traverse the LLVM functions looking for constants
955 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
957 // Add all of the basic blocks and instructions
958 for (Function::const_iterator BB = FI->begin(),
959 E = FI->end(); BB != E; ++BB) {
960 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
962 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
963 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
972 void CppWriter::printVariableUses(const GlobalVariable *GV) {
973 nl(Out) << "// Type Definitions";
975 printType(GV->getType());
976 if (GV->hasInitializer()) {
977 Constant* Init = GV->getInitializer();
978 printType(Init->getType());
979 if (Function* F = dyn_cast<Function>(Init)) {
980 nl(Out)<< "/ Function Declarations"; nl(Out);
981 printFunctionHead(F);
982 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
983 nl(Out) << "// Global Variable Declarations"; nl(Out);
984 printVariableHead(gv);
986 nl(Out) << "// Constant Definitions"; nl(Out);
989 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
990 nl(Out) << "// Global Variable Definitions"; nl(Out);
991 printVariableBody(gv);
996 void CppWriter::printVariableHead(const GlobalVariable *GV) {
997 nl(Out) << "GlobalVariable* " << getCppName(GV);
999 Out << " = mod->getGlobalVariable(getGlobalContext(), ";
1000 printEscapedString(GV->getName());
1001 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
1002 nl(Out) << "if (!" << getCppName(GV) << ") {";
1003 in(); nl(Out) << getCppName(GV);
1005 Out << " = new GlobalVariable(/*Module=*/*mod, ";
1006 nl(Out) << "/*Type=*/";
1007 printCppName(GV->getType()->getElementType());
1009 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
1011 nl(Out) << "/*Linkage=*/";
1012 printLinkageType(GV->getLinkage());
1014 nl(Out) << "/*Initializer=*/0, ";
1015 if (GV->hasInitializer()) {
1016 Out << "// has initializer, specified below";
1018 nl(Out) << "/*Name=*/\"";
1019 printEscapedString(GV->getName());
1023 if (GV->hasSection()) {
1025 Out << "->setSection(\"";
1026 printEscapedString(GV->getSection());
1030 if (GV->getAlignment()) {
1032 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1035 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1037 Out << "->setVisibility(";
1038 printVisibilityType(GV->getVisibility());
1043 out(); Out << "}"; nl(Out);
1047 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1048 if (GV->hasInitializer()) {
1050 Out << "->setInitializer(";
1051 Out << getCppName(GV->getInitializer()) << ");";
1056 std::string CppWriter::getOpName(Value* V) {
1057 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1058 return getCppName(V);
1060 // See if its alread in the map of forward references, if so just return the
1061 // name we already set up for it
1062 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1063 if (I != ForwardRefs.end())
1066 // This is a new forward reference. Generate a unique name for it
1067 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1069 // Yes, this is a hack. An Argument is the smallest instantiable value that
1070 // we can make as a placeholder for the real value. We'll replace these
1071 // Argument instances later.
1072 Out << "Argument* " << result << " = new Argument("
1073 << getCppName(V->getType()) << ");";
1075 ForwardRefs[V] = result;
1079 // printInstruction - This member is called for each Instruction in a function.
1080 void CppWriter::printInstruction(const Instruction *I,
1081 const std::string& bbname) {
1082 std::string iName(getCppName(I));
1084 // Before we emit this instruction, we need to take care of generating any
1085 // forward references. So, we get the names of all the operands in advance
1086 std::string* opNames = new std::string[I->getNumOperands()];
1087 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1088 opNames[i] = getOpName(I->getOperand(i));
1091 switch (I->getOpcode()) {
1093 error("Invalid instruction");
1096 case Instruction::Ret: {
1097 const ReturnInst* ret = cast<ReturnInst>(I);
1098 Out << "ReturnInst::Create(getGlobalContext(), "
1099 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1102 case Instruction::Br: {
1103 const BranchInst* br = cast<BranchInst>(I);
1104 Out << "BranchInst::Create(" ;
1105 if (br->getNumOperands() == 3 ) {
1106 Out << opNames[2] << ", "
1107 << opNames[1] << ", "
1108 << opNames[0] << ", ";
1110 } else if (br->getNumOperands() == 1) {
1111 Out << opNames[0] << ", ";
1113 error("Branch with 2 operands?");
1115 Out << bbname << ");";
1118 case Instruction::Switch: {
1119 const SwitchInst* sw = cast<SwitchInst>(I);
1120 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1121 << opNames[0] << ", "
1122 << opNames[1] << ", "
1123 << sw->getNumCases() << ", " << bbname << ");";
1125 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1126 Out << iName << "->addCase("
1127 << opNames[i] << ", "
1128 << opNames[i+1] << ");";
1133 case Instruction::Invoke: {
1134 const InvokeInst* inv = cast<InvokeInst>(I);
1135 Out << "std::vector<Value*> " << iName << "_params;";
1137 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1138 Out << iName << "_params.push_back("
1139 << opNames[i] << ");";
1142 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1143 << opNames[0] << ", "
1144 << opNames[1] << ", "
1145 << opNames[2] << ", "
1146 << iName << "_params.begin(), " << iName << "_params.end(), \"";
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::Unwind: {
1158 Out << "new UnwindInst("
1162 case Instruction::Unreachable: {
1163 Out << "new UnreachableInst("
1164 << "getGlobalContext(), "
1168 case Instruction::Add:
1169 case Instruction::FAdd:
1170 case Instruction::Sub:
1171 case Instruction::FSub:
1172 case Instruction::Mul:
1173 case Instruction::FMul:
1174 case Instruction::UDiv:
1175 case Instruction::SDiv:
1176 case Instruction::FDiv:
1177 case Instruction::URem:
1178 case Instruction::SRem:
1179 case Instruction::FRem:
1180 case Instruction::And:
1181 case Instruction::Or:
1182 case Instruction::Xor:
1183 case Instruction::Shl:
1184 case Instruction::LShr:
1185 case Instruction::AShr:{
1186 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1187 switch (I->getOpcode()) {
1188 case Instruction::Add: Out << "Instruction::Add"; break;
1189 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1190 case Instruction::Sub: Out << "Instruction::Sub"; break;
1191 case Instruction::FSub: Out << "Instruction::FSub"; break;
1192 case Instruction::Mul: Out << "Instruction::Mul"; break;
1193 case Instruction::FMul: Out << "Instruction::FMul"; break;
1194 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1195 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1196 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1197 case Instruction::URem:Out << "Instruction::URem"; break;
1198 case Instruction::SRem:Out << "Instruction::SRem"; break;
1199 case Instruction::FRem:Out << "Instruction::FRem"; break;
1200 case Instruction::And: Out << "Instruction::And"; break;
1201 case Instruction::Or: Out << "Instruction::Or"; break;
1202 case Instruction::Xor: Out << "Instruction::Xor"; break;
1203 case Instruction::Shl: Out << "Instruction::Shl"; break;
1204 case Instruction::LShr:Out << "Instruction::LShr"; break;
1205 case Instruction::AShr:Out << "Instruction::AShr"; break;
1206 default: Out << "Instruction::BadOpCode"; break;
1208 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1209 printEscapedString(I->getName());
1210 Out << "\", " << bbname << ");";
1213 case Instruction::FCmp: {
1214 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1215 switch (cast<FCmpInst>(I)->getPredicate()) {
1216 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1217 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1218 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1219 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1220 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1221 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1222 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1223 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1224 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1225 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1226 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1227 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1228 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1229 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1230 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1231 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1232 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1234 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1235 printEscapedString(I->getName());
1239 case Instruction::ICmp: {
1240 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1241 switch (cast<ICmpInst>(I)->getPredicate()) {
1242 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1243 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1244 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1245 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1246 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1247 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1248 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1249 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1250 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1251 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1252 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1254 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1255 printEscapedString(I->getName());
1259 case Instruction::Malloc: {
1260 const MallocInst* mallocI = cast<MallocInst>(I);
1261 Out << "MallocInst* " << iName << " = new MallocInst("
1262 << getCppName(mallocI->getAllocatedType()) << ", ";
1263 if (mallocI->isArrayAllocation())
1264 Out << opNames[0] << ", " ;
1266 printEscapedString(mallocI->getName());
1267 Out << "\", " << bbname << ");";
1268 if (mallocI->getAlignment())
1269 nl(Out) << iName << "->setAlignment("
1270 << mallocI->getAlignment() << ");";
1273 case Instruction::Free: {
1274 Out << "FreeInst* " << iName << " = new FreeInst("
1275 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1278 case Instruction::Alloca: {
1279 const AllocaInst* allocaI = cast<AllocaInst>(I);
1280 Out << "AllocaInst* " << iName << " = new AllocaInst("
1281 << getCppName(allocaI->getAllocatedType()) << ", ";
1282 if (allocaI->isArrayAllocation())
1283 Out << opNames[0] << ", ";
1285 printEscapedString(allocaI->getName());
1286 Out << "\", " << bbname << ");";
1287 if (allocaI->getAlignment())
1288 nl(Out) << iName << "->setAlignment("
1289 << allocaI->getAlignment() << ");";
1292 case Instruction::Load:{
1293 const LoadInst* load = cast<LoadInst>(I);
1294 Out << "LoadInst* " << iName << " = new LoadInst("
1295 << opNames[0] << ", \"";
1296 printEscapedString(load->getName());
1297 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1298 << ", " << bbname << ");";
1301 case Instruction::Store: {
1302 const StoreInst* store = cast<StoreInst>(I);
1303 Out << " new StoreInst("
1304 << opNames[0] << ", "
1305 << opNames[1] << ", "
1306 << (store->isVolatile() ? "true" : "false")
1307 << ", " << bbname << ");";
1310 case Instruction::GetElementPtr: {
1311 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1312 if (gep->getNumOperands() <= 2) {
1313 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1315 if (gep->getNumOperands() == 2)
1316 Out << ", " << opNames[1];
1318 Out << "std::vector<Value*> " << iName << "_indices;";
1320 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1321 Out << iName << "_indices.push_back("
1322 << opNames[i] << ");";
1325 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1326 << opNames[0] << ", " << iName << "_indices.begin(), "
1327 << iName << "_indices.end()";
1330 printEscapedString(gep->getName());
1331 Out << "\", " << bbname << ");";
1334 case Instruction::PHI: {
1335 const PHINode* phi = cast<PHINode>(I);
1337 Out << "PHINode* " << iName << " = PHINode::Create("
1338 << getCppName(phi->getType()) << ", \"";
1339 printEscapedString(phi->getName());
1340 Out << "\", " << bbname << ");";
1341 nl(Out) << iName << "->reserveOperandSpace("
1342 << phi->getNumIncomingValues()
1345 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1346 Out << iName << "->addIncoming("
1347 << opNames[i] << ", " << opNames[i+1] << ");";
1352 case Instruction::Trunc:
1353 case Instruction::ZExt:
1354 case Instruction::SExt:
1355 case Instruction::FPTrunc:
1356 case Instruction::FPExt:
1357 case Instruction::FPToUI:
1358 case Instruction::FPToSI:
1359 case Instruction::UIToFP:
1360 case Instruction::SIToFP:
1361 case Instruction::PtrToInt:
1362 case Instruction::IntToPtr:
1363 case Instruction::BitCast: {
1364 const CastInst* cst = cast<CastInst>(I);
1365 Out << "CastInst* " << iName << " = new ";
1366 switch (I->getOpcode()) {
1367 case Instruction::Trunc: Out << "TruncInst"; break;
1368 case Instruction::ZExt: Out << "ZExtInst"; break;
1369 case Instruction::SExt: Out << "SExtInst"; break;
1370 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1371 case Instruction::FPExt: Out << "FPExtInst"; break;
1372 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1373 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1374 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1375 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1376 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1377 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1378 case Instruction::BitCast: Out << "BitCastInst"; break;
1379 default: assert(!"Unreachable"); break;
1381 Out << "(" << opNames[0] << ", "
1382 << getCppName(cst->getType()) << ", \"";
1383 printEscapedString(cst->getName());
1384 Out << "\", " << bbname << ");";
1387 case Instruction::Call:{
1388 const CallInst* call = cast<CallInst>(I);
1389 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1390 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1391 << getCppName(ila->getFunctionType()) << ", \""
1392 << ila->getAsmString() << "\", \""
1393 << ila->getConstraintString() << "\","
1394 << (ila->hasSideEffects() ? "true" : "false") << ");";
1397 if (call->getNumOperands() > 2) {
1398 Out << "std::vector<Value*> " << iName << "_params;";
1400 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1401 Out << iName << "_params.push_back(" << opNames[i] << ");";
1404 Out << "CallInst* " << iName << " = CallInst::Create("
1405 << opNames[0] << ", " << iName << "_params.begin(), "
1406 << iName << "_params.end(), \"";
1407 } else if (call->getNumOperands() == 2) {
1408 Out << "CallInst* " << iName << " = CallInst::Create("
1409 << opNames[0] << ", " << opNames[1] << ", \"";
1411 Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
1414 printEscapedString(call->getName());
1415 Out << "\", " << bbname << ");";
1416 nl(Out) << iName << "->setCallingConv(";
1417 printCallingConv(call->getCallingConv());
1419 nl(Out) << iName << "->setTailCall("
1420 << (call->isTailCall() ? "true":"false");
1422 printAttributes(call->getAttributes(), iName);
1423 Out << iName << "->setAttributes(" << iName << "_PAL);";
1427 case Instruction::Select: {
1428 const SelectInst* sel = cast<SelectInst>(I);
1429 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1430 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1431 printEscapedString(sel->getName());
1432 Out << "\", " << bbname << ");";
1435 case Instruction::UserOp1:
1437 case Instruction::UserOp2: {
1438 /// FIXME: What should be done here?
1441 case Instruction::VAArg: {
1442 const VAArgInst* va = cast<VAArgInst>(I);
1443 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1444 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1445 printEscapedString(va->getName());
1446 Out << "\", " << bbname << ");";
1449 case Instruction::ExtractElement: {
1450 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1451 Out << "ExtractElementInst* " << getCppName(eei)
1452 << " = new ExtractElementInst(" << opNames[0]
1453 << ", " << opNames[1] << ", \"";
1454 printEscapedString(eei->getName());
1455 Out << "\", " << bbname << ");";
1458 case Instruction::InsertElement: {
1459 const InsertElementInst* iei = cast<InsertElementInst>(I);
1460 Out << "InsertElementInst* " << getCppName(iei)
1461 << " = InsertElementInst::Create(" << opNames[0]
1462 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1463 printEscapedString(iei->getName());
1464 Out << "\", " << bbname << ");";
1467 case Instruction::ShuffleVector: {
1468 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1469 Out << "ShuffleVectorInst* " << getCppName(svi)
1470 << " = new ShuffleVectorInst(" << opNames[0]
1471 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1472 printEscapedString(svi->getName());
1473 Out << "\", " << bbname << ");";
1476 case Instruction::ExtractValue: {
1477 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1478 Out << "std::vector<unsigned> " << iName << "_indices;";
1480 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1481 Out << iName << "_indices.push_back("
1482 << evi->idx_begin()[i] << ");";
1485 Out << "ExtractValueInst* " << getCppName(evi)
1486 << " = ExtractValueInst::Create(" << opNames[0]
1488 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1489 printEscapedString(evi->getName());
1490 Out << "\", " << bbname << ");";
1493 case Instruction::InsertValue: {
1494 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1495 Out << "std::vector<unsigned> " << iName << "_indices;";
1497 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1498 Out << iName << "_indices.push_back("
1499 << ivi->idx_begin()[i] << ");";
1502 Out << "InsertValueInst* " << getCppName(ivi)
1503 << " = InsertValueInst::Create(" << opNames[0]
1504 << ", " << opNames[1] << ", "
1505 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1506 printEscapedString(ivi->getName());
1507 Out << "\", " << bbname << ");";
1511 DefinedValues.insert(I);
1516 // Print out the types, constants and declarations needed by one function
1517 void CppWriter::printFunctionUses(const Function* F) {
1518 nl(Out) << "// Type Definitions"; nl(Out);
1520 // Print the function's return type
1521 printType(F->getReturnType());
1523 // Print the function's function type
1524 printType(F->getFunctionType());
1526 // Print the types of each of the function's arguments
1527 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1529 printType(AI->getType());
1533 // Print type definitions for every type referenced by an instruction and
1534 // make a note of any global values or constants that are referenced
1535 SmallPtrSet<GlobalValue*,64> gvs;
1536 SmallPtrSet<Constant*,64> consts;
1537 for (Function::const_iterator BB = F->begin(), BE = F->end();
1539 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1541 // Print the type of the instruction itself
1542 printType(I->getType());
1544 // Print the type of each of the instruction's operands
1545 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1546 Value* operand = I->getOperand(i);
1547 printType(operand->getType());
1549 // If the operand references a GVal or Constant, make a note of it
1550 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1552 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1553 if (GVar->hasInitializer())
1554 consts.insert(GVar->getInitializer());
1555 } else if (Constant* C = dyn_cast<Constant>(operand))
1561 // Print the function declarations for any functions encountered
1562 nl(Out) << "// Function Declarations"; nl(Out);
1563 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1565 if (Function* Fun = dyn_cast<Function>(*I)) {
1566 if (!is_inline || Fun != F)
1567 printFunctionHead(Fun);
1571 // Print the global variable declarations for any variables encountered
1572 nl(Out) << "// Global Variable Declarations"; nl(Out);
1573 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1575 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1576 printVariableHead(F);
1579 // Print the constants found
1580 nl(Out) << "// Constant Definitions"; nl(Out);
1581 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1582 E = consts.end(); I != E; ++I) {
1586 // Process the global variables definitions now that all the constants have
1587 // been emitted. These definitions just couple the gvars with their constant
1589 nl(Out) << "// Global Variable Definitions"; nl(Out);
1590 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1592 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1593 printVariableBody(GV);
1597 void CppWriter::printFunctionHead(const Function* F) {
1598 nl(Out) << "Function* " << getCppName(F);
1600 Out << " = mod->getFunction(\"";
1601 printEscapedString(F->getName());
1602 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1603 nl(Out) << "if (!" << getCppName(F) << ") {";
1604 nl(Out) << getCppName(F);
1606 Out<< " = Function::Create(";
1607 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1608 nl(Out) << "/*Linkage=*/";
1609 printLinkageType(F->getLinkage());
1611 nl(Out) << "/*Name=*/\"";
1612 printEscapedString(F->getName());
1613 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1616 Out << "->setCallingConv(";
1617 printCallingConv(F->getCallingConv());
1620 if (F->hasSection()) {
1622 Out << "->setSection(\"" << F->getSection() << "\");";
1625 if (F->getAlignment()) {
1627 Out << "->setAlignment(" << F->getAlignment() << ");";
1630 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1632 Out << "->setVisibility(";
1633 printVisibilityType(F->getVisibility());
1639 Out << "->setGC(\"" << F->getGC() << "\");";
1646 printAttributes(F->getAttributes(), getCppName(F));
1648 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1652 void CppWriter::printFunctionBody(const Function *F) {
1653 if (F->isDeclaration())
1654 return; // external functions have no bodies.
1656 // Clear the DefinedValues and ForwardRefs maps because we can't have
1657 // cross-function forward refs
1658 ForwardRefs.clear();
1659 DefinedValues.clear();
1661 // Create all the argument values
1663 if (!F->arg_empty()) {
1664 Out << "Function::arg_iterator args = " << getCppName(F)
1665 << "->arg_begin();";
1668 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1670 Out << "Value* " << getCppName(AI) << " = args++;";
1672 if (AI->hasName()) {
1673 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1679 // Create all the basic blocks
1681 for (Function::const_iterator BI = F->begin(), BE = F->end();
1683 std::string bbname(getCppName(BI));
1684 Out << "BasicBlock* " << bbname <<
1685 " = BasicBlock::Create(getGlobalContext(), \"";
1687 printEscapedString(BI->getName());
1688 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1692 // Output all of its basic blocks... for the function
1693 for (Function::const_iterator BI = F->begin(), BE = F->end();
1695 std::string bbname(getCppName(BI));
1696 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1699 // Output all of the instructions in the basic block...
1700 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1702 printInstruction(I,bbname);
1706 // Loop over the ForwardRefs and resolve them now that all instructions
1708 if (!ForwardRefs.empty()) {
1709 nl(Out) << "// Resolve Forward References";
1713 while (!ForwardRefs.empty()) {
1714 ForwardRefMap::iterator I = ForwardRefs.begin();
1715 Out << I->second << "->replaceAllUsesWith("
1716 << getCppName(I->first) << "); delete " << I->second << ";";
1718 ForwardRefs.erase(I);
1722 void CppWriter::printInline(const std::string& fname,
1723 const std::string& func) {
1724 const Function* F = TheModule->getFunction(func);
1726 error(std::string("Function '") + func + "' not found in input module");
1729 if (F->isDeclaration()) {
1730 error(std::string("Function '") + func + "' is external!");
1733 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1735 unsigned arg_count = 1;
1736 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1738 Out << ", Value* arg_" << arg_count;
1743 printFunctionUses(F);
1744 printFunctionBody(F);
1746 Out << "return " << getCppName(F->begin()) << ";";
1751 void CppWriter::printModuleBody() {
1752 // Print out all the type definitions
1753 nl(Out) << "// Type Definitions"; nl(Out);
1754 printTypes(TheModule);
1756 // Functions can call each other and global variables can reference them so
1757 // define all the functions first before emitting their function bodies.
1758 nl(Out) << "// Function Declarations"; nl(Out);
1759 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1761 printFunctionHead(I);
1763 // Process the global variables declarations. We can't initialze them until
1764 // after the constants are printed so just print a header for each global
1765 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1766 for (Module::const_global_iterator I = TheModule->global_begin(),
1767 E = TheModule->global_end(); I != E; ++I) {
1768 printVariableHead(I);
1771 // Print out all the constants definitions. Constants don't recurse except
1772 // through GlobalValues. All GlobalValues have been declared at this point
1773 // so we can proceed to generate the constants.
1774 nl(Out) << "// Constant Definitions"; nl(Out);
1775 printConstants(TheModule);
1777 // Process the global variables definitions now that all the constants have
1778 // been emitted. These definitions just couple the gvars with their constant
1780 nl(Out) << "// Global Variable Definitions"; nl(Out);
1781 for (Module::const_global_iterator I = TheModule->global_begin(),
1782 E = TheModule->global_end(); I != E; ++I) {
1783 printVariableBody(I);
1786 // Finally, we can safely put out all of the function bodies.
1787 nl(Out) << "// Function Definitions"; nl(Out);
1788 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1790 if (!I->isDeclaration()) {
1791 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1795 printFunctionBody(I);
1802 void CppWriter::printProgram(const std::string& fname,
1803 const std::string& mName) {
1804 Out << "#include <llvm/LLVMContext.h>\n";
1805 Out << "#include <llvm/Module.h>\n";
1806 Out << "#include <llvm/DerivedTypes.h>\n";
1807 Out << "#include <llvm/Constants.h>\n";
1808 Out << "#include <llvm/GlobalVariable.h>\n";
1809 Out << "#include <llvm/Function.h>\n";
1810 Out << "#include <llvm/CallingConv.h>\n";
1811 Out << "#include <llvm/BasicBlock.h>\n";
1812 Out << "#include <llvm/Instructions.h>\n";
1813 Out << "#include <llvm/InlineAsm.h>\n";
1814 Out << "#include <llvm/Support/FormattedStream.h>\n";
1815 Out << "#include <llvm/Support/MathExtras.h>\n";
1816 Out << "#include <llvm/Pass.h>\n";
1817 Out << "#include <llvm/PassManager.h>\n";
1818 Out << "#include <llvm/ADT/SmallVector.h>\n";
1819 Out << "#include <llvm/Analysis/Verifier.h>\n";
1820 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1821 Out << "#include <algorithm>\n";
1822 Out << "using namespace llvm;\n\n";
1823 Out << "Module* " << fname << "();\n\n";
1824 Out << "int main(int argc, char**argv) {\n";
1825 Out << " Module* Mod = " << fname << "();\n";
1826 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1827 Out << " PassManager PM;\n";
1828 Out << " PM.add(createPrintModulePass(&outs()));\n";
1829 Out << " PM.run(*Mod);\n";
1830 Out << " return 0;\n";
1832 printModule(fname,mName);
1835 void CppWriter::printModule(const std::string& fname,
1836 const std::string& mName) {
1837 nl(Out) << "Module* " << fname << "() {";
1838 nl(Out,1) << "// Module Construction";
1839 nl(Out) << "Module* mod = new Module(\"";
1840 printEscapedString(mName);
1841 Out << "\", getGlobalContext());";
1842 if (!TheModule->getTargetTriple().empty()) {
1843 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1845 if (!TheModule->getTargetTriple().empty()) {
1846 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1850 if (!TheModule->getModuleInlineAsm().empty()) {
1851 nl(Out) << "mod->setModuleInlineAsm(\"";
1852 printEscapedString(TheModule->getModuleInlineAsm());
1857 // Loop over the dependent libraries and emit them.
1858 Module::lib_iterator LI = TheModule->lib_begin();
1859 Module::lib_iterator LE = TheModule->lib_end();
1861 Out << "mod->addLibrary(\"" << *LI << "\");";
1866 nl(Out) << "return mod;";
1871 void CppWriter::printContents(const std::string& fname,
1872 const std::string& mName) {
1873 Out << "\nModule* " << fname << "(Module *mod) {\n";
1874 Out << "\nmod->setModuleIdentifier(\"";
1875 printEscapedString(mName);
1878 Out << "\nreturn mod;\n";
1882 void CppWriter::printFunction(const std::string& fname,
1883 const std::string& funcName) {
1884 const Function* F = TheModule->getFunction(funcName);
1886 error(std::string("Function '") + funcName + "' not found in input module");
1889 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1890 printFunctionUses(F);
1891 printFunctionHead(F);
1892 printFunctionBody(F);
1893 Out << "return " << getCppName(F) << ";\n";
1897 void CppWriter::printFunctions() {
1898 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1899 Module::const_iterator I = funcs.begin();
1900 Module::const_iterator IE = funcs.end();
1902 for (; I != IE; ++I) {
1903 const Function &func = *I;
1904 if (!func.isDeclaration()) {
1905 std::string name("define_");
1906 name += func.getName();
1907 printFunction(name, func.getName());
1912 void CppWriter::printVariable(const std::string& fname,
1913 const std::string& varName) {
1914 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1917 error(std::string("Variable '") + varName + "' not found in input module");
1920 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1921 printVariableUses(GV);
1922 printVariableHead(GV);
1923 printVariableBody(GV);
1924 Out << "return " << getCppName(GV) << ";\n";
1928 void CppWriter::printType(const std::string& fname,
1929 const std::string& typeName) {
1930 const Type* Ty = TheModule->getTypeByName(typeName);
1932 error(std::string("Type '") + typeName + "' not found in input module");
1935 Out << "\nType* " << fname << "(Module *mod) {\n";
1937 Out << "return " << getCppName(Ty) << ";\n";
1941 bool CppWriter::runOnModule(Module &M) {
1945 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1947 // Get the name of the function we're supposed to generate
1948 std::string fname = FuncName.getValue();
1950 // Get the name of the thing we are to generate
1951 std::string tgtname = NameToGenerate.getValue();
1952 if (GenerationType == GenModule ||
1953 GenerationType == GenContents ||
1954 GenerationType == GenProgram ||
1955 GenerationType == GenFunctions) {
1956 if (tgtname == "!bad!") {
1957 if (M.getModuleIdentifier() == "-")
1958 tgtname = "<stdin>";
1960 tgtname = M.getModuleIdentifier();
1962 } else if (tgtname == "!bad!")
1963 error("You must use the -for option with -gen-{function,variable,type}");
1965 switch (WhatToGenerate(GenerationType)) {
1968 fname = "makeLLVMModule";
1969 printProgram(fname,tgtname);
1973 fname = "makeLLVMModule";
1974 printModule(fname,tgtname);
1978 fname = "makeLLVMModuleContents";
1979 printContents(fname,tgtname);
1983 fname = "makeLLVMFunction";
1984 printFunction(fname,tgtname);
1991 fname = "makeLLVMInline";
1992 printInline(fname,tgtname);
1996 fname = "makeLLVMVariable";
1997 printVariable(fname,tgtname);
2001 fname = "makeLLVMType";
2002 printType(fname,tgtname);
2005 error("Invalid generation option");
2012 char CppWriter::ID = 0;
2014 //===----------------------------------------------------------------------===//
2015 // External Interface declaration
2016 //===----------------------------------------------------------------------===//
2018 bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
2019 formatted_raw_ostream &o,
2020 CodeGenFileType FileType,
2021 CodeGenOpt::Level OptLevel) {
2022 if (FileType != TargetMachine::AssemblyFile) return true;
2023 PM.add(new CppWriter(o));