1 //===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the writing of the LLVM IR as a set of C++ calls to the
11 // LLVM IR interface. The input module is assumed to be verified.
13 //===----------------------------------------------------------------------===//
15 #include "CPPTargetMachine.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instruction.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/PassManager.h"
25 #include "llvm/MC/MCSubtargetInfo.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/FormattedStream.h"
31 #include "llvm/Target/TargetRegistry.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Config/config.h"
39 static cl::opt
<std::string
>
40 FuncName("cppfname", cl::desc("Specify the name of the generated function"),
41 cl::value_desc("function name"));
54 static cl::opt
<WhatToGenerate
> GenerationType("cppgen", cl::Optional
,
55 cl::desc("Choose what kind of output to generate"),
58 clEnumValN(GenProgram
, "program", "Generate a complete program"),
59 clEnumValN(GenModule
, "module", "Generate a module definition"),
60 clEnumValN(GenContents
, "contents", "Generate contents of a module"),
61 clEnumValN(GenFunction
, "function", "Generate a function definition"),
62 clEnumValN(GenFunctions
,"functions", "Generate all function definitions"),
63 clEnumValN(GenInline
, "inline", "Generate an inline function"),
64 clEnumValN(GenVariable
, "variable", "Generate a variable definition"),
65 clEnumValN(GenType
, "type", "Generate a type definition"),
70 static cl::opt
<std::string
> NameToGenerate("cppfor", cl::Optional
,
71 cl::desc("Specify the name of the thing to generate"),
74 extern "C" void LLVMInitializeCppBackendTarget() {
75 // Register the target.
76 RegisterTargetMachine
<CPPTargetMachine
> X(TheCppBackendTarget
);
79 extern "C" void LLVMInitializeCppBackendMCSubtargetInfo() {
80 RegisterMCSubtargetInfo
<MCSubtargetInfo
> X(TheCppBackendTarget
);
84 typedef std::vector
<const Type
*> TypeList
;
85 typedef std::map
<const Type
*,std::string
> TypeMap
;
86 typedef std::map
<const Value
*,std::string
> ValueMap
;
87 typedef std::set
<std::string
> NameSet
;
88 typedef std::set
<const Type
*> TypeSet
;
89 typedef std::set
<const Value
*> ValueSet
;
90 typedef std::map
<const Value
*,std::string
> ForwardRefMap
;
92 /// CppWriter - This class is the main chunk of code that converts an LLVM
93 /// module to a C++ translation unit.
94 class CppWriter
: public ModulePass
{
95 formatted_raw_ostream
&Out
;
96 const Module
*TheModule
;
100 TypeMap UnresolvedTypes
;
103 TypeSet DefinedTypes
;
104 ValueSet DefinedValues
;
105 ForwardRefMap ForwardRefs
;
107 unsigned indent_level
;
111 explicit CppWriter(formatted_raw_ostream
&o
) :
112 ModulePass(ID
), Out(o
), uniqueNum(0), is_inline(false), indent_level(0){}
114 virtual const char *getPassName() const { return "C++ backend"; }
116 bool runOnModule(Module
&M
);
118 void printProgram(const std::string
& fname
, const std::string
& modName
);
119 void printModule(const std::string
& fname
, const std::string
& modName
);
120 void printContents(const std::string
& fname
, const std::string
& modName
);
121 void printFunction(const std::string
& fname
, const std::string
& funcName
);
122 void printFunctions();
123 void printInline(const std::string
& fname
, const std::string
& funcName
);
124 void printVariable(const std::string
& fname
, const std::string
& varName
);
125 void printType(const std::string
& fname
, const std::string
& typeName
);
127 void error(const std::string
& msg
);
130 formatted_raw_ostream
& nl(formatted_raw_ostream
&Out
, int delta
= 0);
131 inline void in() { indent_level
++; }
132 inline void out() { if (indent_level
>0) indent_level
--; }
135 void printLinkageType(GlobalValue::LinkageTypes LT
);
136 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes
);
137 void printCallingConv(CallingConv::ID cc
);
138 void printEscapedString(const std::string
& str
);
139 void printCFP(const ConstantFP
* CFP
);
141 std::string
getCppName(const Type
* val
);
142 inline void printCppName(const Type
* val
);
144 std::string
getCppName(const Value
* val
);
145 inline void printCppName(const Value
* val
);
147 void printAttributes(const AttrListPtr
&PAL
, const std::string
&name
);
148 bool printTypeInternal(const Type
* Ty
);
149 inline void printType(const Type
* Ty
);
150 void printTypes(const Module
* M
);
152 void printConstant(const Constant
*CPV
);
153 void printConstants(const Module
* M
);
155 void printVariableUses(const GlobalVariable
*GV
);
156 void printVariableHead(const GlobalVariable
*GV
);
157 void printVariableBody(const GlobalVariable
*GV
);
159 void printFunctionUses(const Function
*F
);
160 void printFunctionHead(const Function
*F
);
161 void printFunctionBody(const Function
*F
);
162 void printInstruction(const Instruction
*I
, const std::string
& bbname
);
163 std::string
getOpName(Value
*);
165 void printModuleBody();
167 } // end anonymous namespace.
169 formatted_raw_ostream
&CppWriter::nl(formatted_raw_ostream
&Out
, int delta
) {
171 if (delta
>= 0 || indent_level
>= unsigned(-delta
))
172 indent_level
+= delta
;
173 Out
.indent(indent_level
);
177 static inline void sanitize(std::string
&str
) {
178 for (size_t i
= 0; i
< str
.length(); ++i
)
179 if (!isalnum(str
[i
]) && str
[i
] != '_')
183 static std::string
getTypePrefix(const Type
*Ty
) {
184 switch (Ty
->getTypeID()) {
185 case Type::VoidTyID
: return "void_";
186 case Type::IntegerTyID
:
187 return "int" + utostr(cast
<IntegerType
>(Ty
)->getBitWidth()) + "_";
188 case Type::FloatTyID
: return "float_";
189 case Type::DoubleTyID
: return "double_";
190 case Type::LabelTyID
: return "label_";
191 case Type::FunctionTyID
: return "func_";
192 case Type::StructTyID
: return "struct_";
193 case Type::ArrayTyID
: return "array_";
194 case Type::PointerTyID
: return "ptr_";
195 case Type::VectorTyID
: return "packed_";
196 default: return "other_";
201 void CppWriter::error(const std::string
& msg
) {
202 report_fatal_error(msg
);
205 // printCFP - Print a floating point constant .. very carefully :)
206 // This makes sure that conversion to/from floating yields the same binary
207 // result so that we don't lose precision.
208 void CppWriter::printCFP(const ConstantFP
*CFP
) {
210 APFloat APF
= APFloat(CFP
->getValueAPF()); // copy
211 if (CFP
->getType() == Type::getFloatTy(CFP
->getContext()))
212 APF
.convert(APFloat::IEEEdouble
, APFloat::rmNearestTiesToEven
, &ignored
);
213 Out
<< "ConstantFP::get(mod->getContext(), ";
217 sprintf(Buffer
, "%A", APF
.convertToDouble());
218 if ((!strncmp(Buffer
, "0x", 2) ||
219 !strncmp(Buffer
, "-0x", 3) ||
220 !strncmp(Buffer
, "+0x", 3)) &&
221 APF
.bitwiseIsEqual(APFloat(atof(Buffer
)))) {
222 if (CFP
->getType() == Type::getDoubleTy(CFP
->getContext()))
223 Out
<< "BitsToDouble(" << Buffer
<< ")";
225 Out
<< "BitsToFloat((float)" << Buffer
<< ")";
229 std::string StrVal
= ftostr(CFP
->getValueAPF());
231 while (StrVal
[0] == ' ')
232 StrVal
.erase(StrVal
.begin());
234 // Check to make sure that the stringized number is not some string like
235 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
236 if (((StrVal
[0] >= '0' && StrVal
[0] <= '9') ||
237 ((StrVal
[0] == '-' || StrVal
[0] == '+') &&
238 (StrVal
[1] >= '0' && StrVal
[1] <= '9'))) &&
239 (CFP
->isExactlyValue(atof(StrVal
.c_str())))) {
240 if (CFP
->getType() == Type::getDoubleTy(CFP
->getContext()))
243 Out
<< StrVal
<< "f";
244 } else if (CFP
->getType() == Type::getDoubleTy(CFP
->getContext()))
245 Out
<< "BitsToDouble(0x"
246 << utohexstr(CFP
->getValueAPF().bitcastToAPInt().getZExtValue())
247 << "ULL) /* " << StrVal
<< " */";
249 Out
<< "BitsToFloat(0x"
250 << utohexstr((uint32_t)CFP
->getValueAPF().
251 bitcastToAPInt().getZExtValue())
252 << "U) /* " << StrVal
<< " */";
260 void CppWriter::printCallingConv(CallingConv::ID cc
){
261 // Print the calling convention.
263 case CallingConv::C
: Out
<< "CallingConv::C"; break;
264 case CallingConv::Fast
: Out
<< "CallingConv::Fast"; break;
265 case CallingConv::Cold
: Out
<< "CallingConv::Cold"; break;
266 case CallingConv::FirstTargetCC
: Out
<< "CallingConv::FirstTargetCC"; break;
267 default: Out
<< cc
; break;
271 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT
) {
273 case GlobalValue::InternalLinkage
:
274 Out
<< "GlobalValue::InternalLinkage"; break;
275 case GlobalValue::PrivateLinkage
:
276 Out
<< "GlobalValue::PrivateLinkage"; break;
277 case GlobalValue::LinkerPrivateLinkage
:
278 Out
<< "GlobalValue::LinkerPrivateLinkage"; break;
279 case GlobalValue::LinkerPrivateWeakLinkage
:
280 Out
<< "GlobalValue::LinkerPrivateWeakLinkage"; break;
281 case GlobalValue::LinkerPrivateWeakDefAutoLinkage
:
282 Out
<< "GlobalValue::LinkerPrivateWeakDefAutoLinkage"; break;
283 case GlobalValue::AvailableExternallyLinkage
:
284 Out
<< "GlobalValue::AvailableExternallyLinkage "; break;
285 case GlobalValue::LinkOnceAnyLinkage
:
286 Out
<< "GlobalValue::LinkOnceAnyLinkage "; break;
287 case GlobalValue::LinkOnceODRLinkage
:
288 Out
<< "GlobalValue::LinkOnceODRLinkage "; break;
289 case GlobalValue::WeakAnyLinkage
:
290 Out
<< "GlobalValue::WeakAnyLinkage"; break;
291 case GlobalValue::WeakODRLinkage
:
292 Out
<< "GlobalValue::WeakODRLinkage"; break;
293 case GlobalValue::AppendingLinkage
:
294 Out
<< "GlobalValue::AppendingLinkage"; break;
295 case GlobalValue::ExternalLinkage
:
296 Out
<< "GlobalValue::ExternalLinkage"; break;
297 case GlobalValue::DLLImportLinkage
:
298 Out
<< "GlobalValue::DLLImportLinkage"; break;
299 case GlobalValue::DLLExportLinkage
:
300 Out
<< "GlobalValue::DLLExportLinkage"; break;
301 case GlobalValue::ExternalWeakLinkage
:
302 Out
<< "GlobalValue::ExternalWeakLinkage"; break;
303 case GlobalValue::CommonLinkage
:
304 Out
<< "GlobalValue::CommonLinkage"; break;
308 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType
) {
310 default: llvm_unreachable("Unknown GVar visibility");
311 case GlobalValue::DefaultVisibility
:
312 Out
<< "GlobalValue::DefaultVisibility";
314 case GlobalValue::HiddenVisibility
:
315 Out
<< "GlobalValue::HiddenVisibility";
317 case GlobalValue::ProtectedVisibility
:
318 Out
<< "GlobalValue::ProtectedVisibility";
323 // printEscapedString - Print each character of the specified string, escaping
324 // it if it is not printable or if it is an escape char.
325 void CppWriter::printEscapedString(const std::string
&Str
) {
326 for (unsigned i
= 0, e
= Str
.size(); i
!= e
; ++i
) {
327 unsigned char C
= Str
[i
];
328 if (isprint(C
) && C
!= '"' && C
!= '\\') {
332 << (char) ((C
/16 < 10) ? ( C
/16 +'0') : ( C
/16 -10+'A'))
333 << (char)(((C
&15) < 10) ? ((C
&15)+'0') : ((C
&15)-10+'A'));
338 std::string
CppWriter::getCppName(const Type
* Ty
) {
339 // First, handle the primitive types .. easy
340 if (Ty
->isPrimitiveType() || Ty
->isIntegerTy()) {
341 switch (Ty
->getTypeID()) {
342 case Type::VoidTyID
: return "Type::getVoidTy(mod->getContext())";
343 case Type::IntegerTyID
: {
344 unsigned BitWidth
= cast
<IntegerType
>(Ty
)->getBitWidth();
345 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth
) + ")";
347 case Type::X86_FP80TyID
: return "Type::getX86_FP80Ty(mod->getContext())";
348 case Type::FloatTyID
: return "Type::getFloatTy(mod->getContext())";
349 case Type::DoubleTyID
: return "Type::getDoubleTy(mod->getContext())";
350 case Type::LabelTyID
: return "Type::getLabelTy(mod->getContext())";
351 case Type::X86_MMXTyID
: return "Type::getX86_MMXTy(mod->getContext())";
353 error("Invalid primitive type");
356 // shouldn't be returned, but make it sensible
357 return "Type::getVoidTy(mod->getContext())";
360 // Now, see if we've seen the type before and return that
361 TypeMap::iterator I
= TypeNames
.find(Ty
);
362 if (I
!= TypeNames
.end())
365 // Okay, let's build a new name for this type. Start with a prefix
366 const char* prefix
= 0;
367 switch (Ty
->getTypeID()) {
368 case Type::FunctionTyID
: prefix
= "FuncTy_"; break;
369 case Type::StructTyID
: prefix
= "StructTy_"; break;
370 case Type::ArrayTyID
: prefix
= "ArrayTy_"; break;
371 case Type::PointerTyID
: prefix
= "PointerTy_"; break;
372 case Type::VectorTyID
: prefix
= "VectorTy_"; break;
373 default: prefix
= "OtherTy_"; break; // prevent breakage
376 // See if the type has a name in the symboltable and build accordingly
378 if (const StructType
*STy
= dyn_cast
<StructType
>(Ty
))
380 name
= STy
->getName();
383 name
= utostr(uniqueNum
++);
385 name
= std::string(prefix
) + name
;
389 return TypeNames
[Ty
] = name
;
392 void CppWriter::printCppName(const Type
* Ty
) {
393 printEscapedString(getCppName(Ty
));
396 std::string
CppWriter::getCppName(const Value
* val
) {
398 ValueMap::iterator I
= ValueNames
.find(val
);
399 if (I
!= ValueNames
.end() && I
->first
== val
)
402 if (const GlobalVariable
* GV
= dyn_cast
<GlobalVariable
>(val
)) {
403 name
= std::string("gvar_") +
404 getTypePrefix(GV
->getType()->getElementType());
405 } else if (isa
<Function
>(val
)) {
406 name
= std::string("func_");
407 } else if (const Constant
* C
= dyn_cast
<Constant
>(val
)) {
408 name
= std::string("const_") + getTypePrefix(C
->getType());
409 } else if (const Argument
* Arg
= dyn_cast
<Argument
>(val
)) {
411 unsigned argNum
= std::distance(Arg
->getParent()->arg_begin(),
412 Function::const_arg_iterator(Arg
)) + 1;
413 name
= std::string("arg_") + utostr(argNum
);
414 NameSet::iterator NI
= UsedNames
.find(name
);
415 if (NI
!= UsedNames
.end())
416 name
+= std::string("_") + utostr(uniqueNum
++);
417 UsedNames
.insert(name
);
418 return ValueNames
[val
] = name
;
420 name
= getTypePrefix(val
->getType());
423 name
= getTypePrefix(val
->getType());
426 name
+= val
->getName();
428 name
+= utostr(uniqueNum
++);
430 NameSet::iterator NI
= UsedNames
.find(name
);
431 if (NI
!= UsedNames
.end())
432 name
+= std::string("_") + utostr(uniqueNum
++);
433 UsedNames
.insert(name
);
434 return ValueNames
[val
] = name
;
437 void CppWriter::printCppName(const Value
* val
) {
438 printEscapedString(getCppName(val
));
441 void CppWriter::printAttributes(const AttrListPtr
&PAL
,
442 const std::string
&name
) {
443 Out
<< "AttrListPtr " << name
<< "_PAL;";
445 if (!PAL
.isEmpty()) {
446 Out
<< '{'; in(); nl(Out
);
447 Out
<< "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out
);
448 Out
<< "AttributeWithIndex PAWI;"; nl(Out
);
449 for (unsigned i
= 0; i
< PAL
.getNumSlots(); ++i
) {
450 unsigned index
= PAL
.getSlot(i
).Index
;
451 Attributes attrs
= PAL
.getSlot(i
).Attrs
;
452 Out
<< "PAWI.Index = " << index
<< "U; PAWI.Attrs = 0 ";
453 #define HANDLE_ATTR(X) \
454 if (attrs & Attribute::X) \
455 Out << " | Attribute::" #X; \
456 attrs &= ~Attribute::X;
460 HANDLE_ATTR(NoReturn
);
462 HANDLE_ATTR(StructRet
);
463 HANDLE_ATTR(NoUnwind
);
464 HANDLE_ATTR(NoAlias
);
467 HANDLE_ATTR(ReadNone
);
468 HANDLE_ATTR(ReadOnly
);
469 HANDLE_ATTR(NoInline
);
470 HANDLE_ATTR(AlwaysInline
);
471 HANDLE_ATTR(OptimizeForSize
);
472 HANDLE_ATTR(StackProtect
);
473 HANDLE_ATTR(StackProtectReq
);
474 HANDLE_ATTR(NoCapture
);
475 HANDLE_ATTR(NoRedZone
);
476 HANDLE_ATTR(NoImplicitFloat
);
478 HANDLE_ATTR(InlineHint
);
480 if (attrs
& Attribute::StackAlignment
)
481 Out
<< " | Attribute::constructStackAlignmentFromInt("
482 << Attribute::getStackAlignmentFromAttrs(attrs
)
484 attrs
&= ~Attribute::StackAlignment
;
485 assert(attrs
== 0 && "Unhandled attribute!");
488 Out
<< "Attrs.push_back(PAWI);";
491 Out
<< name
<< "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
498 bool CppWriter::printTypeInternal(const Type
* Ty
) {
499 // We don't print definitions for primitive types
500 if (Ty
->isPrimitiveType() || Ty
->isIntegerTy())
503 // If we already defined this type, we don't need to define it again.
504 if (DefinedTypes
.find(Ty
) != DefinedTypes
.end())
507 // Everything below needs the name for the type so get it now.
508 std::string
typeName(getCppName(Ty
));
510 // Search the type stack for recursion. If we find it, then generate this
511 // as an OpaqueType, but make sure not to do this multiple times because
512 // the type could appear in multiple places on the stack. Once the opaque
513 // definition is issued, it must not be re-issued. Consequently we have to
514 // check the UnresolvedTypes list as well.
515 TypeList::const_iterator TI
= std::find(TypeStack
.begin(), TypeStack
.end(),
517 if (TI
!= TypeStack
.end()) {
518 TypeMap::const_iterator I
= UnresolvedTypes
.find(Ty
);
519 if (I
== UnresolvedTypes
.end()) {
520 Out
<< "PATypeHolder " << typeName
;
521 Out
<< "_fwd = OpaqueType::get(mod->getContext());";
523 UnresolvedTypes
[Ty
] = typeName
;
528 // We're going to print a derived type which, by definition, contains other
529 // types. So, push this one we're printing onto the type stack to assist with
530 // recursive definitions.
531 TypeStack
.push_back(Ty
);
533 // Print the type definition
534 switch (Ty
->getTypeID()) {
535 case Type::FunctionTyID
: {
536 const FunctionType
* FT
= cast
<FunctionType
>(Ty
);
537 Out
<< "std::vector<const Type*>" << typeName
<< "_args;";
539 FunctionType::param_iterator PI
= FT
->param_begin();
540 FunctionType::param_iterator PE
= FT
->param_end();
541 for (; PI
!= PE
; ++PI
) {
542 const Type
* argTy
= static_cast<const Type
*>(*PI
);
543 bool isForward
= printTypeInternal(argTy
);
544 std::string
argName(getCppName(argTy
));
545 Out
<< typeName
<< "_args.push_back(" << argName
;
551 bool isForward
= printTypeInternal(FT
->getReturnType());
552 std::string
retTypeName(getCppName(FT
->getReturnType()));
553 Out
<< "FunctionType* " << typeName
<< " = FunctionType::get(";
554 in(); nl(Out
) << "/*Result=*/" << retTypeName
;
558 nl(Out
) << "/*Params=*/" << typeName
<< "_args,";
559 nl(Out
) << "/*isVarArg=*/" << (FT
->isVarArg() ? "true" : "false") << ");";
564 case Type::StructTyID
: {
565 const StructType
* ST
= cast
<StructType
>(Ty
);
566 Out
<< "std::vector<const Type*>" << typeName
<< "_fields;";
568 StructType::element_iterator EI
= ST
->element_begin();
569 StructType::element_iterator EE
= ST
->element_end();
570 for (; EI
!= EE
; ++EI
) {
571 const Type
* fieldTy
= static_cast<const Type
*>(*EI
);
572 bool isForward
= printTypeInternal(fieldTy
);
573 std::string
fieldName(getCppName(fieldTy
));
574 Out
<< typeName
<< "_fields.push_back(" << fieldName
;
581 Out
<< "StructType *" << typeName
<< " = ";
582 if (ST
->isAnonymous()) {
583 Out
<< "StructType::get(" << "mod->getContext(), ";
585 Out
<< "StructType::createNamed(mod->getContext(), \"";
586 printEscapedString(ST
->getName());
589 Out
<< typeName
<< "->setBody(";
591 Out
<< typeName
<< "_fields, /*isPacked=*/"
592 << (ST
->isPacked() ? "true" : "false") << ");";
596 case Type::ArrayTyID
: {
597 const ArrayType
* AT
= cast
<ArrayType
>(Ty
);
598 const Type
* ET
= AT
->getElementType();
599 bool isForward
= printTypeInternal(ET
);
600 std::string
elemName(getCppName(ET
));
601 Out
<< "ArrayType* " << typeName
<< " = ArrayType::get("
602 << elemName
<< (isForward
? "_fwd" : "")
603 << ", " << utostr(AT
->getNumElements()) << ");";
607 case Type::PointerTyID
: {
608 const PointerType
* PT
= cast
<PointerType
>(Ty
);
609 const Type
* ET
= PT
->getElementType();
610 bool isForward
= printTypeInternal(ET
);
611 std::string
elemName(getCppName(ET
));
612 Out
<< "PointerType* " << typeName
<< " = PointerType::get("
613 << elemName
<< (isForward
? "_fwd" : "")
614 << ", " << utostr(PT
->getAddressSpace()) << ");";
618 case Type::VectorTyID
: {
619 const VectorType
* PT
= cast
<VectorType
>(Ty
);
620 const Type
* ET
= PT
->getElementType();
621 bool isForward
= printTypeInternal(ET
);
622 std::string
elemName(getCppName(ET
));
623 Out
<< "VectorType* " << typeName
<< " = VectorType::get("
624 << elemName
<< (isForward
? "_fwd" : "")
625 << ", " << utostr(PT
->getNumElements()) << ");";
630 error("Invalid TypeID");
633 // Pop us off the type stack
634 TypeStack
.pop_back();
636 // Indicate that this type is now defined.
637 DefinedTypes
.insert(Ty
);
639 // Early resolve as many unresolved types as possible. Search the unresolved
640 // types map for the type we just printed. Now that its definition is complete
641 // we can resolve any previous references to it. This prevents a cascade of
643 TypeMap::iterator I
= UnresolvedTypes
.find(Ty
);
644 if (I
!= UnresolvedTypes
.end()) {
645 Out
<< "cast<OpaqueType>(" << I
->second
646 << "_fwd.get())->refineAbstractTypeTo(" << I
->second
<< ");";
648 Out
<< I
->second
<< " = cast<";
649 switch (Ty
->getTypeID()) {
650 case Type::FunctionTyID
: Out
<< "FunctionType"; break;
651 case Type::ArrayTyID
: Out
<< "ArrayType"; break;
652 case Type::StructTyID
: Out
<< "StructType"; break;
653 case Type::VectorTyID
: Out
<< "VectorType"; break;
654 case Type::PointerTyID
: Out
<< "PointerType"; break;
655 default: Out
<< "NoSuchDerivedType"; break;
657 Out
<< ">(" << I
->second
<< "_fwd.get());";
659 UnresolvedTypes
.erase(I
);
662 // Finally, separate the type definition from other with a newline.
665 // We weren't a recursive type
669 // Prints a type definition. Returns true if it could not resolve all the
670 // types in the definition but had to use a forward reference.
671 void CppWriter::printType(const Type
* Ty
) {
672 assert(TypeStack
.empty());
674 printTypeInternal(Ty
);
675 assert(TypeStack
.empty());
678 void CppWriter::printTypes(const Module
* M
) {
679 // Add all of the global variables to the value table.
680 for (Module::const_global_iterator I
= TheModule
->global_begin(),
681 E
= TheModule
->global_end(); I
!= E
; ++I
) {
682 if (I
->hasInitializer())
683 printType(I
->getInitializer()->getType());
684 printType(I
->getType());
687 // Add all the functions to the table
688 for (Module::const_iterator FI
= TheModule
->begin(), FE
= TheModule
->end();
690 printType(FI
->getReturnType());
691 printType(FI
->getFunctionType());
692 // Add all the function arguments
693 for (Function::const_arg_iterator AI
= FI
->arg_begin(),
694 AE
= FI
->arg_end(); AI
!= AE
; ++AI
) {
695 printType(AI
->getType());
698 // Add all of the basic blocks and instructions
699 for (Function::const_iterator BB
= FI
->begin(),
700 E
= FI
->end(); BB
!= E
; ++BB
) {
701 printType(BB
->getType());
702 for (BasicBlock::const_iterator I
= BB
->begin(), E
= BB
->end(); I
!=E
;
704 printType(I
->getType());
705 for (unsigned i
= 0; i
< I
->getNumOperands(); ++i
)
706 printType(I
->getOperand(i
)->getType());
713 // printConstant - Print out a constant pool entry...
714 void CppWriter::printConstant(const Constant
*CV
) {
715 // First, if the constant is actually a GlobalValue (variable or function)
716 // or its already in the constant list then we've printed it already and we
718 if (isa
<GlobalValue
>(CV
) || ValueNames
.find(CV
) != ValueNames
.end())
721 std::string
constName(getCppName(CV
));
722 std::string
typeName(getCppName(CV
->getType()));
724 if (isa
<GlobalValue
>(CV
)) {
725 // Skip variables and functions, we emit them elsewhere
729 if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CV
)) {
730 std::string constValue
= CI
->getValue().toString(10, true);
731 Out
<< "ConstantInt* " << constName
732 << " = ConstantInt::get(mod->getContext(), APInt("
733 << cast
<IntegerType
>(CI
->getType())->getBitWidth()
734 << ", StringRef(\"" << constValue
<< "\"), 10));";
735 } else if (isa
<ConstantAggregateZero
>(CV
)) {
736 Out
<< "ConstantAggregateZero* " << constName
737 << " = ConstantAggregateZero::get(" << typeName
<< ");";
738 } else if (isa
<ConstantPointerNull
>(CV
)) {
739 Out
<< "ConstantPointerNull* " << constName
740 << " = ConstantPointerNull::get(" << typeName
<< ");";
741 } else if (const ConstantFP
*CFP
= dyn_cast
<ConstantFP
>(CV
)) {
742 Out
<< "ConstantFP* " << constName
<< " = ";
745 } else if (const ConstantArray
*CA
= dyn_cast
<ConstantArray
>(CV
)) {
746 if (CA
->isString() &&
747 CA
->getType()->getElementType() ==
748 Type::getInt8Ty(CA
->getContext())) {
749 Out
<< "Constant* " << constName
<<
750 " = ConstantArray::get(mod->getContext(), \"";
751 std::string tmp
= CA
->getAsString();
752 bool nullTerminate
= false;
753 if (tmp
[tmp
.length()-1] == 0) {
754 tmp
.erase(tmp
.length()-1);
755 nullTerminate
= true;
757 printEscapedString(tmp
);
758 // Determine if we want null termination or not.
760 Out
<< "\", true"; // Indicate that the null terminator should be
763 Out
<< "\", false";// No null terminator
766 Out
<< "std::vector<Constant*> " << constName
<< "_elems;";
768 unsigned N
= CA
->getNumOperands();
769 for (unsigned i
= 0; i
< N
; ++i
) {
770 printConstant(CA
->getOperand(i
)); // recurse to print operands
771 Out
<< constName
<< "_elems.push_back("
772 << getCppName(CA
->getOperand(i
)) << ");";
775 Out
<< "Constant* " << constName
<< " = ConstantArray::get("
776 << typeName
<< ", " << constName
<< "_elems);";
778 } else if (const ConstantStruct
*CS
= dyn_cast
<ConstantStruct
>(CV
)) {
779 Out
<< "std::vector<Constant*> " << constName
<< "_fields;";
781 unsigned N
= CS
->getNumOperands();
782 for (unsigned i
= 0; i
< N
; i
++) {
783 printConstant(CS
->getOperand(i
));
784 Out
<< constName
<< "_fields.push_back("
785 << getCppName(CS
->getOperand(i
)) << ");";
788 Out
<< "Constant* " << constName
<< " = ConstantStruct::get("
789 << typeName
<< ", " << constName
<< "_fields);";
790 } else if (const ConstantVector
*CP
= dyn_cast
<ConstantVector
>(CV
)) {
791 Out
<< "std::vector<Constant*> " << constName
<< "_elems;";
793 unsigned N
= CP
->getNumOperands();
794 for (unsigned i
= 0; i
< N
; ++i
) {
795 printConstant(CP
->getOperand(i
));
796 Out
<< constName
<< "_elems.push_back("
797 << getCppName(CP
->getOperand(i
)) << ");";
800 Out
<< "Constant* " << constName
<< " = ConstantVector::get("
801 << typeName
<< ", " << constName
<< "_elems);";
802 } else if (isa
<UndefValue
>(CV
)) {
803 Out
<< "UndefValue* " << constName
<< " = UndefValue::get("
805 } else if (const ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(CV
)) {
806 if (CE
->getOpcode() == Instruction::GetElementPtr
) {
807 Out
<< "std::vector<Constant*> " << constName
<< "_indices;";
809 printConstant(CE
->getOperand(0));
810 for (unsigned i
= 1; i
< CE
->getNumOperands(); ++i
) {
811 printConstant(CE
->getOperand(i
));
812 Out
<< constName
<< "_indices.push_back("
813 << getCppName(CE
->getOperand(i
)) << ");";
816 Out
<< "Constant* " << constName
817 << " = ConstantExpr::getGetElementPtr("
818 << getCppName(CE
->getOperand(0)) << ", "
819 << "&" << constName
<< "_indices[0], "
820 << constName
<< "_indices.size()"
822 } else if (CE
->isCast()) {
823 printConstant(CE
->getOperand(0));
824 Out
<< "Constant* " << constName
<< " = ConstantExpr::getCast(";
825 switch (CE
->getOpcode()) {
826 default: llvm_unreachable("Invalid cast opcode");
827 case Instruction::Trunc
: Out
<< "Instruction::Trunc"; break;
828 case Instruction::ZExt
: Out
<< "Instruction::ZExt"; break;
829 case Instruction::SExt
: Out
<< "Instruction::SExt"; break;
830 case Instruction::FPTrunc
: Out
<< "Instruction::FPTrunc"; break;
831 case Instruction::FPExt
: Out
<< "Instruction::FPExt"; break;
832 case Instruction::FPToUI
: Out
<< "Instruction::FPToUI"; break;
833 case Instruction::FPToSI
: Out
<< "Instruction::FPToSI"; break;
834 case Instruction::UIToFP
: Out
<< "Instruction::UIToFP"; break;
835 case Instruction::SIToFP
: Out
<< "Instruction::SIToFP"; break;
836 case Instruction::PtrToInt
: Out
<< "Instruction::PtrToInt"; break;
837 case Instruction::IntToPtr
: Out
<< "Instruction::IntToPtr"; break;
838 case Instruction::BitCast
: Out
<< "Instruction::BitCast"; break;
840 Out
<< ", " << getCppName(CE
->getOperand(0)) << ", "
841 << getCppName(CE
->getType()) << ");";
843 unsigned N
= CE
->getNumOperands();
844 for (unsigned i
= 0; i
< N
; ++i
) {
845 printConstant(CE
->getOperand(i
));
847 Out
<< "Constant* " << constName
<< " = ConstantExpr::";
848 switch (CE
->getOpcode()) {
849 case Instruction::Add
: Out
<< "getAdd("; break;
850 case Instruction::FAdd
: Out
<< "getFAdd("; break;
851 case Instruction::Sub
: Out
<< "getSub("; break;
852 case Instruction::FSub
: Out
<< "getFSub("; break;
853 case Instruction::Mul
: Out
<< "getMul("; break;
854 case Instruction::FMul
: Out
<< "getFMul("; break;
855 case Instruction::UDiv
: Out
<< "getUDiv("; break;
856 case Instruction::SDiv
: Out
<< "getSDiv("; break;
857 case Instruction::FDiv
: Out
<< "getFDiv("; break;
858 case Instruction::URem
: Out
<< "getURem("; break;
859 case Instruction::SRem
: Out
<< "getSRem("; break;
860 case Instruction::FRem
: Out
<< "getFRem("; break;
861 case Instruction::And
: Out
<< "getAnd("; break;
862 case Instruction::Or
: Out
<< "getOr("; break;
863 case Instruction::Xor
: Out
<< "getXor("; break;
864 case Instruction::ICmp
:
865 Out
<< "getICmp(ICmpInst::ICMP_";
866 switch (CE
->getPredicate()) {
867 case ICmpInst::ICMP_EQ
: Out
<< "EQ"; break;
868 case ICmpInst::ICMP_NE
: Out
<< "NE"; break;
869 case ICmpInst::ICMP_SLT
: Out
<< "SLT"; break;
870 case ICmpInst::ICMP_ULT
: Out
<< "ULT"; break;
871 case ICmpInst::ICMP_SGT
: Out
<< "SGT"; break;
872 case ICmpInst::ICMP_UGT
: Out
<< "UGT"; break;
873 case ICmpInst::ICMP_SLE
: Out
<< "SLE"; break;
874 case ICmpInst::ICMP_ULE
: Out
<< "ULE"; break;
875 case ICmpInst::ICMP_SGE
: Out
<< "SGE"; break;
876 case ICmpInst::ICMP_UGE
: Out
<< "UGE"; break;
877 default: error("Invalid ICmp Predicate");
880 case Instruction::FCmp
:
881 Out
<< "getFCmp(FCmpInst::FCMP_";
882 switch (CE
->getPredicate()) {
883 case FCmpInst::FCMP_FALSE
: Out
<< "FALSE"; break;
884 case FCmpInst::FCMP_ORD
: Out
<< "ORD"; break;
885 case FCmpInst::FCMP_UNO
: Out
<< "UNO"; break;
886 case FCmpInst::FCMP_OEQ
: Out
<< "OEQ"; break;
887 case FCmpInst::FCMP_UEQ
: Out
<< "UEQ"; break;
888 case FCmpInst::FCMP_ONE
: Out
<< "ONE"; break;
889 case FCmpInst::FCMP_UNE
: Out
<< "UNE"; break;
890 case FCmpInst::FCMP_OLT
: Out
<< "OLT"; break;
891 case FCmpInst::FCMP_ULT
: Out
<< "ULT"; break;
892 case FCmpInst::FCMP_OGT
: Out
<< "OGT"; break;
893 case FCmpInst::FCMP_UGT
: Out
<< "UGT"; break;
894 case FCmpInst::FCMP_OLE
: Out
<< "OLE"; break;
895 case FCmpInst::FCMP_ULE
: Out
<< "ULE"; break;
896 case FCmpInst::FCMP_OGE
: Out
<< "OGE"; break;
897 case FCmpInst::FCMP_UGE
: Out
<< "UGE"; break;
898 case FCmpInst::FCMP_TRUE
: Out
<< "TRUE"; break;
899 default: error("Invalid FCmp Predicate");
902 case Instruction::Shl
: Out
<< "getShl("; break;
903 case Instruction::LShr
: Out
<< "getLShr("; break;
904 case Instruction::AShr
: Out
<< "getAShr("; break;
905 case Instruction::Select
: Out
<< "getSelect("; break;
906 case Instruction::ExtractElement
: Out
<< "getExtractElement("; break;
907 case Instruction::InsertElement
: Out
<< "getInsertElement("; break;
908 case Instruction::ShuffleVector
: Out
<< "getShuffleVector("; break;
910 error("Invalid constant expression");
913 Out
<< getCppName(CE
->getOperand(0));
914 for (unsigned i
= 1; i
< CE
->getNumOperands(); ++i
)
915 Out
<< ", " << getCppName(CE
->getOperand(i
));
918 } else if (const BlockAddress
*BA
= dyn_cast
<BlockAddress
>(CV
)) {
919 Out
<< "Constant* " << constName
<< " = ";
920 Out
<< "BlockAddress::get(" << getOpName(BA
->getBasicBlock()) << ");";
922 error("Bad Constant");
923 Out
<< "Constant* " << constName
<< " = 0; ";
928 void CppWriter::printConstants(const Module
* M
) {
929 // Traverse all the global variables looking for constant initializers
930 for (Module::const_global_iterator I
= TheModule
->global_begin(),
931 E
= TheModule
->global_end(); I
!= E
; ++I
)
932 if (I
->hasInitializer())
933 printConstant(I
->getInitializer());
935 // Traverse the LLVM functions looking for constants
936 for (Module::const_iterator FI
= TheModule
->begin(), FE
= TheModule
->end();
938 // Add all of the basic blocks and instructions
939 for (Function::const_iterator BB
= FI
->begin(),
940 E
= FI
->end(); BB
!= E
; ++BB
) {
941 for (BasicBlock::const_iterator I
= BB
->begin(), E
= BB
->end(); I
!=E
;
943 for (unsigned i
= 0; i
< I
->getNumOperands(); ++i
) {
944 if (Constant
* C
= dyn_cast
<Constant
>(I
->getOperand(i
))) {
953 void CppWriter::printVariableUses(const GlobalVariable
*GV
) {
954 nl(Out
) << "// Type Definitions";
956 printType(GV
->getType());
957 if (GV
->hasInitializer()) {
958 const Constant
*Init
= GV
->getInitializer();
959 printType(Init
->getType());
960 if (const Function
*F
= dyn_cast
<Function
>(Init
)) {
961 nl(Out
)<< "/ Function Declarations"; nl(Out
);
962 printFunctionHead(F
);
963 } else if (const GlobalVariable
* gv
= dyn_cast
<GlobalVariable
>(Init
)) {
964 nl(Out
) << "// Global Variable Declarations"; nl(Out
);
965 printVariableHead(gv
);
967 nl(Out
) << "// Global Variable Definitions"; nl(Out
);
968 printVariableBody(gv
);
970 nl(Out
) << "// Constant Definitions"; nl(Out
);
976 void CppWriter::printVariableHead(const GlobalVariable
*GV
) {
977 nl(Out
) << "GlobalVariable* " << getCppName(GV
);
979 Out
<< " = mod->getGlobalVariable(mod->getContext(), ";
980 printEscapedString(GV
->getName());
981 Out
<< ", " << getCppName(GV
->getType()->getElementType()) << ",true)";
982 nl(Out
) << "if (!" << getCppName(GV
) << ") {";
983 in(); nl(Out
) << getCppName(GV
);
985 Out
<< " = new GlobalVariable(/*Module=*/*mod, ";
986 nl(Out
) << "/*Type=*/";
987 printCppName(GV
->getType()->getElementType());
989 nl(Out
) << "/*isConstant=*/" << (GV
->isConstant()?"true":"false");
991 nl(Out
) << "/*Linkage=*/";
992 printLinkageType(GV
->getLinkage());
994 nl(Out
) << "/*Initializer=*/0, ";
995 if (GV
->hasInitializer()) {
996 Out
<< "// has initializer, specified below";
998 nl(Out
) << "/*Name=*/\"";
999 printEscapedString(GV
->getName());
1003 if (GV
->hasSection()) {
1005 Out
<< "->setSection(\"";
1006 printEscapedString(GV
->getSection());
1010 if (GV
->getAlignment()) {
1012 Out
<< "->setAlignment(" << utostr(GV
->getAlignment()) << ");";
1015 if (GV
->getVisibility() != GlobalValue::DefaultVisibility
) {
1017 Out
<< "->setVisibility(";
1018 printVisibilityType(GV
->getVisibility());
1022 if (GV
->isThreadLocal()) {
1024 Out
<< "->setThreadLocal(true);";
1028 out(); Out
<< "}"; nl(Out
);
1032 void CppWriter::printVariableBody(const GlobalVariable
*GV
) {
1033 if (GV
->hasInitializer()) {
1035 Out
<< "->setInitializer(";
1036 Out
<< getCppName(GV
->getInitializer()) << ");";
1041 std::string
CppWriter::getOpName(Value
* V
) {
1042 if (!isa
<Instruction
>(V
) || DefinedValues
.find(V
) != DefinedValues
.end())
1043 return getCppName(V
);
1045 // See if its alread in the map of forward references, if so just return the
1046 // name we already set up for it
1047 ForwardRefMap::const_iterator I
= ForwardRefs
.find(V
);
1048 if (I
!= ForwardRefs
.end())
1051 // This is a new forward reference. Generate a unique name for it
1052 std::string
result(std::string("fwdref_") + utostr(uniqueNum
++));
1054 // Yes, this is a hack. An Argument is the smallest instantiable value that
1055 // we can make as a placeholder for the real value. We'll replace these
1056 // Argument instances later.
1057 Out
<< "Argument* " << result
<< " = new Argument("
1058 << getCppName(V
->getType()) << ");";
1060 ForwardRefs
[V
] = result
;
1064 // printInstruction - This member is called for each Instruction in a function.
1065 void CppWriter::printInstruction(const Instruction
*I
,
1066 const std::string
& bbname
) {
1067 std::string
iName(getCppName(I
));
1069 // Before we emit this instruction, we need to take care of generating any
1070 // forward references. So, we get the names of all the operands in advance
1071 const unsigned Ops(I
->getNumOperands());
1072 std::string
* opNames
= new std::string
[Ops
];
1073 for (unsigned i
= 0; i
< Ops
; i
++)
1074 opNames
[i
] = getOpName(I
->getOperand(i
));
1076 switch (I
->getOpcode()) {
1078 error("Invalid instruction");
1081 case Instruction::Ret
: {
1082 const ReturnInst
* ret
= cast
<ReturnInst
>(I
);
1083 Out
<< "ReturnInst::Create(mod->getContext(), "
1084 << (ret
->getReturnValue() ? opNames
[0] + ", " : "") << bbname
<< ");";
1087 case Instruction::Br
: {
1088 const BranchInst
* br
= cast
<BranchInst
>(I
);
1089 Out
<< "BranchInst::Create(" ;
1090 if (br
->getNumOperands() == 3) {
1091 Out
<< opNames
[2] << ", "
1092 << opNames
[1] << ", "
1093 << opNames
[0] << ", ";
1095 } else if (br
->getNumOperands() == 1) {
1096 Out
<< opNames
[0] << ", ";
1098 error("Branch with 2 operands?");
1100 Out
<< bbname
<< ");";
1103 case Instruction::Switch
: {
1104 const SwitchInst
*SI
= cast
<SwitchInst
>(I
);
1105 Out
<< "SwitchInst* " << iName
<< " = SwitchInst::Create("
1106 << opNames
[0] << ", "
1107 << opNames
[1] << ", "
1108 << SI
->getNumCases() << ", " << bbname
<< ");";
1110 for (unsigned i
= 2; i
!= SI
->getNumOperands(); i
+= 2) {
1111 Out
<< iName
<< "->addCase("
1112 << opNames
[i
] << ", "
1113 << opNames
[i
+1] << ");";
1118 case Instruction::IndirectBr
: {
1119 const IndirectBrInst
*IBI
= cast
<IndirectBrInst
>(I
);
1120 Out
<< "IndirectBrInst *" << iName
<< " = IndirectBrInst::Create("
1121 << opNames
[0] << ", " << IBI
->getNumDestinations() << ");";
1123 for (unsigned i
= 1; i
!= IBI
->getNumOperands(); ++i
) {
1124 Out
<< iName
<< "->addDestination(" << opNames
[i
] << ");";
1129 case Instruction::Invoke
: {
1130 const InvokeInst
* inv
= cast
<InvokeInst
>(I
);
1131 Out
<< "std::vector<Value*> " << iName
<< "_params;";
1133 for (unsigned i
= 0; i
< inv
->getNumArgOperands(); ++i
) {
1134 Out
<< iName
<< "_params.push_back("
1135 << getOpName(inv
->getArgOperand(i
)) << ");";
1138 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1139 Out
<< "InvokeInst *" << iName
<< " = InvokeInst::Create("
1140 << getOpName(inv
->getCalledFunction()) << ", "
1141 << getOpName(inv
->getNormalDest()) << ", "
1142 << getOpName(inv
->getUnwindDest()) << ", "
1143 << iName
<< "_params.begin(), "
1144 << iName
<< "_params.end(), \"";
1145 printEscapedString(inv
->getName());
1146 Out
<< "\", " << bbname
<< ");";
1147 nl(Out
) << iName
<< "->setCallingConv(";
1148 printCallingConv(inv
->getCallingConv());
1150 printAttributes(inv
->getAttributes(), iName
);
1151 Out
<< iName
<< "->setAttributes(" << iName
<< "_PAL);";
1155 case Instruction::Unwind
: {
1156 Out
<< "new UnwindInst("
1160 case Instruction::Unreachable
: {
1161 Out
<< "new UnreachableInst("
1162 << "mod->getContext(), "
1166 case Instruction::Add
:
1167 case Instruction::FAdd
:
1168 case Instruction::Sub
:
1169 case Instruction::FSub
:
1170 case Instruction::Mul
:
1171 case Instruction::FMul
:
1172 case Instruction::UDiv
:
1173 case Instruction::SDiv
:
1174 case Instruction::FDiv
:
1175 case Instruction::URem
:
1176 case Instruction::SRem
:
1177 case Instruction::FRem
:
1178 case Instruction::And
:
1179 case Instruction::Or
:
1180 case Instruction::Xor
:
1181 case Instruction::Shl
:
1182 case Instruction::LShr
:
1183 case Instruction::AShr
:{
1184 Out
<< "BinaryOperator* " << iName
<< " = BinaryOperator::Create(";
1185 switch (I
->getOpcode()) {
1186 case Instruction::Add
: Out
<< "Instruction::Add"; break;
1187 case Instruction::FAdd
: Out
<< "Instruction::FAdd"; break;
1188 case Instruction::Sub
: Out
<< "Instruction::Sub"; break;
1189 case Instruction::FSub
: Out
<< "Instruction::FSub"; break;
1190 case Instruction::Mul
: Out
<< "Instruction::Mul"; break;
1191 case Instruction::FMul
: Out
<< "Instruction::FMul"; break;
1192 case Instruction::UDiv
:Out
<< "Instruction::UDiv"; break;
1193 case Instruction::SDiv
:Out
<< "Instruction::SDiv"; break;
1194 case Instruction::FDiv
:Out
<< "Instruction::FDiv"; break;
1195 case Instruction::URem
:Out
<< "Instruction::URem"; break;
1196 case Instruction::SRem
:Out
<< "Instruction::SRem"; break;
1197 case Instruction::FRem
:Out
<< "Instruction::FRem"; break;
1198 case Instruction::And
: Out
<< "Instruction::And"; break;
1199 case Instruction::Or
: Out
<< "Instruction::Or"; break;
1200 case Instruction::Xor
: Out
<< "Instruction::Xor"; break;
1201 case Instruction::Shl
: Out
<< "Instruction::Shl"; break;
1202 case Instruction::LShr
:Out
<< "Instruction::LShr"; break;
1203 case Instruction::AShr
:Out
<< "Instruction::AShr"; break;
1204 default: Out
<< "Instruction::BadOpCode"; break;
1206 Out
<< ", " << opNames
[0] << ", " << opNames
[1] << ", \"";
1207 printEscapedString(I
->getName());
1208 Out
<< "\", " << bbname
<< ");";
1211 case Instruction::FCmp
: {
1212 Out
<< "FCmpInst* " << iName
<< " = new FCmpInst(*" << bbname
<< ", ";
1213 switch (cast
<FCmpInst
>(I
)->getPredicate()) {
1214 case FCmpInst::FCMP_FALSE
: Out
<< "FCmpInst::FCMP_FALSE"; break;
1215 case FCmpInst::FCMP_OEQ
: Out
<< "FCmpInst::FCMP_OEQ"; break;
1216 case FCmpInst::FCMP_OGT
: Out
<< "FCmpInst::FCMP_OGT"; break;
1217 case FCmpInst::FCMP_OGE
: Out
<< "FCmpInst::FCMP_OGE"; break;
1218 case FCmpInst::FCMP_OLT
: Out
<< "FCmpInst::FCMP_OLT"; break;
1219 case FCmpInst::FCMP_OLE
: Out
<< "FCmpInst::FCMP_OLE"; break;
1220 case FCmpInst::FCMP_ONE
: Out
<< "FCmpInst::FCMP_ONE"; break;
1221 case FCmpInst::FCMP_ORD
: Out
<< "FCmpInst::FCMP_ORD"; break;
1222 case FCmpInst::FCMP_UNO
: Out
<< "FCmpInst::FCMP_UNO"; break;
1223 case FCmpInst::FCMP_UEQ
: Out
<< "FCmpInst::FCMP_UEQ"; break;
1224 case FCmpInst::FCMP_UGT
: Out
<< "FCmpInst::FCMP_UGT"; break;
1225 case FCmpInst::FCMP_UGE
: Out
<< "FCmpInst::FCMP_UGE"; break;
1226 case FCmpInst::FCMP_ULT
: Out
<< "FCmpInst::FCMP_ULT"; break;
1227 case FCmpInst::FCMP_ULE
: Out
<< "FCmpInst::FCMP_ULE"; break;
1228 case FCmpInst::FCMP_UNE
: Out
<< "FCmpInst::FCMP_UNE"; break;
1229 case FCmpInst::FCMP_TRUE
: Out
<< "FCmpInst::FCMP_TRUE"; break;
1230 default: Out
<< "FCmpInst::BAD_ICMP_PREDICATE"; break;
1232 Out
<< ", " << opNames
[0] << ", " << opNames
[1] << ", \"";
1233 printEscapedString(I
->getName());
1237 case Instruction::ICmp
: {
1238 Out
<< "ICmpInst* " << iName
<< " = new ICmpInst(*" << bbname
<< ", ";
1239 switch (cast
<ICmpInst
>(I
)->getPredicate()) {
1240 case ICmpInst::ICMP_EQ
: Out
<< "ICmpInst::ICMP_EQ"; break;
1241 case ICmpInst::ICMP_NE
: Out
<< "ICmpInst::ICMP_NE"; break;
1242 case ICmpInst::ICMP_ULE
: Out
<< "ICmpInst::ICMP_ULE"; break;
1243 case ICmpInst::ICMP_SLE
: Out
<< "ICmpInst::ICMP_SLE"; break;
1244 case ICmpInst::ICMP_UGE
: Out
<< "ICmpInst::ICMP_UGE"; break;
1245 case ICmpInst::ICMP_SGE
: Out
<< "ICmpInst::ICMP_SGE"; break;
1246 case ICmpInst::ICMP_ULT
: Out
<< "ICmpInst::ICMP_ULT"; break;
1247 case ICmpInst::ICMP_SLT
: Out
<< "ICmpInst::ICMP_SLT"; break;
1248 case ICmpInst::ICMP_UGT
: Out
<< "ICmpInst::ICMP_UGT"; break;
1249 case ICmpInst::ICMP_SGT
: Out
<< "ICmpInst::ICMP_SGT"; break;
1250 default: Out
<< "ICmpInst::BAD_ICMP_PREDICATE"; break;
1252 Out
<< ", " << opNames
[0] << ", " << opNames
[1] << ", \"";
1253 printEscapedString(I
->getName());
1257 case Instruction::Alloca
: {
1258 const AllocaInst
* allocaI
= cast
<AllocaInst
>(I
);
1259 Out
<< "AllocaInst* " << iName
<< " = new AllocaInst("
1260 << getCppName(allocaI
->getAllocatedType()) << ", ";
1261 if (allocaI
->isArrayAllocation())
1262 Out
<< opNames
[0] << ", ";
1264 printEscapedString(allocaI
->getName());
1265 Out
<< "\", " << bbname
<< ");";
1266 if (allocaI
->getAlignment())
1267 nl(Out
) << iName
<< "->setAlignment("
1268 << allocaI
->getAlignment() << ");";
1271 case Instruction::Load
: {
1272 const LoadInst
* load
= cast
<LoadInst
>(I
);
1273 Out
<< "LoadInst* " << iName
<< " = new LoadInst("
1274 << opNames
[0] << ", \"";
1275 printEscapedString(load
->getName());
1276 Out
<< "\", " << (load
->isVolatile() ? "true" : "false" )
1277 << ", " << bbname
<< ");";
1280 case Instruction::Store
: {
1281 const StoreInst
* store
= cast
<StoreInst
>(I
);
1282 Out
<< " new StoreInst("
1283 << opNames
[0] << ", "
1284 << opNames
[1] << ", "
1285 << (store
->isVolatile() ? "true" : "false")
1286 << ", " << bbname
<< ");";
1289 case Instruction::GetElementPtr
: {
1290 const GetElementPtrInst
* gep
= cast
<GetElementPtrInst
>(I
);
1291 if (gep
->getNumOperands() <= 2) {
1292 Out
<< "GetElementPtrInst* " << iName
<< " = GetElementPtrInst::Create("
1294 if (gep
->getNumOperands() == 2)
1295 Out
<< ", " << opNames
[1];
1297 Out
<< "std::vector<Value*> " << iName
<< "_indices;";
1299 for (unsigned i
= 1; i
< gep
->getNumOperands(); ++i
) {
1300 Out
<< iName
<< "_indices.push_back("
1301 << opNames
[i
] << ");";
1304 Out
<< "Instruction* " << iName
<< " = GetElementPtrInst::Create("
1305 << opNames
[0] << ", " << iName
<< "_indices.begin(), "
1306 << iName
<< "_indices.end()";
1309 printEscapedString(gep
->getName());
1310 Out
<< "\", " << bbname
<< ");";
1313 case Instruction::PHI
: {
1314 const PHINode
* phi
= cast
<PHINode
>(I
);
1316 Out
<< "PHINode* " << iName
<< " = PHINode::Create("
1317 << getCppName(phi
->getType()) << ", "
1318 << phi
->getNumIncomingValues() << ", \"";
1319 printEscapedString(phi
->getName());
1320 Out
<< "\", " << bbname
<< ");";
1322 for (unsigned i
= 0; i
< phi
->getNumIncomingValues(); ++i
) {
1323 Out
<< iName
<< "->addIncoming("
1324 << opNames
[PHINode::getOperandNumForIncomingValue(i
)] << ", "
1325 << getOpName(phi
->getIncomingBlock(i
)) << ");";
1330 case Instruction::Trunc
:
1331 case Instruction::ZExt
:
1332 case Instruction::SExt
:
1333 case Instruction::FPTrunc
:
1334 case Instruction::FPExt
:
1335 case Instruction::FPToUI
:
1336 case Instruction::FPToSI
:
1337 case Instruction::UIToFP
:
1338 case Instruction::SIToFP
:
1339 case Instruction::PtrToInt
:
1340 case Instruction::IntToPtr
:
1341 case Instruction::BitCast
: {
1342 const CastInst
* cst
= cast
<CastInst
>(I
);
1343 Out
<< "CastInst* " << iName
<< " = new ";
1344 switch (I
->getOpcode()) {
1345 case Instruction::Trunc
: Out
<< "TruncInst"; break;
1346 case Instruction::ZExt
: Out
<< "ZExtInst"; break;
1347 case Instruction::SExt
: Out
<< "SExtInst"; break;
1348 case Instruction::FPTrunc
: Out
<< "FPTruncInst"; break;
1349 case Instruction::FPExt
: Out
<< "FPExtInst"; break;
1350 case Instruction::FPToUI
: Out
<< "FPToUIInst"; break;
1351 case Instruction::FPToSI
: Out
<< "FPToSIInst"; break;
1352 case Instruction::UIToFP
: Out
<< "UIToFPInst"; break;
1353 case Instruction::SIToFP
: Out
<< "SIToFPInst"; break;
1354 case Instruction::PtrToInt
: Out
<< "PtrToIntInst"; break;
1355 case Instruction::IntToPtr
: Out
<< "IntToPtrInst"; break;
1356 case Instruction::BitCast
: Out
<< "BitCastInst"; break;
1357 default: assert(!"Unreachable"); break;
1359 Out
<< "(" << opNames
[0] << ", "
1360 << getCppName(cst
->getType()) << ", \"";
1361 printEscapedString(cst
->getName());
1362 Out
<< "\", " << bbname
<< ");";
1365 case Instruction::Call
: {
1366 const CallInst
* call
= cast
<CallInst
>(I
);
1367 if (const InlineAsm
* ila
= dyn_cast
<InlineAsm
>(call
->getCalledValue())) {
1368 Out
<< "InlineAsm* " << getCppName(ila
) << " = InlineAsm::get("
1369 << getCppName(ila
->getFunctionType()) << ", \""
1370 << ila
->getAsmString() << "\", \""
1371 << ila
->getConstraintString() << "\","
1372 << (ila
->hasSideEffects() ? "true" : "false") << ");";
1375 if (call
->getNumArgOperands() > 1) {
1376 Out
<< "std::vector<Value*> " << iName
<< "_params;";
1378 for (unsigned i
= 0; i
< call
->getNumArgOperands(); ++i
) {
1379 Out
<< iName
<< "_params.push_back(" << opNames
[i
] << ");";
1382 Out
<< "CallInst* " << iName
<< " = CallInst::Create("
1383 << opNames
[call
->getNumArgOperands()] << ", "
1384 << iName
<< "_params.begin(), "
1385 << iName
<< "_params.end(), \"";
1386 } else if (call
->getNumArgOperands() == 1) {
1387 Out
<< "CallInst* " << iName
<< " = CallInst::Create("
1388 << opNames
[call
->getNumArgOperands()] << ", " << opNames
[0] << ", \"";
1390 Out
<< "CallInst* " << iName
<< " = CallInst::Create("
1391 << opNames
[call
->getNumArgOperands()] << ", \"";
1393 printEscapedString(call
->getName());
1394 Out
<< "\", " << bbname
<< ");";
1395 nl(Out
) << iName
<< "->setCallingConv(";
1396 printCallingConv(call
->getCallingConv());
1398 nl(Out
) << iName
<< "->setTailCall("
1399 << (call
->isTailCall() ? "true" : "false");
1402 printAttributes(call
->getAttributes(), iName
);
1403 Out
<< iName
<< "->setAttributes(" << iName
<< "_PAL);";
1407 case Instruction::Select
: {
1408 const SelectInst
* sel
= cast
<SelectInst
>(I
);
1409 Out
<< "SelectInst* " << getCppName(sel
) << " = SelectInst::Create(";
1410 Out
<< opNames
[0] << ", " << opNames
[1] << ", " << opNames
[2] << ", \"";
1411 printEscapedString(sel
->getName());
1412 Out
<< "\", " << bbname
<< ");";
1415 case Instruction::UserOp1
:
1417 case Instruction::UserOp2
: {
1418 /// FIXME: What should be done here?
1421 case Instruction::VAArg
: {
1422 const VAArgInst
* va
= cast
<VAArgInst
>(I
);
1423 Out
<< "VAArgInst* " << getCppName(va
) << " = new VAArgInst("
1424 << opNames
[0] << ", " << getCppName(va
->getType()) << ", \"";
1425 printEscapedString(va
->getName());
1426 Out
<< "\", " << bbname
<< ");";
1429 case Instruction::ExtractElement
: {
1430 const ExtractElementInst
* eei
= cast
<ExtractElementInst
>(I
);
1431 Out
<< "ExtractElementInst* " << getCppName(eei
)
1432 << " = new ExtractElementInst(" << opNames
[0]
1433 << ", " << opNames
[1] << ", \"";
1434 printEscapedString(eei
->getName());
1435 Out
<< "\", " << bbname
<< ");";
1438 case Instruction::InsertElement
: {
1439 const InsertElementInst
* iei
= cast
<InsertElementInst
>(I
);
1440 Out
<< "InsertElementInst* " << getCppName(iei
)
1441 << " = InsertElementInst::Create(" << opNames
[0]
1442 << ", " << opNames
[1] << ", " << opNames
[2] << ", \"";
1443 printEscapedString(iei
->getName());
1444 Out
<< "\", " << bbname
<< ");";
1447 case Instruction::ShuffleVector
: {
1448 const ShuffleVectorInst
* svi
= cast
<ShuffleVectorInst
>(I
);
1449 Out
<< "ShuffleVectorInst* " << getCppName(svi
)
1450 << " = new ShuffleVectorInst(" << opNames
[0]
1451 << ", " << opNames
[1] << ", " << opNames
[2] << ", \"";
1452 printEscapedString(svi
->getName());
1453 Out
<< "\", " << bbname
<< ");";
1456 case Instruction::ExtractValue
: {
1457 const ExtractValueInst
*evi
= cast
<ExtractValueInst
>(I
);
1458 Out
<< "std::vector<unsigned> " << iName
<< "_indices;";
1460 for (unsigned i
= 0; i
< evi
->getNumIndices(); ++i
) {
1461 Out
<< iName
<< "_indices.push_back("
1462 << evi
->idx_begin()[i
] << ");";
1465 Out
<< "ExtractValueInst* " << getCppName(evi
)
1466 << " = ExtractValueInst::Create(" << opNames
[0]
1468 << iName
<< "_indices.begin(), " << iName
<< "_indices.end(), \"";
1469 printEscapedString(evi
->getName());
1470 Out
<< "\", " << bbname
<< ");";
1473 case Instruction::InsertValue
: {
1474 const InsertValueInst
*ivi
= cast
<InsertValueInst
>(I
);
1475 Out
<< "std::vector<unsigned> " << iName
<< "_indices;";
1477 for (unsigned i
= 0; i
< ivi
->getNumIndices(); ++i
) {
1478 Out
<< iName
<< "_indices.push_back("
1479 << ivi
->idx_begin()[i
] << ");";
1482 Out
<< "InsertValueInst* " << getCppName(ivi
)
1483 << " = InsertValueInst::Create(" << opNames
[0]
1484 << ", " << opNames
[1] << ", "
1485 << iName
<< "_indices.begin(), " << iName
<< "_indices.end(), \"";
1486 printEscapedString(ivi
->getName());
1487 Out
<< "\", " << bbname
<< ");";
1491 DefinedValues
.insert(I
);
1496 // Print out the types, constants and declarations needed by one function
1497 void CppWriter::printFunctionUses(const Function
* F
) {
1498 nl(Out
) << "// Type Definitions"; nl(Out
);
1500 // Print the function's return type
1501 printType(F
->getReturnType());
1503 // Print the function's function type
1504 printType(F
->getFunctionType());
1506 // Print the types of each of the function's arguments
1507 for (Function::const_arg_iterator AI
= F
->arg_begin(), AE
= F
->arg_end();
1509 printType(AI
->getType());
1513 // Print type definitions for every type referenced by an instruction and
1514 // make a note of any global values or constants that are referenced
1515 SmallPtrSet
<GlobalValue
*,64> gvs
;
1516 SmallPtrSet
<Constant
*,64> consts
;
1517 for (Function::const_iterator BB
= F
->begin(), BE
= F
->end();
1519 for (BasicBlock::const_iterator I
= BB
->begin(), E
= BB
->end();
1521 // Print the type of the instruction itself
1522 printType(I
->getType());
1524 // Print the type of each of the instruction's operands
1525 for (unsigned i
= 0; i
< I
->getNumOperands(); ++i
) {
1526 Value
* operand
= I
->getOperand(i
);
1527 printType(operand
->getType());
1529 // If the operand references a GVal or Constant, make a note of it
1530 if (GlobalValue
* GV
= dyn_cast
<GlobalValue
>(operand
)) {
1532 if (GenerationType
!= GenFunction
)
1533 if (GlobalVariable
*GVar
= dyn_cast
<GlobalVariable
>(GV
))
1534 if (GVar
->hasInitializer())
1535 consts
.insert(GVar
->getInitializer());
1536 } else if (Constant
* C
= dyn_cast
<Constant
>(operand
)) {
1538 for (unsigned j
= 0; j
< C
->getNumOperands(); ++j
) {
1539 // If the operand references a GVal or Constant, make a note of it
1540 Value
* operand
= C
->getOperand(j
);
1541 printType(operand
->getType());
1542 if (GlobalValue
* GV
= dyn_cast
<GlobalValue
>(operand
)) {
1544 if (GenerationType
!= GenFunction
)
1545 if (GlobalVariable
*GVar
= dyn_cast
<GlobalVariable
>(GV
))
1546 if (GVar
->hasInitializer())
1547 consts
.insert(GVar
->getInitializer());
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 if (GenerationType
!= GenFunction
) {
1584 nl(Out
) << "// Global Variable Definitions"; nl(Out
);
1585 for (SmallPtrSet
<GlobalValue
*,64>::iterator I
= gvs
.begin(), E
= gvs
.end();
1587 if (GlobalVariable
* GV
= dyn_cast
<GlobalVariable
>(*I
))
1588 printVariableBody(GV
);
1593 void CppWriter::printFunctionHead(const Function
* F
) {
1594 nl(Out
) << "Function* " << getCppName(F
);
1596 Out
<< " = mod->getFunction(\"";
1597 printEscapedString(F
->getName());
1598 Out
<< "\", " << getCppName(F
->getFunctionType()) << ");";
1599 nl(Out
) << "if (!" << getCppName(F
) << ") {";
1600 nl(Out
) << getCppName(F
);
1602 Out
<< " = Function::Create(";
1603 nl(Out
,1) << "/*Type=*/" << getCppName(F
->getFunctionType()) << ",";
1604 nl(Out
) << "/*Linkage=*/";
1605 printLinkageType(F
->getLinkage());
1607 nl(Out
) << "/*Name=*/\"";
1608 printEscapedString(F
->getName());
1609 Out
<< "\", mod); " << (F
->isDeclaration()? "// (external, no body)" : "");
1612 Out
<< "->setCallingConv(";
1613 printCallingConv(F
->getCallingConv());
1616 if (F
->hasSection()) {
1618 Out
<< "->setSection(\"" << F
->getSection() << "\");";
1621 if (F
->getAlignment()) {
1623 Out
<< "->setAlignment(" << F
->getAlignment() << ");";
1626 if (F
->getVisibility() != GlobalValue::DefaultVisibility
) {
1628 Out
<< "->setVisibility(";
1629 printVisibilityType(F
->getVisibility());
1635 Out
<< "->setGC(\"" << F
->getGC() << "\");";
1642 printAttributes(F
->getAttributes(), getCppName(F
));
1644 Out
<< "->setAttributes(" << getCppName(F
) << "_PAL);";
1648 void CppWriter::printFunctionBody(const Function
*F
) {
1649 if (F
->isDeclaration())
1650 return; // external functions have no bodies.
1652 // Clear the DefinedValues and ForwardRefs maps because we can't have
1653 // cross-function forward refs
1654 ForwardRefs
.clear();
1655 DefinedValues
.clear();
1657 // Create all the argument values
1659 if (!F
->arg_empty()) {
1660 Out
<< "Function::arg_iterator args = " << getCppName(F
)
1661 << "->arg_begin();";
1664 for (Function::const_arg_iterator AI
= F
->arg_begin(), AE
= F
->arg_end();
1666 Out
<< "Value* " << getCppName(AI
) << " = args++;";
1668 if (AI
->hasName()) {
1669 Out
<< getCppName(AI
) << "->setName(\"" << AI
->getName() << "\");";
1675 // Create all the basic blocks
1677 for (Function::const_iterator BI
= F
->begin(), BE
= F
->end();
1679 std::string
bbname(getCppName(BI
));
1680 Out
<< "BasicBlock* " << bbname
<<
1681 " = BasicBlock::Create(mod->getContext(), \"";
1683 printEscapedString(BI
->getName());
1684 Out
<< "\"," << getCppName(BI
->getParent()) << ",0);";
1688 // Output all of its basic blocks... for the function
1689 for (Function::const_iterator BI
= F
->begin(), BE
= F
->end();
1691 std::string
bbname(getCppName(BI
));
1692 nl(Out
) << "// Block " << BI
->getName() << " (" << bbname
<< ")";
1695 // Output all of the instructions in the basic block...
1696 for (BasicBlock::const_iterator I
= BI
->begin(), E
= BI
->end();
1698 printInstruction(I
,bbname
);
1702 // Loop over the ForwardRefs and resolve them now that all instructions
1704 if (!ForwardRefs
.empty()) {
1705 nl(Out
) << "// Resolve Forward References";
1709 while (!ForwardRefs
.empty()) {
1710 ForwardRefMap::iterator I
= ForwardRefs
.begin();
1711 Out
<< I
->second
<< "->replaceAllUsesWith("
1712 << getCppName(I
->first
) << "); delete " << I
->second
<< ";";
1714 ForwardRefs
.erase(I
);
1718 void CppWriter::printInline(const std::string
& fname
,
1719 const std::string
& func
) {
1720 const Function
* F
= TheModule
->getFunction(func
);
1722 error(std::string("Function '") + func
+ "' not found in input module");
1725 if (F
->isDeclaration()) {
1726 error(std::string("Function '") + func
+ "' is external!");
1729 nl(Out
) << "BasicBlock* " << fname
<< "(Module* mod, Function *"
1731 unsigned arg_count
= 1;
1732 for (Function::const_arg_iterator AI
= F
->arg_begin(), AE
= F
->arg_end();
1734 Out
<< ", Value* arg_" << arg_count
;
1739 printFunctionUses(F
);
1740 printFunctionBody(F
);
1742 Out
<< "return " << getCppName(F
->begin()) << ";";
1747 void CppWriter::printModuleBody() {
1748 // Print out all the type definitions
1749 nl(Out
) << "// Type Definitions"; nl(Out
);
1750 printTypes(TheModule
);
1752 // Functions can call each other and global variables can reference them so
1753 // define all the functions first before emitting their function bodies.
1754 nl(Out
) << "// Function Declarations"; nl(Out
);
1755 for (Module::const_iterator I
= TheModule
->begin(), E
= TheModule
->end();
1757 printFunctionHead(I
);
1759 // Process the global variables declarations. We can't initialze them until
1760 // after the constants are printed so just print a header for each global
1761 nl(Out
) << "// Global Variable Declarations\n"; nl(Out
);
1762 for (Module::const_global_iterator I
= TheModule
->global_begin(),
1763 E
= TheModule
->global_end(); I
!= E
; ++I
) {
1764 printVariableHead(I
);
1767 // Print out all the constants definitions. Constants don't recurse except
1768 // through GlobalValues. All GlobalValues have been declared at this point
1769 // so we can proceed to generate the constants.
1770 nl(Out
) << "// Constant Definitions"; nl(Out
);
1771 printConstants(TheModule
);
1773 // Process the global variables definitions now that all the constants have
1774 // been emitted. These definitions just couple the gvars with their constant
1776 nl(Out
) << "// Global Variable Definitions"; nl(Out
);
1777 for (Module::const_global_iterator I
= TheModule
->global_begin(),
1778 E
= TheModule
->global_end(); I
!= E
; ++I
) {
1779 printVariableBody(I
);
1782 // Finally, we can safely put out all of the function bodies.
1783 nl(Out
) << "// Function Definitions"; nl(Out
);
1784 for (Module::const_iterator I
= TheModule
->begin(), E
= TheModule
->end();
1786 if (!I
->isDeclaration()) {
1787 nl(Out
) << "// Function: " << I
->getName() << " (" << getCppName(I
)
1791 printFunctionBody(I
);
1798 void CppWriter::printProgram(const std::string
& fname
,
1799 const std::string
& mName
) {
1800 Out
<< "#include <llvm/LLVMContext.h>\n";
1801 Out
<< "#include <llvm/Module.h>\n";
1802 Out
<< "#include <llvm/DerivedTypes.h>\n";
1803 Out
<< "#include <llvm/Constants.h>\n";
1804 Out
<< "#include <llvm/GlobalVariable.h>\n";
1805 Out
<< "#include <llvm/Function.h>\n";
1806 Out
<< "#include <llvm/CallingConv.h>\n";
1807 Out
<< "#include <llvm/BasicBlock.h>\n";
1808 Out
<< "#include <llvm/Instructions.h>\n";
1809 Out
<< "#include <llvm/InlineAsm.h>\n";
1810 Out
<< "#include <llvm/Support/FormattedStream.h>\n";
1811 Out
<< "#include <llvm/Support/MathExtras.h>\n";
1812 Out
<< "#include <llvm/Pass.h>\n";
1813 Out
<< "#include <llvm/PassManager.h>\n";
1814 Out
<< "#include <llvm/ADT/SmallVector.h>\n";
1815 Out
<< "#include <llvm/Analysis/Verifier.h>\n";
1816 Out
<< "#include <llvm/Assembly/PrintModulePass.h>\n";
1817 Out
<< "#include <algorithm>\n";
1818 Out
<< "using namespace llvm;\n\n";
1819 Out
<< "Module* " << fname
<< "();\n\n";
1820 Out
<< "int main(int argc, char**argv) {\n";
1821 Out
<< " Module* Mod = " << fname
<< "();\n";
1822 Out
<< " verifyModule(*Mod, PrintMessageAction);\n";
1823 Out
<< " PassManager PM;\n";
1824 Out
<< " PM.add(createPrintModulePass(&outs()));\n";
1825 Out
<< " PM.run(*Mod);\n";
1826 Out
<< " return 0;\n";
1828 printModule(fname
,mName
);
1831 void CppWriter::printModule(const std::string
& fname
,
1832 const std::string
& mName
) {
1833 nl(Out
) << "Module* " << fname
<< "() {";
1834 nl(Out
,1) << "// Module Construction";
1835 nl(Out
) << "Module* mod = new Module(\"";
1836 printEscapedString(mName
);
1837 Out
<< "\", getGlobalContext());";
1838 if (!TheModule
->getTargetTriple().empty()) {
1839 nl(Out
) << "mod->setDataLayout(\"" << TheModule
->getDataLayout() << "\");";
1841 if (!TheModule
->getTargetTriple().empty()) {
1842 nl(Out
) << "mod->setTargetTriple(\"" << TheModule
->getTargetTriple()
1846 if (!TheModule
->getModuleInlineAsm().empty()) {
1847 nl(Out
) << "mod->setModuleInlineAsm(\"";
1848 printEscapedString(TheModule
->getModuleInlineAsm());
1853 // Loop over the dependent libraries and emit them.
1854 Module::lib_iterator LI
= TheModule
->lib_begin();
1855 Module::lib_iterator LE
= TheModule
->lib_end();
1857 Out
<< "mod->addLibrary(\"" << *LI
<< "\");";
1862 nl(Out
) << "return mod;";
1867 void CppWriter::printContents(const std::string
& fname
,
1868 const std::string
& mName
) {
1869 Out
<< "\nModule* " << fname
<< "(Module *mod) {\n";
1870 Out
<< "\nmod->setModuleIdentifier(\"";
1871 printEscapedString(mName
);
1874 Out
<< "\nreturn mod;\n";
1878 void CppWriter::printFunction(const std::string
& fname
,
1879 const std::string
& funcName
) {
1880 const Function
* F
= TheModule
->getFunction(funcName
);
1882 error(std::string("Function '") + funcName
+ "' not found in input module");
1885 Out
<< "\nFunction* " << fname
<< "(Module *mod) {\n";
1886 printFunctionUses(F
);
1887 printFunctionHead(F
);
1888 printFunctionBody(F
);
1889 Out
<< "return " << getCppName(F
) << ";\n";
1893 void CppWriter::printFunctions() {
1894 const Module::FunctionListType
&funcs
= TheModule
->getFunctionList();
1895 Module::const_iterator I
= funcs
.begin();
1896 Module::const_iterator IE
= funcs
.end();
1898 for (; I
!= IE
; ++I
) {
1899 const Function
&func
= *I
;
1900 if (!func
.isDeclaration()) {
1901 std::string
name("define_");
1902 name
+= func
.getName();
1903 printFunction(name
, func
.getName());
1908 void CppWriter::printVariable(const std::string
& fname
,
1909 const std::string
& varName
) {
1910 const GlobalVariable
* GV
= TheModule
->getNamedGlobal(varName
);
1913 error(std::string("Variable '") + varName
+ "' not found in input module");
1916 Out
<< "\nGlobalVariable* " << fname
<< "(Module *mod) {\n";
1917 printVariableUses(GV
);
1918 printVariableHead(GV
);
1919 printVariableBody(GV
);
1920 Out
<< "return " << getCppName(GV
) << ";\n";
1924 void CppWriter::printType(const std::string
&fname
,
1925 const std::string
&typeName
) {
1926 const Type
* Ty
= TheModule
->getTypeByName(typeName
);
1928 error(std::string("Type '") + typeName
+ "' not found in input module");
1931 Out
<< "\nType* " << fname
<< "(Module *mod) {\n";
1933 Out
<< "return " << getCppName(Ty
) << ";\n";
1937 bool CppWriter::runOnModule(Module
&M
) {
1941 Out
<< "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1943 // Get the name of the function we're supposed to generate
1944 std::string fname
= FuncName
.getValue();
1946 // Get the name of the thing we are to generate
1947 std::string tgtname
= NameToGenerate
.getValue();
1948 if (GenerationType
== GenModule
||
1949 GenerationType
== GenContents
||
1950 GenerationType
== GenProgram
||
1951 GenerationType
== GenFunctions
) {
1952 if (tgtname
== "!bad!") {
1953 if (M
.getModuleIdentifier() == "-")
1954 tgtname
= "<stdin>";
1956 tgtname
= M
.getModuleIdentifier();
1958 } else if (tgtname
== "!bad!")
1959 error("You must use the -for option with -gen-{function,variable,type}");
1961 switch (WhatToGenerate(GenerationType
)) {
1964 fname
= "makeLLVMModule";
1965 printProgram(fname
,tgtname
);
1969 fname
= "makeLLVMModule";
1970 printModule(fname
,tgtname
);
1974 fname
= "makeLLVMModuleContents";
1975 printContents(fname
,tgtname
);
1979 fname
= "makeLLVMFunction";
1980 printFunction(fname
,tgtname
);
1987 fname
= "makeLLVMInline";
1988 printInline(fname
,tgtname
);
1992 fname
= "makeLLVMVariable";
1993 printVariable(fname
,tgtname
);
1997 fname
= "makeLLVMType";
1998 printType(fname
,tgtname
);
2001 error("Invalid generation option");
2007 char CppWriter::ID
= 0;
2009 //===----------------------------------------------------------------------===//
2010 // External Interface declaration
2011 //===----------------------------------------------------------------------===//
2013 bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase
&PM
,
2014 formatted_raw_ostream
&o
,
2015 CodeGenFileType FileType
,
2016 CodeGenOpt::Level OptLevel
,
2017 bool DisableVerify
) {
2018 if (FileType
!= TargetMachine::CGFT_AssemblyFile
) return true;
2019 PM
.add(new CppWriter(o
));