llvm.org GIT mirror llvm / 5027652
First step of implementing PR1538: move llvm2cpp logic to new 'target' git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@50189 91177308-0d34-0410-b5e6-96231b3b80d8 Anton Korobeynikov 11 years ago
6 changed file(s) with 2038 addition(s) and 5 deletion(s). Raw diff Collapse all Expand all
362362 [Build specific host targets: all,host-only,{target-name} (default=all)]),,
363363 enableval=all)
364364 case "$enableval" in
365 all) TARGETS_TO_BUILD="X86 Sparc PowerPC Alpha IA64 ARM Mips CellSPU CBackend MSIL" ;;
365 all) TARGETS_TO_BUILD="X86 Sparc PowerPC Alpha IA64 ARM Mips CellSPU CBackend MSIL CppBackend" ;;
366366 host-only)
367367 case "$llvm_cv_target_arch" in
368368 x86) TARGETS_TO_BUILD="X86" ;;
390390 spu) TARGETS_TO_BUILD="CellSPU $TARGETS_TO_BUILD" ;;
391391 cbe) TARGETS_TO_BUILD="CBackend $TARGETS_TO_BUILD" ;;
392392 msil) TARGETS_TO_BUILD="MSIL $TARGETS_TO_BUILD" ;;
393 cpp) TARGETS_TO_BUILD="CppBackend $TARGETS_TO_BUILD" ;;
393394 *) AC_MSG_ERROR([Unrecognized target $a_target]) ;;
394395 esac
395396 done
47424742 fi
47434743
47444744 case "$enableval" in
4745 all) TARGETS_TO_BUILD="X86 Sparc PowerPC Alpha IA64 ARM Mips CellSPU CBackend MSIL" ;;
4745 all) TARGETS_TO_BUILD="X86 Sparc PowerPC Alpha IA64 ARM Mips CellSPU CBackend MSIL CppBackend" ;;
47464746 host-only)
47474747 case "$llvm_cv_target_arch" in
47484748 x86) TARGETS_TO_BUILD="X86" ;;
47724772 spu) TARGETS_TO_BUILD="CellSPU $TARGETS_TO_BUILD" ;;
47734773 cbe) TARGETS_TO_BUILD="CBackend $TARGETS_TO_BUILD" ;;
47744774 msil) TARGETS_TO_BUILD="MSIL $TARGETS_TO_BUILD" ;;
4775 cpp) TARGETS_TO_BUILD="CppBackend $TARGETS_TO_BUILD" ;;
47754776 *) { { echo "$as_me:$LINENO: error: Unrecognized target $a_target" >&5
47764777 echo "$as_me: error: Unrecognized target $a_target" >&2;}
47774778 { (exit 1); exit 1; }; } ;;
0 //===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the writing of the LLVM IR as a set of C++ calls to the
10 // LLVM IR interface. The input module is assumed to be verified.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "CPPTargetMachine.h"
15 #include "llvm/CallingConv.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/InlineAsm.h"
19 #include "llvm/Instruction.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Pass.h"
23 #include "llvm/PassManager.h"
24 #include "llvm/TypeSymbolTable.h"
25 #include "llvm/Target/TargetMachineRegistry.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/CFG.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Config/config.h"
34 #include
35 #include
36 #include
37
38 using namespace llvm;
39
40 static cl::opt
41 FuncName("funcname", cl::desc("Specify the name of the generated function"),
42 cl::value_desc("function name"));
43
44 enum WhatToGenerate {
45 GenProgram,
46 GenModule,
47 GenContents,
48 GenFunction,
49 GenFunctions,
50 GenInline,
51 GenVariable,
52 GenType
53 };
54
55 static cl::opt GenerationType(cl::Optional,
56 cl::desc("Choose what kind of output to generate"),
57 cl::init(GenProgram),
58 cl::values(
59 clEnumValN(GenProgram, "gen-program", "Generate a complete program"),
60 clEnumValN(GenModule, "gen-module", "Generate a module definition"),
61 clEnumValN(GenContents, "gen-contents", "Generate contents of a module"),
62 clEnumValN(GenFunction, "gen-function", "Generate a function definition"),
63 clEnumValN(GenFunctions,"gen-functions", "Generate all function definitions"),
64 clEnumValN(GenInline, "gen-inline", "Generate an inline function"),
65 clEnumValN(GenVariable, "gen-variable", "Generate a variable definition"),
66 clEnumValN(GenType, "gen-type", "Generate a type definition"),
67 clEnumValEnd
68 )
69 );
70
71 static cl::opt NameToGenerate("for", cl::Optional,
72 cl::desc("Specify the name of the thing to generate"),
73 cl::init("!bad!"));
74
75 namespace {
76 // Register the target.
77 RegisterTarget X("cpp", " C++ backend");
78
79 typedef std::vector TypeList;
80 typedef std::map TypeMap;
81 typedef std::map ValueMap;
82 typedef std::set NameSet;
83 typedef std::set TypeSet;
84 typedef std::set ValueSet;
85 typedef std::map ForwardRefMap;
86
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 const char* progname;
91 std::ostream &Out;
92 const Module *TheModule;
93 uint64_t uniqueNum;
94 TypeMap TypeNames;
95 ValueMap ValueNames;
96 TypeMap UnresolvedTypes;
97 TypeList TypeStack;
98 NameSet UsedNames;
99 TypeSet DefinedTypes;
100 ValueSet DefinedValues;
101 ForwardRefMap ForwardRefs;
102 bool is_inline;
103
104 public:
105 static char ID;
106 explicit CppWriter(std::ostream &o) : ModulePass((intptr_t)&ID), Out(o) {}
107
108 virtual const char *getPassName() const { return "C++ backend"; }
109
110 bool runOnModule(Module &M);
111
112 bool doInitialization(Module &M) {
113 uniqueNum = 0;
114 is_inline = false;
115
116 TypeNames.clear();
117 ValueNames.clear();
118 UnresolvedTypes.clear();
119 TypeStack.clear();
120 UsedNames.clear();
121 DefinedTypes.clear();
122 DefinedValues.clear();
123 ForwardRefs.clear();
124
125 return false;
126 }
127
128 void printProgram(const std::string& fname, const std::string& modName );
129 void printModule(const std::string& fname, const std::string& modName );
130 void printContents(const std::string& fname, const std::string& modName );
131 void printFunction(const std::string& fname, const std::string& funcName );
132 void printFunctions();
133 void printInline(const std::string& fname, const std::string& funcName );
134 void printVariable(const std::string& fname, const std::string& varName );
135 void printType(const std::string& fname, const std::string& typeName );
136
137 void error(const std::string& msg);
138
139 private:
140 void printLinkageType(GlobalValue::LinkageTypes LT);
141 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
142 void printCallingConv(unsigned cc);
143 void printEscapedString(const std::string& str);
144 void printCFP(const ConstantFP* CFP);
145
146 std::string getCppName(const Type* val);
147 inline void printCppName(const Type* val);
148
149 std::string getCppName(const Value* val);
150 inline void printCppName(const Value* val);
151
152 void printParamAttrs(const PAListPtr &PAL, const std::string &name);
153 bool printTypeInternal(const Type* Ty);
154 inline void printType(const Type* Ty);
155 void printTypes(const Module* M);
156
157 void printConstant(const Constant *CPV);
158 void printConstants(const Module* M);
159
160 void printVariableUses(const GlobalVariable *GV);
161 void printVariableHead(const GlobalVariable *GV);
162 void printVariableBody(const GlobalVariable *GV);
163
164 void printFunctionUses(const Function *F);
165 void printFunctionHead(const Function *F);
166 void printFunctionBody(const Function *F);
167 void printInstruction(const Instruction *I, const std::string& bbname);
168 std::string getOpName(Value*);
169
170 void printModuleBody();
171 };
172
173 static unsigned indent_level = 0;
174 inline std::ostream& nl(std::ostream& Out, int delta = 0) {
175 Out << "\n";
176 if (delta >= 0 || indent_level >= unsigned(-delta))
177 indent_level += delta;
178 for (unsigned i = 0; i < indent_level; ++i)
179 Out << " ";
180 return Out;
181 }
182
183 inline void in() { indent_level++; }
184 inline void out() { if (indent_level >0) indent_level--; }
185
186 inline void
187 sanitize(std::string& str) {
188 for (size_t i = 0; i < str.length(); ++i)
189 if (!isalnum(str[i]) && str[i] != '_')
190 str[i] = '_';
191 }
192
193 inline std::string
194 getTypePrefix(const Type* Ty ) {
195 switch (Ty->getTypeID()) {
196 case Type::VoidTyID: return "void_";
197 case Type::IntegerTyID:
198 return std::string("int") + utostr(cast(Ty)->getBitWidth()) +
199 "_";
200 case Type::FloatTyID: return "float_";
201 case Type::DoubleTyID: return "double_";
202 case Type::LabelTyID: return "label_";
203 case Type::FunctionTyID: return "func_";
204 case Type::StructTyID: return "struct_";
205 case Type::ArrayTyID: return "array_";
206 case Type::PointerTyID: return "ptr_";
207 case Type::VectorTyID: return "packed_";
208 case Type::OpaqueTyID: return "opaque_";
209 default: return "other_";
210 }
211 return "unknown_";
212 }
213
214 // Looks up the type in the symbol table and returns a pointer to its name or
215 // a null pointer if it wasn't found. Note that this isn't the same as the
216 // Mode::getTypeName function which will return an empty string, not a null
217 // pointer if the name is not found.
218 inline const std::string*
219 findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
220 TypeSymbolTable::const_iterator TI = ST.begin();
221 TypeSymbolTable::const_iterator TE = ST.end();
222 for (;TI != TE; ++TI)
223 if (TI->second == Ty)
224 return &(TI->first);
225 return 0;
226 }
227
228 void CppWriter::error(const std::string& msg) {
229 std::cerr << progname << ": " << msg << "\n";
230 exit(2);
231 }
232
233 // printCFP - Print a floating point constant .. very carefully :)
234 // This makes sure that conversion to/from floating yields the same binary
235 // result so that we don't lose precision.
236 void CppWriter::printCFP(const ConstantFP *CFP) {
237 APFloat APF = APFloat(CFP->getValueAPF()); // copy
238 if (CFP->getType() == Type::FloatTy)
239 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
240 Out << "ConstantFP::get(";
241 if (CFP->getType() == Type::DoubleTy)
242 Out << "Type::DoubleTy, ";
243 else
244 Out << "Type::FloatTy, ";
245 Out << "APFloat(";
246 #if HAVE_PRINTF_A
247 char Buffer[100];
248 sprintf(Buffer, "%A", APF.convertToDouble());
249 if ((!strncmp(Buffer, "0x", 2) ||
250 !strncmp(Buffer, "-0x", 3) ||
251 !strncmp(Buffer, "+0x", 3)) &&
252 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
253 if (CFP->getType() == Type::DoubleTy)
254 Out << "BitsToDouble(" << Buffer << ")";
255 else
256 Out << "BitsToFloat((float)" << Buffer << ")";
257 Out << ")";
258 } else {
259 #endif
260 std::string StrVal = ftostr(CFP->getValueAPF());
261
262 while (StrVal[0] == ' ')
263 StrVal.erase(StrVal.begin());
264
265 // Check to make sure that the stringized number is not some string like
266 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
267 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
268 ((StrVal[0] == '-' || StrVal[0] == '+') &&
269 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
270 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
271 if (CFP->getType() == Type::DoubleTy)
272 Out << StrVal;
273 else
274 Out << StrVal << "f";
275 } else if (CFP->getType() == Type::DoubleTy)
276 Out << "BitsToDouble(0x" << std::hex
277 << CFP->getValueAPF().convertToAPInt().getZExtValue()
278 << std::dec << "ULL) /* " << StrVal << " */";
279 else
280 Out << "BitsToFloat(0x" << std::hex
281 << (uint32_t)CFP->getValueAPF().convertToAPInt().getZExtValue()
282 << std::dec << "U) /* " << StrVal << " */";
283 Out << ")";
284 #if HAVE_PRINTF_A
285 }
286 #endif
287 Out << ")";
288 }
289
290 void CppWriter::printCallingConv(unsigned cc){
291 // Print the calling convention.
292 switch (cc) {
293 case CallingConv::C: Out << "CallingConv::C"; break;
294 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
295 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
296 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
297 default: Out << cc; break;
298 }
299 }
300
301 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
302 switch (LT) {
303 case GlobalValue::InternalLinkage:
304 Out << "GlobalValue::InternalLinkage"; break;
305 case GlobalValue::LinkOnceLinkage:
306 Out << "GlobalValue::LinkOnceLinkage "; break;
307 case GlobalValue::WeakLinkage:
308 Out << "GlobalValue::WeakLinkage"; break;
309 case GlobalValue::AppendingLinkage:
310 Out << "GlobalValue::AppendingLinkage"; break;
311 case GlobalValue::ExternalLinkage:
312 Out << "GlobalValue::ExternalLinkage"; break;
313 case GlobalValue::DLLImportLinkage:
314 Out << "GlobalValue::DLLImportLinkage"; break;
315 case GlobalValue::DLLExportLinkage:
316 Out << "GlobalValue::DLLExportLinkage"; break;
317 case GlobalValue::ExternalWeakLinkage:
318 Out << "GlobalValue::ExternalWeakLinkage"; break;
319 case GlobalValue::GhostLinkage:
320 Out << "GlobalValue::GhostLinkage"; break;
321 }
322 }
323
324 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
325 switch (VisType) {
326 default: assert(0 && "Unknown GVar visibility");
327 case GlobalValue::DefaultVisibility:
328 Out << "GlobalValue::DefaultVisibility";
329 break;
330 case GlobalValue::HiddenVisibility:
331 Out << "GlobalValue::HiddenVisibility";
332 break;
333 case GlobalValue::ProtectedVisibility:
334 Out << "GlobalValue::ProtectedVisibility";
335 break;
336 }
337 }
338
339 // printEscapedString - Print each character of the specified string, escaping
340 // it if it is not printable or if it is an escape char.
341 void CppWriter::printEscapedString(const std::string &Str) {
342 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
343 unsigned char C = Str[i];
344 if (isprint(C) && C != '"' && C != '\\') {
345 Out << C;
346 } else {
347 Out << "\\x"
348 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
349 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
350 }
351 }
352 }
353
354 std::string CppWriter::getCppName(const Type* Ty) {
355 // First, handle the primitive types .. easy
356 if (Ty->isPrimitiveType() || Ty->isInteger()) {
357 switch (Ty->getTypeID()) {
358 case Type::VoidTyID: return "Type::VoidTy";
359 case Type::IntegerTyID: {
360 unsigned BitWidth = cast(Ty)->getBitWidth();
361 return "IntegerType::get(" + utostr(BitWidth) + ")";
362 }
363 case Type::FloatTyID: return "Type::FloatTy";
364 case Type::DoubleTyID: return "Type::DoubleTy";
365 case Type::LabelTyID: return "Type::LabelTy";
366 default:
367 error("Invalid primitive type");
368 break;
369 }
370 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
371 }
372
373 // Now, see if we've seen the type before and return that
374 TypeMap::iterator I = TypeNames.find(Ty);
375 if (I != TypeNames.end())
376 return I->second;
377
378 // Okay, let's build a new name for this type. Start with a prefix
379 const char* prefix = 0;
380 switch (Ty->getTypeID()) {
381 case Type::FunctionTyID: prefix = "FuncTy_"; break;
382 case Type::StructTyID: prefix = "StructTy_"; break;
383 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
384 case Type::PointerTyID: prefix = "PointerTy_"; break;
385 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
386 case Type::VectorTyID: prefix = "VectorTy_"; break;
387 default: prefix = "OtherTy_"; break; // prevent breakage
388 }
389
390 // See if the type has a name in the symboltable and build accordingly
391 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
392 std::string name;
393 if (tName)
394 name = std::string(prefix) + *tName;
395 else
396 name = std::string(prefix) + utostr(uniqueNum++);
397 sanitize(name);
398
399 // Save the name
400 return TypeNames[Ty] = name;
401 }
402
403 void CppWriter::printCppName(const Type* Ty) {
404 printEscapedString(getCppName(Ty));
405 }
406
407 std::string CppWriter::getCppName(const Value* val) {
408 std::string name;
409 ValueMap::iterator I = ValueNames.find(val);
410 if (I != ValueNames.end() && I->first == val)
411 return I->second;
412
413 if (const GlobalVariable* GV = dyn_cast(val)) {
414 name = std::string("gvar_") +
415 getTypePrefix(GV->getType()->getElementType());
416 } else if (isa(val)) {
417 name = std::string("func_");
418 } else if (const Constant* C = dyn_cast(val)) {
419 name = std::string("const_") + getTypePrefix(C->getType());
420 } else if (const Argument* Arg = dyn_cast(val)) {
421 if (is_inline) {
422 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
423 Function::const_arg_iterator(Arg)) + 1;
424 name = std::string("arg_") + utostr(argNum);
425 NameSet::iterator NI = UsedNames.find(name);
426 if (NI != UsedNames.end())
427 name += std::string("_") + utostr(uniqueNum++);
428 UsedNames.insert(name);
429 return ValueNames[val] = name;
430 } else {
431 name = getTypePrefix(val->getType());
432 }
433 } else {
434 name = getTypePrefix(val->getType());
435 }
436 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
437 sanitize(name);
438 NameSet::iterator NI = UsedNames.find(name);
439 if (NI != UsedNames.end())
440 name += std::string("_") + utostr(uniqueNum++);
441 UsedNames.insert(name);
442 return ValueNames[val] = name;
443 }
444
445 void CppWriter::printCppName(const Value* val) {
446 printEscapedString(getCppName(val));
447 }
448
449 void CppWriter::printParamAttrs(const PAListPtr &PAL,
450 const std::string &name) {
451 Out << "PAListPtr " << name << "_PAL = 0;";
452 nl(Out);
453 if (!PAL.isEmpty()) {
454 Out << '{'; in(); nl(Out);
455 Out << "SmallVector Attrs;"; nl(Out);
456 Out << "ParamAttrsWithIndex PAWI;"; nl(Out);
457 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
458 uint16_t index = PAL.getSlot(i).Index;
459 ParameterAttributes attrs = PAL.getSlot(i).Attrs;
460 Out << "PAWI.index = " << index << "; PAWI.attrs = 0 ";
461 if (attrs & ParamAttr::SExt)
462 Out << " | ParamAttr::SExt";
463 if (attrs & ParamAttr::ZExt)
464 Out << " | ParamAttr::ZExt";
465 if (attrs & ParamAttr::StructRet)
466 Out << " | ParamAttr::StructRet";
467 if (attrs & ParamAttr::InReg)
468 Out << " | ParamAttr::InReg";
469 if (attrs & ParamAttr::NoReturn)
470 Out << " | ParamAttr::NoReturn";
471 if (attrs & ParamAttr::NoUnwind)
472 Out << " | ParamAttr::NoUnwind";
473 if (attrs & ParamAttr::ByVal)
474 Out << " | ParamAttr::ByVal";
475 if (attrs & ParamAttr::NoAlias)
476 Out << " | ParamAttr::NoAlias";
477 if (attrs & ParamAttr::Nest)
478 Out << " | ParamAttr::Nest";
479 if (attrs & ParamAttr::ReadNone)
480 Out << " | ParamAttr::ReadNone";
481 if (attrs & ParamAttr::ReadOnly)
482 Out << " | ParamAttr::ReadOnly";
483 Out << ";";
484 nl(Out);
485 Out << "Attrs.push_back(PAWI);";
486 nl(Out);
487 }
488 Out << name << "_PAL = PAListPtr::get(Attrs.begin(), Attrs.end());";
489 nl(Out);
490 out(); nl(Out);
491 Out << '}'; nl(Out);
492 }
493 }
494
495 bool CppWriter::printTypeInternal(const Type* Ty) {
496 // We don't print definitions for primitive types
497 if (Ty->isPrimitiveType() || Ty->isInteger())
498 return false;
499
500 // If we already defined this type, we don't need to define it again.
501 if (DefinedTypes.find(Ty) != DefinedTypes.end())
502 return false;
503
504 // Everything below needs the name for the type so get it now.
505 std::string typeName(getCppName(Ty));
506
507 // Search the type stack for recursion. If we find it, then generate this
508 // as an OpaqueType, but make sure not to do this multiple times because
509 // the type could appear in multiple places on the stack. Once the opaque
510 // definition is issued, it must not be re-issued. Consequently we have to
511 // check the UnresolvedTypes list as well.
512 TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
513 Ty);
514 if (TI != TypeStack.end()) {
515 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
516 if (I == UnresolvedTypes.end()) {
517 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
518 nl(Out);
519 UnresolvedTypes[Ty] = typeName;
520 }
521 return true;
522 }
523
524 // We're going to print a derived type which, by definition, contains other
525 // types. So, push this one we're printing onto the type stack to assist with
526 // recursive definitions.
527 TypeStack.push_back(Ty);
528
529 // Print the type definition
530 switch (Ty->getTypeID()) {
531 case Type::FunctionTyID: {
532 const FunctionType* FT = cast(Ty);
533 Out << "std::vector" << typeName << "_args;";
534 nl(Out);
535 FunctionType::param_iterator PI = FT->param_begin();
536 FunctionType::param_iterator PE = FT->param_end();
537 for (; PI != PE; ++PI) {
538 const Type* argTy = static_cast(*PI);
539 bool isForward = printTypeInternal(argTy);
540 std::string argName(getCppName(argTy));
541 Out << typeName << "_args.push_back(" << argName;
542 if (isForward)
543 Out << "_fwd";
544 Out << ");";
545 nl(Out);
546 }
547 bool isForward = printTypeInternal(FT->getReturnType());
548 std::string retTypeName(getCppName(FT->getReturnType()));
549 Out << "FunctionType* " << typeName << " = FunctionType::get(";
550 in(); nl(Out) << "/*Result=*/" << retTypeName;
551 if (isForward)
552 Out << "_fwd";
553 Out << ",";
554 nl(Out) << "/*Params=*/" << typeName << "_args,";
555 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
556 out();
557 nl(Out);
558 break;
559 }
560 case Type::StructTyID: {
561 const StructType* ST = cast(Ty);
562 Out << "std::vector" << typeName << "_fields;";
563 nl(Out);
564 StructType::element_iterator EI = ST->element_begin();
565 StructType::element_iterator EE = ST->element_end();
566 for (; EI != EE; ++EI) {
567 const Type* fieldTy = static_cast(*EI);
568 bool isForward = printTypeInternal(fieldTy);
569 std::string fieldName(getCppName(fieldTy));
570 Out << typeName << "_fields.push_back(" << fieldName;
571 if (isForward)
572 Out << "_fwd";
573 Out << ");";
574 nl(Out);
575 }
576 Out << "StructType* " << typeName << " = StructType::get("
577 << typeName << "_fields, /*isPacked=*/"
578 << (ST->isPacked() ? "true" : "false") << ");";
579 nl(Out);
580 break;
581 }
582 case Type::ArrayTyID: {
583 const ArrayType* AT = cast(Ty);
584 const Type* ET = AT->getElementType();
585 bool isForward = printTypeInternal(ET);
586 std::string elemName(getCppName(ET));
587 Out << "ArrayType* " << typeName << " = ArrayType::get("
588 << elemName << (isForward ? "_fwd" : "")
589 << ", " << utostr(AT->getNumElements()) << ");";
590 nl(Out);
591 break;
592 }
593 case Type::PointerTyID: {
594 const PointerType* PT = cast(Ty);
595 const Type* ET = PT->getElementType();
596 bool isForward = printTypeInternal(ET);
597 std::string elemName(getCppName(ET));
598 Out << "PointerType* " << typeName << " = PointerType::get("
599 << elemName << (isForward ? "_fwd" : "")
600 << ", " << utostr(PT->getAddressSpace()) << ");";
601 nl(Out);
602 break;
603 }
604 case Type::VectorTyID: {
605 const VectorType* PT = cast(Ty);
606 const Type* ET = PT->getElementType();
607 bool isForward = printTypeInternal(ET);
608 std::string elemName(getCppName(ET));
609 Out << "VectorType* " << typeName << " = VectorType::get("
610 << elemName << (isForward ? "_fwd" : "")
611 << ", " << utostr(PT->getNumElements()) << ");";
612 nl(Out);
613 break;
614 }
615 case Type::OpaqueTyID: {
616 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
617 nl(Out);
618 break;
619 }
620 default:
621 error("Invalid TypeID");
622 }
623
624 // If the type had a name, make sure we recreate it.
625 const std::string* progTypeName =
626 findTypeName(TheModule->getTypeSymbolTable(),Ty);
627 if (progTypeName) {
628 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
629 << typeName << ");";
630 nl(Out);
631 }
632
633 // Pop us off the type stack
634 TypeStack.pop_back();
635
636 // Indicate that this type is now defined.
637 DefinedTypes.insert(Ty);
638
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
642 // unresolved types.
643 TypeMap::iterator I = UnresolvedTypes.find(Ty);
644 if (I != UnresolvedTypes.end()) {
645 Out << "cast(" << I->second
646 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
647 nl(Out);
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 case Type::OpaqueTyID: Out << "OpaqueType"; break;
656 default: Out << "NoSuchDerivedType"; break;
657 }
658 Out << ">(" << I->second << "_fwd.get());";
659 nl(Out); nl(Out);
660 UnresolvedTypes.erase(I);
661 }
662
663 // Finally, separate the type definition from other with a newline.
664 nl(Out);
665
666 // We weren't a recursive type
667 return false;
668 }
669
670 // Prints a type definition. Returns true if it could not resolve all the
671 // types in the definition but had to use a forward reference.
672 void CppWriter::printType(const Type* Ty) {
673 assert(TypeStack.empty());
674 TypeStack.clear();
675 printTypeInternal(Ty);
676 assert(TypeStack.empty());
677 }
678
679 void CppWriter::printTypes(const Module* M) {
680 // Walk the symbol table and print out all its types
681 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
682 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
683 TI != TE; ++TI) {
684
685 // For primitive types and types already defined, just add a name
686 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
687 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
688 TNI != TypeNames.end()) {
689 Out << "mod->addTypeName(\"";
690 printEscapedString(TI->first);
691 Out << "\", " << getCppName(TI->second) << ");";
692 nl(Out);
693 // For everything else, define the type
694 } else {
695 printType(TI->second);
696 }
697 }
698
699 // Add all of the global variables to the value table...
700 for (Module::const_global_iterator I = TheModule->global_begin(),
701 E = TheModule->global_end(); I != E; ++I) {
702 if (I->hasInitializer())
703 printType(I->getInitializer()->getType());
704 printType(I->getType());
705 }
706
707 // Add all the functions to the table
708 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
709 FI != FE; ++FI) {
710 printType(FI->getReturnType());
711 printType(FI->getFunctionType());
712 // Add all the function arguments
713 for (Function::const_arg_iterator AI = FI->arg_begin(),
714 AE = FI->arg_end(); AI != AE; ++AI) {
715 printType(AI->getType());
716 }
717
718 // Add all of the basic blocks and instructions
719 for (Function::const_iterator BB = FI->begin(),
720 E = FI->end(); BB != E; ++BB) {
721 printType(BB->getType());
722 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
723 ++I) {
724 printType(I->getType());
725 for (unsigned i = 0; i < I->getNumOperands(); ++i)
726 printType(I->getOperand(i)->getType());
727 }
728 }
729 }
730 }
731
732
733 // printConstant - Print out a constant pool entry...
734 void CppWriter::printConstant(const Constant *CV) {
735 // First, if the constant is actually a GlobalValue (variable or function)
736 // or its already in the constant list then we've printed it already and we
737 // can just return.
738 if (isa(CV) || ValueNames.find(CV) != ValueNames.end())
739 return;
740
741 std::string constName(getCppName(CV));
742 std::string typeName(getCppName(CV->getType()));
743 if (CV->isNullValue()) {
744 Out << "Constant* " << constName << " = Constant::getNullValue("
745 << typeName << ");";
746 nl(Out);
747 return;
748 }
749 if (isa(CV)) {
750 // Skip variables and functions, we emit them elsewhere
751 return;
752 }
753 if (const ConstantInt *CI = dyn_cast(CV)) {
754 Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
755 << cast(CI->getType())->getBitWidth() << ", "
756 << " \"" << CI->getValue().toStringSigned(10) << "\", 10));";
757 } else if (isa(CV)) {
758 Out << "ConstantAggregateZero* " << constName
759 << " = ConstantAggregateZero::get(" << typeName << ");";
760 } else if (isa(CV)) {
761 Out << "ConstantPointerNull* " << constName
762 << " = ConstanPointerNull::get(" << typeName << ");";
763 } else if (const ConstantFP *CFP = dyn_cast(CV)) {
764 Out << "ConstantFP* " << constName << " = ";
765 printCFP(CFP);
766 Out << ";";
767 } else if (const ConstantArray *CA = dyn_cast(CV)) {
768 if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
769 Out << "Constant* " << constName << " = ConstantArray::get(\"";
770 std::string tmp = CA->getAsString();
771 bool nullTerminate = false;
772 if (tmp[tmp.length()-1] == 0) {
773 tmp.erase(tmp.length()-1);
774 nullTerminate = true;
775 }
776 printEscapedString(tmp);
777 // Determine if we want null termination or not.
778 if (nullTerminate)
779 Out << "\", true"; // Indicate that the null terminator should be
780 // added.
781 else
782 Out << "\", false";// No null terminator
783 Out << ");";
784 } else {
785 Out << "std::vector " << constName << "_elems;";
786 nl(Out);
787 unsigned N = CA->getNumOperands();
788 for (unsigned i = 0; i < N; ++i) {
789 printConstant(CA->getOperand(i)); // recurse to print operands
790 Out << constName << "_elems.push_back("
791 << getCppName(CA->getOperand(i)) << ");";
792 nl(Out);
793 }
794 Out << "Constant* " << constName << " = ConstantArray::get("
795 << typeName << ", " << constName << "_elems);";
796 }
797 } else if (const ConstantStruct *CS = dyn_cast(CV)) {
798 Out << "std::vector " << constName << "_fields;";
799 nl(Out);
800 unsigned N = CS->getNumOperands();
801 for (unsigned i = 0; i < N; i++) {
802 printConstant(CS->getOperand(i));
803 Out << constName << "_fields.push_back("
804 << getCppName(CS->getOperand(i)) << ");";
805 nl(Out);
806 }
807 Out << "Constant* " << constName << " = ConstantStruct::get("
808 << typeName << ", " << constName << "_fields);";
809 } else if (const ConstantVector *CP = dyn_cast(CV)) {
810 Out << "std::vector " << constName << "_elems;";
811 nl(Out);
812 unsigned N = CP->getNumOperands();
813 for (unsigned i = 0; i < N; ++i) {
814 printConstant(CP->getOperand(i));
815 Out << constName << "_elems.push_back("
816 << getCppName(CP->getOperand(i)) << ");";
817 nl(Out);
818 }
819 Out << "Constant* " << constName << " = ConstantVector::get("
820 << typeName << ", " << constName << "_elems);";
821 } else if (isa(CV)) {
822 Out << "UndefValue* " << constName << " = UndefValue::get("
823 << typeName << ");";
824 } else if (const ConstantExpr *CE = dyn_cast(CV)) {
825 if (CE->getOpcode() == Instruction::GetElementPtr) {
826 Out << "std::vector " << constName << "_indices;";
827 nl(Out);
828 printConstant(CE->getOperand(0));
829 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
830 printConstant(CE->getOperand(i));
831 Out << constName << "_indices.push_back("
832 << getCppName(CE->getOperand(i)) << ");";
833 nl(Out);
834 }
835 Out << "Constant* " << constName
836 << " = ConstantExpr::getGetElementPtr("
837 << getCppName(CE->getOperand(0)) << ", "
838 << "&" << constName << "_indices[0], "
839 << constName << "_indices.size()"
840 << " );";
841 } else if (CE->isCast()) {
842 printConstant(CE->getOperand(0));
843 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
844 switch (CE->getOpcode()) {
845 default: assert(0 && "Invalid cast opcode");
846 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
847 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
848 case Instruction::SExt: Out << "Instruction::SExt"; break;
849 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
850 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
851 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
852 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
853 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
854 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
855 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
856 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
857 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
858 }
859 Out << ", " << getCppName(CE->getOperand(0)) << ", "
860 << getCppName(CE->getType()) << ");";
861 } else {
862 unsigned N = CE->getNumOperands();
863 for (unsigned i = 0; i < N; ++i ) {
864 printConstant(CE->getOperand(i));
865 }
866 Out << "Constant* " << constName << " = ConstantExpr::";
867 switch (CE->getOpcode()) {
868 case Instruction::Add: Out << "getAdd("; break;
869 case Instruction::Sub: Out << "getSub("; break;
870 case Instruction::Mul: Out << "getMul("; break;
871 case Instruction::UDiv: Out << "getUDiv("; break;
872 case Instruction::SDiv: Out << "getSDiv("; break;
873 case Instruction::FDiv: Out << "getFDiv("; break;
874 case Instruction::URem: Out << "getURem("; break;
875 case Instruction::SRem: Out << "getSRem("; break;
876 case Instruction::FRem: Out << "getFRem("; break;
877 case Instruction::And: Out << "getAnd("; break;
878 case Instruction::Or: Out << "getOr("; break;
879 case Instruction::Xor: Out << "getXor("; break;
880 case Instruction::ICmp:
881 Out << "getICmp(ICmpInst::ICMP_";
882 switch (CE->getPredicate()) {
883 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
884 case ICmpInst::ICMP_NE: Out << "NE"; break;
885 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
886 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
887 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
888 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
889 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
890 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
891 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
892 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
893 default: error("Invalid ICmp Predicate");
894 }
895 break;
896 case Instruction::FCmp:
897 Out << "getFCmp(FCmpInst::FCMP_";
898 switch (CE->getPredicate()) {
899 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
900 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
901 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
902 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
903 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
904 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
905 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
906 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
907 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
908 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
909 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
910 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
911 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
912 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
913 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
914 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
915 default: error("Invalid FCmp Predicate");
916 }
917 break;
918 case Instruction::Shl: Out << "getShl("; break;
919 case Instruction::LShr: Out << "getLShr("; break;
920 case Instruction::AShr: Out << "getAShr("; break;
921 case Instruction::Select: Out << "getSelect("; break;
922 case Instruction::ExtractElement: Out << "getExtractElement("; break;
923 case Instruction::InsertElement: Out << "getInsertElement("; break;
924 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
925 default:
926 error("Invalid constant expression");
927 break;
928 }
929 Out << getCppName(CE->getOperand(0));
930 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
931 Out << ", " << getCppName(CE->getOperand(i));
932 Out << ");";
933 }
934 } else {
935 error("Bad Constant");
936 Out << "Constant* " << constName << " = 0; ";
937 }
938 nl(Out);
939 }
940
941 void CppWriter::printConstants(const Module* M) {
942 // Traverse all the global variables looking for constant initializers
943 for (Module::const_global_iterator I = TheModule->global_begin(),
944 E = TheModule->global_end(); I != E; ++I)
945 if (I->hasInitializer())
946 printConstant(I->getInitializer());
947
948 // Traverse the LLVM functions looking for constants
949 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
950 FI != FE; ++FI) {
951 // Add all of the basic blocks and instructions
952 for (Function::const_iterator BB = FI->begin(),
953 E = FI->end(); BB != E; ++BB) {
954 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
955 ++I) {
956 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
957 if (Constant* C = dyn_cast(I->getOperand(i))) {
958 printConstant(C);
959 }
960 }
961 }
962 }
963 }
964 }
965
966 void CppWriter::printVariableUses(const GlobalVariable *GV) {
967 nl(Out) << "// Type Definitions";
968 nl(Out);
969 printType(GV->getType());
970 if (GV->hasInitializer()) {
971 Constant* Init = GV->getInitializer();
972 printType(Init->getType());
973 if (Function* F = dyn_cast(Init)) {
974 nl(Out)<< "/ Function Declarations"; nl(Out);
975 printFunctionHead(F);
976 } else if (GlobalVariable* gv = dyn_cast(Init)) {
977 nl(Out) << "// Global Variable Declarations"; nl(Out);
978 printVariableHead(gv);
979 } else {
980 nl(Out) << "// Constant Definitions"; nl(Out);
981 printConstant(gv);
982 }
983 if (GlobalVariable* gv = dyn_cast(Init)) {
984 nl(Out) << "// Global Variable Definitions"; nl(Out);
985 printVariableBody(gv);
986 }
987 }
988 }
989
990 void CppWriter::printVariableHead(const GlobalVariable *GV) {
991 nl(Out) << "GlobalVariable* " << getCppName(GV);
992 if (is_inline) {
993 Out << " = mod->getGlobalVariable(";
994 printEscapedString(GV->getName());
995 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
996 nl(Out) << "if (!" << getCppName(GV) << ") {";
997 in(); nl(Out) << getCppName(GV);
998 }
999 Out << " = new GlobalVariable(";
1000 nl(Out) << "/*Type=*/";
1001 printCppName(GV->getType()->getElementType());
1002 Out << ",";
1003 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
1004 Out << ",";
1005 nl(Out) << "/*Linkage=*/";
1006 printLinkageType(GV->getLinkage());
1007 Out << ",";
1008 nl(Out) << "/*Initializer=*/0, ";
1009 if (GV->hasInitializer()) {
1010 Out << "// has initializer, specified below";
1011 }
1012 nl(Out) << "/*Name=*/\"";
1013 printEscapedString(GV->getName());
1014 Out << "\",";
1015 nl(Out) << "mod);";
1016 nl(Out);
1017
1018 if (GV->hasSection()) {
1019 printCppName(GV);
1020 Out << "->setSection(\"";
1021 printEscapedString(GV->getSection());
1022 Out << "\");";
1023 nl(Out);
1024 }
1025 if (GV->getAlignment()) {
1026 printCppName(GV);
1027 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1028 nl(Out);
1029 }
1030 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1031 printCppName(GV);
1032 Out << "->setVisibility(";
1033 printVisibilityType(GV->getVisibility());
1034 Out << ");";
1035 nl(Out);
1036 }
1037 if (is_inline) {
1038 out(); Out << "}"; nl(Out);
1039 }
1040 }
1041
1042 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1043 if (GV->hasInitializer()) {
1044 printCppName(GV);
1045 Out << "->setInitializer(";
1046 Out << getCppName(GV->getInitializer()) << ");";
1047 nl(Out);
1048 }
1049 }
1050
1051 std::string CppWriter::getOpName(Value* V) {
1052 if (!isa(V) || DefinedValues.find(V) != DefinedValues.end())
1053 return getCppName(V);
1054
1055 // See if its alread in the map of forward references, if so just return the
1056 // name we already set up for it
1057 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1058 if (I != ForwardRefs.end())
1059 return I->second;
1060
1061 // This is a new forward reference. Generate a unique name for it
1062 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1063
1064 // Yes, this is a hack. An Argument is the smallest instantiable value that
1065 // we can make as a placeholder for the real value. We'll replace these
1066 // Argument instances later.
1067 Out << "Argument* " << result << " = new Argument("
1068 << getCppName(V->getType()) << ");";
1069 nl(Out);
1070 ForwardRefs[V] = result;
1071 return result;
1072 }
1073
1074 // printInstruction - This member is called for each Instruction in a function.
1075 void CppWriter::printInstruction(const Instruction *I,
1076 const std::string& bbname) {
1077 std::string iName(getCppName(I));
1078
1079 // Before we emit this instruction, we need to take care of generating any
1080 // forward references. So, we get the names of all the operands in advance
1081 std::string* opNames = new std::string[I->getNumOperands()];
1082 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1083 opNames[i] = getOpName(I->getOperand(i));
1084 }
1085
1086 switch (I->getOpcode()) {
1087 case Instruction::Ret: {
1088 const ReturnInst* ret = cast(I);
1089 Out << "ReturnInst::Create("
1090 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1091 break;
1092 }
1093 case Instruction::Br: {
1094 const BranchInst* br = cast(I);
1095 Out << "BranchInst::Create(" ;
1096 if (br->getNumOperands() == 3 ) {
1097 Out << opNames[0] << ", "
1098 << opNames[1] << ", "
1099 << opNames[2] << ", ";
1100
1101 } else if (br->getNumOperands() == 1) {
1102 Out << opNames[0] << ", ";
1103 } else {
1104 error("Branch with 2 operands?");
1105 }
1106 Out << bbname << ");";
1107 break;
1108 }
1109 case Instruction::Switch: {
1110 const SwitchInst* sw = cast(I);
1111 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1112 << opNames[0] << ", "
1113 << opNames[1] << ", "
1114 << sw->getNumCases() << ", " << bbname << ");";
1115 nl(Out);
1116 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1117 Out << iName << "->addCase("
1118 << opNames[i] << ", "
1119 << opNames[i+1] << ");";
1120 nl(Out);
1121 }
1122 break;
1123 }
1124 case Instruction::Invoke: {
1125 const InvokeInst* inv = cast(I);
1126 Out << "std::vector " << iName << "_params;";
1127 nl(Out);
1128 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1129 Out << iName << "_params.push_back("
1130 << opNames[i] << ");";
1131 nl(Out);
1132 }
1133 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1134 << opNames[0] << ", "
1135 << opNames[1] << ", "
1136 << opNames[2] << ", "
1137 << iName << "_params.begin(), " << iName << "_params.end(), \"";
1138 printEscapedString(inv->getName());
1139 Out << "\", " << bbname << ");";
1140 nl(Out) << iName << "->setCallingConv(";
1141 printCallingConv(inv->getCallingConv());
1142 Out << ");";
1143 printParamAttrs(inv->getParamAttrs(), iName);
1144 Out << iName << "->setParamAttrs(" << iName << "_PAL);";
1145 nl(Out);
1146 break;
1147 }
1148 case Instruction::Unwind: {
1149 Out << "new UnwindInst("
1150 << bbname << ");";
1151 break;
1152 }
1153 case Instruction::Unreachable:{
1154 Out << "new UnreachableInst("
1155 << bbname << ");";
1156 break;
1157 }
1158 case Instruction::Add:
1159 case Instruction::Sub:
1160 case Instruction::Mul:
1161 case Instruction::UDiv:
1162 case Instruction::SDiv:
1163 case Instruction::FDiv:
1164 case Instruction::URem:
1165 case Instruction::SRem:
1166 case Instruction::FRem:
1167 case Instruction::And:
1168 case Instruction::Or:
1169 case Instruction::Xor:
1170 case Instruction::Shl:
1171 case Instruction::LShr:
1172 case Instruction::AShr:{
1173 Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
1174 switch (I->getOpcode()) {
1175 case Instruction::Add: Out << "Instruction::Add"; break;
1176 case Instruction::Sub: Out << "Instruction::Sub"; break;
1177 case Instruction::Mul: Out << "Instruction::Mul"; break;
1178 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1179 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1180 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1181 case Instruction::URem:Out << "Instruction::URem"; break;
1182 case Instruction::SRem:Out << "Instruction::SRem"; break;
1183 case Instruction::FRem:Out << "Instruction::FRem"; break;
1184 case Instruction::And: Out << "Instruction::And"; break;
1185 case Instruction::Or: Out << "Instruction::Or"; break;
1186 case Instruction::Xor: Out << "Instruction::Xor"; break;
1187 case Instruction::Shl: Out << "Instruction::Shl"; break;
1188 case Instruction::LShr:Out << "Instruction::LShr"; break;
1189 case Instruction::AShr:Out << "Instruction::AShr"; break;
1190 default: Out << "Instruction::BadOpCode"; break;
1191 }
1192 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1193 printEscapedString(I->getName());
1194 Out << "\", " << bbname << ");";
1195 break;
1196 }
1197 case Instruction::FCmp: {
1198 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1199 switch (cast(I)->getPredicate()) {
1200 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1201 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1202 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1203 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1204 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1205 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1206 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1207 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1208 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1209 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1210 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1211 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1212 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1213 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1214 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1215 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1216 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1217 }
1218 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1219 printEscapedString(I->getName());
1220 Out << "\", " << bbname << ");";
1221 break;
1222 }
1223 case Instruction::ICmp: {
1224 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1225 switch (cast(I)->getPredicate()) {
1226 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1227 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1228 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1229 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1230 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1231 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1232 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1233 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1234 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1235 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1236 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1237 }
1238 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1239 printEscapedString(I->getName());
1240 Out << "\", " << bbname << ");";
1241 break;
1242 }
1243 case Instruction::Malloc: {
1244 const MallocInst* mallocI = cast(I);
1245 Out << "MallocInst* " << iName << " = new MallocInst("
1246 << getCppName(mallocI->getAllocatedType()) << ", ";
1247 if (mallocI->isArrayAllocation())
1248 Out << opNames[0] << ", " ;
1249 Out << "\"";
1250 printEscapedString(mallocI->getName());
1251 Out << "\", " << bbname << ");";
1252 if (mallocI->getAlignment())
1253 nl(Out) << iName << "->setAlignment("
1254 << mallocI->getAlignment() << ");";
1255 break;
1256 }
1257 case Instruction::Free: {
1258 Out << "FreeInst* " << iName << " = new FreeInst("
1259 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1260 break;
1261 }
1262 case Instruction::Alloca: {
1263 const AllocaInst* allocaI = cast(I);
1264 Out << "AllocaInst* " << iName << " = new AllocaInst("
1265 << getCppName(allocaI->getAllocatedType()) << ", ";
1266 if (allocaI->isArrayAllocation())
1267 Out << opNames[0] << ", ";
1268 Out << "\"";
1269 printEscapedString(allocaI->getName());
1270 Out << "\", " << bbname << ");";
1271 if (allocaI->getAlignment())
1272 nl(Out) << iName << "->setAlignment("
1273 << allocaI->getAlignment() << ");";
1274 break;
1275 }
1276 case Instruction::Load:{
1277 const LoadInst* load = cast(I);
1278 Out << "LoadInst* " << iName << " = new LoadInst("
1279 << opNames[0] << ", \"";
1280 printEscapedString(load->getName());
1281 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1282 << ", " << bbname << ");";
1283 break;
1284 }
1285 case Instruction::Store: {
1286 const StoreInst* store = cast(I);
1287 Out << "StoreInst* " << iName << " = new StoreInst("
1288 << opNames[0] << ", "
1289 << opNames[1] << ", "
1290 << (store->isVolatile() ? "true" : "false")
1291 << ", " << bbname << ");";
1292 break;
1293 }
1294 case Instruction::GetElementPtr: {
1295 const GetElementPtrInst* gep = cast(I);
1296 if (gep->getNumOperands() <= 2) {
1297 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1298 << opNames[0];
1299 if (gep->getNumOperands() == 2)
1300 Out << ", " << opNames[1];
1301 } else {
1302 Out << "std::vector " << iName << "_indices;";
1303 nl(Out);
1304 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1305 Out << iName << "_indices.push_back("
1306 << opNames[i] << ");";
1307 nl(Out);
1308 }
1309 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1310 << opNames[0] << ", " << iName << "_indices.begin(), "
1311 << iName << "_indices.end()";
1312 }
1313 Out << ", \"";
1314 printEscapedString(gep->getName());
1315 Out << "\", " << bbname << ");";
1316 break;
1317 }
1318 case Instruction::PHI: {
1319 const PHINode* phi = cast(I);
1320
1321 Out << "PHINode* " << iName << " = PHINode::Create("
1322 << getCppName(phi->getType()) << ", \"";
1323 printEscapedString(phi->getName());
1324 Out << "\", " << bbname << ");";
1325 nl(Out) << iName << "->reserveOperandSpace("
1326 << phi->getNumIncomingValues()
1327 << ");";
1328 nl(Out);
1329 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1330 Out << iName << "->addIncoming("
1331 << opNames[i] << ", " << opNames[i+1] << ");";
1332 nl(Out);
1333 }
1334 break;
1335 }
1336 case Instruction::Trunc:
1337 case Instruction::ZExt:
1338 case Instruction::SExt:
1339 case Instruction::FPTrunc:
1340 case Instruction::FPExt:
1341 case Instruction::FPToUI:
1342 case Instruction::FPToSI:
1343 case Instruction::UIToFP:
1344 case Instruction::SIToFP:
1345 case Instruction::PtrToInt:
1346 case Instruction::IntToPtr:
1347 case Instruction::BitCast: {
1348 const CastInst* cst = cast(I);
1349 Out << "CastInst* " << iName << " = new ";
1350 switch (I->getOpcode()) {
1351 case Instruction::Trunc: Out << "TruncInst"; break;
1352 case Instruction::ZExt: Out << "ZExtInst"; break;
1353 case Instruction::SExt: Out << "SExtInst"; break;
1354 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1355 case Instruction::FPExt: Out << "FPExtInst"; break;
1356 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1357 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1358 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1359 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1360 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1361 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1362 case Instruction::BitCast: Out << "BitCastInst"; break;
1363 default: assert(!"Unreachable"); break;
1364 }
1365 Out << "(" << opNames[0] << ", "
1366 << getCppName(cst->getType()) << ", \"";
1367 printEscapedString(cst->getName());
1368 Out << "\", " << bbname << ");";
1369 break;
1370 }
1371 case Instruction::Call:{
1372 const CallInst* call = cast(I);
1373 if (InlineAsm* ila = dyn_cast(call->getOperand(0))) {
1374 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1375 << getCppName(ila->getFunctionType()) << ", \""
1376 << ila->getAsmString() << "\", \""
1377 << ila->getConstraintString() << "\","
1378 << (ila->hasSideEffects() ? "true" : "false") << ");";
1379 nl(Out);
1380 }
1381 if (call->getNumOperands() > 2) {
1382 Out << "std::vector " << iName << "_params;";
1383 nl(Out);
1384 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1385 Out << iName << "_params.push_back(" << opNames[i] << ");";
1386 nl(Out);
1387 }
1388 Out << "CallInst* " << iName << " = CallInst::Create("
1389 << opNames[0] << ", " << iName << "_params.begin(), "
1390 << iName << "_params.end(), \"";
1391 } else if (call->getNumOperands() == 2) {
1392 Out << "CallInst* " << iName << " = CallInst::Create("
1393 << opNames[0] << ", " << opNames[1] << ", \"";
1394 } else {
1395 Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
1396 << ", \"";
1397 }
1398 printEscapedString(call->getName());
1399 Out << "\", " << bbname << ");";
1400 nl(Out) << iName << "->setCallingConv(";
1401 printCallingConv(call->getCallingConv());
1402 Out << ");";
1403 nl(Out) << iName << "->setTailCall("
1404 << (call->isTailCall() ? "true":"false");
1405 Out << ");";
1406 printParamAttrs(call->getParamAttrs(), iName);
1407 Out << iName << "->setParamAttrs(" << iName << "_PAL);";
1408 nl(Out);
1409 break;
1410 }
1411 case Instruction::Select: {
1412 const SelectInst* sel = cast(I);
1413 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1414 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1415 printEscapedString(sel->getName());
1416 Out << "\", " << bbname << ");";
1417 break;
1418 }
1419 case Instruction::UserOp1:
1420 /// FALL THROUGH
1421 case Instruction::UserOp2: {
1422 /// FIXME: What should be done here?
1423 break;
1424 }
1425 case Instruction::VAArg: {
1426 const VAArgInst* va = cast(I);
1427 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1428 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1429 printEscapedString(va->getName());
1430 Out << "\", " << bbname << ");";
1431 break;
1432 }
1433 case Instruction::ExtractElement: {
1434 const ExtractElementInst* eei = cast(I);
1435 Out << "ExtractElementInst* " << getCppName(eei)
1436 << " = new ExtractElementInst(" << opNames[0]
1437 << ", " << opNames[1] << ", \"";
1438 printEscapedString(eei->getName());
1439 Out << "\", " << bbname << ");";
1440 break;
1441 }
1442 case Instruction::InsertElement: {
1443 const InsertElementInst* iei = cast(I);
1444 Out << "InsertElementInst* " << getCppName(iei)
1445 << " = InsertElementInst::Create(" << opNames[0]
1446 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1447 printEscapedString(iei->getName());
1448 Out << "\", " << bbname << ");";
1449 break;
1450 }
1451 case Instruction::ShuffleVector: {
1452 const ShuffleVectorInst* svi = cast(I);
1453 Out << "ShuffleVectorInst* " << getCppName(svi)
1454 << " = new ShuffleVectorInst(" << opNames[0]
1455 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1456 printEscapedString(svi->getName());
1457 Out << "\", " << bbname << ");";
1458 break;
1459 }
1460 }
1461 DefinedValues.insert(I);
1462 nl(Out);
1463 delete [] opNames;
1464 }
1465
1466 // Print out the types, constants and declarations needed by one function
1467 void CppWriter::printFunctionUses(const Function* F) {
1468 nl(Out) << "// Type Definitions"; nl(Out);
1469 if (!is_inline) {
1470 // Print the function's return type
1471 printType(F->getReturnType());
1472
1473 // Print the function's function type
1474 printType(F->getFunctionType());
1475
1476 // Print the types of each of the function's arguments
1477 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1478 AI != AE; ++AI) {
1479 printType(AI->getType());
1480 }
1481 }
1482
1483 // Print type definitions for every type referenced by an instruction and
1484 // make a note of any global values or constants that are referenced
1485 SmallPtrSet gvs;
1486 SmallPtrSet consts;
1487 for (Function::const_iterator BB = F->begin(), BE = F->end();
1488 BB != BE; ++BB){
1489 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1490 I != E; ++I) {
1491 // Print the type of the instruction itself
1492 printType(I->getType());
1493
1494 // Print the type of each of the instruction's operands
1495 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1496 Value* operand = I->getOperand(i);
1497 printType(operand->getType());
1498
1499 // If the operand references a GVal or Constant, make a note of it
1500 if (GlobalValue* GV = dyn_cast(operand)) {
1501 gvs.insert(GV);
1502 if (GlobalVariable *GVar = dyn_cast(GV))
1503 if (GVar->hasInitializer())
1504 consts.insert(GVar->getInitializer());
1505 } else if (Constant* C = dyn_cast(operand))
1506 consts.insert(C);
1507 }
1508 }
1509 }
1510
1511 // Print the function declarations for any functions encountered
1512 nl(Out) << "// Function Declarations"; nl(Out);
1513 for (SmallPtrSet::iterator I = gvs.begin(), E = gvs.end();
1514 I != E; ++I) {
1515 if (Function* Fun = dyn_cast(*I)) {
1516 if (!is_inline || Fun != F)
1517 printFunctionHead(Fun);
1518 }
1519 }
1520
1521 // Print the global variable declarations for any variables encountered
1522 nl(Out) << "// Global Variable Declarations"; nl(Out);
1523 for (SmallPtrSet::iterator I = gvs.begin(), E = gvs.end();
1524 I != E; ++I) {
1525 if (GlobalVariable* F = dyn_cast(*I))
1526 printVariableHead(F);
1527 }
1528
1529 // Print the constants found
1530 nl(Out) << "// Constant Definitions"; nl(Out);
1531 for (SmallPtrSet::iterator I = consts.begin(),
1532 E = consts.end(); I != E; ++I) {
1533 printConstant(*I);
1534 }
1535
1536 // Process the global variables definitions now that all the constants have
1537 // been emitted. These definitions just couple the gvars with their constant
1538 // initializers.
1539 nl(Out) << "// Global Variable Definitions"; nl(Out);
1540 for (SmallPtrSet::iterator I = gvs.begin(), E = gvs.end();
1541 I != E; ++I) {
1542 if (GlobalVariable* GV = dyn_cast(*I))
1543 printVariableBody(GV);
1544 }
1545 }
1546
1547 void CppWriter::printFunctionHead(const Function* F) {
1548 nl(Out) << "Function* " << getCppName(F);
1549 if (is_inline) {
1550 Out << " = mod->getFunction(\"";
1551 printEscapedString(F->getName());
1552 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1553 nl(Out) << "if (!" << getCppName(F) << ") {";
1554 nl(Out) << getCppName(F);
1555 }
1556 Out<< " = Function::Create(";
1557 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1558 nl(Out) << "/*Linkage=*/";
1559 printLinkageType(F->getLinkage());
1560 Out << ",";
1561 nl(Out) << "/*Name=*/\"";
1562 printEscapedString(F->getName());
1563 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1564 nl(Out,-1);
1565 printCppName(F);
1566 Out << "->setCallingConv(";
1567 printCallingConv(F->getCallingConv());
1568 Out << ");";
1569 nl(Out);
1570 if (F->hasSection()) {
1571 printCppName(F);
1572 Out << "->setSection(\"" << F->getSection() << "\");";
1573 nl(Out);
1574 }
1575 if (F->getAlignment()) {
1576 printCppName(F);
1577 Out << "->setAlignment(" << F->getAlignment() << ");";
1578 nl(Out);
1579 }
1580 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1581 printCppName(F);
1582 Out << "->setVisibility(";
1583 printVisibilityType(F->getVisibility());
1584 Out << ");";
1585 nl(Out);
1586 }
1587 if (F->hasCollector()) {
1588 printCppName(F);
1589 Out << "->setCollector(\"" << F->getCollector() << "\");";
1590 nl(Out);
1591 }
1592 if (is_inline) {
1593 Out << "}";
1594 nl(Out);
1595 }
1596 printParamAttrs(F->getParamAttrs(), getCppName(F));
1597 printCppName(F);
1598 Out << "->setParamAttrs(" << getCppName(F) << "_PAL);";
1599 nl(Out);
1600 }
1601
1602 void CppWriter::printFunctionBody(const Function *F) {
1603 if (F->isDeclaration())
1604 return; // external functions have no bodies.
1605
1606 // Clear the DefinedValues and ForwardRefs maps because we can't have
1607 // cross-function forward refs
1608 ForwardRefs.clear();
1609 DefinedValues.clear();
1610
1611 // Create all the argument values
1612 if (!is_inline) {
1613 if (!F->arg_empty()) {
1614 Out << "Function::arg_iterator args = " << getCppName(F)
1615 << "->arg_begin();";
1616 nl(Out);
1617 }
1618 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1619 AI != AE; ++AI) {
1620 Out << "Value* " << getCppName(AI) << " = args++;";
1621 nl(Out);
1622 if (AI->hasName()) {
1623 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1624 nl(Out);
1625 }
1626 }
1627 }
1628
1629 // Create all the basic blocks
1630 nl(Out);
1631 for (Function::const_iterator BI = F->begin(), BE = F->end();
1632 BI != BE; ++BI) {
1633 std::string bbname(getCppName(BI));
1634 Out << "BasicBlock* " << bbname << " = BasicBlock::Create(\"";
1635 if (BI->hasName())
1636 printEscapedString(BI->getName());
1637 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1638 nl(Out);
1639 }
1640
1641 // Output all of its basic blocks... for the function
1642 for (Function::const_iterator BI = F->begin(), BE = F->end();
1643 BI != BE; ++BI) {
1644 std::string bbname(getCppName(BI));
1645 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1646 nl(Out);
1647
1648 // Output all of the instructions in the basic block...
1649 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1650 I != E; ++I) {
1651 printInstruction(I,bbname);
1652 }
1653 }
1654
1655 // Loop over the ForwardRefs and resolve them now that all instructions
1656 // are generated.
1657 if (!ForwardRefs.empty()) {
1658 nl(Out) << "// Resolve Forward References";
1659 nl(Out);
1660 }
1661
1662 while (!ForwardRefs.empty()) {
1663 ForwardRefMap::iterator I = ForwardRefs.begin();
1664 Out << I->second << "->replaceAllUsesWith("
1665 << getCppName(I->first) << "); delete " << I->second << ";";
1666 nl(Out);
1667 ForwardRefs.erase(I);
1668 }
1669 }
1670
1671 void CppWriter::printInline(const std::string& fname,
1672 const std::string& func) {
1673 const Function* F = TheModule->getFunction(func);
1674 if (!F) {
1675 error(std::string("Function '") + func + "' not found in input module");
1676 return;
1677 }
1678 if (F->isDeclaration()) {
1679 error(std::string("Function '") + func + "' is external!");
1680 return;
1681 }
1682 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1683 << getCppName(F);
1684 unsigned arg_count = 1;
1685 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1686 AI != AE; ++AI) {
1687 Out << ", Value* arg_" << arg_count;
1688 }
1689 Out << ") {";
1690 nl(Out);
1691 is_inline = true;
1692 printFunctionUses(F);
1693 printFunctionBody(F);
1694 is_inline = false;
1695 Out << "return " << getCppName(F->begin()) << ";";
1696 nl(Out) << "}";
1697 nl(Out);
1698 }
1699
1700 void CppWriter::printModuleBody() {
1701 // Print out all the type definitions
1702 nl(Out) << "// Type Definitions"; nl(Out);
1703 printTypes(TheModule);
1704
1705 // Functions can call each other and global variables can reference them so
1706 // define all the functions first before emitting their function bodies.
1707 nl(Out) << "// Function Declarations"; nl(Out);
1708 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1709 I != E; ++I)
1710 printFunctionHead(I);
1711
1712 // Process the global variables declarations. We can't initialze them until
1713 // after the constants are printed so just print a header for each global
1714 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1715 for (Module::const_global_iterator I = TheModule->global_begin(),
1716 E = TheModule->global_end(); I != E; ++I) {
1717 printVariableHead(I);
1718 }
1719
1720 // Print out all the constants definitions. Constants don't recurse except
1721 // through GlobalValues. All GlobalValues have been declared at this point
1722 // so we can proceed to generate the constants.
1723 nl(Out) << "// Constant Definitions"; nl(Out);
1724 printConstants(TheModule);
1725
1726 // Process the global variables definitions now that all the constants have
1727 // been emitted. These definitions just couple the gvars with their constant
1728 // initializers.
1729 nl(Out) << "// Global Variable Definitions"; nl(Out);
1730 for (Module::const_global_iterator I = TheModule->global_begin(),
1731 E = TheModule->global_end(); I != E; ++I) {
1732 printVariableBody(I);
1733 }
1734
1735 // Finally, we can safely put out all of the function bodies.
1736 nl(Out) << "// Function Definitions"; nl(Out);
1737 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1738 I != E; ++I) {
1739 if (!I->isDeclaration()) {
1740 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1741 << ")";
1742 nl(Out) << "{";
1743 nl(Out,1);
1744 printFunctionBody(I);
1745 nl(Out,-1) << "}";
1746 nl(Out);
1747 }
1748 }
1749 }
1750
1751 void CppWriter::printProgram(const std::string& fname,
1752 const std::string& mName) {
1753 Out << "#include \n";
1754 Out << "#include \n";
1755 Out << "#include \n";
1756 Out << "#include \n";
1757 Out << "#include \n";
1758 Out << "#include \n";
1759 Out << "#include \n";
1760 Out << "#include \n";
1761 Out << "#include \n";
1762 Out << "#include \n";
1763 Out << "#include \n";
1764 Out << "#include \n";
1765 Out << "#include \n";
1766 Out << "#include \n";
1767 Out << "#include \n";
1768 Out << "#include \n\n";
1769 Out << "using namespace llvm;\n\n";
1770 Out << "Module* " << fname << "();\n\n";
1771 Out << "int main(int argc, char**argv) {\n";
1772 Out << " Module* Mod = " << fname << "();\n";
1773 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1774 Out << " std::cerr.flush();\n";
1775 Out << " std::cout.flush();\n";
1776 Out << " PassManager PM;\n";
1777 Out << " PM.add(new PrintModulePass(&llvm::cout));\n";
1778 Out << " PM.run(*Mod);\n";
1779 Out << " return 0;\n";
1780 Out << "}\n\n";
1781 printModule(fname,mName);
1782 }
1783
1784 void CppWriter::printModule(const std::string& fname,
1785 const std::string& mName) {
1786 nl(Out) << "Module* " << fname << "() {";
1787 nl(Out,1) << "// Module Construction";
1788 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1789 if (!TheModule->getTargetTriple().empty()) {
1790 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1791 }
1792 if (!TheModule->getTargetTriple().empty()) {
1793 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1794 << "\");";
1795 }
1796
1797 if (!TheModule->getModuleInlineAsm().empty()) {
1798 nl(Out) << "mod->setModuleInlineAsm(\"";
1799 printEscapedString(TheModule->getModuleInlineAsm());
1800 Out << "\");";
1801 }
1802 nl(Out);
1803
1804 // Loop over the dependent libraries and emit them.
1805 Module::lib_iterator LI = TheModule->lib_begin();
1806 Module::lib_iterator LE = TheModule->lib_end();
1807 while (LI != LE) {
1808 Out << "mod->addLibrary(\"" << *LI << "\");";
1809 nl(Out);
1810 ++LI;
1811 }
1812 printModuleBody();
1813 nl(Out) << "return mod;";
1814 nl(Out,-1) << "}";
1815 nl(Out);
1816 }
1817
1818 void CppWriter::printContents(const std::string& fname,
1819 const std::string& mName) {
1820 Out << "\nModule* " << fname << "(Module *mod) {\n";
1821 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1822 printModuleBody();
1823 Out << "\nreturn mod;\n";
1824 Out << "\n}\n";
1825 }
1826
1827 void CppWriter::printFunction(const std::string& fname,
1828 const std::string& funcName) {
1829 const Function* F = TheModule->getFunction(funcName);
1830 if (!F) {
1831 error(std::string("Function '") + funcName + "' not found in input module");
1832 return;
1833 }
1834 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1835 printFunctionUses(F);
1836 printFunctionHead(F);
1837 printFunctionBody(F);
1838 Out << "return " << getCppName(F) << ";\n";
1839 Out << "}\n";
1840 }
1841
1842 void CppWriter::printFunctions() {
1843 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1844 Module::const_iterator I = funcs.begin();
1845 Module::const_iterator IE = funcs.end();
1846
1847 for (; I != IE; ++I) {
1848 const Function &func = *I;
1849 if (!func.isDeclaration()) {
1850 std::string name("define_");
1851 name += func.getName();
1852 printFunction(name, func.getName());
1853 }
1854 }
1855 }
1856
1857 void CppWriter::printVariable(const std::string& fname,
1858 const std::string& varName) {
1859 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1860
1861 if (!GV) {
1862 error(std::string("Variable '") + varName + "' not found in input module");
1863 return;
1864 }
1865 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1866 printVariableUses(GV);
1867 printVariableHead(GV);
1868 printVariableBody(GV);
1869 Out << "return " << getCppName(GV) << ";\n";
1870 Out << "}\n";
1871 }
1872
1873 void CppWriter::printType(const std::string& fname,
1874 const std::string& typeName) {
1875 const Type* Ty = TheModule->getTypeByName(typeName);
1876 if (!Ty) {
1877 error(std::string("Type '") + typeName + "' not found in input module");
1878 return;
1879 }
1880 Out << "\nType* " << fname << "(Module *mod) {\n";
1881 printType(Ty);
1882 Out << "return " << getCppName(Ty) << ";\n";
1883 Out << "}\n";
1884 }
1885
1886 bool CppWriter::runOnModule(Module &M) {
1887 TheModule = &M;
1888
1889 // Emit a header
1890 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1891
1892 // Get the name of the function we're supposed to generate
1893 std::string fname = FuncName.getValue();
1894
1895 // Get the name of the thing we are to generate
1896 std::string tgtname = NameToGenerate.getValue();
1897 if (GenerationType == GenModule ||
1898 GenerationType == GenContents ||
1899 GenerationType == GenProgram ||
1900 GenerationType == GenFunctions) {
1901 if (tgtname == "!bad!") {
1902 if (M.getModuleIdentifier() == "-")
1903 tgtname = "";
1904 else
1905 tgtname = M.getModuleIdentifier();
1906 }
1907 } else if (tgtname == "!bad!")
1908 error("You must use the -for option with -gen-{function,variable,type}");
1909
1910 switch (WhatToGenerate(GenerationType)) {
1911 case GenProgram:
1912 if (fname.empty())
1913 fname = "makeLLVMModule";
1914 printProgram(fname,tgtname);
1915 break;
1916 case GenModule:
1917 if (fname.empty())
1918 fname = "makeLLVMModule";
1919 printModule(fname,tgtname);
1920 break;
1921 case GenContents:
1922 if (fname.empty())
1923 fname = "makeLLVMModuleContents";
1924 printContents(fname,tgtname);
1925 break;
1926 case GenFunction:
1927 if (fname.empty())
1928 fname = "makeLLVMFunction";
1929 printFunction(fname,tgtname);
1930 break;
1931 case GenFunctions:
1932 printFunctions();
1933 break;
1934 case GenInline:
1935 if (fname.empty())
1936 fname = "makeLLVMInline";
1937 printInline(fname,tgtname);
1938 break;
1939 case GenVariable:
1940 if (fname.empty())
1941 fname = "makeLLVMVariable";
1942 printVariable(fname,tgtname);
1943 break;
1944 case GenType:
1945 if (fname.empty())
1946 fname = "makeLLVMType";
1947 printType(fname,tgtname);
1948 break;
1949 default:
1950 error("Invalid generation option");
1951 }
1952
1953 return false;
1954 }
1955 }
1956
1957 char CppWriter::ID = 0;
1958
1959 //===----------------------------------------------------------------------===//
1960 // External Interface declaration
1961 //===----------------------------------------------------------------------===//
1962
1963 bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
1964 std::ostream &o,
1965 CodeGenFileType FileType,
1966 bool Fast) {
1967 if (FileType != TargetMachine::AssemblyFile) return true;
1968 PM.add(new CppWriter(o));
1969 return false;
1970 }
0 //===-- CPPTargetMachine.h - TargetMachine for the C++ backend --*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file declares the TargetMachine that is used by the C++ backend.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef CPPTARGETMACHINE_H
14 #define CPPTARGETMACHINE_H
15
16 #include "llvm/Target/TargetMachine.h"
17 #include "llvm/Target/TargetData.h"
18
19 namespace llvm {
20
21 struct CPPTargetMachine : public TargetMachine {
22 const TargetData DataLayout; // Calculates type size & alignment
23
24 CPPTargetMachine(const Module &M, const std::string &FS)
25 : DataLayout(&M) {}
26
27 virtual bool WantsWholeFile() const { return true; }
28 virtual bool addPassesToEmitWholeFile(PassManager &PM, std::ostream &Out,
29 CodeGenFileType FileType, bool Fast);
30
31 // This class always works, but shouldn't be the default in most cases.
32 static unsigned getModuleMatchQuality(const Module &M) { return 1; }
33
34 virtual const TargetData *getTargetData() const { return &DataLayout; }
35 };
36
37 } // End llvm namespace
38
39
40 #endif
0 ##===- lib/Target/CppBackend/Makefile --- ------------------*- Makefile -*-===##
1 #
2 # The LLVM Compiler Infrastructure
3 #
4 # This file is distributed under the University of Illinois Open Source
5 # License. See LICENSE.TXT for details.
6 #
7 ##===----------------------------------------------------------------------===##
8
9 LEVEL = ../../..
10 LIBRARYNAME = LLVMCppBackend
11 include $(LEVEL)/Makefile.common
12
13 CompileCommonOpts += -Wno-format
133133
134134 switch (FileType) {
135135 case TargetMachine::AssemblyFile:
136 if (MArch->Name[0] != 'c' || MArch->Name[1] != 0) // not CBE
136 if (MArch->Name[0] == 'c') {
137 if (MArch->Name[1] == 0)
138 OutputFilename += ".cbe.c";
139 else if (MArch->Name[1] == 'p' && MArch->Name[2] == 'p')
140 OutputFilename += ".cpp";
141 else
142 OutputFilename += ".s";
143 } else
137144 OutputFilename += ".s";
138 else
139 OutputFilename += ".cbe.c";
140145 break;
141146 case TargetMachine::ObjectFile:
142147 OutputFilename += ".o";