blob: fc5be98828031c7896185c1cfd34e68c2c29b545 [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"
Bill Wendling1a53ead2008-07-27 23:18:30 +000031#include "llvm/Support/Streams.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000032#include "llvm/Config/config.h"
33#include <algorithm>
Anton Korobeynikov50276522008-04-23 22:29:24 +000034#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) {
Bill Wendling1a53ead2008-07-27 23:18:30 +0000212 cerr << progname << ": " << msg << "\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000213 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)) {
Anton Korobeynikov70053c32008-08-18 20:03:45 +0000735 std::string constValue = CI->getValue().toString(10, true);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000736 Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
Chris Lattnerfad86b02008-08-17 07:19:36 +0000737 << cast<IntegerType>(CI->getType())->getBitWidth() << ", \""
Anton Korobeynikov70053c32008-08-18 20:03:45 +0000738 << constValue << "\", " << constValue.length() << ", 10));";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000739 } else if (isa<ConstantAggregateZero>(CV)) {
740 Out << "ConstantAggregateZero* " << constName
741 << " = ConstantAggregateZero::get(" << typeName << ");";
742 } else if (isa<ConstantPointerNull>(CV)) {
743 Out << "ConstantPointerNull* " << constName
744 << " = ConstanPointerNull::get(" << typeName << ");";
745 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
746 Out << "ConstantFP* " << constName << " = ";
747 printCFP(CFP);
748 Out << ";";
749 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
750 if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
751 Out << "Constant* " << constName << " = ConstantArray::get(\"";
752 std::string tmp = CA->getAsString();
753 bool nullTerminate = false;
754 if (tmp[tmp.length()-1] == 0) {
755 tmp.erase(tmp.length()-1);
756 nullTerminate = true;
757 }
758 printEscapedString(tmp);
759 // Determine if we want null termination or not.
760 if (nullTerminate)
761 Out << "\", true"; // Indicate that the null terminator should be
762 // added.
763 else
764 Out << "\", false";// No null terminator
765 Out << ");";
766 } else {
767 Out << "std::vector<Constant*> " << constName << "_elems;";
768 nl(Out);
769 unsigned N = CA->getNumOperands();
770 for (unsigned i = 0; i < N; ++i) {
771 printConstant(CA->getOperand(i)); // recurse to print operands
772 Out << constName << "_elems.push_back("
773 << getCppName(CA->getOperand(i)) << ");";
774 nl(Out);
775 }
776 Out << "Constant* " << constName << " = ConstantArray::get("
777 << typeName << ", " << constName << "_elems);";
778 }
779 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
780 Out << "std::vector<Constant*> " << constName << "_fields;";
781 nl(Out);
782 unsigned N = CS->getNumOperands();
783 for (unsigned i = 0; i < N; i++) {
784 printConstant(CS->getOperand(i));
785 Out << constName << "_fields.push_back("
786 << getCppName(CS->getOperand(i)) << ");";
787 nl(Out);
788 }
789 Out << "Constant* " << constName << " = ConstantStruct::get("
790 << typeName << ", " << constName << "_fields);";
791 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
792 Out << "std::vector<Constant*> " << constName << "_elems;";
793 nl(Out);
794 unsigned N = CP->getNumOperands();
795 for (unsigned i = 0; i < N; ++i) {
796 printConstant(CP->getOperand(i));
797 Out << constName << "_elems.push_back("
798 << getCppName(CP->getOperand(i)) << ");";
799 nl(Out);
800 }
801 Out << "Constant* " << constName << " = ConstantVector::get("
802 << typeName << ", " << constName << "_elems);";
803 } else if (isa<UndefValue>(CV)) {
804 Out << "UndefValue* " << constName << " = UndefValue::get("
805 << typeName << ");";
806 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
807 if (CE->getOpcode() == Instruction::GetElementPtr) {
808 Out << "std::vector<Constant*> " << constName << "_indices;";
809 nl(Out);
810 printConstant(CE->getOperand(0));
811 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
812 printConstant(CE->getOperand(i));
813 Out << constName << "_indices.push_back("
814 << getCppName(CE->getOperand(i)) << ");";
815 nl(Out);
816 }
817 Out << "Constant* " << constName
818 << " = ConstantExpr::getGetElementPtr("
819 << getCppName(CE->getOperand(0)) << ", "
820 << "&" << constName << "_indices[0], "
821 << constName << "_indices.size()"
822 << " );";
823 } else if (CE->isCast()) {
824 printConstant(CE->getOperand(0));
825 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
826 switch (CE->getOpcode()) {
827 default: assert(0 && "Invalid cast opcode");
828 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
829 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
830 case Instruction::SExt: Out << "Instruction::SExt"; break;
831 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
832 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
833 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
834 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
835 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
836 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
837 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
838 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
839 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
840 }
841 Out << ", " << getCppName(CE->getOperand(0)) << ", "
842 << getCppName(CE->getType()) << ");";
843 } else {
844 unsigned N = CE->getNumOperands();
845 for (unsigned i = 0; i < N; ++i ) {
846 printConstant(CE->getOperand(i));
847 }
848 Out << "Constant* " << constName << " = ConstantExpr::";
849 switch (CE->getOpcode()) {
850 case Instruction::Add: Out << "getAdd("; break;
851 case Instruction::Sub: Out << "getSub("; break;
852 case Instruction::Mul: Out << "getMul("; break;
853 case Instruction::UDiv: Out << "getUDiv("; break;
854 case Instruction::SDiv: Out << "getSDiv("; break;
855 case Instruction::FDiv: Out << "getFDiv("; break;
856 case Instruction::URem: Out << "getURem("; break;
857 case Instruction::SRem: Out << "getSRem("; break;
858 case Instruction::FRem: Out << "getFRem("; break;
859 case Instruction::And: Out << "getAnd("; break;
860 case Instruction::Or: Out << "getOr("; break;
861 case Instruction::Xor: Out << "getXor("; break;
862 case Instruction::ICmp:
863 Out << "getICmp(ICmpInst::ICMP_";
864 switch (CE->getPredicate()) {
865 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
866 case ICmpInst::ICMP_NE: Out << "NE"; break;
867 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
868 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
869 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
870 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
871 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
872 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
873 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
874 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
875 default: error("Invalid ICmp Predicate");
876 }
877 break;
878 case Instruction::FCmp:
879 Out << "getFCmp(FCmpInst::FCMP_";
880 switch (CE->getPredicate()) {
881 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
882 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
883 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
884 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
885 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
886 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
887 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
888 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
889 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
890 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
891 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
892 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
893 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
894 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
895 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
896 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
897 default: error("Invalid FCmp Predicate");
898 }
899 break;
900 case Instruction::Shl: Out << "getShl("; break;
901 case Instruction::LShr: Out << "getLShr("; break;
902 case Instruction::AShr: Out << "getAShr("; break;
903 case Instruction::Select: Out << "getSelect("; break;
904 case Instruction::ExtractElement: Out << "getExtractElement("; break;
905 case Instruction::InsertElement: Out << "getInsertElement("; break;
906 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
907 default:
908 error("Invalid constant expression");
909 break;
910 }
911 Out << getCppName(CE->getOperand(0));
912 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
913 Out << ", " << getCppName(CE->getOperand(i));
914 Out << ");";
915 }
916 } else {
917 error("Bad Constant");
918 Out << "Constant* " << constName << " = 0; ";
919 }
920 nl(Out);
921 }
922
923 void CppWriter::printConstants(const Module* M) {
924 // Traverse all the global variables looking for constant initializers
925 for (Module::const_global_iterator I = TheModule->global_begin(),
926 E = TheModule->global_end(); I != E; ++I)
927 if (I->hasInitializer())
928 printConstant(I->getInitializer());
929
930 // Traverse the LLVM functions looking for constants
931 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
932 FI != FE; ++FI) {
933 // Add all of the basic blocks and instructions
934 for (Function::const_iterator BB = FI->begin(),
935 E = FI->end(); BB != E; ++BB) {
936 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
937 ++I) {
938 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
939 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
940 printConstant(C);
941 }
942 }
943 }
944 }
945 }
946 }
947
948 void CppWriter::printVariableUses(const GlobalVariable *GV) {
949 nl(Out) << "// Type Definitions";
950 nl(Out);
951 printType(GV->getType());
952 if (GV->hasInitializer()) {
953 Constant* Init = GV->getInitializer();
954 printType(Init->getType());
955 if (Function* F = dyn_cast<Function>(Init)) {
956 nl(Out)<< "/ Function Declarations"; nl(Out);
957 printFunctionHead(F);
958 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
959 nl(Out) << "// Global Variable Declarations"; nl(Out);
960 printVariableHead(gv);
961 } else {
962 nl(Out) << "// Constant Definitions"; nl(Out);
963 printConstant(gv);
964 }
965 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
966 nl(Out) << "// Global Variable Definitions"; nl(Out);
967 printVariableBody(gv);
968 }
969 }
970 }
971
972 void CppWriter::printVariableHead(const GlobalVariable *GV) {
973 nl(Out) << "GlobalVariable* " << getCppName(GV);
974 if (is_inline) {
975 Out << " = mod->getGlobalVariable(";
976 printEscapedString(GV->getName());
977 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
978 nl(Out) << "if (!" << getCppName(GV) << ") {";
979 in(); nl(Out) << getCppName(GV);
980 }
981 Out << " = new GlobalVariable(";
982 nl(Out) << "/*Type=*/";
983 printCppName(GV->getType()->getElementType());
984 Out << ",";
985 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
986 Out << ",";
987 nl(Out) << "/*Linkage=*/";
988 printLinkageType(GV->getLinkage());
989 Out << ",";
990 nl(Out) << "/*Initializer=*/0, ";
991 if (GV->hasInitializer()) {
992 Out << "// has initializer, specified below";
993 }
994 nl(Out) << "/*Name=*/\"";
995 printEscapedString(GV->getName());
996 Out << "\",";
997 nl(Out) << "mod);";
998 nl(Out);
999
1000 if (GV->hasSection()) {
1001 printCppName(GV);
1002 Out << "->setSection(\"";
1003 printEscapedString(GV->getSection());
1004 Out << "\");";
1005 nl(Out);
1006 }
1007 if (GV->getAlignment()) {
1008 printCppName(GV);
1009 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1010 nl(Out);
1011 }
1012 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1013 printCppName(GV);
1014 Out << "->setVisibility(";
1015 printVisibilityType(GV->getVisibility());
1016 Out << ");";
1017 nl(Out);
1018 }
1019 if (is_inline) {
1020 out(); Out << "}"; nl(Out);
1021 }
1022 }
1023
1024 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1025 if (GV->hasInitializer()) {
1026 printCppName(GV);
1027 Out << "->setInitializer(";
1028 Out << getCppName(GV->getInitializer()) << ");";
1029 nl(Out);
1030 }
1031 }
1032
1033 std::string CppWriter::getOpName(Value* V) {
1034 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1035 return getCppName(V);
1036
1037 // See if its alread in the map of forward references, if so just return the
1038 // name we already set up for it
1039 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1040 if (I != ForwardRefs.end())
1041 return I->second;
1042
1043 // This is a new forward reference. Generate a unique name for it
1044 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1045
1046 // Yes, this is a hack. An Argument is the smallest instantiable value that
1047 // we can make as a placeholder for the real value. We'll replace these
1048 // Argument instances later.
1049 Out << "Argument* " << result << " = new Argument("
1050 << getCppName(V->getType()) << ");";
1051 nl(Out);
1052 ForwardRefs[V] = result;
1053 return result;
1054 }
1055
1056 // printInstruction - This member is called for each Instruction in a function.
1057 void CppWriter::printInstruction(const Instruction *I,
1058 const std::string& bbname) {
1059 std::string iName(getCppName(I));
1060
1061 // Before we emit this instruction, we need to take care of generating any
1062 // forward references. So, we get the names of all the operands in advance
1063 std::string* opNames = new std::string[I->getNumOperands()];
1064 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1065 opNames[i] = getOpName(I->getOperand(i));
1066 }
1067
1068 switch (I->getOpcode()) {
Dan Gohman26825a82008-06-09 14:09:13 +00001069 default:
1070 error("Invalid instruction");
1071 break;
1072
Anton Korobeynikov50276522008-04-23 22:29:24 +00001073 case Instruction::Ret: {
1074 const ReturnInst* ret = cast<ReturnInst>(I);
1075 Out << "ReturnInst::Create("
1076 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1077 break;
1078 }
1079 case Instruction::Br: {
1080 const BranchInst* br = cast<BranchInst>(I);
1081 Out << "BranchInst::Create(" ;
1082 if (br->getNumOperands() == 3 ) {
1083 Out << opNames[0] << ", "
1084 << opNames[1] << ", "
1085 << opNames[2] << ", ";
1086
1087 } else if (br->getNumOperands() == 1) {
1088 Out << opNames[0] << ", ";
1089 } else {
1090 error("Branch with 2 operands?");
1091 }
1092 Out << bbname << ");";
1093 break;
1094 }
1095 case Instruction::Switch: {
1096 const SwitchInst* sw = cast<SwitchInst>(I);
1097 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1098 << opNames[0] << ", "
1099 << opNames[1] << ", "
1100 << sw->getNumCases() << ", " << bbname << ");";
1101 nl(Out);
1102 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1103 Out << iName << "->addCase("
1104 << opNames[i] << ", "
1105 << opNames[i+1] << ");";
1106 nl(Out);
1107 }
1108 break;
1109 }
1110 case Instruction::Invoke: {
1111 const InvokeInst* inv = cast<InvokeInst>(I);
1112 Out << "std::vector<Value*> " << iName << "_params;";
1113 nl(Out);
1114 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1115 Out << iName << "_params.push_back("
1116 << opNames[i] << ");";
1117 nl(Out);
1118 }
1119 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1120 << opNames[0] << ", "
1121 << opNames[1] << ", "
1122 << opNames[2] << ", "
1123 << iName << "_params.begin(), " << iName << "_params.end(), \"";
1124 printEscapedString(inv->getName());
1125 Out << "\", " << bbname << ");";
1126 nl(Out) << iName << "->setCallingConv(";
1127 printCallingConv(inv->getCallingConv());
1128 Out << ");";
1129 printParamAttrs(inv->getParamAttrs(), iName);
1130 Out << iName << "->setParamAttrs(" << iName << "_PAL);";
1131 nl(Out);
1132 break;
1133 }
1134 case Instruction::Unwind: {
1135 Out << "new UnwindInst("
1136 << bbname << ");";
1137 break;
1138 }
1139 case Instruction::Unreachable:{
1140 Out << "new UnreachableInst("
1141 << bbname << ");";
1142 break;
1143 }
1144 case Instruction::Add:
1145 case Instruction::Sub:
1146 case Instruction::Mul:
1147 case Instruction::UDiv:
1148 case Instruction::SDiv:
1149 case Instruction::FDiv:
1150 case Instruction::URem:
1151 case Instruction::SRem:
1152 case Instruction::FRem:
1153 case Instruction::And:
1154 case Instruction::Or:
1155 case Instruction::Xor:
1156 case Instruction::Shl:
1157 case Instruction::LShr:
1158 case Instruction::AShr:{
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001159 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001160 switch (I->getOpcode()) {
1161 case Instruction::Add: Out << "Instruction::Add"; break;
1162 case Instruction::Sub: Out << "Instruction::Sub"; break;
1163 case Instruction::Mul: Out << "Instruction::Mul"; break;
1164 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1165 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1166 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1167 case Instruction::URem:Out << "Instruction::URem"; break;
1168 case Instruction::SRem:Out << "Instruction::SRem"; break;
1169 case Instruction::FRem:Out << "Instruction::FRem"; break;
1170 case Instruction::And: Out << "Instruction::And"; break;
1171 case Instruction::Or: Out << "Instruction::Or"; break;
1172 case Instruction::Xor: Out << "Instruction::Xor"; break;
1173 case Instruction::Shl: Out << "Instruction::Shl"; break;
1174 case Instruction::LShr:Out << "Instruction::LShr"; break;
1175 case Instruction::AShr:Out << "Instruction::AShr"; break;
1176 default: Out << "Instruction::BadOpCode"; break;
1177 }
1178 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1179 printEscapedString(I->getName());
1180 Out << "\", " << bbname << ");";
1181 break;
1182 }
1183 case Instruction::FCmp: {
1184 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1185 switch (cast<FCmpInst>(I)->getPredicate()) {
1186 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1187 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1188 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1189 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1190 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1191 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1192 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1193 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1194 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1195 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1196 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1197 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1198 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1199 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1200 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1201 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1202 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1203 }
1204 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1205 printEscapedString(I->getName());
1206 Out << "\", " << bbname << ");";
1207 break;
1208 }
1209 case Instruction::ICmp: {
1210 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1211 switch (cast<ICmpInst>(I)->getPredicate()) {
1212 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1213 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1214 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1215 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1216 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1217 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1218 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1219 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1220 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1221 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1222 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1223 }
1224 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1225 printEscapedString(I->getName());
1226 Out << "\", " << bbname << ");";
1227 break;
1228 }
1229 case Instruction::Malloc: {
1230 const MallocInst* mallocI = cast<MallocInst>(I);
1231 Out << "MallocInst* " << iName << " = new MallocInst("
1232 << getCppName(mallocI->getAllocatedType()) << ", ";
1233 if (mallocI->isArrayAllocation())
1234 Out << opNames[0] << ", " ;
1235 Out << "\"";
1236 printEscapedString(mallocI->getName());
1237 Out << "\", " << bbname << ");";
1238 if (mallocI->getAlignment())
1239 nl(Out) << iName << "->setAlignment("
1240 << mallocI->getAlignment() << ");";
1241 break;
1242 }
1243 case Instruction::Free: {
1244 Out << "FreeInst* " << iName << " = new FreeInst("
1245 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1246 break;
1247 }
1248 case Instruction::Alloca: {
1249 const AllocaInst* allocaI = cast<AllocaInst>(I);
1250 Out << "AllocaInst* " << iName << " = new AllocaInst("
1251 << getCppName(allocaI->getAllocatedType()) << ", ";
1252 if (allocaI->isArrayAllocation())
1253 Out << opNames[0] << ", ";
1254 Out << "\"";
1255 printEscapedString(allocaI->getName());
1256 Out << "\", " << bbname << ");";
1257 if (allocaI->getAlignment())
1258 nl(Out) << iName << "->setAlignment("
1259 << allocaI->getAlignment() << ");";
1260 break;
1261 }
1262 case Instruction::Load:{
1263 const LoadInst* load = cast<LoadInst>(I);
1264 Out << "LoadInst* " << iName << " = new LoadInst("
1265 << opNames[0] << ", \"";
1266 printEscapedString(load->getName());
1267 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1268 << ", " << bbname << ");";
1269 break;
1270 }
1271 case Instruction::Store: {
1272 const StoreInst* store = cast<StoreInst>(I);
1273 Out << "StoreInst* " << iName << " = new StoreInst("
1274 << opNames[0] << ", "
1275 << opNames[1] << ", "
1276 << (store->isVolatile() ? "true" : "false")
1277 << ", " << bbname << ");";
1278 break;
1279 }
1280 case Instruction::GetElementPtr: {
1281 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1282 if (gep->getNumOperands() <= 2) {
1283 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1284 << opNames[0];
1285 if (gep->getNumOperands() == 2)
1286 Out << ", " << opNames[1];
1287 } else {
1288 Out << "std::vector<Value*> " << iName << "_indices;";
1289 nl(Out);
1290 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1291 Out << iName << "_indices.push_back("
1292 << opNames[i] << ");";
1293 nl(Out);
1294 }
1295 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1296 << opNames[0] << ", " << iName << "_indices.begin(), "
1297 << iName << "_indices.end()";
1298 }
1299 Out << ", \"";
1300 printEscapedString(gep->getName());
1301 Out << "\", " << bbname << ");";
1302 break;
1303 }
1304 case Instruction::PHI: {
1305 const PHINode* phi = cast<PHINode>(I);
1306
1307 Out << "PHINode* " << iName << " = PHINode::Create("
1308 << getCppName(phi->getType()) << ", \"";
1309 printEscapedString(phi->getName());
1310 Out << "\", " << bbname << ");";
1311 nl(Out) << iName << "->reserveOperandSpace("
1312 << phi->getNumIncomingValues()
1313 << ");";
1314 nl(Out);
1315 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1316 Out << iName << "->addIncoming("
1317 << opNames[i] << ", " << opNames[i+1] << ");";
1318 nl(Out);
1319 }
1320 break;
1321 }
1322 case Instruction::Trunc:
1323 case Instruction::ZExt:
1324 case Instruction::SExt:
1325 case Instruction::FPTrunc:
1326 case Instruction::FPExt:
1327 case Instruction::FPToUI:
1328 case Instruction::FPToSI:
1329 case Instruction::UIToFP:
1330 case Instruction::SIToFP:
1331 case Instruction::PtrToInt:
1332 case Instruction::IntToPtr:
1333 case Instruction::BitCast: {
1334 const CastInst* cst = cast<CastInst>(I);
1335 Out << "CastInst* " << iName << " = new ";
1336 switch (I->getOpcode()) {
1337 case Instruction::Trunc: Out << "TruncInst"; break;
1338 case Instruction::ZExt: Out << "ZExtInst"; break;
1339 case Instruction::SExt: Out << "SExtInst"; break;
1340 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1341 case Instruction::FPExt: Out << "FPExtInst"; break;
1342 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1343 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1344 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1345 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1346 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1347 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1348 case Instruction::BitCast: Out << "BitCastInst"; break;
1349 default: assert(!"Unreachable"); break;
1350 }
1351 Out << "(" << opNames[0] << ", "
1352 << getCppName(cst->getType()) << ", \"";
1353 printEscapedString(cst->getName());
1354 Out << "\", " << bbname << ");";
1355 break;
1356 }
1357 case Instruction::Call:{
1358 const CallInst* call = cast<CallInst>(I);
1359 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1360 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1361 << getCppName(ila->getFunctionType()) << ", \""
1362 << ila->getAsmString() << "\", \""
1363 << ila->getConstraintString() << "\","
1364 << (ila->hasSideEffects() ? "true" : "false") << ");";
1365 nl(Out);
1366 }
1367 if (call->getNumOperands() > 2) {
1368 Out << "std::vector<Value*> " << iName << "_params;";
1369 nl(Out);
1370 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1371 Out << iName << "_params.push_back(" << opNames[i] << ");";
1372 nl(Out);
1373 }
1374 Out << "CallInst* " << iName << " = CallInst::Create("
1375 << opNames[0] << ", " << iName << "_params.begin(), "
1376 << iName << "_params.end(), \"";
1377 } else if (call->getNumOperands() == 2) {
1378 Out << "CallInst* " << iName << " = CallInst::Create("
1379 << opNames[0] << ", " << opNames[1] << ", \"";
1380 } else {
1381 Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
1382 << ", \"";
1383 }
1384 printEscapedString(call->getName());
1385 Out << "\", " << bbname << ");";
1386 nl(Out) << iName << "->setCallingConv(";
1387 printCallingConv(call->getCallingConv());
1388 Out << ");";
1389 nl(Out) << iName << "->setTailCall("
1390 << (call->isTailCall() ? "true":"false");
1391 Out << ");";
1392 printParamAttrs(call->getParamAttrs(), iName);
1393 Out << iName << "->setParamAttrs(" << iName << "_PAL);";
1394 nl(Out);
1395 break;
1396 }
1397 case Instruction::Select: {
1398 const SelectInst* sel = cast<SelectInst>(I);
1399 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1400 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1401 printEscapedString(sel->getName());
1402 Out << "\", " << bbname << ");";
1403 break;
1404 }
1405 case Instruction::UserOp1:
1406 /// FALL THROUGH
1407 case Instruction::UserOp2: {
1408 /// FIXME: What should be done here?
1409 break;
1410 }
1411 case Instruction::VAArg: {
1412 const VAArgInst* va = cast<VAArgInst>(I);
1413 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1414 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1415 printEscapedString(va->getName());
1416 Out << "\", " << bbname << ");";
1417 break;
1418 }
1419 case Instruction::ExtractElement: {
1420 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1421 Out << "ExtractElementInst* " << getCppName(eei)
1422 << " = new ExtractElementInst(" << opNames[0]
1423 << ", " << opNames[1] << ", \"";
1424 printEscapedString(eei->getName());
1425 Out << "\", " << bbname << ");";
1426 break;
1427 }
1428 case Instruction::InsertElement: {
1429 const InsertElementInst* iei = cast<InsertElementInst>(I);
1430 Out << "InsertElementInst* " << getCppName(iei)
1431 << " = InsertElementInst::Create(" << opNames[0]
1432 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1433 printEscapedString(iei->getName());
1434 Out << "\", " << bbname << ");";
1435 break;
1436 }
1437 case Instruction::ShuffleVector: {
1438 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1439 Out << "ShuffleVectorInst* " << getCppName(svi)
1440 << " = new ShuffleVectorInst(" << opNames[0]
1441 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1442 printEscapedString(svi->getName());
1443 Out << "\", " << bbname << ");";
1444 break;
1445 }
Dan Gohman75146a62008-06-09 14:12:10 +00001446 case Instruction::ExtractValue: {
1447 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1448 Out << "std::vector<unsigned> " << iName << "_indices;";
1449 nl(Out);
1450 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1451 Out << iName << "_indices.push_back("
1452 << evi->idx_begin()[i] << ");";
1453 nl(Out);
1454 }
1455 Out << "ExtractValueInst* " << getCppName(evi)
1456 << " = ExtractValueInst::Create(" << opNames[0]
1457 << ", "
1458 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1459 printEscapedString(evi->getName());
1460 Out << "\", " << bbname << ");";
1461 break;
1462 }
1463 case Instruction::InsertValue: {
1464 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1465 Out << "std::vector<unsigned> " << iName << "_indices;";
1466 nl(Out);
1467 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1468 Out << iName << "_indices.push_back("
1469 << ivi->idx_begin()[i] << ");";
1470 nl(Out);
1471 }
1472 Out << "InsertValueInst* " << getCppName(ivi)
1473 << " = InsertValueInst::Create(" << opNames[0]
1474 << ", " << opNames[1] << ", "
1475 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1476 printEscapedString(ivi->getName());
1477 Out << "\", " << bbname << ");";
1478 break;
1479 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001480 }
1481 DefinedValues.insert(I);
1482 nl(Out);
1483 delete [] opNames;
1484}
1485
1486 // Print out the types, constants and declarations needed by one function
1487 void CppWriter::printFunctionUses(const Function* F) {
1488 nl(Out) << "// Type Definitions"; nl(Out);
1489 if (!is_inline) {
1490 // Print the function's return type
1491 printType(F->getReturnType());
1492
1493 // Print the function's function type
1494 printType(F->getFunctionType());
1495
1496 // Print the types of each of the function's arguments
1497 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1498 AI != AE; ++AI) {
1499 printType(AI->getType());
1500 }
1501 }
1502
1503 // Print type definitions for every type referenced by an instruction and
1504 // make a note of any global values or constants that are referenced
1505 SmallPtrSet<GlobalValue*,64> gvs;
1506 SmallPtrSet<Constant*,64> consts;
1507 for (Function::const_iterator BB = F->begin(), BE = F->end();
1508 BB != BE; ++BB){
1509 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1510 I != E; ++I) {
1511 // Print the type of the instruction itself
1512 printType(I->getType());
1513
1514 // Print the type of each of the instruction's operands
1515 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1516 Value* operand = I->getOperand(i);
1517 printType(operand->getType());
1518
1519 // If the operand references a GVal or Constant, make a note of it
1520 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1521 gvs.insert(GV);
1522 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1523 if (GVar->hasInitializer())
1524 consts.insert(GVar->getInitializer());
1525 } else if (Constant* C = dyn_cast<Constant>(operand))
1526 consts.insert(C);
1527 }
1528 }
1529 }
1530
1531 // Print the function declarations for any functions encountered
1532 nl(Out) << "// Function Declarations"; nl(Out);
1533 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1534 I != E; ++I) {
1535 if (Function* Fun = dyn_cast<Function>(*I)) {
1536 if (!is_inline || Fun != F)
1537 printFunctionHead(Fun);
1538 }
1539 }
1540
1541 // Print the global variable declarations for any variables encountered
1542 nl(Out) << "// Global Variable Declarations"; nl(Out);
1543 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1544 I != E; ++I) {
1545 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1546 printVariableHead(F);
1547 }
1548
1549 // Print the constants found
1550 nl(Out) << "// Constant Definitions"; nl(Out);
1551 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1552 E = consts.end(); I != E; ++I) {
1553 printConstant(*I);
1554 }
1555
1556 // Process the global variables definitions now that all the constants have
1557 // been emitted. These definitions just couple the gvars with their constant
1558 // initializers.
1559 nl(Out) << "// Global Variable Definitions"; nl(Out);
1560 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1561 I != E; ++I) {
1562 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1563 printVariableBody(GV);
1564 }
1565 }
1566
1567 void CppWriter::printFunctionHead(const Function* F) {
1568 nl(Out) << "Function* " << getCppName(F);
1569 if (is_inline) {
1570 Out << " = mod->getFunction(\"";
1571 printEscapedString(F->getName());
1572 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1573 nl(Out) << "if (!" << getCppName(F) << ") {";
1574 nl(Out) << getCppName(F);
1575 }
1576 Out<< " = Function::Create(";
1577 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1578 nl(Out) << "/*Linkage=*/";
1579 printLinkageType(F->getLinkage());
1580 Out << ",";
1581 nl(Out) << "/*Name=*/\"";
1582 printEscapedString(F->getName());
1583 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1584 nl(Out,-1);
1585 printCppName(F);
1586 Out << "->setCallingConv(";
1587 printCallingConv(F->getCallingConv());
1588 Out << ");";
1589 nl(Out);
1590 if (F->hasSection()) {
1591 printCppName(F);
1592 Out << "->setSection(\"" << F->getSection() << "\");";
1593 nl(Out);
1594 }
1595 if (F->getAlignment()) {
1596 printCppName(F);
1597 Out << "->setAlignment(" << F->getAlignment() << ");";
1598 nl(Out);
1599 }
1600 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1601 printCppName(F);
1602 Out << "->setVisibility(";
1603 printVisibilityType(F->getVisibility());
1604 Out << ");";
1605 nl(Out);
1606 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001607 if (F->hasGC()) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001608 printCppName(F);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001609 Out << "->setGC(\"" << F->getGC() << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001610 nl(Out);
1611 }
1612 if (is_inline) {
1613 Out << "}";
1614 nl(Out);
1615 }
1616 printParamAttrs(F->getParamAttrs(), getCppName(F));
1617 printCppName(F);
1618 Out << "->setParamAttrs(" << getCppName(F) << "_PAL);";
1619 nl(Out);
1620 }
1621
1622 void CppWriter::printFunctionBody(const Function *F) {
1623 if (F->isDeclaration())
1624 return; // external functions have no bodies.
1625
1626 // Clear the DefinedValues and ForwardRefs maps because we can't have
1627 // cross-function forward refs
1628 ForwardRefs.clear();
1629 DefinedValues.clear();
1630
1631 // Create all the argument values
1632 if (!is_inline) {
1633 if (!F->arg_empty()) {
1634 Out << "Function::arg_iterator args = " << getCppName(F)
1635 << "->arg_begin();";
1636 nl(Out);
1637 }
1638 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1639 AI != AE; ++AI) {
1640 Out << "Value* " << getCppName(AI) << " = args++;";
1641 nl(Out);
1642 if (AI->hasName()) {
1643 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1644 nl(Out);
1645 }
1646 }
1647 }
1648
1649 // Create all the basic blocks
1650 nl(Out);
1651 for (Function::const_iterator BI = F->begin(), BE = F->end();
1652 BI != BE; ++BI) {
1653 std::string bbname(getCppName(BI));
1654 Out << "BasicBlock* " << bbname << " = BasicBlock::Create(\"";
1655 if (BI->hasName())
1656 printEscapedString(BI->getName());
1657 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1658 nl(Out);
1659 }
1660
1661 // Output all of its basic blocks... for the function
1662 for (Function::const_iterator BI = F->begin(), BE = F->end();
1663 BI != BE; ++BI) {
1664 std::string bbname(getCppName(BI));
1665 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1666 nl(Out);
1667
1668 // Output all of the instructions in the basic block...
1669 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1670 I != E; ++I) {
1671 printInstruction(I,bbname);
1672 }
1673 }
1674
1675 // Loop over the ForwardRefs and resolve them now that all instructions
1676 // are generated.
1677 if (!ForwardRefs.empty()) {
1678 nl(Out) << "// Resolve Forward References";
1679 nl(Out);
1680 }
1681
1682 while (!ForwardRefs.empty()) {
1683 ForwardRefMap::iterator I = ForwardRefs.begin();
1684 Out << I->second << "->replaceAllUsesWith("
1685 << getCppName(I->first) << "); delete " << I->second << ";";
1686 nl(Out);
1687 ForwardRefs.erase(I);
1688 }
1689 }
1690
1691 void CppWriter::printInline(const std::string& fname,
1692 const std::string& func) {
1693 const Function* F = TheModule->getFunction(func);
1694 if (!F) {
1695 error(std::string("Function '") + func + "' not found in input module");
1696 return;
1697 }
1698 if (F->isDeclaration()) {
1699 error(std::string("Function '") + func + "' is external!");
1700 return;
1701 }
1702 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1703 << getCppName(F);
1704 unsigned arg_count = 1;
1705 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1706 AI != AE; ++AI) {
1707 Out << ", Value* arg_" << arg_count;
1708 }
1709 Out << ") {";
1710 nl(Out);
1711 is_inline = true;
1712 printFunctionUses(F);
1713 printFunctionBody(F);
1714 is_inline = false;
1715 Out << "return " << getCppName(F->begin()) << ";";
1716 nl(Out) << "}";
1717 nl(Out);
1718 }
1719
1720 void CppWriter::printModuleBody() {
1721 // Print out all the type definitions
1722 nl(Out) << "// Type Definitions"; nl(Out);
1723 printTypes(TheModule);
1724
1725 // Functions can call each other and global variables can reference them so
1726 // define all the functions first before emitting their function bodies.
1727 nl(Out) << "// Function Declarations"; nl(Out);
1728 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1729 I != E; ++I)
1730 printFunctionHead(I);
1731
1732 // Process the global variables declarations. We can't initialze them until
1733 // after the constants are printed so just print a header for each global
1734 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1735 for (Module::const_global_iterator I = TheModule->global_begin(),
1736 E = TheModule->global_end(); I != E; ++I) {
1737 printVariableHead(I);
1738 }
1739
1740 // Print out all the constants definitions. Constants don't recurse except
1741 // through GlobalValues. All GlobalValues have been declared at this point
1742 // so we can proceed to generate the constants.
1743 nl(Out) << "// Constant Definitions"; nl(Out);
1744 printConstants(TheModule);
1745
1746 // Process the global variables definitions now that all the constants have
1747 // been emitted. These definitions just couple the gvars with their constant
1748 // initializers.
1749 nl(Out) << "// Global Variable Definitions"; nl(Out);
1750 for (Module::const_global_iterator I = TheModule->global_begin(),
1751 E = TheModule->global_end(); I != E; ++I) {
1752 printVariableBody(I);
1753 }
1754
1755 // Finally, we can safely put out all of the function bodies.
1756 nl(Out) << "// Function Definitions"; nl(Out);
1757 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1758 I != E; ++I) {
1759 if (!I->isDeclaration()) {
1760 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1761 << ")";
1762 nl(Out) << "{";
1763 nl(Out,1);
1764 printFunctionBody(I);
1765 nl(Out,-1) << "}";
1766 nl(Out);
1767 }
1768 }
1769 }
1770
1771 void CppWriter::printProgram(const std::string& fname,
1772 const std::string& mName) {
1773 Out << "#include <llvm/Module.h>\n";
1774 Out << "#include <llvm/DerivedTypes.h>\n";
1775 Out << "#include <llvm/Constants.h>\n";
1776 Out << "#include <llvm/GlobalVariable.h>\n";
1777 Out << "#include <llvm/Function.h>\n";
1778 Out << "#include <llvm/CallingConv.h>\n";
1779 Out << "#include <llvm/BasicBlock.h>\n";
1780 Out << "#include <llvm/Instructions.h>\n";
1781 Out << "#include <llvm/InlineAsm.h>\n";
1782 Out << "#include <llvm/Support/MathExtras.h>\n";
1783 Out << "#include <llvm/Pass.h>\n";
1784 Out << "#include <llvm/PassManager.h>\n";
Nicolas Geoffray9474ede2008-05-14 07:52:03 +00001785 Out << "#include <llvm/ADT/SmallVector.h>\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001786 Out << "#include <llvm/Analysis/Verifier.h>\n";
1787 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1788 Out << "#include <algorithm>\n";
1789 Out << "#include <iostream>\n\n";
1790 Out << "using namespace llvm;\n\n";
1791 Out << "Module* " << fname << "();\n\n";
1792 Out << "int main(int argc, char**argv) {\n";
1793 Out << " Module* Mod = " << fname << "();\n";
1794 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1795 Out << " std::cerr.flush();\n";
1796 Out << " std::cout.flush();\n";
1797 Out << " PassManager PM;\n";
1798 Out << " PM.add(new PrintModulePass(&llvm::cout));\n";
1799 Out << " PM.run(*Mod);\n";
1800 Out << " return 0;\n";
1801 Out << "}\n\n";
1802 printModule(fname,mName);
1803 }
1804
1805 void CppWriter::printModule(const std::string& fname,
1806 const std::string& mName) {
1807 nl(Out) << "Module* " << fname << "() {";
1808 nl(Out,1) << "// Module Construction";
1809 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1810 if (!TheModule->getTargetTriple().empty()) {
1811 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1812 }
1813 if (!TheModule->getTargetTriple().empty()) {
1814 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1815 << "\");";
1816 }
1817
1818 if (!TheModule->getModuleInlineAsm().empty()) {
1819 nl(Out) << "mod->setModuleInlineAsm(\"";
1820 printEscapedString(TheModule->getModuleInlineAsm());
1821 Out << "\");";
1822 }
1823 nl(Out);
1824
1825 // Loop over the dependent libraries and emit them.
1826 Module::lib_iterator LI = TheModule->lib_begin();
1827 Module::lib_iterator LE = TheModule->lib_end();
1828 while (LI != LE) {
1829 Out << "mod->addLibrary(\"" << *LI << "\");";
1830 nl(Out);
1831 ++LI;
1832 }
1833 printModuleBody();
1834 nl(Out) << "return mod;";
1835 nl(Out,-1) << "}";
1836 nl(Out);
1837 }
1838
1839 void CppWriter::printContents(const std::string& fname,
1840 const std::string& mName) {
1841 Out << "\nModule* " << fname << "(Module *mod) {\n";
1842 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1843 printModuleBody();
1844 Out << "\nreturn mod;\n";
1845 Out << "\n}\n";
1846 }
1847
1848 void CppWriter::printFunction(const std::string& fname,
1849 const std::string& funcName) {
1850 const Function* F = TheModule->getFunction(funcName);
1851 if (!F) {
1852 error(std::string("Function '") + funcName + "' not found in input module");
1853 return;
1854 }
1855 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1856 printFunctionUses(F);
1857 printFunctionHead(F);
1858 printFunctionBody(F);
1859 Out << "return " << getCppName(F) << ";\n";
1860 Out << "}\n";
1861 }
1862
1863 void CppWriter::printFunctions() {
1864 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1865 Module::const_iterator I = funcs.begin();
1866 Module::const_iterator IE = funcs.end();
1867
1868 for (; I != IE; ++I) {
1869 const Function &func = *I;
1870 if (!func.isDeclaration()) {
1871 std::string name("define_");
1872 name += func.getName();
1873 printFunction(name, func.getName());
1874 }
1875 }
1876 }
1877
1878 void CppWriter::printVariable(const std::string& fname,
1879 const std::string& varName) {
1880 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1881
1882 if (!GV) {
1883 error(std::string("Variable '") + varName + "' not found in input module");
1884 return;
1885 }
1886 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1887 printVariableUses(GV);
1888 printVariableHead(GV);
1889 printVariableBody(GV);
1890 Out << "return " << getCppName(GV) << ";\n";
1891 Out << "}\n";
1892 }
1893
1894 void CppWriter::printType(const std::string& fname,
1895 const std::string& typeName) {
1896 const Type* Ty = TheModule->getTypeByName(typeName);
1897 if (!Ty) {
1898 error(std::string("Type '") + typeName + "' not found in input module");
1899 return;
1900 }
1901 Out << "\nType* " << fname << "(Module *mod) {\n";
1902 printType(Ty);
1903 Out << "return " << getCppName(Ty) << ";\n";
1904 Out << "}\n";
1905 }
1906
1907 bool CppWriter::runOnModule(Module &M) {
1908 TheModule = &M;
1909
1910 // Emit a header
1911 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1912
1913 // Get the name of the function we're supposed to generate
1914 std::string fname = FuncName.getValue();
1915
1916 // Get the name of the thing we are to generate
1917 std::string tgtname = NameToGenerate.getValue();
1918 if (GenerationType == GenModule ||
1919 GenerationType == GenContents ||
1920 GenerationType == GenProgram ||
1921 GenerationType == GenFunctions) {
1922 if (tgtname == "!bad!") {
1923 if (M.getModuleIdentifier() == "-")
1924 tgtname = "<stdin>";
1925 else
1926 tgtname = M.getModuleIdentifier();
1927 }
1928 } else if (tgtname == "!bad!")
1929 error("You must use the -for option with -gen-{function,variable,type}");
1930
1931 switch (WhatToGenerate(GenerationType)) {
1932 case GenProgram:
1933 if (fname.empty())
1934 fname = "makeLLVMModule";
1935 printProgram(fname,tgtname);
1936 break;
1937 case GenModule:
1938 if (fname.empty())
1939 fname = "makeLLVMModule";
1940 printModule(fname,tgtname);
1941 break;
1942 case GenContents:
1943 if (fname.empty())
1944 fname = "makeLLVMModuleContents";
1945 printContents(fname,tgtname);
1946 break;
1947 case GenFunction:
1948 if (fname.empty())
1949 fname = "makeLLVMFunction";
1950 printFunction(fname,tgtname);
1951 break;
1952 case GenFunctions:
1953 printFunctions();
1954 break;
1955 case GenInline:
1956 if (fname.empty())
1957 fname = "makeLLVMInline";
1958 printInline(fname,tgtname);
1959 break;
1960 case GenVariable:
1961 if (fname.empty())
1962 fname = "makeLLVMVariable";
1963 printVariable(fname,tgtname);
1964 break;
1965 case GenType:
1966 if (fname.empty())
1967 fname = "makeLLVMType";
1968 printType(fname,tgtname);
1969 break;
1970 default:
1971 error("Invalid generation option");
1972 }
1973
1974 return false;
1975 }
1976}
1977
1978char CppWriter::ID = 0;
1979
1980//===----------------------------------------------------------------------===//
1981// External Interface declaration
1982//===----------------------------------------------------------------------===//
1983
1984bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
1985 std::ostream &o,
1986 CodeGenFileType FileType,
1987 bool Fast) {
1988 if (FileType != TargetMachine::AssemblyFile) return true;
1989 PM.add(new CppWriter(o));
1990 return false;
1991}