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/ADT/StringExtras.h"
32 #include "llvm/Config/config.h"
38 static cl::opt<std::string>
39 FuncName("cppfname", cl::desc("Specify the name of the generated function"),
40 cl::value_desc("function name"));
53 static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
54 cl::desc("Choose what kind of output to generate"),
57 clEnumValN(GenProgram, "program", "Generate a complete program"),
58 clEnumValN(GenModule, "module", "Generate a module definition"),
59 clEnumValN(GenContents, "contents", "Generate contents of a module"),
60 clEnumValN(GenFunction, "function", "Generate a function definition"),
61 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
62 clEnumValN(GenInline, "inline", "Generate an inline function"),
63 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
64 clEnumValN(GenType, "type", "Generate a type definition"),
69 static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
70 cl::desc("Specify the name of the thing to generate"),
73 extern "C" void LLVMInitializeCppBackendTarget() {
74 // Register the target.
75 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
79 typedef std::vector<const Type*> TypeList;
80 typedef std::map<const Type*,std::string> TypeMap;
81 typedef std::map<const Value*,std::string> ValueMap;
82 typedef std::set<std::string> NameSet;
83 typedef std::set<const Type*> TypeSet;
84 typedef std::set<const Value*> ValueSet;
85 typedef std::map<const Value*,std::string> ForwardRefMap;
87 /// CppWriter - This class is the main chunk of code that converts an LLVM
88 /// module to a C++ translation unit.
89 class CppWriter : public ModulePass {
90 formatted_raw_ostream &Out;
91 const Module *TheModule;
95 TypeMap UnresolvedTypes;
99 ValueSet DefinedValues;
100 ForwardRefMap ForwardRefs;
105 explicit CppWriter(formatted_raw_ostream &o) :
106 ModulePass(&ID), Out(o), uniqueNum(0), is_inline(false) {}
108 virtual const char *getPassName() const { return "C++ backend"; }
110 bool runOnModule(Module &M);
112 void printProgram(const std::string& fname, const std::string& modName );
113 void printModule(const std::string& fname, const std::string& modName );
114 void printContents(const std::string& fname, const std::string& modName );
115 void printFunction(const std::string& fname, const std::string& funcName );
116 void printFunctions();
117 void printInline(const std::string& fname, const std::string& funcName );
118 void printVariable(const std::string& fname, const std::string& varName );
119 void printType(const std::string& fname, const std::string& typeName );
121 void error(const std::string& msg);
124 void printLinkageType(GlobalValue::LinkageTypes LT);
125 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
126 void printCallingConv(CallingConv::ID cc);
127 void printEscapedString(const std::string& str);
128 void printCFP(const ConstantFP* CFP);
130 std::string getCppName(const Type* val);
131 inline void printCppName(const Type* val);
133 std::string getCppName(const Value* val);
134 inline void printCppName(const Value* val);
136 void printAttributes(const AttrListPtr &PAL, const std::string &name);
137 bool printTypeInternal(const Type* Ty);
138 inline void printType(const Type* Ty);
139 void printTypes(const Module* M);
141 void printConstant(const Constant *CPV);
142 void printConstants(const Module* M);
144 void printVariableUses(const GlobalVariable *GV);
145 void printVariableHead(const GlobalVariable *GV);
146 void printVariableBody(const GlobalVariable *GV);
148 void printFunctionUses(const Function *F);
149 void printFunctionHead(const Function *F);
150 void printFunctionBody(const Function *F);
151 void printInstruction(const Instruction *I, const std::string& bbname);
152 std::string getOpName(Value*);
154 void printModuleBody();
157 static unsigned indent_level = 0;
158 inline formatted_raw_ostream& nl(formatted_raw_ostream& Out, int delta = 0) {
160 if (delta >= 0 || indent_level >= unsigned(-delta))
161 indent_level += delta;
162 for (unsigned i = 0; i < indent_level; ++i)
167 inline void in() { indent_level++; }
168 inline void out() { if (indent_level >0) indent_level--; }
171 sanitize(std::string& str) {
172 for (size_t i = 0; i < str.length(); ++i)
173 if (!isalnum(str[i]) && str[i] != '_')
178 getTypePrefix(const Type* Ty ) {
179 switch (Ty->getTypeID()) {
180 case Type::VoidTyID: return "void_";
181 case Type::IntegerTyID:
182 return std::string("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 case Type::OpaqueTyID: return "opaque_";
193 default: return "other_";
198 // Looks up the type in the symbol table and returns a pointer to its name or
199 // a null pointer if it wasn't found. Note that this isn't the same as the
200 // Mode::getTypeName function which will return an empty string, not a null
201 // pointer if the name is not found.
202 inline const std::string*
203 findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
204 TypeSymbolTable::const_iterator TI = ST.begin();
205 TypeSymbolTable::const_iterator TE = ST.end();
206 for (;TI != TE; ++TI)
207 if (TI->second == Ty)
212 void CppWriter::error(const std::string& msg) {
213 llvm_report_error(msg);
216 // printCFP - Print a floating point constant .. very carefully :)
217 // This makes sure that conversion to/from floating yields the same binary
218 // result so that we don't lose precision.
219 void CppWriter::printCFP(const ConstantFP *CFP) {
221 APFloat APF = APFloat(CFP->getValueAPF()); // copy
222 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
223 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
224 Out << "ConstantFP::get(getGlobalContext(), ";
228 sprintf(Buffer, "%A", APF.convertToDouble());
229 if ((!strncmp(Buffer, "0x", 2) ||
230 !strncmp(Buffer, "-0x", 3) ||
231 !strncmp(Buffer, "+0x", 3)) &&
232 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
233 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
234 Out << "BitsToDouble(" << Buffer << ")";
236 Out << "BitsToFloat((float)" << Buffer << ")";
240 std::string StrVal = ftostr(CFP->getValueAPF());
242 while (StrVal[0] == ' ')
243 StrVal.erase(StrVal.begin());
245 // Check to make sure that the stringized number is not some string like
246 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
247 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
248 ((StrVal[0] == '-' || StrVal[0] == '+') &&
249 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
250 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
251 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
254 Out << StrVal << "f";
255 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
256 Out << "BitsToDouble(0x"
257 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
258 << "ULL) /* " << StrVal << " */";
260 Out << "BitsToFloat(0x"
261 << utohexstr((uint32_t)CFP->getValueAPF().
262 bitcastToAPInt().getZExtValue())
263 << "U) /* " << StrVal << " */";
271 void CppWriter::printCallingConv(CallingConv::ID cc){
272 // Print the calling convention.
274 case CallingConv::C: Out << "CallingConv::C"; break;
275 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
276 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
277 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
278 default: Out << cc; break;
282 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
284 case GlobalValue::InternalLinkage:
285 Out << "GlobalValue::InternalLinkage"; break;
286 case GlobalValue::PrivateLinkage:
287 Out << "GlobalValue::PrivateLinkage"; break;
288 case GlobalValue::LinkerPrivateLinkage:
289 Out << "GlobalValue::LinkerPrivateLinkage"; break;
290 case GlobalValue::AvailableExternallyLinkage:
291 Out << "GlobalValue::AvailableExternallyLinkage "; break;
292 case GlobalValue::LinkOnceAnyLinkage:
293 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
294 case GlobalValue::LinkOnceODRLinkage:
295 Out << "GlobalValue::LinkOnceODRLinkage "; break;
296 case GlobalValue::WeakAnyLinkage:
297 Out << "GlobalValue::WeakAnyLinkage"; break;
298 case GlobalValue::WeakODRLinkage:
299 Out << "GlobalValue::WeakODRLinkage"; break;
300 case GlobalValue::AppendingLinkage:
301 Out << "GlobalValue::AppendingLinkage"; break;
302 case GlobalValue::ExternalLinkage:
303 Out << "GlobalValue::ExternalLinkage"; break;
304 case GlobalValue::DLLImportLinkage:
305 Out << "GlobalValue::DLLImportLinkage"; break;
306 case GlobalValue::DLLExportLinkage:
307 Out << "GlobalValue::DLLExportLinkage"; break;
308 case GlobalValue::ExternalWeakLinkage:
309 Out << "GlobalValue::ExternalWeakLinkage"; break;
310 case GlobalValue::GhostLinkage:
311 Out << "GlobalValue::GhostLinkage"; break;
312 case GlobalValue::CommonLinkage:
313 Out << "GlobalValue::CommonLinkage"; break;
317 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
319 default: llvm_unreachable("Unknown GVar visibility");
320 case GlobalValue::DefaultVisibility:
321 Out << "GlobalValue::DefaultVisibility";
323 case GlobalValue::HiddenVisibility:
324 Out << "GlobalValue::HiddenVisibility";
326 case GlobalValue::ProtectedVisibility:
327 Out << "GlobalValue::ProtectedVisibility";
332 // printEscapedString - Print each character of the specified string, escaping
333 // it if it is not printable or if it is an escape char.
334 void CppWriter::printEscapedString(const std::string &Str) {
335 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
336 unsigned char C = Str[i];
337 if (isprint(C) && C != '"' && C != '\\') {
341 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
342 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
347 std::string CppWriter::getCppName(const Type* Ty) {
348 // First, handle the primitive types .. easy
349 if (Ty->isPrimitiveType() || Ty->isInteger()) {
350 switch (Ty->getTypeID()) {
351 case Type::VoidTyID: return "Type::getVoidTy(getGlobalContext())";
352 case Type::IntegerTyID: {
353 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
354 return "IntegerType::get(getGlobalContext(), " + utostr(BitWidth) + ")";
356 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(getGlobalContext())";
357 case Type::FloatTyID: return "Type::getFloatTy(getGlobalContext())";
358 case Type::DoubleTyID: return "Type::getDoubleTy(getGlobalContext())";
359 case Type::LabelTyID: return "Type::getLabelTy(getGlobalContext())";
361 error("Invalid primitive type");
364 // shouldn't be returned, but make it sensible
365 return "Type::getVoidTy(getGlobalContext())";
368 // Now, see if we've seen the type before and return that
369 TypeMap::iterator I = TypeNames.find(Ty);
370 if (I != TypeNames.end())
373 // Okay, let's build a new name for this type. Start with a prefix
374 const char* prefix = 0;
375 switch (Ty->getTypeID()) {
376 case Type::FunctionTyID: prefix = "FuncTy_"; break;
377 case Type::StructTyID: prefix = "StructTy_"; break;
378 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
379 case Type::PointerTyID: prefix = "PointerTy_"; break;
380 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
381 case Type::VectorTyID: prefix = "VectorTy_"; break;
382 default: prefix = "OtherTy_"; break; // prevent breakage
385 // See if the type has a name in the symboltable and build accordingly
386 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
389 name = std::string(prefix) + *tName;
391 name = std::string(prefix) + utostr(uniqueNum++);
395 return TypeNames[Ty] = name;
398 void CppWriter::printCppName(const Type* Ty) {
399 printEscapedString(getCppName(Ty));
402 std::string CppWriter::getCppName(const Value* val) {
404 ValueMap::iterator I = ValueNames.find(val);
405 if (I != ValueNames.end() && I->first == val)
408 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
409 name = std::string("gvar_") +
410 getTypePrefix(GV->getType()->getElementType());
411 } else if (isa<Function>(val)) {
412 name = std::string("func_");
413 } else if (const Constant* C = dyn_cast<Constant>(val)) {
414 name = std::string("const_") + getTypePrefix(C->getType());
415 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
417 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
418 Function::const_arg_iterator(Arg)) + 1;
419 name = std::string("arg_") + utostr(argNum);
420 NameSet::iterator NI = UsedNames.find(name);
421 if (NI != UsedNames.end())
422 name += std::string("_") + utostr(uniqueNum++);
423 UsedNames.insert(name);
424 return ValueNames[val] = name;
426 name = getTypePrefix(val->getType());
429 name = getTypePrefix(val->getType());
432 name += val->getName();
434 name += utostr(uniqueNum++);
436 NameSet::iterator NI = UsedNames.find(name);
437 if (NI != UsedNames.end())
438 name += std::string("_") + utostr(uniqueNum++);
439 UsedNames.insert(name);
440 return ValueNames[val] = name;
443 void CppWriter::printCppName(const Value* val) {
444 printEscapedString(getCppName(val));
447 void CppWriter::printAttributes(const AttrListPtr &PAL,
448 const std::string &name) {
449 Out << "AttrListPtr " << name << "_PAL;";
451 if (!PAL.isEmpty()) {
452 Out << '{'; in(); nl(Out);
453 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
454 Out << "AttributeWithIndex PAWI;"; nl(Out);
455 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
456 unsigned index = PAL.getSlot(i).Index;
457 Attributes attrs = PAL.getSlot(i).Attrs;
458 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
459 #define HANDLE_ATTR(X) \
460 if (attrs & Attribute::X) \
461 Out << " | Attribute::" #X; \
462 attrs &= ~Attribute::X;
466 HANDLE_ATTR(NoReturn);
468 HANDLE_ATTR(StructRet);
469 HANDLE_ATTR(NoUnwind);
470 HANDLE_ATTR(NoAlias);
473 HANDLE_ATTR(ReadNone);
474 HANDLE_ATTR(ReadOnly);
475 HANDLE_ATTR(InlineHint);
476 HANDLE_ATTR(NoInline);
477 HANDLE_ATTR(AlwaysInline);
478 HANDLE_ATTR(OptimizeForSize);
479 HANDLE_ATTR(StackProtect);
480 HANDLE_ATTR(StackProtectReq);
481 HANDLE_ATTR(NoCapture);
483 assert(attrs == 0 && "Unhandled attribute!");
486 Out << "Attrs.push_back(PAWI);";
489 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
496 bool CppWriter::printTypeInternal(const Type* Ty) {
497 // We don't print definitions for primitive types
498 if (Ty->isPrimitiveType() || Ty->isInteger())
501 // If we already defined this type, we don't need to define it again.
502 if (DefinedTypes.find(Ty) != DefinedTypes.end())
505 // Everything below needs the name for the type so get it now.
506 std::string typeName(getCppName(Ty));
508 // Search the type stack for recursion. If we find it, then generate this
509 // as an OpaqueType, but make sure not to do this multiple times because
510 // the type could appear in multiple places on the stack. Once the opaque
511 // definition is issued, it must not be re-issued. Consequently we have to
512 // check the UnresolvedTypes list as well.
513 TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
515 if (TI != TypeStack.end()) {
516 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
517 if (I == UnresolvedTypes.end()) {
518 Out << "PATypeHolder " << typeName;
519 Out << "_fwd = OpaqueType::get(getGlobalContext());";
521 UnresolvedTypes[Ty] = typeName;
526 // We're going to print a derived type which, by definition, contains other
527 // types. So, push this one we're printing onto the type stack to assist with
528 // recursive definitions.
529 TypeStack.push_back(Ty);
531 // Print the type definition
532 switch (Ty->getTypeID()) {
533 case Type::FunctionTyID: {
534 const FunctionType* FT = cast<FunctionType>(Ty);
535 Out << "std::vector<const Type*>" << typeName << "_args;";
537 FunctionType::param_iterator PI = FT->param_begin();
538 FunctionType::param_iterator PE = FT->param_end();
539 for (; PI != PE; ++PI) {
540 const Type* argTy = static_cast<const Type*>(*PI);
541 bool isForward = printTypeInternal(argTy);
542 std::string argName(getCppName(argTy));
543 Out << typeName << "_args.push_back(" << argName;
549 bool isForward = printTypeInternal(FT->getReturnType());
550 std::string retTypeName(getCppName(FT->getReturnType()));
551 Out << "FunctionType* " << typeName << " = FunctionType::get(";
552 in(); nl(Out) << "/*Result=*/" << retTypeName;
556 nl(Out) << "/*Params=*/" << typeName << "_args,";
557 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
562 case Type::StructTyID: {
563 const StructType* ST = cast<StructType>(Ty);
564 Out << "std::vector<const Type*>" << typeName << "_fields;";
566 StructType::element_iterator EI = ST->element_begin();
567 StructType::element_iterator EE = ST->element_end();
568 for (; EI != EE; ++EI) {
569 const Type* fieldTy = static_cast<const Type*>(*EI);
570 bool isForward = printTypeInternal(fieldTy);
571 std::string fieldName(getCppName(fieldTy));
572 Out << typeName << "_fields.push_back(" << fieldName;
578 Out << "StructType* " << typeName << " = StructType::get("
579 << "mod->getContext(), "
580 << typeName << "_fields, /*isPacked=*/"
581 << (ST->isPacked() ? "true" : "false") << ");";
585 case Type::ArrayTyID: {
586 const ArrayType* AT = cast<ArrayType>(Ty);
587 const Type* ET = AT->getElementType();
588 bool isForward = printTypeInternal(ET);
589 std::string elemName(getCppName(ET));
590 Out << "ArrayType* " << typeName << " = ArrayType::get("
591 << elemName << (isForward ? "_fwd" : "")
592 << ", " << utostr(AT->getNumElements()) << ");";
596 case Type::PointerTyID: {
597 const PointerType* PT = cast<PointerType>(Ty);
598 const Type* ET = PT->getElementType();
599 bool isForward = printTypeInternal(ET);
600 std::string elemName(getCppName(ET));
601 Out << "PointerType* " << typeName << " = PointerType::get("
602 << elemName << (isForward ? "_fwd" : "")
603 << ", " << utostr(PT->getAddressSpace()) << ");";
607 case Type::VectorTyID: {
608 const VectorType* PT = cast<VectorType>(Ty);
609 const Type* ET = PT->getElementType();
610 bool isForward = printTypeInternal(ET);
611 std::string elemName(getCppName(ET));
612 Out << "VectorType* " << typeName << " = VectorType::get("
613 << elemName << (isForward ? "_fwd" : "")
614 << ", " << utostr(PT->getNumElements()) << ");";
618 case Type::OpaqueTyID: {
619 Out << "OpaqueType* " << typeName;
620 Out << " = OpaqueType::get(getGlobalContext());";
625 error("Invalid TypeID");
628 // If the type had a name, make sure we recreate it.
629 const std::string* progTypeName =
630 findTypeName(TheModule->getTypeSymbolTable(),Ty);
632 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
637 // Pop us off the type stack
638 TypeStack.pop_back();
640 // Indicate that this type is now defined.
641 DefinedTypes.insert(Ty);
643 // Early resolve as many unresolved types as possible. Search the unresolved
644 // types map for the type we just printed. Now that its definition is complete
645 // we can resolve any previous references to it. This prevents a cascade of
647 TypeMap::iterator I = UnresolvedTypes.find(Ty);
648 if (I != UnresolvedTypes.end()) {
649 Out << "cast<OpaqueType>(" << I->second
650 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
652 Out << I->second << " = cast<";
653 switch (Ty->getTypeID()) {
654 case Type::FunctionTyID: Out << "FunctionType"; break;
655 case Type::ArrayTyID: Out << "ArrayType"; break;
656 case Type::StructTyID: Out << "StructType"; break;
657 case Type::VectorTyID: Out << "VectorType"; break;
658 case Type::PointerTyID: Out << "PointerType"; break;
659 case Type::OpaqueTyID: Out << "OpaqueType"; break;
660 default: Out << "NoSuchDerivedType"; break;
662 Out << ">(" << I->second << "_fwd.get());";
664 UnresolvedTypes.erase(I);
667 // Finally, separate the type definition from other with a newline.
670 // We weren't a recursive type
674 // Prints a type definition. Returns true if it could not resolve all the
675 // types in the definition but had to use a forward reference.
676 void CppWriter::printType(const Type* Ty) {
677 assert(TypeStack.empty());
679 printTypeInternal(Ty);
680 assert(TypeStack.empty());
683 void CppWriter::printTypes(const Module* M) {
684 // Walk the symbol table and print out all its types
685 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
686 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
689 // For primitive types and types already defined, just add a name
690 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
691 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
692 TNI != TypeNames.end()) {
693 Out << "mod->addTypeName(\"";
694 printEscapedString(TI->first);
695 Out << "\", " << getCppName(TI->second) << ");";
697 // For everything else, define the type
699 printType(TI->second);
703 // Add all of the global variables to the value table...
704 for (Module::const_global_iterator I = TheModule->global_begin(),
705 E = TheModule->global_end(); I != E; ++I) {
706 if (I->hasInitializer())
707 printType(I->getInitializer()->getType());
708 printType(I->getType());
711 // Add all the functions to the table
712 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
714 printType(FI->getReturnType());
715 printType(FI->getFunctionType());
716 // Add all the function arguments
717 for (Function::const_arg_iterator AI = FI->arg_begin(),
718 AE = FI->arg_end(); AI != AE; ++AI) {
719 printType(AI->getType());
722 // Add all of the basic blocks and instructions
723 for (Function::const_iterator BB = FI->begin(),
724 E = FI->end(); BB != E; ++BB) {
725 printType(BB->getType());
726 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
728 printType(I->getType());
729 for (unsigned i = 0; i < I->getNumOperands(); ++i)
730 printType(I->getOperand(i)->getType());
737 // printConstant - Print out a constant pool entry...
738 void CppWriter::printConstant(const Constant *CV) {
739 // First, if the constant is actually a GlobalValue (variable or function)
740 // or its already in the constant list then we've printed it already and we
742 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
745 std::string constName(getCppName(CV));
746 std::string typeName(getCppName(CV->getType()));
748 if (isa<GlobalValue>(CV)) {
749 // Skip variables and functions, we emit them elsewhere
753 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
754 std::string constValue = CI->getValue().toString(10, true);
755 Out << "ConstantInt* " << constName
756 << " = ConstantInt::get(getGlobalContext(), APInt("
757 << cast<IntegerType>(CI->getType())->getBitWidth()
758 << ", StringRef(\"" << constValue << "\"), 10));";
759 } else if (isa<ConstantAggregateZero>(CV)) {
760 Out << "ConstantAggregateZero* " << constName
761 << " = ConstantAggregateZero::get(" << typeName << ");";
762 } else if (isa<ConstantPointerNull>(CV)) {
763 Out << "ConstantPointerNull* " << constName
764 << " = ConstantPointerNull::get(" << typeName << ");";
765 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
766 Out << "ConstantFP* " << constName << " = ";
769 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
770 if (CA->isString() &&
771 CA->getType()->getElementType() ==
772 Type::getInt8Ty(CA->getContext())) {
773 Out << "Constant* " << constName <<
774 " = ConstantArray::get(getGlobalContext(), \"";
775 std::string tmp = CA->getAsString();
776 bool nullTerminate = false;
777 if (tmp[tmp.length()-1] == 0) {
778 tmp.erase(tmp.length()-1);
779 nullTerminate = true;
781 printEscapedString(tmp);
782 // Determine if we want null termination or not.
784 Out << "\", true"; // Indicate that the null terminator should be
787 Out << "\", false";// No null terminator
790 Out << "std::vector<Constant*> " << constName << "_elems;";
792 unsigned N = CA->getNumOperands();
793 for (unsigned i = 0; i < N; ++i) {
794 printConstant(CA->getOperand(i)); // recurse to print operands
795 Out << constName << "_elems.push_back("
796 << getCppName(CA->getOperand(i)) << ");";
799 Out << "Constant* " << constName << " = ConstantArray::get("
800 << typeName << ", " << constName << "_elems);";
802 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
803 Out << "std::vector<Constant*> " << constName << "_fields;";
805 unsigned N = CS->getNumOperands();
806 for (unsigned i = 0; i < N; i++) {
807 printConstant(CS->getOperand(i));
808 Out << constName << "_fields.push_back("
809 << getCppName(CS->getOperand(i)) << ");";
812 Out << "Constant* " << constName << " = ConstantStruct::get("
813 << typeName << ", " << constName << "_fields);";
814 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
815 Out << "std::vector<Constant*> " << constName << "_elems;";
817 unsigned N = CP->getNumOperands();
818 for (unsigned i = 0; i < N; ++i) {
819 printConstant(CP->getOperand(i));
820 Out << constName << "_elems.push_back("
821 << getCppName(CP->getOperand(i)) << ");";
824 Out << "Constant* " << constName << " = ConstantVector::get("
825 << typeName << ", " << constName << "_elems);";
826 } else if (isa<UndefValue>(CV)) {
827 Out << "UndefValue* " << constName << " = UndefValue::get("
829 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
830 if (CE->getOpcode() == Instruction::GetElementPtr) {
831 Out << "std::vector<Constant*> " << constName << "_indices;";
833 printConstant(CE->getOperand(0));
834 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
835 printConstant(CE->getOperand(i));
836 Out << constName << "_indices.push_back("
837 << getCppName(CE->getOperand(i)) << ");";
840 Out << "Constant* " << constName
841 << " = ConstantExpr::getGetElementPtr("
842 << getCppName(CE->getOperand(0)) << ", "
843 << "&" << constName << "_indices[0], "
844 << constName << "_indices.size()"
846 } else if (CE->isCast()) {
847 printConstant(CE->getOperand(0));
848 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
849 switch (CE->getOpcode()) {
850 default: llvm_unreachable("Invalid cast opcode");
851 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
852 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
853 case Instruction::SExt: Out << "Instruction::SExt"; break;
854 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
855 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
856 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
857 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
858 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
859 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
860 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
861 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
862 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
864 Out << ", " << getCppName(CE->getOperand(0)) << ", "
865 << getCppName(CE->getType()) << ");";
867 unsigned N = CE->getNumOperands();
868 for (unsigned i = 0; i < N; ++i ) {
869 printConstant(CE->getOperand(i));
871 Out << "Constant* " << constName << " = ConstantExpr::";
872 switch (CE->getOpcode()) {
873 case Instruction::Add: Out << "getAdd("; break;
874 case Instruction::FAdd: Out << "getFAdd("; break;
875 case Instruction::Sub: Out << "getSub("; break;
876 case Instruction::FSub: Out << "getFSub("; break;
877 case Instruction::Mul: Out << "getMul("; break;
878 case Instruction::FMul: Out << "getFMul("; break;
879 case Instruction::UDiv: Out << "getUDiv("; break;
880 case Instruction::SDiv: Out << "getSDiv("; break;
881 case Instruction::FDiv: Out << "getFDiv("; break;
882 case Instruction::URem: Out << "getURem("; break;
883 case Instruction::SRem: Out << "getSRem("; break;
884 case Instruction::FRem: Out << "getFRem("; break;
885 case Instruction::And: Out << "getAnd("; break;
886 case Instruction::Or: Out << "getOr("; break;
887 case Instruction::Xor: Out << "getXor("; break;
888 case Instruction::ICmp:
889 Out << "getICmp(ICmpInst::ICMP_";
890 switch (CE->getPredicate()) {
891 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
892 case ICmpInst::ICMP_NE: Out << "NE"; break;
893 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
894 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
895 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
896 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
897 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
898 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
899 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
900 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
901 default: error("Invalid ICmp Predicate");
904 case Instruction::FCmp:
905 Out << "getFCmp(FCmpInst::FCMP_";
906 switch (CE->getPredicate()) {
907 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
908 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
909 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
910 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
911 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
912 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
913 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
914 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
915 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
916 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
917 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
918 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
919 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
920 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
921 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
922 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
923 default: error("Invalid FCmp Predicate");
926 case Instruction::Shl: Out << "getShl("; break;
927 case Instruction::LShr: Out << "getLShr("; break;
928 case Instruction::AShr: Out << "getAShr("; break;
929 case Instruction::Select: Out << "getSelect("; break;
930 case Instruction::ExtractElement: Out << "getExtractElement("; break;
931 case Instruction::InsertElement: Out << "getInsertElement("; break;
932 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
934 error("Invalid constant expression");
937 Out << getCppName(CE->getOperand(0));
938 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
939 Out << ", " << getCppName(CE->getOperand(i));
943 error("Bad Constant");
944 Out << "Constant* " << constName << " = 0; ";
949 void CppWriter::printConstants(const Module* M) {
950 // Traverse all the global variables looking for constant initializers
951 for (Module::const_global_iterator I = TheModule->global_begin(),
952 E = TheModule->global_end(); I != E; ++I)
953 if (I->hasInitializer())
954 printConstant(I->getInitializer());
956 // Traverse the LLVM functions looking for constants
957 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
959 // Add all of the basic blocks and instructions
960 for (Function::const_iterator BB = FI->begin(),
961 E = FI->end(); BB != E; ++BB) {
962 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
964 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
965 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
974 void CppWriter::printVariableUses(const GlobalVariable *GV) {
975 nl(Out) << "// Type Definitions";
977 printType(GV->getType());
978 if (GV->hasInitializer()) {
979 Constant* Init = GV->getInitializer();
980 printType(Init->getType());
981 if (Function* F = dyn_cast<Function>(Init)) {
982 nl(Out)<< "/ Function Declarations"; nl(Out);
983 printFunctionHead(F);
984 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
985 nl(Out) << "// Global Variable Declarations"; nl(Out);
986 printVariableHead(gv);
988 nl(Out) << "// Constant Definitions"; nl(Out);
991 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
992 nl(Out) << "// Global Variable Definitions"; nl(Out);
993 printVariableBody(gv);
998 void CppWriter::printVariableHead(const GlobalVariable *GV) {
999 nl(Out) << "GlobalVariable* " << getCppName(GV);
1001 Out << " = mod->getGlobalVariable(getGlobalContext(), ";
1002 printEscapedString(GV->getName());
1003 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
1004 nl(Out) << "if (!" << getCppName(GV) << ") {";
1005 in(); nl(Out) << getCppName(GV);
1007 Out << " = new GlobalVariable(/*Module=*/*mod, ";
1008 nl(Out) << "/*Type=*/";
1009 printCppName(GV->getType()->getElementType());
1011 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
1013 nl(Out) << "/*Linkage=*/";
1014 printLinkageType(GV->getLinkage());
1016 nl(Out) << "/*Initializer=*/0, ";
1017 if (GV->hasInitializer()) {
1018 Out << "// has initializer, specified below";
1020 nl(Out) << "/*Name=*/\"";
1021 printEscapedString(GV->getName());
1025 if (GV->hasSection()) {
1027 Out << "->setSection(\"";
1028 printEscapedString(GV->getSection());
1032 if (GV->getAlignment()) {
1034 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1037 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1039 Out << "->setVisibility(";
1040 printVisibilityType(GV->getVisibility());
1045 out(); Out << "}"; nl(Out);
1049 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1050 if (GV->hasInitializer()) {
1052 Out << "->setInitializer(";
1053 Out << getCppName(GV->getInitializer()) << ");";
1058 std::string CppWriter::getOpName(Value* V) {
1059 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1060 return getCppName(V);
1062 // See if its alread in the map of forward references, if so just return the
1063 // name we already set up for it
1064 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1065 if (I != ForwardRefs.end())
1068 // This is a new forward reference. Generate a unique name for it
1069 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1071 // Yes, this is a hack. An Argument is the smallest instantiable value that
1072 // we can make as a placeholder for the real value. We'll replace these
1073 // Argument instances later.
1074 Out << "Argument* " << result << " = new Argument("
1075 << getCppName(V->getType()) << ");";
1077 ForwardRefs[V] = result;
1081 // printInstruction - This member is called for each Instruction in a function.
1082 void CppWriter::printInstruction(const Instruction *I,
1083 const std::string& bbname) {
1084 std::string iName(getCppName(I));
1086 // Before we emit this instruction, we need to take care of generating any
1087 // forward references. So, we get the names of all the operands in advance
1088 std::string* opNames = new std::string[I->getNumOperands()];
1089 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1090 opNames[i] = getOpName(I->getOperand(i));
1093 switch (I->getOpcode()) {
1095 error("Invalid instruction");
1098 case Instruction::Ret: {
1099 const ReturnInst* ret = cast<ReturnInst>(I);
1100 Out << "ReturnInst::Create(getGlobalContext(), "
1101 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1104 case Instruction::Br: {
1105 const BranchInst* br = cast<BranchInst>(I);
1106 Out << "BranchInst::Create(" ;
1107 if (br->getNumOperands() == 3 ) {
1108 Out << opNames[2] << ", "
1109 << opNames[1] << ", "
1110 << opNames[0] << ", ";
1112 } else if (br->getNumOperands() == 1) {
1113 Out << opNames[0] << ", ";
1115 error("Branch with 2 operands?");
1117 Out << bbname << ");";
1120 case Instruction::Switch: {
1121 const SwitchInst *SI = cast<SwitchInst>(I);
1122 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1123 << opNames[0] << ", "
1124 << opNames[1] << ", "
1125 << SI->getNumCases() << ", " << bbname << ");";
1127 for (unsigned i = 2; i != SI->getNumOperands(); i += 2) {
1128 Out << iName << "->addCase("
1129 << opNames[i] << ", "
1130 << opNames[i+1] << ");";
1135 case Instruction::IndBr: {
1136 const IndBrInst *IBI = cast<IndBrInst>(I);
1137 Out << "IndBrInst *" << iName << " = IndBrInst::Create("
1138 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1140 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1141 Out << iName << "->addDestination(" << opNames[i] << ");";
1146 case Instruction::Invoke: {
1147 const InvokeInst* inv = cast<InvokeInst>(I);
1148 Out << "std::vector<Value*> " << iName << "_params;";
1150 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1151 Out << iName << "_params.push_back("
1152 << opNames[i] << ");";
1155 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1156 << opNames[0] << ", "
1157 << opNames[1] << ", "
1158 << opNames[2] << ", "
1159 << iName << "_params.begin(), " << iName << "_params.end(), \"";
1160 printEscapedString(inv->getName());
1161 Out << "\", " << bbname << ");";
1162 nl(Out) << iName << "->setCallingConv(";
1163 printCallingConv(inv->getCallingConv());
1165 printAttributes(inv->getAttributes(), iName);
1166 Out << iName << "->setAttributes(" << iName << "_PAL);";
1170 case Instruction::Unwind: {
1171 Out << "new UnwindInst("
1175 case Instruction::Unreachable: {
1176 Out << "new UnreachableInst("
1177 << "getGlobalContext(), "
1181 case Instruction::Add:
1182 case Instruction::FAdd:
1183 case Instruction::Sub:
1184 case Instruction::FSub:
1185 case Instruction::Mul:
1186 case Instruction::FMul:
1187 case Instruction::UDiv:
1188 case Instruction::SDiv:
1189 case Instruction::FDiv:
1190 case Instruction::URem:
1191 case Instruction::SRem:
1192 case Instruction::FRem:
1193 case Instruction::And:
1194 case Instruction::Or:
1195 case Instruction::Xor:
1196 case Instruction::Shl:
1197 case Instruction::LShr:
1198 case Instruction::AShr:{
1199 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1200 switch (I->getOpcode()) {
1201 case Instruction::Add: Out << "Instruction::Add"; break;
1202 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1203 case Instruction::Sub: Out << "Instruction::Sub"; break;
1204 case Instruction::FSub: Out << "Instruction::FSub"; break;
1205 case Instruction::Mul: Out << "Instruction::Mul"; break;
1206 case Instruction::FMul: Out << "Instruction::FMul"; break;
1207 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1208 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1209 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1210 case Instruction::URem:Out << "Instruction::URem"; break;
1211 case Instruction::SRem:Out << "Instruction::SRem"; break;
1212 case Instruction::FRem:Out << "Instruction::FRem"; break;
1213 case Instruction::And: Out << "Instruction::And"; break;
1214 case Instruction::Or: Out << "Instruction::Or"; break;
1215 case Instruction::Xor: Out << "Instruction::Xor"; break;
1216 case Instruction::Shl: Out << "Instruction::Shl"; break;
1217 case Instruction::LShr:Out << "Instruction::LShr"; break;
1218 case Instruction::AShr:Out << "Instruction::AShr"; break;
1219 default: Out << "Instruction::BadOpCode"; break;
1221 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1222 printEscapedString(I->getName());
1223 Out << "\", " << bbname << ");";
1226 case Instruction::FCmp: {
1227 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1228 switch (cast<FCmpInst>(I)->getPredicate()) {
1229 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1230 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1231 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1232 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1233 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1234 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1235 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1236 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1237 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1238 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1239 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1240 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1241 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1242 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1243 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1244 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1245 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1247 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1248 printEscapedString(I->getName());
1252 case Instruction::ICmp: {
1253 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1254 switch (cast<ICmpInst>(I)->getPredicate()) {
1255 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1256 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1257 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1258 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1259 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1260 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1261 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1262 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1263 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1264 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1265 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1267 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1268 printEscapedString(I->getName());
1272 case Instruction::Alloca: {
1273 const AllocaInst* allocaI = cast<AllocaInst>(I);
1274 Out << "AllocaInst* " << iName << " = new AllocaInst("
1275 << getCppName(allocaI->getAllocatedType()) << ", ";
1276 if (allocaI->isArrayAllocation())
1277 Out << opNames[0] << ", ";
1279 printEscapedString(allocaI->getName());
1280 Out << "\", " << bbname << ");";
1281 if (allocaI->getAlignment())
1282 nl(Out) << iName << "->setAlignment("
1283 << allocaI->getAlignment() << ");";
1286 case Instruction::Load:{
1287 const LoadInst* load = cast<LoadInst>(I);
1288 Out << "LoadInst* " << iName << " = new LoadInst("
1289 << opNames[0] << ", \"";
1290 printEscapedString(load->getName());
1291 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1292 << ", " << bbname << ");";
1295 case Instruction::Store: {
1296 const StoreInst* store = cast<StoreInst>(I);
1297 Out << " new StoreInst("
1298 << opNames[0] << ", "
1299 << opNames[1] << ", "
1300 << (store->isVolatile() ? "true" : "false")
1301 << ", " << bbname << ");";
1304 case Instruction::GetElementPtr: {
1305 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1306 if (gep->getNumOperands() <= 2) {
1307 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1309 if (gep->getNumOperands() == 2)
1310 Out << ", " << opNames[1];
1312 Out << "std::vector<Value*> " << iName << "_indices;";
1314 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1315 Out << iName << "_indices.push_back("
1316 << opNames[i] << ");";
1319 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1320 << opNames[0] << ", " << iName << "_indices.begin(), "
1321 << iName << "_indices.end()";
1324 printEscapedString(gep->getName());
1325 Out << "\", " << bbname << ");";
1328 case Instruction::PHI: {
1329 const PHINode* phi = cast<PHINode>(I);
1331 Out << "PHINode* " << iName << " = PHINode::Create("
1332 << getCppName(phi->getType()) << ", \"";
1333 printEscapedString(phi->getName());
1334 Out << "\", " << bbname << ");";
1335 nl(Out) << iName << "->reserveOperandSpace("
1336 << phi->getNumIncomingValues()
1339 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1340 Out << iName << "->addIncoming("
1341 << opNames[i] << ", " << opNames[i+1] << ");";
1346 case Instruction::Trunc:
1347 case Instruction::ZExt:
1348 case Instruction::SExt:
1349 case Instruction::FPTrunc:
1350 case Instruction::FPExt:
1351 case Instruction::FPToUI:
1352 case Instruction::FPToSI:
1353 case Instruction::UIToFP:
1354 case Instruction::SIToFP:
1355 case Instruction::PtrToInt:
1356 case Instruction::IntToPtr:
1357 case Instruction::BitCast: {
1358 const CastInst* cst = cast<CastInst>(I);
1359 Out << "CastInst* " << iName << " = new ";
1360 switch (I->getOpcode()) {
1361 case Instruction::Trunc: Out << "TruncInst"; break;
1362 case Instruction::ZExt: Out << "ZExtInst"; break;
1363 case Instruction::SExt: Out << "SExtInst"; break;
1364 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1365 case Instruction::FPExt: Out << "FPExtInst"; break;
1366 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1367 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1368 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1369 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1370 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1371 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1372 case Instruction::BitCast: Out << "BitCastInst"; break;
1373 default: assert(!"Unreachable"); break;
1375 Out << "(" << opNames[0] << ", "
1376 << getCppName(cst->getType()) << ", \"";
1377 printEscapedString(cst->getName());
1378 Out << "\", " << bbname << ");";
1381 case Instruction::Call:{
1382 const CallInst* call = cast<CallInst>(I);
1383 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1384 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1385 << getCppName(ila->getFunctionType()) << ", \""
1386 << ila->getAsmString() << "\", \""
1387 << ila->getConstraintString() << "\","
1388 << (ila->hasSideEffects() ? "true" : "false") << ");";
1391 if (call->getNumOperands() > 2) {
1392 Out << "std::vector<Value*> " << iName << "_params;";
1394 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1395 Out << iName << "_params.push_back(" << opNames[i] << ");";
1398 Out << "CallInst* " << iName << " = CallInst::Create("
1399 << opNames[0] << ", " << iName << "_params.begin(), "
1400 << iName << "_params.end(), \"";
1401 } else if (call->getNumOperands() == 2) {
1402 Out << "CallInst* " << iName << " = CallInst::Create("
1403 << opNames[0] << ", " << opNames[1] << ", \"";
1405 Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
1408 printEscapedString(call->getName());
1409 Out << "\", " << bbname << ");";
1410 nl(Out) << iName << "->setCallingConv(";
1411 printCallingConv(call->getCallingConv());
1413 nl(Out) << iName << "->setTailCall("
1414 << (call->isTailCall() ? "true":"false");
1416 printAttributes(call->getAttributes(), iName);
1417 Out << iName << "->setAttributes(" << iName << "_PAL);";
1421 case Instruction::Select: {
1422 const SelectInst* sel = cast<SelectInst>(I);
1423 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1424 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1425 printEscapedString(sel->getName());
1426 Out << "\", " << bbname << ");";
1429 case Instruction::UserOp1:
1431 case Instruction::UserOp2: {
1432 /// FIXME: What should be done here?
1435 case Instruction::VAArg: {
1436 const VAArgInst* va = cast<VAArgInst>(I);
1437 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1438 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1439 printEscapedString(va->getName());
1440 Out << "\", " << bbname << ");";
1443 case Instruction::ExtractElement: {
1444 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1445 Out << "ExtractElementInst* " << getCppName(eei)
1446 << " = new ExtractElementInst(" << opNames[0]
1447 << ", " << opNames[1] << ", \"";
1448 printEscapedString(eei->getName());
1449 Out << "\", " << bbname << ");";
1452 case Instruction::InsertElement: {
1453 const InsertElementInst* iei = cast<InsertElementInst>(I);
1454 Out << "InsertElementInst* " << getCppName(iei)
1455 << " = InsertElementInst::Create(" << opNames[0]
1456 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1457 printEscapedString(iei->getName());
1458 Out << "\", " << bbname << ");";
1461 case Instruction::ShuffleVector: {
1462 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1463 Out << "ShuffleVectorInst* " << getCppName(svi)
1464 << " = new ShuffleVectorInst(" << opNames[0]
1465 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1466 printEscapedString(svi->getName());
1467 Out << "\", " << bbname << ");";
1470 case Instruction::ExtractValue: {
1471 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1472 Out << "std::vector<unsigned> " << iName << "_indices;";
1474 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1475 Out << iName << "_indices.push_back("
1476 << evi->idx_begin()[i] << ");";
1479 Out << "ExtractValueInst* " << getCppName(evi)
1480 << " = ExtractValueInst::Create(" << opNames[0]
1482 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1483 printEscapedString(evi->getName());
1484 Out << "\", " << bbname << ");";
1487 case Instruction::InsertValue: {
1488 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1489 Out << "std::vector<unsigned> " << iName << "_indices;";
1491 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1492 Out << iName << "_indices.push_back("
1493 << ivi->idx_begin()[i] << ");";
1496 Out << "InsertValueInst* " << getCppName(ivi)
1497 << " = InsertValueInst::Create(" << opNames[0]
1498 << ", " << opNames[1] << ", "
1499 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1500 printEscapedString(ivi->getName());
1501 Out << "\", " << bbname << ");";
1505 DefinedValues.insert(I);
1510 // Print out the types, constants and declarations needed by one function
1511 void CppWriter::printFunctionUses(const Function* F) {
1512 nl(Out) << "// Type Definitions"; nl(Out);
1514 // Print the function's return type
1515 printType(F->getReturnType());
1517 // Print the function's function type
1518 printType(F->getFunctionType());
1520 // Print the types of each of the function's arguments
1521 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1523 printType(AI->getType());
1527 // Print type definitions for every type referenced by an instruction and
1528 // make a note of any global values or constants that are referenced
1529 SmallPtrSet<GlobalValue*,64> gvs;
1530 SmallPtrSet<Constant*,64> consts;
1531 for (Function::const_iterator BB = F->begin(), BE = F->end();
1533 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1535 // Print the type of the instruction itself
1536 printType(I->getType());
1538 // Print the type of each of the instruction's operands
1539 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1540 Value* operand = I->getOperand(i);
1541 printType(operand->getType());
1543 // If the operand references a GVal or Constant, make a note of it
1544 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1546 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1547 if (GVar->hasInitializer())
1548 consts.insert(GVar->getInitializer());
1549 } else if (Constant* C = dyn_cast<Constant>(operand))
1555 // Print the function declarations for any functions encountered
1556 nl(Out) << "// Function Declarations"; nl(Out);
1557 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1559 if (Function* Fun = dyn_cast<Function>(*I)) {
1560 if (!is_inline || Fun != F)
1561 printFunctionHead(Fun);
1565 // Print the global variable declarations for any variables encountered
1566 nl(Out) << "// Global Variable Declarations"; nl(Out);
1567 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1569 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1570 printVariableHead(F);
1573 // Print the constants found
1574 nl(Out) << "// Constant Definitions"; nl(Out);
1575 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1576 E = consts.end(); I != E; ++I) {
1580 // Process the global variables definitions now that all the constants have
1581 // been emitted. These definitions just couple the gvars with their constant
1583 nl(Out) << "// Global Variable Definitions"; nl(Out);
1584 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1586 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1587 printVariableBody(GV);
1591 void CppWriter::printFunctionHead(const Function* F) {
1592 nl(Out) << "Function* " << getCppName(F);
1594 Out << " = mod->getFunction(\"";
1595 printEscapedString(F->getName());
1596 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1597 nl(Out) << "if (!" << getCppName(F) << ") {";
1598 nl(Out) << getCppName(F);
1600 Out<< " = Function::Create(";
1601 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1602 nl(Out) << "/*Linkage=*/";
1603 printLinkageType(F->getLinkage());
1605 nl(Out) << "/*Name=*/\"";
1606 printEscapedString(F->getName());
1607 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1610 Out << "->setCallingConv(";
1611 printCallingConv(F->getCallingConv());
1614 if (F->hasSection()) {
1616 Out << "->setSection(\"" << F->getSection() << "\");";
1619 if (F->getAlignment()) {
1621 Out << "->setAlignment(" << F->getAlignment() << ");";
1624 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1626 Out << "->setVisibility(";
1627 printVisibilityType(F->getVisibility());
1633 Out << "->setGC(\"" << F->getGC() << "\");";
1640 printAttributes(F->getAttributes(), getCppName(F));
1642 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1646 void CppWriter::printFunctionBody(const Function *F) {
1647 if (F->isDeclaration())
1648 return; // external functions have no bodies.
1650 // Clear the DefinedValues and ForwardRefs maps because we can't have
1651 // cross-function forward refs
1652 ForwardRefs.clear();
1653 DefinedValues.clear();
1655 // Create all the argument values
1657 if (!F->arg_empty()) {
1658 Out << "Function::arg_iterator args = " << getCppName(F)
1659 << "->arg_begin();";
1662 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1664 Out << "Value* " << getCppName(AI) << " = args++;";
1666 if (AI->hasName()) {
1667 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1673 // Create all the basic blocks
1675 for (Function::const_iterator BI = F->begin(), BE = F->end();
1677 std::string bbname(getCppName(BI));
1678 Out << "BasicBlock* " << bbname <<
1679 " = BasicBlock::Create(getGlobalContext(), \"";
1681 printEscapedString(BI->getName());
1682 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1686 // Output all of its basic blocks... for the function
1687 for (Function::const_iterator BI = F->begin(), BE = F->end();
1689 std::string bbname(getCppName(BI));
1690 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1693 // Output all of the instructions in the basic block...
1694 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1696 printInstruction(I,bbname);
1700 // Loop over the ForwardRefs and resolve them now that all instructions
1702 if (!ForwardRefs.empty()) {
1703 nl(Out) << "// Resolve Forward References";
1707 while (!ForwardRefs.empty()) {
1708 ForwardRefMap::iterator I = ForwardRefs.begin();
1709 Out << I->second << "->replaceAllUsesWith("
1710 << getCppName(I->first) << "); delete " << I->second << ";";
1712 ForwardRefs.erase(I);
1716 void CppWriter::printInline(const std::string& fname,
1717 const std::string& func) {
1718 const Function* F = TheModule->getFunction(func);
1720 error(std::string("Function '") + func + "' not found in input module");
1723 if (F->isDeclaration()) {
1724 error(std::string("Function '") + func + "' is external!");
1727 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1729 unsigned arg_count = 1;
1730 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1732 Out << ", Value* arg_" << arg_count;
1737 printFunctionUses(F);
1738 printFunctionBody(F);
1740 Out << "return " << getCppName(F->begin()) << ";";
1745 void CppWriter::printModuleBody() {
1746 // Print out all the type definitions
1747 nl(Out) << "// Type Definitions"; nl(Out);
1748 printTypes(TheModule);
1750 // Functions can call each other and global variables can reference them so
1751 // define all the functions first before emitting their function bodies.
1752 nl(Out) << "// Function Declarations"; nl(Out);
1753 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1755 printFunctionHead(I);
1757 // Process the global variables declarations. We can't initialze them until
1758 // after the constants are printed so just print a header for each global
1759 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1760 for (Module::const_global_iterator I = TheModule->global_begin(),
1761 E = TheModule->global_end(); I != E; ++I) {
1762 printVariableHead(I);
1765 // Print out all the constants definitions. Constants don't recurse except
1766 // through GlobalValues. All GlobalValues have been declared at this point
1767 // so we can proceed to generate the constants.
1768 nl(Out) << "// Constant Definitions"; nl(Out);
1769 printConstants(TheModule);
1771 // Process the global variables definitions now that all the constants have
1772 // been emitted. These definitions just couple the gvars with their constant
1774 nl(Out) << "// Global Variable Definitions"; nl(Out);
1775 for (Module::const_global_iterator I = TheModule->global_begin(),
1776 E = TheModule->global_end(); I != E; ++I) {
1777 printVariableBody(I);
1780 // Finally, we can safely put out all of the function bodies.
1781 nl(Out) << "// Function Definitions"; nl(Out);
1782 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1784 if (!I->isDeclaration()) {
1785 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1789 printFunctionBody(I);
1796 void CppWriter::printProgram(const std::string& fname,
1797 const std::string& mName) {
1798 Out << "#include <llvm/LLVMContext.h>\n";
1799 Out << "#include <llvm/Module.h>\n";
1800 Out << "#include <llvm/DerivedTypes.h>\n";
1801 Out << "#include <llvm/Constants.h>\n";
1802 Out << "#include <llvm/GlobalVariable.h>\n";
1803 Out << "#include <llvm/Function.h>\n";
1804 Out << "#include <llvm/CallingConv.h>\n";
1805 Out << "#include <llvm/BasicBlock.h>\n";
1806 Out << "#include <llvm/Instructions.h>\n";
1807 Out << "#include <llvm/InlineAsm.h>\n";
1808 Out << "#include <llvm/Support/FormattedStream.h>\n";
1809 Out << "#include <llvm/Support/MathExtras.h>\n";
1810 Out << "#include <llvm/Pass.h>\n";
1811 Out << "#include <llvm/PassManager.h>\n";
1812 Out << "#include <llvm/ADT/SmallVector.h>\n";
1813 Out << "#include <llvm/Analysis/Verifier.h>\n";
1814 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1815 Out << "#include <algorithm>\n";
1816 Out << "using namespace llvm;\n\n";
1817 Out << "Module* " << fname << "();\n\n";
1818 Out << "int main(int argc, char**argv) {\n";
1819 Out << " Module* Mod = " << fname << "();\n";
1820 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1821 Out << " PassManager PM;\n";
1822 Out << " PM.add(createPrintModulePass(&outs()));\n";
1823 Out << " PM.run(*Mod);\n";
1824 Out << " return 0;\n";
1826 printModule(fname,mName);
1829 void CppWriter::printModule(const std::string& fname,
1830 const std::string& mName) {
1831 nl(Out) << "Module* " << fname << "() {";
1832 nl(Out,1) << "// Module Construction";
1833 nl(Out) << "Module* mod = new Module(\"";
1834 printEscapedString(mName);
1835 Out << "\", getGlobalContext());";
1836 if (!TheModule->getTargetTriple().empty()) {
1837 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1839 if (!TheModule->getTargetTriple().empty()) {
1840 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1844 if (!TheModule->getModuleInlineAsm().empty()) {
1845 nl(Out) << "mod->setModuleInlineAsm(\"";
1846 printEscapedString(TheModule->getModuleInlineAsm());
1851 // Loop over the dependent libraries and emit them.
1852 Module::lib_iterator LI = TheModule->lib_begin();
1853 Module::lib_iterator LE = TheModule->lib_end();
1855 Out << "mod->addLibrary(\"" << *LI << "\");";
1860 nl(Out) << "return mod;";
1865 void CppWriter::printContents(const std::string& fname,
1866 const std::string& mName) {
1867 Out << "\nModule* " << fname << "(Module *mod) {\n";
1868 Out << "\nmod->setModuleIdentifier(\"";
1869 printEscapedString(mName);
1872 Out << "\nreturn mod;\n";
1876 void CppWriter::printFunction(const std::string& fname,
1877 const std::string& funcName) {
1878 const Function* F = TheModule->getFunction(funcName);
1880 error(std::string("Function '") + funcName + "' not found in input module");
1883 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1884 printFunctionUses(F);
1885 printFunctionHead(F);
1886 printFunctionBody(F);
1887 Out << "return " << getCppName(F) << ";\n";
1891 void CppWriter::printFunctions() {
1892 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1893 Module::const_iterator I = funcs.begin();
1894 Module::const_iterator IE = funcs.end();
1896 for (; I != IE; ++I) {
1897 const Function &func = *I;
1898 if (!func.isDeclaration()) {
1899 std::string name("define_");
1900 name += func.getName();
1901 printFunction(name, func.getName());
1906 void CppWriter::printVariable(const std::string& fname,
1907 const std::string& varName) {
1908 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1911 error(std::string("Variable '") + varName + "' not found in input module");
1914 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1915 printVariableUses(GV);
1916 printVariableHead(GV);
1917 printVariableBody(GV);
1918 Out << "return " << getCppName(GV) << ";\n";
1922 void CppWriter::printType(const std::string& fname,
1923 const std::string& typeName) {
1924 const Type* Ty = TheModule->getTypeByName(typeName);
1926 error(std::string("Type '") + typeName + "' not found in input module");
1929 Out << "\nType* " << fname << "(Module *mod) {\n";
1931 Out << "return " << getCppName(Ty) << ";\n";
1935 bool CppWriter::runOnModule(Module &M) {
1939 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1941 // Get the name of the function we're supposed to generate
1942 std::string fname = FuncName.getValue();
1944 // Get the name of the thing we are to generate
1945 std::string tgtname = NameToGenerate.getValue();
1946 if (GenerationType == GenModule ||
1947 GenerationType == GenContents ||
1948 GenerationType == GenProgram ||
1949 GenerationType == GenFunctions) {
1950 if (tgtname == "!bad!") {
1951 if (M.getModuleIdentifier() == "-")
1952 tgtname = "<stdin>";
1954 tgtname = M.getModuleIdentifier();
1956 } else if (tgtname == "!bad!")
1957 error("You must use the -for option with -gen-{function,variable,type}");
1959 switch (WhatToGenerate(GenerationType)) {
1962 fname = "makeLLVMModule";
1963 printProgram(fname,tgtname);
1967 fname = "makeLLVMModule";
1968 printModule(fname,tgtname);
1972 fname = "makeLLVMModuleContents";
1973 printContents(fname,tgtname);
1977 fname = "makeLLVMFunction";
1978 printFunction(fname,tgtname);
1985 fname = "makeLLVMInline";
1986 printInline(fname,tgtname);
1990 fname = "makeLLVMVariable";
1991 printVariable(fname,tgtname);
1995 fname = "makeLLVMType";
1996 printType(fname,tgtname);
1999 error("Invalid generation option");
2006 char CppWriter::ID = 0;
2008 //===----------------------------------------------------------------------===//
2009 // External Interface declaration
2010 //===----------------------------------------------------------------------===//
2012 bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
2013 formatted_raw_ostream &o,
2014 CodeGenFileType FileType,
2015 CodeGenOpt::Level OptLevel) {
2016 if (FileType != TargetMachine::AssemblyFile) return true;
2017 PM.add(new CppWriter(o));