blob: b51621d882a7496a03cee2e19d92053043e8cb4b [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"
Owen Andersoncb371882008-08-21 00:14:44 +000032#include "llvm/Support/raw_ostream.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000033#include "llvm/Config/config.h"
34#include <algorithm>
Anton Korobeynikov50276522008-04-23 22:29:24 +000035#include <set>
36
37using namespace llvm;
38
39static cl::opt<std::string>
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000040FuncName("cppfname", cl::desc("Specify the name of the generated function"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000041 cl::value_desc("function name"));
42
43enum WhatToGenerate {
44 GenProgram,
45 GenModule,
46 GenContents,
47 GenFunction,
48 GenFunctions,
49 GenInline,
50 GenVariable,
51 GenType
52};
53
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000054static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000055 cl::desc("Choose what kind of output to generate"),
56 cl::init(GenProgram),
57 cl::values(
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000058 clEnumValN(GenProgram, "program", "Generate a complete program"),
59 clEnumValN(GenModule, "module", "Generate a module definition"),
60 clEnumValN(GenContents, "contents", "Generate contents of a module"),
61 clEnumValN(GenFunction, "function", "Generate a function definition"),
62 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
63 clEnumValN(GenInline, "inline", "Generate an inline function"),
64 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
65 clEnumValN(GenType, "type", "Generate a type definition"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000066 clEnumValEnd
67 )
68);
69
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000070static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000071 cl::desc("Specify the name of the thing to generate"),
72 cl::init("!bad!"));
73
Dan Gohman844731a2008-05-13 00:00:25 +000074// Register the target.
Dan Gohmanb8cab922008-10-14 20:25:08 +000075static RegisterTarget<CPPTargetMachine> X("cpp", "C++ backend");
Anton Korobeynikov50276522008-04-23 22:29:24 +000076
Dan Gohman844731a2008-05-13 00:00:25 +000077namespace {
Anton Korobeynikov50276522008-04-23 22:29:24 +000078 typedef std::vector<const Type*> TypeList;
79 typedef std::map<const Type*,std::string> TypeMap;
80 typedef std::map<const Value*,std::string> ValueMap;
81 typedef std::set<std::string> NameSet;
82 typedef std::set<const Type*> TypeSet;
83 typedef std::set<const Value*> ValueSet;
84 typedef std::map<const Value*,std::string> ForwardRefMap;
85
86 /// CppWriter - This class is the main chunk of code that converts an LLVM
87 /// module to a C++ translation unit.
88 class CppWriter : public ModulePass {
89 const char* progname;
Owen Andersoncb371882008-08-21 00:14:44 +000090 raw_ostream &Out;
Anton Korobeynikov50276522008-04-23 22:29:24 +000091 const Module *TheModule;
92 uint64_t uniqueNum;
93 TypeMap TypeNames;
94 ValueMap ValueNames;
95 TypeMap UnresolvedTypes;
96 TypeList TypeStack;
97 NameSet UsedNames;
98 TypeSet DefinedTypes;
99 ValueSet DefinedValues;
100 ForwardRefMap ForwardRefs;
101 bool is_inline;
102
103 public:
104 static char ID;
Owen Andersoncb371882008-08-21 00:14:44 +0000105 explicit CppWriter(raw_ostream &o) :
Dan Gohmanae73dc12008-09-04 17:05:41 +0000106 ModulePass(&ID), Out(o), uniqueNum(0), is_inline(false) {}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000107
108 virtual const char *getPassName() const { return "C++ backend"; }
109
110 bool runOnModule(Module &M);
111
Anton Korobeynikov50276522008-04-23 22:29:24 +0000112 void printProgram(const std::string& fname, const std::string& modName );
113 void printModule(const std::string& fname, const std::string& modName );
114 void printContents(const std::string& fname, const std::string& modName );
115 void printFunction(const std::string& fname, const std::string& funcName );
116 void printFunctions();
117 void printInline(const std::string& fname, const std::string& funcName );
118 void printVariable(const std::string& fname, const std::string& varName );
119 void printType(const std::string& fname, const std::string& typeName );
120
121 void error(const std::string& msg);
122
123 private:
124 void printLinkageType(GlobalValue::LinkageTypes LT);
125 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
126 void printCallingConv(unsigned cc);
127 void printEscapedString(const std::string& str);
128 void printCFP(const ConstantFP* CFP);
129
130 std::string getCppName(const Type* val);
131 inline void printCppName(const Type* val);
132
133 std::string getCppName(const Value* val);
134 inline void printCppName(const Value* val);
135
Devang Patel05988662008-09-25 21:00:45 +0000136 void printAttributes(const AttrListPtr &PAL, const std::string &name);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000137 bool printTypeInternal(const Type* Ty);
138 inline void printType(const Type* Ty);
139 void printTypes(const Module* M);
140
141 void printConstant(const Constant *CPV);
142 void printConstants(const Module* M);
143
144 void printVariableUses(const GlobalVariable *GV);
145 void printVariableHead(const GlobalVariable *GV);
146 void printVariableBody(const GlobalVariable *GV);
147
148 void printFunctionUses(const Function *F);
149 void printFunctionHead(const Function *F);
150 void printFunctionBody(const Function *F);
151 void printInstruction(const Instruction *I, const std::string& bbname);
152 std::string getOpName(Value*);
153
154 void printModuleBody();
155 };
156
157 static unsigned indent_level = 0;
Owen Andersoncb371882008-08-21 00:14:44 +0000158 inline raw_ostream& nl(raw_ostream& Out, int delta = 0) {
Anton Korobeynikov50276522008-04-23 22:29:24 +0000159 Out << "\n";
160 if (delta >= 0 || indent_level >= unsigned(-delta))
161 indent_level += delta;
162 for (unsigned i = 0; i < indent_level; ++i)
163 Out << " ";
164 return Out;
165 }
166
167 inline void in() { indent_level++; }
168 inline void out() { if (indent_level >0) indent_level--; }
169
170 inline void
171 sanitize(std::string& str) {
172 for (size_t i = 0; i < str.length(); ++i)
173 if (!isalnum(str[i]) && str[i] != '_')
174 str[i] = '_';
175 }
176
177 inline std::string
178 getTypePrefix(const Type* Ty ) {
179 switch (Ty->getTypeID()) {
180 case Type::VoidTyID: return "void_";
181 case Type::IntegerTyID:
182 return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
183 "_";
184 case Type::FloatTyID: return "float_";
185 case Type::DoubleTyID: return "double_";
186 case Type::LabelTyID: return "label_";
187 case Type::FunctionTyID: return "func_";
188 case Type::StructTyID: return "struct_";
189 case Type::ArrayTyID: return "array_";
190 case Type::PointerTyID: return "ptr_";
191 case Type::VectorTyID: return "packed_";
192 case Type::OpaqueTyID: return "opaque_";
193 default: return "other_";
194 }
195 return "unknown_";
196 }
197
198 // Looks up the type in the symbol table and returns a pointer to its name or
199 // a null pointer if it wasn't found. Note that this isn't the same as the
200 // Mode::getTypeName function which will return an empty string, not a null
201 // pointer if the name is not found.
202 inline const std::string*
203 findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
204 TypeSymbolTable::const_iterator TI = ST.begin();
205 TypeSymbolTable::const_iterator TE = ST.end();
206 for (;TI != TE; ++TI)
207 if (TI->second == Ty)
208 return &(TI->first);
209 return 0;
210 }
211
212 void CppWriter::error(const std::string& msg) {
Bill Wendling1a53ead2008-07-27 23:18:30 +0000213 cerr << progname << ": " << msg << "\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000214 exit(2);
215 }
216
217 // printCFP - Print a floating point constant .. very carefully :)
218 // This makes sure that conversion to/from floating yields the same binary
219 // result so that we don't lose precision.
220 void CppWriter::printCFP(const ConstantFP *CFP) {
Dale Johannesen23a98552008-10-09 23:00:39 +0000221 bool ignored;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000222 APFloat APF = APFloat(CFP->getValueAPF()); // copy
223 if (CFP->getType() == Type::FloatTy)
Dale Johannesen23a98552008-10-09 23:00:39 +0000224 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000225 Out << "ConstantFP::get(";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000226 Out << "APFloat(";
227#if HAVE_PRINTF_A
228 char Buffer[100];
229 sprintf(Buffer, "%A", APF.convertToDouble());
230 if ((!strncmp(Buffer, "0x", 2) ||
231 !strncmp(Buffer, "-0x", 3) ||
232 !strncmp(Buffer, "+0x", 3)) &&
233 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
234 if (CFP->getType() == Type::DoubleTy)
235 Out << "BitsToDouble(" << Buffer << ")";
236 else
237 Out << "BitsToFloat((float)" << Buffer << ")";
238 Out << ")";
239 } else {
240#endif
241 std::string StrVal = ftostr(CFP->getValueAPF());
242
243 while (StrVal[0] == ' ')
244 StrVal.erase(StrVal.begin());
245
246 // Check to make sure that the stringized number is not some string like
247 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
248 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
249 ((StrVal[0] == '-' || StrVal[0] == '+') &&
250 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
251 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
252 if (CFP->getType() == Type::DoubleTy)
253 Out << StrVal;
254 else
255 Out << StrVal << "f";
256 } else if (CFP->getType() == Type::DoubleTy)
Owen Andersoncb371882008-08-21 00:14:44 +0000257 Out << "BitsToDouble(0x"
Dale Johannesen7111b022008-10-09 18:53:47 +0000258 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
Owen Andersoncb371882008-08-21 00:14:44 +0000259 << "ULL) /* " << StrVal << " */";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000260 else
Owen Andersoncb371882008-08-21 00:14:44 +0000261 Out << "BitsToFloat(0x"
Dale Johannesen7111b022008-10-09 18:53:47 +0000262 << utohexstr((uint32_t)CFP->getValueAPF().
263 bitcastToAPInt().getZExtValue())
Owen Andersoncb371882008-08-21 00:14:44 +0000264 << "U) /* " << StrVal << " */";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000265 Out << ")";
266#if HAVE_PRINTF_A
267 }
268#endif
269 Out << ")";
270 }
271
272 void CppWriter::printCallingConv(unsigned cc){
273 // Print the calling convention.
274 switch (cc) {
275 case CallingConv::C: Out << "CallingConv::C"; break;
276 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
277 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
278 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
279 default: Out << cc; break;
280 }
281 }
282
283 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
284 switch (LT) {
285 case GlobalValue::InternalLinkage:
286 Out << "GlobalValue::InternalLinkage"; break;
287 case GlobalValue::LinkOnceLinkage:
288 Out << "GlobalValue::LinkOnceLinkage "; break;
289 case GlobalValue::WeakLinkage:
290 Out << "GlobalValue::WeakLinkage"; break;
291 case GlobalValue::AppendingLinkage:
292 Out << "GlobalValue::AppendingLinkage"; break;
293 case GlobalValue::ExternalLinkage:
294 Out << "GlobalValue::ExternalLinkage"; break;
295 case GlobalValue::DLLImportLinkage:
296 Out << "GlobalValue::DLLImportLinkage"; break;
297 case GlobalValue::DLLExportLinkage:
298 Out << "GlobalValue::DLLExportLinkage"; break;
299 case GlobalValue::ExternalWeakLinkage:
300 Out << "GlobalValue::ExternalWeakLinkage"; break;
301 case GlobalValue::GhostLinkage:
302 Out << "GlobalValue::GhostLinkage"; break;
Dale Johannesenaafce772008-05-14 20:12:51 +0000303 case GlobalValue::CommonLinkage:
304 Out << "GlobalValue::CommonLinkage"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000305 }
306 }
307
308 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
309 switch (VisType) {
310 default: assert(0 && "Unknown GVar visibility");
311 case GlobalValue::DefaultVisibility:
312 Out << "GlobalValue::DefaultVisibility";
313 break;
314 case GlobalValue::HiddenVisibility:
315 Out << "GlobalValue::HiddenVisibility";
316 break;
317 case GlobalValue::ProtectedVisibility:
318 Out << "GlobalValue::ProtectedVisibility";
319 break;
320 }
321 }
322
323 // printEscapedString - Print each character of the specified string, escaping
324 // it if it is not printable or if it is an escape char.
325 void CppWriter::printEscapedString(const std::string &Str) {
326 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
327 unsigned char C = Str[i];
328 if (isprint(C) && C != '"' && C != '\\') {
329 Out << C;
330 } else {
331 Out << "\\x"
332 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
333 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
334 }
335 }
336 }
337
338 std::string CppWriter::getCppName(const Type* Ty) {
339 // First, handle the primitive types .. easy
340 if (Ty->isPrimitiveType() || Ty->isInteger()) {
341 switch (Ty->getTypeID()) {
342 case Type::VoidTyID: return "Type::VoidTy";
343 case Type::IntegerTyID: {
344 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
345 return "IntegerType::get(" + utostr(BitWidth) + ")";
346 }
347 case Type::FloatTyID: return "Type::FloatTy";
348 case Type::DoubleTyID: return "Type::DoubleTy";
349 case Type::LabelTyID: return "Type::LabelTy";
350 default:
351 error("Invalid primitive type");
352 break;
353 }
354 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
355 }
356
357 // Now, see if we've seen the type before and return that
358 TypeMap::iterator I = TypeNames.find(Ty);
359 if (I != TypeNames.end())
360 return I->second;
361
362 // Okay, let's build a new name for this type. Start with a prefix
363 const char* prefix = 0;
364 switch (Ty->getTypeID()) {
365 case Type::FunctionTyID: prefix = "FuncTy_"; break;
366 case Type::StructTyID: prefix = "StructTy_"; break;
367 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
368 case Type::PointerTyID: prefix = "PointerTy_"; break;
369 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
370 case Type::VectorTyID: prefix = "VectorTy_"; break;
371 default: prefix = "OtherTy_"; break; // prevent breakage
372 }
373
374 // See if the type has a name in the symboltable and build accordingly
375 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
376 std::string name;
377 if (tName)
378 name = std::string(prefix) + *tName;
379 else
380 name = std::string(prefix) + utostr(uniqueNum++);
381 sanitize(name);
382
383 // Save the name
384 return TypeNames[Ty] = name;
385 }
386
387 void CppWriter::printCppName(const Type* Ty) {
388 printEscapedString(getCppName(Ty));
389 }
390
391 std::string CppWriter::getCppName(const Value* val) {
392 std::string name;
393 ValueMap::iterator I = ValueNames.find(val);
394 if (I != ValueNames.end() && I->first == val)
395 return I->second;
396
397 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
398 name = std::string("gvar_") +
399 getTypePrefix(GV->getType()->getElementType());
400 } else if (isa<Function>(val)) {
401 name = std::string("func_");
402 } else if (const Constant* C = dyn_cast<Constant>(val)) {
403 name = std::string("const_") + getTypePrefix(C->getType());
404 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
405 if (is_inline) {
406 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
407 Function::const_arg_iterator(Arg)) + 1;
408 name = std::string("arg_") + utostr(argNum);
409 NameSet::iterator NI = UsedNames.find(name);
410 if (NI != UsedNames.end())
411 name += std::string("_") + utostr(uniqueNum++);
412 UsedNames.insert(name);
413 return ValueNames[val] = name;
414 } else {
415 name = getTypePrefix(val->getType());
416 }
417 } else {
418 name = getTypePrefix(val->getType());
419 }
420 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
421 sanitize(name);
422 NameSet::iterator NI = UsedNames.find(name);
423 if (NI != UsedNames.end())
424 name += std::string("_") + utostr(uniqueNum++);
425 UsedNames.insert(name);
426 return ValueNames[val] = name;
427 }
428
429 void CppWriter::printCppName(const Value* val) {
430 printEscapedString(getCppName(val));
431 }
432
Devang Patel05988662008-09-25 21:00:45 +0000433 void CppWriter::printAttributes(const AttrListPtr &PAL,
Anton Korobeynikov50276522008-04-23 22:29:24 +0000434 const std::string &name) {
Devang Patel05988662008-09-25 21:00:45 +0000435 Out << "AttrListPtr " << name << "_PAL;";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000436 nl(Out);
437 if (!PAL.isEmpty()) {
438 Out << '{'; in(); nl(Out);
Devang Patel05988662008-09-25 21:00:45 +0000439 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
440 Out << "AttributeWithIndex PAWI;"; nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000441 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
Nicolas Geoffrayd9afb4d2008-11-08 15:36:01 +0000442 unsigned index = PAL.getSlot(i).Index;
Devang Pateleaf42ab2008-09-23 23:03:40 +0000443 Attributes attrs = PAL.getSlot(i).Attrs;
Nicolas Geoffrayd9afb4d2008-11-08 15:36:01 +0000444 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
Devang Patel05988662008-09-25 21:00:45 +0000445 if (attrs & Attribute::SExt)
446 Out << " | Attribute::SExt";
447 if (attrs & Attribute::ZExt)
448 Out << " | Attribute::ZExt";
449 if (attrs & Attribute::StructRet)
450 Out << " | Attribute::StructRet";
451 if (attrs & Attribute::InReg)
452 Out << " | Attribute::InReg";
453 if (attrs & Attribute::NoReturn)
454 Out << " | Attribute::NoReturn";
455 if (attrs & Attribute::NoUnwind)
456 Out << " | Attribute::NoUnwind";
457 if (attrs & Attribute::ByVal)
458 Out << " | Attribute::ByVal";
459 if (attrs & Attribute::NoAlias)
460 Out << " | Attribute::NoAlias";
461 if (attrs & Attribute::Nest)
462 Out << " | Attribute::Nest";
463 if (attrs & Attribute::ReadNone)
464 Out << " | Attribute::ReadNone";
465 if (attrs & Attribute::ReadOnly)
466 Out << " | Attribute::ReadOnly";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000467 Out << ";";
468 nl(Out);
469 Out << "Attrs.push_back(PAWI);";
470 nl(Out);
471 }
Devang Patel05988662008-09-25 21:00:45 +0000472 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000473 nl(Out);
474 out(); nl(Out);
475 Out << '}'; nl(Out);
476 }
477 }
478
479 bool CppWriter::printTypeInternal(const Type* Ty) {
480 // We don't print definitions for primitive types
481 if (Ty->isPrimitiveType() || Ty->isInteger())
482 return false;
483
484 // If we already defined this type, we don't need to define it again.
485 if (DefinedTypes.find(Ty) != DefinedTypes.end())
486 return false;
487
488 // Everything below needs the name for the type so get it now.
489 std::string typeName(getCppName(Ty));
490
491 // Search the type stack for recursion. If we find it, then generate this
492 // as an OpaqueType, but make sure not to do this multiple times because
493 // the type could appear in multiple places on the stack. Once the opaque
494 // definition is issued, it must not be re-issued. Consequently we have to
495 // check the UnresolvedTypes list as well.
496 TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
497 Ty);
498 if (TI != TypeStack.end()) {
499 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
500 if (I == UnresolvedTypes.end()) {
501 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
502 nl(Out);
503 UnresolvedTypes[Ty] = typeName;
504 }
505 return true;
506 }
507
508 // We're going to print a derived type which, by definition, contains other
509 // types. So, push this one we're printing onto the type stack to assist with
510 // recursive definitions.
511 TypeStack.push_back(Ty);
512
513 // Print the type definition
514 switch (Ty->getTypeID()) {
515 case Type::FunctionTyID: {
516 const FunctionType* FT = cast<FunctionType>(Ty);
517 Out << "std::vector<const Type*>" << typeName << "_args;";
518 nl(Out);
519 FunctionType::param_iterator PI = FT->param_begin();
520 FunctionType::param_iterator PE = FT->param_end();
521 for (; PI != PE; ++PI) {
522 const Type* argTy = static_cast<const Type*>(*PI);
523 bool isForward = printTypeInternal(argTy);
524 std::string argName(getCppName(argTy));
525 Out << typeName << "_args.push_back(" << argName;
526 if (isForward)
527 Out << "_fwd";
528 Out << ");";
529 nl(Out);
530 }
531 bool isForward = printTypeInternal(FT->getReturnType());
532 std::string retTypeName(getCppName(FT->getReturnType()));
533 Out << "FunctionType* " << typeName << " = FunctionType::get(";
534 in(); nl(Out) << "/*Result=*/" << retTypeName;
535 if (isForward)
536 Out << "_fwd";
537 Out << ",";
538 nl(Out) << "/*Params=*/" << typeName << "_args,";
539 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
540 out();
541 nl(Out);
542 break;
543 }
544 case Type::StructTyID: {
545 const StructType* ST = cast<StructType>(Ty);
546 Out << "std::vector<const Type*>" << typeName << "_fields;";
547 nl(Out);
548 StructType::element_iterator EI = ST->element_begin();
549 StructType::element_iterator EE = ST->element_end();
550 for (; EI != EE; ++EI) {
551 const Type* fieldTy = static_cast<const Type*>(*EI);
552 bool isForward = printTypeInternal(fieldTy);
553 std::string fieldName(getCppName(fieldTy));
554 Out << typeName << "_fields.push_back(" << fieldName;
555 if (isForward)
556 Out << "_fwd";
557 Out << ");";
558 nl(Out);
559 }
560 Out << "StructType* " << typeName << " = StructType::get("
561 << typeName << "_fields, /*isPacked=*/"
562 << (ST->isPacked() ? "true" : "false") << ");";
563 nl(Out);
564 break;
565 }
566 case Type::ArrayTyID: {
567 const ArrayType* AT = cast<ArrayType>(Ty);
568 const Type* ET = AT->getElementType();
569 bool isForward = printTypeInternal(ET);
570 std::string elemName(getCppName(ET));
571 Out << "ArrayType* " << typeName << " = ArrayType::get("
572 << elemName << (isForward ? "_fwd" : "")
573 << ", " << utostr(AT->getNumElements()) << ");";
574 nl(Out);
575 break;
576 }
577 case Type::PointerTyID: {
578 const PointerType* PT = cast<PointerType>(Ty);
579 const Type* ET = PT->getElementType();
580 bool isForward = printTypeInternal(ET);
581 std::string elemName(getCppName(ET));
582 Out << "PointerType* " << typeName << " = PointerType::get("
583 << elemName << (isForward ? "_fwd" : "")
584 << ", " << utostr(PT->getAddressSpace()) << ");";
585 nl(Out);
586 break;
587 }
588 case Type::VectorTyID: {
589 const VectorType* PT = cast<VectorType>(Ty);
590 const Type* ET = PT->getElementType();
591 bool isForward = printTypeInternal(ET);
592 std::string elemName(getCppName(ET));
593 Out << "VectorType* " << typeName << " = VectorType::get("
594 << elemName << (isForward ? "_fwd" : "")
595 << ", " << utostr(PT->getNumElements()) << ");";
596 nl(Out);
597 break;
598 }
599 case Type::OpaqueTyID: {
600 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
601 nl(Out);
602 break;
603 }
604 default:
605 error("Invalid TypeID");
606 }
607
608 // If the type had a name, make sure we recreate it.
609 const std::string* progTypeName =
610 findTypeName(TheModule->getTypeSymbolTable(),Ty);
611 if (progTypeName) {
612 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
613 << typeName << ");";
614 nl(Out);
615 }
616
617 // Pop us off the type stack
618 TypeStack.pop_back();
619
620 // Indicate that this type is now defined.
621 DefinedTypes.insert(Ty);
622
623 // Early resolve as many unresolved types as possible. Search the unresolved
624 // types map for the type we just printed. Now that its definition is complete
625 // we can resolve any previous references to it. This prevents a cascade of
626 // unresolved types.
627 TypeMap::iterator I = UnresolvedTypes.find(Ty);
628 if (I != UnresolvedTypes.end()) {
629 Out << "cast<OpaqueType>(" << I->second
630 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
631 nl(Out);
632 Out << I->second << " = cast<";
633 switch (Ty->getTypeID()) {
634 case Type::FunctionTyID: Out << "FunctionType"; break;
635 case Type::ArrayTyID: Out << "ArrayType"; break;
636 case Type::StructTyID: Out << "StructType"; break;
637 case Type::VectorTyID: Out << "VectorType"; break;
638 case Type::PointerTyID: Out << "PointerType"; break;
639 case Type::OpaqueTyID: Out << "OpaqueType"; break;
640 default: Out << "NoSuchDerivedType"; break;
641 }
642 Out << ">(" << I->second << "_fwd.get());";
643 nl(Out); nl(Out);
644 UnresolvedTypes.erase(I);
645 }
646
647 // Finally, separate the type definition from other with a newline.
648 nl(Out);
649
650 // We weren't a recursive type
651 return false;
652 }
653
654 // Prints a type definition. Returns true if it could not resolve all the
655 // types in the definition but had to use a forward reference.
656 void CppWriter::printType(const Type* Ty) {
657 assert(TypeStack.empty());
658 TypeStack.clear();
659 printTypeInternal(Ty);
660 assert(TypeStack.empty());
661 }
662
663 void CppWriter::printTypes(const Module* M) {
664 // Walk the symbol table and print out all its types
665 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
666 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
667 TI != TE; ++TI) {
668
669 // For primitive types and types already defined, just add a name
670 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
671 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
672 TNI != TypeNames.end()) {
673 Out << "mod->addTypeName(\"";
674 printEscapedString(TI->first);
675 Out << "\", " << getCppName(TI->second) << ");";
676 nl(Out);
677 // For everything else, define the type
678 } else {
679 printType(TI->second);
680 }
681 }
682
683 // Add all of the global variables to the value table...
684 for (Module::const_global_iterator I = TheModule->global_begin(),
685 E = TheModule->global_end(); I != E; ++I) {
686 if (I->hasInitializer())
687 printType(I->getInitializer()->getType());
688 printType(I->getType());
689 }
690
691 // Add all the functions to the table
692 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
693 FI != FE; ++FI) {
694 printType(FI->getReturnType());
695 printType(FI->getFunctionType());
696 // Add all the function arguments
697 for (Function::const_arg_iterator AI = FI->arg_begin(),
698 AE = FI->arg_end(); AI != AE; ++AI) {
699 printType(AI->getType());
700 }
701
702 // Add all of the basic blocks and instructions
703 for (Function::const_iterator BB = FI->begin(),
704 E = FI->end(); BB != E; ++BB) {
705 printType(BB->getType());
706 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
707 ++I) {
708 printType(I->getType());
709 for (unsigned i = 0; i < I->getNumOperands(); ++i)
710 printType(I->getOperand(i)->getType());
711 }
712 }
713 }
714 }
715
716
717 // printConstant - Print out a constant pool entry...
718 void CppWriter::printConstant(const Constant *CV) {
719 // First, if the constant is actually a GlobalValue (variable or function)
720 // or its already in the constant list then we've printed it already and we
721 // can just return.
722 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
723 return;
724
725 std::string constName(getCppName(CV));
726 std::string typeName(getCppName(CV->getType()));
Anton Korobeynikovff4ca2e2008-10-05 15:07:06 +0000727
Anton Korobeynikov50276522008-04-23 22:29:24 +0000728 if (isa<GlobalValue>(CV)) {
729 // Skip variables and functions, we emit them elsewhere
730 return;
731 }
Anton Korobeynikovff4ca2e2008-10-05 15:07:06 +0000732
Anton Korobeynikov50276522008-04-23 22:29:24 +0000733 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
Anton Korobeynikov70053c32008-08-18 20:03:45 +0000734 std::string constValue = CI->getValue().toString(10, true);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000735 Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
Chris Lattnerfad86b02008-08-17 07:19:36 +0000736 << cast<IntegerType>(CI->getType())->getBitWidth() << ", \""
Anton Korobeynikov70053c32008-08-18 20:03:45 +0000737 << constValue << "\", " << constValue.length() << ", 10));";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000738 } else if (isa<ConstantAggregateZero>(CV)) {
739 Out << "ConstantAggregateZero* " << constName
740 << " = ConstantAggregateZero::get(" << typeName << ");";
741 } else if (isa<ConstantPointerNull>(CV)) {
742 Out << "ConstantPointerNull* " << constName
Anton Korobeynikovff4ca2e2008-10-05 15:07:06 +0000743 << " = ConstantPointerNull::get(" << typeName << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000744 } 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()) {
Dan Gohman26825a82008-06-09 14:09:13 +00001068 default:
1069 error("Invalid instruction");
1070 break;
1071
Anton Korobeynikov50276522008-04-23 22:29:24 +00001072 case Instruction::Ret: {
1073 const ReturnInst* ret = cast<ReturnInst>(I);
1074 Out << "ReturnInst::Create("
1075 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1076 break;
1077 }
1078 case Instruction::Br: {
1079 const BranchInst* br = cast<BranchInst>(I);
1080 Out << "BranchInst::Create(" ;
1081 if (br->getNumOperands() == 3 ) {
1082 Out << opNames[0] << ", "
1083 << opNames[1] << ", "
1084 << opNames[2] << ", ";
1085
1086 } else if (br->getNumOperands() == 1) {
1087 Out << opNames[0] << ", ";
1088 } else {
1089 error("Branch with 2 operands?");
1090 }
1091 Out << bbname << ");";
1092 break;
1093 }
1094 case Instruction::Switch: {
1095 const SwitchInst* sw = cast<SwitchInst>(I);
1096 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1097 << opNames[0] << ", "
1098 << opNames[1] << ", "
1099 << sw->getNumCases() << ", " << bbname << ");";
1100 nl(Out);
1101 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1102 Out << iName << "->addCase("
1103 << opNames[i] << ", "
1104 << opNames[i+1] << ");";
1105 nl(Out);
1106 }
1107 break;
1108 }
1109 case Instruction::Invoke: {
1110 const InvokeInst* inv = cast<InvokeInst>(I);
1111 Out << "std::vector<Value*> " << iName << "_params;";
1112 nl(Out);
1113 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1114 Out << iName << "_params.push_back("
1115 << opNames[i] << ");";
1116 nl(Out);
1117 }
1118 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1119 << opNames[0] << ", "
1120 << opNames[1] << ", "
1121 << opNames[2] << ", "
1122 << iName << "_params.begin(), " << iName << "_params.end(), \"";
1123 printEscapedString(inv->getName());
1124 Out << "\", " << bbname << ");";
1125 nl(Out) << iName << "->setCallingConv(";
1126 printCallingConv(inv->getCallingConv());
1127 Out << ");";
Devang Patel05988662008-09-25 21:00:45 +00001128 printAttributes(inv->getAttributes(), iName);
1129 Out << iName << "->setAttributes(" << iName << "_PAL);";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001130 nl(Out);
1131 break;
1132 }
1133 case Instruction::Unwind: {
1134 Out << "new UnwindInst("
1135 << bbname << ");";
1136 break;
1137 }
1138 case Instruction::Unreachable:{
1139 Out << "new UnreachableInst("
1140 << bbname << ");";
1141 break;
1142 }
1143 case Instruction::Add:
1144 case Instruction::Sub:
1145 case Instruction::Mul:
1146 case Instruction::UDiv:
1147 case Instruction::SDiv:
1148 case Instruction::FDiv:
1149 case Instruction::URem:
1150 case Instruction::SRem:
1151 case Instruction::FRem:
1152 case Instruction::And:
1153 case Instruction::Or:
1154 case Instruction::Xor:
1155 case Instruction::Shl:
1156 case Instruction::LShr:
1157 case Instruction::AShr:{
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001158 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001159 switch (I->getOpcode()) {
1160 case Instruction::Add: Out << "Instruction::Add"; break;
1161 case Instruction::Sub: Out << "Instruction::Sub"; break;
1162 case Instruction::Mul: Out << "Instruction::Mul"; break;
1163 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1164 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1165 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1166 case Instruction::URem:Out << "Instruction::URem"; break;
1167 case Instruction::SRem:Out << "Instruction::SRem"; break;
1168 case Instruction::FRem:Out << "Instruction::FRem"; break;
1169 case Instruction::And: Out << "Instruction::And"; break;
1170 case Instruction::Or: Out << "Instruction::Or"; break;
1171 case Instruction::Xor: Out << "Instruction::Xor"; break;
1172 case Instruction::Shl: Out << "Instruction::Shl"; break;
1173 case Instruction::LShr:Out << "Instruction::LShr"; break;
1174 case Instruction::AShr:Out << "Instruction::AShr"; break;
1175 default: Out << "Instruction::BadOpCode"; break;
1176 }
1177 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1178 printEscapedString(I->getName());
1179 Out << "\", " << bbname << ");";
1180 break;
1181 }
1182 case Instruction::FCmp: {
1183 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1184 switch (cast<FCmpInst>(I)->getPredicate()) {
1185 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1186 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1187 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1188 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1189 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1190 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1191 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1192 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1193 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1194 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1195 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1196 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1197 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1198 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1199 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1200 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1201 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1202 }
1203 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1204 printEscapedString(I->getName());
1205 Out << "\", " << bbname << ");";
1206 break;
1207 }
1208 case Instruction::ICmp: {
1209 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1210 switch (cast<ICmpInst>(I)->getPredicate()) {
1211 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1212 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1213 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1214 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1215 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1216 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1217 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1218 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1219 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1220 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1221 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1222 }
1223 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1224 printEscapedString(I->getName());
1225 Out << "\", " << bbname << ");";
1226 break;
1227 }
1228 case Instruction::Malloc: {
1229 const MallocInst* mallocI = cast<MallocInst>(I);
1230 Out << "MallocInst* " << iName << " = new MallocInst("
1231 << getCppName(mallocI->getAllocatedType()) << ", ";
1232 if (mallocI->isArrayAllocation())
1233 Out << opNames[0] << ", " ;
1234 Out << "\"";
1235 printEscapedString(mallocI->getName());
1236 Out << "\", " << bbname << ");";
1237 if (mallocI->getAlignment())
1238 nl(Out) << iName << "->setAlignment("
1239 << mallocI->getAlignment() << ");";
1240 break;
1241 }
1242 case Instruction::Free: {
1243 Out << "FreeInst* " << iName << " = new FreeInst("
1244 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1245 break;
1246 }
1247 case Instruction::Alloca: {
1248 const AllocaInst* allocaI = cast<AllocaInst>(I);
1249 Out << "AllocaInst* " << iName << " = new AllocaInst("
1250 << getCppName(allocaI->getAllocatedType()) << ", ";
1251 if (allocaI->isArrayAllocation())
1252 Out << opNames[0] << ", ";
1253 Out << "\"";
1254 printEscapedString(allocaI->getName());
1255 Out << "\", " << bbname << ");";
1256 if (allocaI->getAlignment())
1257 nl(Out) << iName << "->setAlignment("
1258 << allocaI->getAlignment() << ");";
1259 break;
1260 }
1261 case Instruction::Load:{
1262 const LoadInst* load = cast<LoadInst>(I);
1263 Out << "LoadInst* " << iName << " = new LoadInst("
1264 << opNames[0] << ", \"";
1265 printEscapedString(load->getName());
1266 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1267 << ", " << bbname << ");";
1268 break;
1269 }
1270 case Instruction::Store: {
1271 const StoreInst* store = cast<StoreInst>(I);
Anton Korobeynikovb0714db2008-11-09 02:54:13 +00001272 Out << " new StoreInst("
Anton Korobeynikov50276522008-04-23 22:29:24 +00001273 << opNames[0] << ", "
1274 << opNames[1] << ", "
1275 << (store->isVolatile() ? "true" : "false")
1276 << ", " << bbname << ");";
1277 break;
1278 }
1279 case Instruction::GetElementPtr: {
1280 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1281 if (gep->getNumOperands() <= 2) {
1282 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1283 << opNames[0];
1284 if (gep->getNumOperands() == 2)
1285 Out << ", " << opNames[1];
1286 } else {
1287 Out << "std::vector<Value*> " << iName << "_indices;";
1288 nl(Out);
1289 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1290 Out << iName << "_indices.push_back("
1291 << opNames[i] << ");";
1292 nl(Out);
1293 }
1294 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1295 << opNames[0] << ", " << iName << "_indices.begin(), "
1296 << iName << "_indices.end()";
1297 }
1298 Out << ", \"";
1299 printEscapedString(gep->getName());
1300 Out << "\", " << bbname << ");";
1301 break;
1302 }
1303 case Instruction::PHI: {
1304 const PHINode* phi = cast<PHINode>(I);
1305
1306 Out << "PHINode* " << iName << " = PHINode::Create("
1307 << getCppName(phi->getType()) << ", \"";
1308 printEscapedString(phi->getName());
1309 Out << "\", " << bbname << ");";
1310 nl(Out) << iName << "->reserveOperandSpace("
1311 << phi->getNumIncomingValues()
1312 << ");";
1313 nl(Out);
1314 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1315 Out << iName << "->addIncoming("
1316 << opNames[i] << ", " << opNames[i+1] << ");";
1317 nl(Out);
1318 }
1319 break;
1320 }
1321 case Instruction::Trunc:
1322 case Instruction::ZExt:
1323 case Instruction::SExt:
1324 case Instruction::FPTrunc:
1325 case Instruction::FPExt:
1326 case Instruction::FPToUI:
1327 case Instruction::FPToSI:
1328 case Instruction::UIToFP:
1329 case Instruction::SIToFP:
1330 case Instruction::PtrToInt:
1331 case Instruction::IntToPtr:
1332 case Instruction::BitCast: {
1333 const CastInst* cst = cast<CastInst>(I);
1334 Out << "CastInst* " << iName << " = new ";
1335 switch (I->getOpcode()) {
1336 case Instruction::Trunc: Out << "TruncInst"; break;
1337 case Instruction::ZExt: Out << "ZExtInst"; break;
1338 case Instruction::SExt: Out << "SExtInst"; break;
1339 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1340 case Instruction::FPExt: Out << "FPExtInst"; break;
1341 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1342 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1343 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1344 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1345 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1346 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1347 case Instruction::BitCast: Out << "BitCastInst"; break;
1348 default: assert(!"Unreachable"); break;
1349 }
1350 Out << "(" << opNames[0] << ", "
1351 << getCppName(cst->getType()) << ", \"";
1352 printEscapedString(cst->getName());
1353 Out << "\", " << bbname << ");";
1354 break;
1355 }
1356 case Instruction::Call:{
1357 const CallInst* call = cast<CallInst>(I);
1358 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1359 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1360 << getCppName(ila->getFunctionType()) << ", \""
1361 << ila->getAsmString() << "\", \""
1362 << ila->getConstraintString() << "\","
1363 << (ila->hasSideEffects() ? "true" : "false") << ");";
1364 nl(Out);
1365 }
1366 if (call->getNumOperands() > 2) {
1367 Out << "std::vector<Value*> " << iName << "_params;";
1368 nl(Out);
1369 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1370 Out << iName << "_params.push_back(" << opNames[i] << ");";
1371 nl(Out);
1372 }
1373 Out << "CallInst* " << iName << " = CallInst::Create("
1374 << opNames[0] << ", " << iName << "_params.begin(), "
1375 << iName << "_params.end(), \"";
1376 } else if (call->getNumOperands() == 2) {
1377 Out << "CallInst* " << iName << " = CallInst::Create("
1378 << opNames[0] << ", " << opNames[1] << ", \"";
1379 } else {
1380 Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
1381 << ", \"";
1382 }
1383 printEscapedString(call->getName());
1384 Out << "\", " << bbname << ");";
1385 nl(Out) << iName << "->setCallingConv(";
1386 printCallingConv(call->getCallingConv());
1387 Out << ");";
1388 nl(Out) << iName << "->setTailCall("
1389 << (call->isTailCall() ? "true":"false");
1390 Out << ");";
Devang Patel05988662008-09-25 21:00:45 +00001391 printAttributes(call->getAttributes(), iName);
1392 Out << iName << "->setAttributes(" << iName << "_PAL);";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001393 nl(Out);
1394 break;
1395 }
1396 case Instruction::Select: {
1397 const SelectInst* sel = cast<SelectInst>(I);
1398 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1399 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1400 printEscapedString(sel->getName());
1401 Out << "\", " << bbname << ");";
1402 break;
1403 }
1404 case Instruction::UserOp1:
1405 /// FALL THROUGH
1406 case Instruction::UserOp2: {
1407 /// FIXME: What should be done here?
1408 break;
1409 }
1410 case Instruction::VAArg: {
1411 const VAArgInst* va = cast<VAArgInst>(I);
1412 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1413 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1414 printEscapedString(va->getName());
1415 Out << "\", " << bbname << ");";
1416 break;
1417 }
1418 case Instruction::ExtractElement: {
1419 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1420 Out << "ExtractElementInst* " << getCppName(eei)
1421 << " = new ExtractElementInst(" << opNames[0]
1422 << ", " << opNames[1] << ", \"";
1423 printEscapedString(eei->getName());
1424 Out << "\", " << bbname << ");";
1425 break;
1426 }
1427 case Instruction::InsertElement: {
1428 const InsertElementInst* iei = cast<InsertElementInst>(I);
1429 Out << "InsertElementInst* " << getCppName(iei)
1430 << " = InsertElementInst::Create(" << opNames[0]
1431 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1432 printEscapedString(iei->getName());
1433 Out << "\", " << bbname << ");";
1434 break;
1435 }
1436 case Instruction::ShuffleVector: {
1437 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1438 Out << "ShuffleVectorInst* " << getCppName(svi)
1439 << " = new ShuffleVectorInst(" << opNames[0]
1440 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1441 printEscapedString(svi->getName());
1442 Out << "\", " << bbname << ");";
1443 break;
1444 }
Dan Gohman75146a62008-06-09 14:12:10 +00001445 case Instruction::ExtractValue: {
1446 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1447 Out << "std::vector<unsigned> " << iName << "_indices;";
1448 nl(Out);
1449 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1450 Out << iName << "_indices.push_back("
1451 << evi->idx_begin()[i] << ");";
1452 nl(Out);
1453 }
1454 Out << "ExtractValueInst* " << getCppName(evi)
1455 << " = ExtractValueInst::Create(" << opNames[0]
1456 << ", "
1457 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1458 printEscapedString(evi->getName());
1459 Out << "\", " << bbname << ");";
1460 break;
1461 }
1462 case Instruction::InsertValue: {
1463 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1464 Out << "std::vector<unsigned> " << iName << "_indices;";
1465 nl(Out);
1466 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1467 Out << iName << "_indices.push_back("
1468 << ivi->idx_begin()[i] << ");";
1469 nl(Out);
1470 }
1471 Out << "InsertValueInst* " << getCppName(ivi)
1472 << " = InsertValueInst::Create(" << opNames[0]
1473 << ", " << opNames[1] << ", "
1474 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1475 printEscapedString(ivi->getName());
1476 Out << "\", " << bbname << ");";
1477 break;
1478 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001479 }
1480 DefinedValues.insert(I);
1481 nl(Out);
1482 delete [] opNames;
1483}
1484
1485 // Print out the types, constants and declarations needed by one function
1486 void CppWriter::printFunctionUses(const Function* F) {
1487 nl(Out) << "// Type Definitions"; nl(Out);
1488 if (!is_inline) {
1489 // Print the function's return type
1490 printType(F->getReturnType());
1491
1492 // Print the function's function type
1493 printType(F->getFunctionType());
1494
1495 // Print the types of each of the function's arguments
1496 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1497 AI != AE; ++AI) {
1498 printType(AI->getType());
1499 }
1500 }
1501
1502 // Print type definitions for every type referenced by an instruction and
1503 // make a note of any global values or constants that are referenced
1504 SmallPtrSet<GlobalValue*,64> gvs;
1505 SmallPtrSet<Constant*,64> consts;
1506 for (Function::const_iterator BB = F->begin(), BE = F->end();
1507 BB != BE; ++BB){
1508 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1509 I != E; ++I) {
1510 // Print the type of the instruction itself
1511 printType(I->getType());
1512
1513 // Print the type of each of the instruction's operands
1514 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1515 Value* operand = I->getOperand(i);
1516 printType(operand->getType());
1517
1518 // If the operand references a GVal or Constant, make a note of it
1519 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1520 gvs.insert(GV);
1521 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1522 if (GVar->hasInitializer())
1523 consts.insert(GVar->getInitializer());
1524 } else if (Constant* C = dyn_cast<Constant>(operand))
1525 consts.insert(C);
1526 }
1527 }
1528 }
1529
1530 // Print the function declarations for any functions encountered
1531 nl(Out) << "// Function Declarations"; nl(Out);
1532 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1533 I != E; ++I) {
1534 if (Function* Fun = dyn_cast<Function>(*I)) {
1535 if (!is_inline || Fun != F)
1536 printFunctionHead(Fun);
1537 }
1538 }
1539
1540 // Print the global variable declarations for any variables encountered
1541 nl(Out) << "// Global Variable Declarations"; nl(Out);
1542 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1543 I != E; ++I) {
1544 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1545 printVariableHead(F);
1546 }
1547
1548 // Print the constants found
1549 nl(Out) << "// Constant Definitions"; nl(Out);
1550 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1551 E = consts.end(); I != E; ++I) {
1552 printConstant(*I);
1553 }
1554
1555 // Process the global variables definitions now that all the constants have
1556 // been emitted. These definitions just couple the gvars with their constant
1557 // initializers.
1558 nl(Out) << "// Global Variable Definitions"; nl(Out);
1559 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1560 I != E; ++I) {
1561 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1562 printVariableBody(GV);
1563 }
1564 }
1565
1566 void CppWriter::printFunctionHead(const Function* F) {
1567 nl(Out) << "Function* " << getCppName(F);
1568 if (is_inline) {
1569 Out << " = mod->getFunction(\"";
1570 printEscapedString(F->getName());
1571 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1572 nl(Out) << "if (!" << getCppName(F) << ") {";
1573 nl(Out) << getCppName(F);
1574 }
1575 Out<< " = Function::Create(";
1576 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1577 nl(Out) << "/*Linkage=*/";
1578 printLinkageType(F->getLinkage());
1579 Out << ",";
1580 nl(Out) << "/*Name=*/\"";
1581 printEscapedString(F->getName());
1582 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1583 nl(Out,-1);
1584 printCppName(F);
1585 Out << "->setCallingConv(";
1586 printCallingConv(F->getCallingConv());
1587 Out << ");";
1588 nl(Out);
1589 if (F->hasSection()) {
1590 printCppName(F);
1591 Out << "->setSection(\"" << F->getSection() << "\");";
1592 nl(Out);
1593 }
1594 if (F->getAlignment()) {
1595 printCppName(F);
1596 Out << "->setAlignment(" << F->getAlignment() << ");";
1597 nl(Out);
1598 }
1599 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1600 printCppName(F);
1601 Out << "->setVisibility(";
1602 printVisibilityType(F->getVisibility());
1603 Out << ");";
1604 nl(Out);
1605 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001606 if (F->hasGC()) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001607 printCppName(F);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001608 Out << "->setGC(\"" << F->getGC() << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001609 nl(Out);
1610 }
1611 if (is_inline) {
1612 Out << "}";
1613 nl(Out);
1614 }
Devang Patel05988662008-09-25 21:00:45 +00001615 printAttributes(F->getAttributes(), getCppName(F));
Anton Korobeynikov50276522008-04-23 22:29:24 +00001616 printCppName(F);
Devang Patel05988662008-09-25 21:00:45 +00001617 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001618 nl(Out);
1619 }
1620
1621 void CppWriter::printFunctionBody(const Function *F) {
1622 if (F->isDeclaration())
1623 return; // external functions have no bodies.
1624
1625 // Clear the DefinedValues and ForwardRefs maps because we can't have
1626 // cross-function forward refs
1627 ForwardRefs.clear();
1628 DefinedValues.clear();
1629
1630 // Create all the argument values
1631 if (!is_inline) {
1632 if (!F->arg_empty()) {
1633 Out << "Function::arg_iterator args = " << getCppName(F)
1634 << "->arg_begin();";
1635 nl(Out);
1636 }
1637 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1638 AI != AE; ++AI) {
1639 Out << "Value* " << getCppName(AI) << " = args++;";
1640 nl(Out);
1641 if (AI->hasName()) {
1642 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1643 nl(Out);
1644 }
1645 }
1646 }
1647
1648 // Create all the basic blocks
1649 nl(Out);
1650 for (Function::const_iterator BI = F->begin(), BE = F->end();
1651 BI != BE; ++BI) {
1652 std::string bbname(getCppName(BI));
1653 Out << "BasicBlock* " << bbname << " = BasicBlock::Create(\"";
1654 if (BI->hasName())
1655 printEscapedString(BI->getName());
1656 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1657 nl(Out);
1658 }
1659
1660 // Output all of its basic blocks... for the function
1661 for (Function::const_iterator BI = F->begin(), BE = F->end();
1662 BI != BE; ++BI) {
1663 std::string bbname(getCppName(BI));
1664 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1665 nl(Out);
1666
1667 // Output all of the instructions in the basic block...
1668 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1669 I != E; ++I) {
1670 printInstruction(I,bbname);
1671 }
1672 }
1673
1674 // Loop over the ForwardRefs and resolve them now that all instructions
1675 // are generated.
1676 if (!ForwardRefs.empty()) {
1677 nl(Out) << "// Resolve Forward References";
1678 nl(Out);
1679 }
1680
1681 while (!ForwardRefs.empty()) {
1682 ForwardRefMap::iterator I = ForwardRefs.begin();
1683 Out << I->second << "->replaceAllUsesWith("
1684 << getCppName(I->first) << "); delete " << I->second << ";";
1685 nl(Out);
1686 ForwardRefs.erase(I);
1687 }
1688 }
1689
1690 void CppWriter::printInline(const std::string& fname,
1691 const std::string& func) {
1692 const Function* F = TheModule->getFunction(func);
1693 if (!F) {
1694 error(std::string("Function '") + func + "' not found in input module");
1695 return;
1696 }
1697 if (F->isDeclaration()) {
1698 error(std::string("Function '") + func + "' is external!");
1699 return;
1700 }
1701 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1702 << getCppName(F);
1703 unsigned arg_count = 1;
1704 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1705 AI != AE; ++AI) {
1706 Out << ", Value* arg_" << arg_count;
1707 }
1708 Out << ") {";
1709 nl(Out);
1710 is_inline = true;
1711 printFunctionUses(F);
1712 printFunctionBody(F);
1713 is_inline = false;
1714 Out << "return " << getCppName(F->begin()) << ";";
1715 nl(Out) << "}";
1716 nl(Out);
1717 }
1718
1719 void CppWriter::printModuleBody() {
1720 // Print out all the type definitions
1721 nl(Out) << "// Type Definitions"; nl(Out);
1722 printTypes(TheModule);
1723
1724 // Functions can call each other and global variables can reference them so
1725 // define all the functions first before emitting their function bodies.
1726 nl(Out) << "// Function Declarations"; nl(Out);
1727 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1728 I != E; ++I)
1729 printFunctionHead(I);
1730
1731 // Process the global variables declarations. We can't initialze them until
1732 // after the constants are printed so just print a header for each global
1733 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1734 for (Module::const_global_iterator I = TheModule->global_begin(),
1735 E = TheModule->global_end(); I != E; ++I) {
1736 printVariableHead(I);
1737 }
1738
1739 // Print out all the constants definitions. Constants don't recurse except
1740 // through GlobalValues. All GlobalValues have been declared at this point
1741 // so we can proceed to generate the constants.
1742 nl(Out) << "// Constant Definitions"; nl(Out);
1743 printConstants(TheModule);
1744
1745 // Process the global variables definitions now that all the constants have
1746 // been emitted. These definitions just couple the gvars with their constant
1747 // initializers.
1748 nl(Out) << "// Global Variable Definitions"; nl(Out);
1749 for (Module::const_global_iterator I = TheModule->global_begin(),
1750 E = TheModule->global_end(); I != E; ++I) {
1751 printVariableBody(I);
1752 }
1753
1754 // Finally, we can safely put out all of the function bodies.
1755 nl(Out) << "// Function Definitions"; nl(Out);
1756 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1757 I != E; ++I) {
1758 if (!I->isDeclaration()) {
1759 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1760 << ")";
1761 nl(Out) << "{";
1762 nl(Out,1);
1763 printFunctionBody(I);
1764 nl(Out,-1) << "}";
1765 nl(Out);
1766 }
1767 }
1768 }
1769
1770 void CppWriter::printProgram(const std::string& fname,
1771 const std::string& mName) {
1772 Out << "#include <llvm/Module.h>\n";
1773 Out << "#include <llvm/DerivedTypes.h>\n";
1774 Out << "#include <llvm/Constants.h>\n";
1775 Out << "#include <llvm/GlobalVariable.h>\n";
1776 Out << "#include <llvm/Function.h>\n";
1777 Out << "#include <llvm/CallingConv.h>\n";
1778 Out << "#include <llvm/BasicBlock.h>\n";
1779 Out << "#include <llvm/Instructions.h>\n";
1780 Out << "#include <llvm/InlineAsm.h>\n";
1781 Out << "#include <llvm/Support/MathExtras.h>\n";
1782 Out << "#include <llvm/Pass.h>\n";
1783 Out << "#include <llvm/PassManager.h>\n";
Nicolas Geoffray9474ede2008-05-14 07:52:03 +00001784 Out << "#include <llvm/ADT/SmallVector.h>\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001785 Out << "#include <llvm/Analysis/Verifier.h>\n";
1786 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1787 Out << "#include <algorithm>\n";
1788 Out << "#include <iostream>\n\n";
1789 Out << "using namespace llvm;\n\n";
1790 Out << "Module* " << fname << "();\n\n";
1791 Out << "int main(int argc, char**argv) {\n";
1792 Out << " Module* Mod = " << fname << "();\n";
1793 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1794 Out << " std::cerr.flush();\n";
1795 Out << " std::cout.flush();\n";
1796 Out << " PassManager PM;\n";
1797 Out << " PM.add(new PrintModulePass(&llvm::cout));\n";
1798 Out << " PM.run(*Mod);\n";
1799 Out << " return 0;\n";
1800 Out << "}\n\n";
1801 printModule(fname,mName);
1802 }
1803
1804 void CppWriter::printModule(const std::string& fname,
1805 const std::string& mName) {
1806 nl(Out) << "Module* " << fname << "() {";
1807 nl(Out,1) << "// Module Construction";
1808 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1809 if (!TheModule->getTargetTriple().empty()) {
1810 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1811 }
1812 if (!TheModule->getTargetTriple().empty()) {
1813 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1814 << "\");";
1815 }
1816
1817 if (!TheModule->getModuleInlineAsm().empty()) {
1818 nl(Out) << "mod->setModuleInlineAsm(\"";
1819 printEscapedString(TheModule->getModuleInlineAsm());
1820 Out << "\");";
1821 }
1822 nl(Out);
1823
1824 // Loop over the dependent libraries and emit them.
1825 Module::lib_iterator LI = TheModule->lib_begin();
1826 Module::lib_iterator LE = TheModule->lib_end();
1827 while (LI != LE) {
1828 Out << "mod->addLibrary(\"" << *LI << "\");";
1829 nl(Out);
1830 ++LI;
1831 }
1832 printModuleBody();
1833 nl(Out) << "return mod;";
1834 nl(Out,-1) << "}";
1835 nl(Out);
1836 }
1837
1838 void CppWriter::printContents(const std::string& fname,
1839 const std::string& mName) {
1840 Out << "\nModule* " << fname << "(Module *mod) {\n";
1841 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1842 printModuleBody();
1843 Out << "\nreturn mod;\n";
1844 Out << "\n}\n";
1845 }
1846
1847 void CppWriter::printFunction(const std::string& fname,
1848 const std::string& funcName) {
1849 const Function* F = TheModule->getFunction(funcName);
1850 if (!F) {
1851 error(std::string("Function '") + funcName + "' not found in input module");
1852 return;
1853 }
1854 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1855 printFunctionUses(F);
1856 printFunctionHead(F);
1857 printFunctionBody(F);
1858 Out << "return " << getCppName(F) << ";\n";
1859 Out << "}\n";
1860 }
1861
1862 void CppWriter::printFunctions() {
1863 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1864 Module::const_iterator I = funcs.begin();
1865 Module::const_iterator IE = funcs.end();
1866
1867 for (; I != IE; ++I) {
1868 const Function &func = *I;
1869 if (!func.isDeclaration()) {
1870 std::string name("define_");
1871 name += func.getName();
1872 printFunction(name, func.getName());
1873 }
1874 }
1875 }
1876
1877 void CppWriter::printVariable(const std::string& fname,
1878 const std::string& varName) {
1879 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1880
1881 if (!GV) {
1882 error(std::string("Variable '") + varName + "' not found in input module");
1883 return;
1884 }
1885 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1886 printVariableUses(GV);
1887 printVariableHead(GV);
1888 printVariableBody(GV);
1889 Out << "return " << getCppName(GV) << ";\n";
1890 Out << "}\n";
1891 }
1892
1893 void CppWriter::printType(const std::string& fname,
1894 const std::string& typeName) {
1895 const Type* Ty = TheModule->getTypeByName(typeName);
1896 if (!Ty) {
1897 error(std::string("Type '") + typeName + "' not found in input module");
1898 return;
1899 }
1900 Out << "\nType* " << fname << "(Module *mod) {\n";
1901 printType(Ty);
1902 Out << "return " << getCppName(Ty) << ";\n";
1903 Out << "}\n";
1904 }
1905
1906 bool CppWriter::runOnModule(Module &M) {
1907 TheModule = &M;
1908
1909 // Emit a header
1910 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1911
1912 // Get the name of the function we're supposed to generate
1913 std::string fname = FuncName.getValue();
1914
1915 // Get the name of the thing we are to generate
1916 std::string tgtname = NameToGenerate.getValue();
1917 if (GenerationType == GenModule ||
1918 GenerationType == GenContents ||
1919 GenerationType == GenProgram ||
1920 GenerationType == GenFunctions) {
1921 if (tgtname == "!bad!") {
1922 if (M.getModuleIdentifier() == "-")
1923 tgtname = "<stdin>";
1924 else
1925 tgtname = M.getModuleIdentifier();
1926 }
1927 } else if (tgtname == "!bad!")
1928 error("You must use the -for option with -gen-{function,variable,type}");
1929
1930 switch (WhatToGenerate(GenerationType)) {
1931 case GenProgram:
1932 if (fname.empty())
1933 fname = "makeLLVMModule";
1934 printProgram(fname,tgtname);
1935 break;
1936 case GenModule:
1937 if (fname.empty())
1938 fname = "makeLLVMModule";
1939 printModule(fname,tgtname);
1940 break;
1941 case GenContents:
1942 if (fname.empty())
1943 fname = "makeLLVMModuleContents";
1944 printContents(fname,tgtname);
1945 break;
1946 case GenFunction:
1947 if (fname.empty())
1948 fname = "makeLLVMFunction";
1949 printFunction(fname,tgtname);
1950 break;
1951 case GenFunctions:
1952 printFunctions();
1953 break;
1954 case GenInline:
1955 if (fname.empty())
1956 fname = "makeLLVMInline";
1957 printInline(fname,tgtname);
1958 break;
1959 case GenVariable:
1960 if (fname.empty())
1961 fname = "makeLLVMVariable";
1962 printVariable(fname,tgtname);
1963 break;
1964 case GenType:
1965 if (fname.empty())
1966 fname = "makeLLVMType";
1967 printType(fname,tgtname);
1968 break;
1969 default:
1970 error("Invalid generation option");
1971 }
1972
1973 return false;
1974 }
1975}
1976
1977char CppWriter::ID = 0;
1978
1979//===----------------------------------------------------------------------===//
1980// External Interface declaration
1981//===----------------------------------------------------------------------===//
1982
1983bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
Owen Andersoncb371882008-08-21 00:14:44 +00001984 raw_ostream &o,
Anton Korobeynikov50276522008-04-23 22:29:24 +00001985 CodeGenFileType FileType,
1986 bool Fast) {
1987 if (FileType != TargetMachine::AssemblyFile) return true;
1988 PM.add(new CppWriter(o));
1989 return false;
1990}