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