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