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