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