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