blob: 71af8a904114653b7e396bacc6edc65cd99bcbd9 [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"
Torok Edwin30464702009-07-08 20:55:50 +000031#include "llvm/Support/ErrorHandling.h"
David Greene71847812009-07-14 20:18:05 +000032#include "llvm/Support/FormattedStream.h"
Bill Wendling1a53ead2008-07-27 23:18:30 +000033#include "llvm/Support/Streams.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000034#include "llvm/Config/config.h"
35#include <algorithm>
Anton Korobeynikov50276522008-04-23 22:29:24 +000036#include <set>
37
38using namespace llvm;
39
40static cl::opt<std::string>
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000041FuncName("cppfname", cl::desc("Specify the name of the generated function"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000042 cl::value_desc("function name"));
43
44enum WhatToGenerate {
45 GenProgram,
46 GenModule,
47 GenContents,
48 GenFunction,
49 GenFunctions,
50 GenInline,
51 GenVariable,
52 GenType
53};
54
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000055static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000056 cl::desc("Choose what kind of output to generate"),
57 cl::init(GenProgram),
58 cl::values(
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000059 clEnumValN(GenProgram, "program", "Generate a complete program"),
60 clEnumValN(GenModule, "module", "Generate a module definition"),
61 clEnumValN(GenContents, "contents", "Generate contents of a module"),
62 clEnumValN(GenFunction, "function", "Generate a function definition"),
63 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
64 clEnumValN(GenInline, "inline", "Generate an inline function"),
65 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
66 clEnumValN(GenType, "type", "Generate a type definition"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000067 clEnumValEnd
68 )
69);
70
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000071static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000072 cl::desc("Specify the name of the thing to generate"),
73 cl::init("!bad!"));
74
Dan Gohman844731a2008-05-13 00:00:25 +000075// Register the target.
Daniel Dunbar51b198a2009-07-15 20:24:03 +000076static RegisterTarget<CPPTargetMachine> X(TheCppBackendTarget, "cpp", "C++ backend");
Anton Korobeynikov50276522008-04-23 22:29:24 +000077
Bob Wilsona96751f2009-06-23 23:59:40 +000078// Force static initialization.
79extern "C" void LLVMInitializeCppBackendTarget() { }
Douglas Gregor1555a232009-06-16 20:12:29 +000080
Dan Gohman844731a2008-05-13 00:00:25 +000081namespace {
Anton Korobeynikov50276522008-04-23 22:29:24 +000082 typedef std::vector<const Type*> TypeList;
83 typedef std::map<const Type*,std::string> TypeMap;
84 typedef std::map<const Value*,std::string> ValueMap;
85 typedef std::set<std::string> NameSet;
86 typedef std::set<const Type*> TypeSet;
87 typedef std::set<const Value*> ValueSet;
88 typedef std::map<const Value*,std::string> ForwardRefMap;
89
90 /// CppWriter - This class is the main chunk of code that converts an LLVM
91 /// module to a C++ translation unit.
92 class CppWriter : public ModulePass {
David Greene71847812009-07-14 20:18:05 +000093 formatted_raw_ostream &Out;
Anton Korobeynikov50276522008-04-23 22:29:24 +000094 const Module *TheModule;
95 uint64_t uniqueNum;
96 TypeMap TypeNames;
97 ValueMap ValueNames;
98 TypeMap UnresolvedTypes;
99 TypeList TypeStack;
100 NameSet UsedNames;
101 TypeSet DefinedTypes;
102 ValueSet DefinedValues;
103 ForwardRefMap ForwardRefs;
104 bool is_inline;
105
106 public:
107 static char ID;
David Greene71847812009-07-14 20:18:05 +0000108 explicit CppWriter(formatted_raw_ostream &o) :
Dan Gohmanae73dc12008-09-04 17:05:41 +0000109 ModulePass(&ID), Out(o), uniqueNum(0), is_inline(false) {}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000110
111 virtual const char *getPassName() const { return "C++ backend"; }
112
113 bool runOnModule(Module &M);
114
Anton Korobeynikov50276522008-04-23 22:29:24 +0000115 void printProgram(const std::string& fname, const std::string& modName );
116 void printModule(const std::string& fname, const std::string& modName );
117 void printContents(const std::string& fname, const std::string& modName );
118 void printFunction(const std::string& fname, const std::string& funcName );
119 void printFunctions();
120 void printInline(const std::string& fname, const std::string& funcName );
121 void printVariable(const std::string& fname, const std::string& varName );
122 void printType(const std::string& fname, const std::string& typeName );
123
124 void error(const std::string& msg);
125
126 private:
127 void printLinkageType(GlobalValue::LinkageTypes LT);
128 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
129 void printCallingConv(unsigned cc);
130 void printEscapedString(const std::string& str);
131 void printCFP(const ConstantFP* CFP);
132
133 std::string getCppName(const Type* val);
134 inline void printCppName(const Type* val);
135
136 std::string getCppName(const Value* val);
137 inline void printCppName(const Value* val);
138
Devang Patel05988662008-09-25 21:00:45 +0000139 void printAttributes(const AttrListPtr &PAL, const std::string &name);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000140 bool printTypeInternal(const Type* Ty);
141 inline void printType(const Type* Ty);
142 void printTypes(const Module* M);
143
144 void printConstant(const Constant *CPV);
145 void printConstants(const Module* M);
146
147 void printVariableUses(const GlobalVariable *GV);
148 void printVariableHead(const GlobalVariable *GV);
149 void printVariableBody(const GlobalVariable *GV);
150
151 void printFunctionUses(const Function *F);
152 void printFunctionHead(const Function *F);
153 void printFunctionBody(const Function *F);
154 void printInstruction(const Instruction *I, const std::string& bbname);
155 std::string getOpName(Value*);
156
157 void printModuleBody();
158 };
159
160 static unsigned indent_level = 0;
David Greene71847812009-07-14 20:18:05 +0000161 inline formatted_raw_ostream& nl(formatted_raw_ostream& Out, int delta = 0) {
Anton Korobeynikov50276522008-04-23 22:29:24 +0000162 Out << "\n";
163 if (delta >= 0 || indent_level >= unsigned(-delta))
164 indent_level += delta;
165 for (unsigned i = 0; i < indent_level; ++i)
166 Out << " ";
167 return Out;
168 }
169
170 inline void in() { indent_level++; }
171 inline void out() { if (indent_level >0) indent_level--; }
172
173 inline void
174 sanitize(std::string& str) {
175 for (size_t i = 0; i < str.length(); ++i)
176 if (!isalnum(str[i]) && str[i] != '_')
177 str[i] = '_';
178 }
179
180 inline std::string
181 getTypePrefix(const Type* Ty ) {
182 switch (Ty->getTypeID()) {
183 case Type::VoidTyID: return "void_";
184 case Type::IntegerTyID:
185 return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
186 "_";
187 case Type::FloatTyID: return "float_";
188 case Type::DoubleTyID: return "double_";
189 case Type::LabelTyID: return "label_";
190 case Type::FunctionTyID: return "func_";
191 case Type::StructTyID: return "struct_";
192 case Type::ArrayTyID: return "array_";
193 case Type::PointerTyID: return "ptr_";
194 case Type::VectorTyID: return "packed_";
195 case Type::OpaqueTyID: return "opaque_";
196 default: return "other_";
197 }
198 return "unknown_";
199 }
200
201 // Looks up the type in the symbol table and returns a pointer to its name or
202 // a null pointer if it wasn't found. Note that this isn't the same as the
203 // Mode::getTypeName function which will return an empty string, not a null
204 // pointer if the name is not found.
205 inline const std::string*
206 findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
207 TypeSymbolTable::const_iterator TI = ST.begin();
208 TypeSymbolTable::const_iterator TE = ST.end();
209 for (;TI != TE; ++TI)
210 if (TI->second == Ty)
211 return &(TI->first);
212 return 0;
213 }
214
215 void CppWriter::error(const std::string& msg) {
Torok Edwin30464702009-07-08 20:55:50 +0000216 llvm_report_error(msg);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000217 }
218
219 // printCFP - Print a floating point constant .. very carefully :)
220 // This makes sure that conversion to/from floating yields the same binary
221 // result so that we don't lose precision.
222 void CppWriter::printCFP(const ConstantFP *CFP) {
Dale Johannesen23a98552008-10-09 23:00:39 +0000223 bool ignored;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000224 APFloat APF = APFloat(CFP->getValueAPF()); // copy
225 if (CFP->getType() == Type::FloatTy)
Dale Johannesen23a98552008-10-09 23:00:39 +0000226 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000227 Out << "ConstantFP::get(";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000228 Out << "APFloat(";
229#if HAVE_PRINTF_A
230 char Buffer[100];
231 sprintf(Buffer, "%A", APF.convertToDouble());
232 if ((!strncmp(Buffer, "0x", 2) ||
233 !strncmp(Buffer, "-0x", 3) ||
234 !strncmp(Buffer, "+0x", 3)) &&
235 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
236 if (CFP->getType() == Type::DoubleTy)
237 Out << "BitsToDouble(" << Buffer << ")";
238 else
239 Out << "BitsToFloat((float)" << Buffer << ")";
240 Out << ")";
241 } else {
242#endif
243 std::string StrVal = ftostr(CFP->getValueAPF());
244
245 while (StrVal[0] == ' ')
246 StrVal.erase(StrVal.begin());
247
248 // Check to make sure that the stringized number is not some string like
249 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
250 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
251 ((StrVal[0] == '-' || StrVal[0] == '+') &&
252 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
253 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
254 if (CFP->getType() == Type::DoubleTy)
255 Out << StrVal;
256 else
257 Out << StrVal << "f";
258 } else if (CFP->getType() == Type::DoubleTy)
Owen Andersoncb371882008-08-21 00:14:44 +0000259 Out << "BitsToDouble(0x"
Dale Johannesen7111b022008-10-09 18:53:47 +0000260 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
Owen Andersoncb371882008-08-21 00:14:44 +0000261 << "ULL) /* " << StrVal << " */";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000262 else
Owen Andersoncb371882008-08-21 00:14:44 +0000263 Out << "BitsToFloat(0x"
Dale Johannesen7111b022008-10-09 18:53:47 +0000264 << utohexstr((uint32_t)CFP->getValueAPF().
265 bitcastToAPInt().getZExtValue())
Owen Andersoncb371882008-08-21 00:14:44 +0000266 << "U) /* " << StrVal << " */";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000267 Out << ")";
268#if HAVE_PRINTF_A
269 }
270#endif
271 Out << ")";
272 }
273
274 void CppWriter::printCallingConv(unsigned cc){
275 // Print the calling convention.
276 switch (cc) {
277 case CallingConv::C: Out << "CallingConv::C"; break;
278 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
279 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
280 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
281 default: Out << cc; break;
282 }
283 }
284
285 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
286 switch (LT) {
287 case GlobalValue::InternalLinkage:
288 Out << "GlobalValue::InternalLinkage"; break;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000289 case GlobalValue::PrivateLinkage:
290 Out << "GlobalValue::PrivateLinkage"; break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000291 case GlobalValue::LinkerPrivateLinkage:
292 Out << "GlobalValue::LinkerPrivateLinkage"; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000293 case GlobalValue::AvailableExternallyLinkage:
294 Out << "GlobalValue::AvailableExternallyLinkage "; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000295 case GlobalValue::LinkOnceAnyLinkage:
296 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
297 case GlobalValue::LinkOnceODRLinkage:
298 Out << "GlobalValue::LinkOnceODRLinkage "; break;
299 case GlobalValue::WeakAnyLinkage:
300 Out << "GlobalValue::WeakAnyLinkage"; break;
301 case GlobalValue::WeakODRLinkage:
302 Out << "GlobalValue::WeakODRLinkage"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000303 case GlobalValue::AppendingLinkage:
304 Out << "GlobalValue::AppendingLinkage"; break;
305 case GlobalValue::ExternalLinkage:
306 Out << "GlobalValue::ExternalLinkage"; break;
307 case GlobalValue::DLLImportLinkage:
308 Out << "GlobalValue::DLLImportLinkage"; break;
309 case GlobalValue::DLLExportLinkage:
310 Out << "GlobalValue::DLLExportLinkage"; break;
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000311 case GlobalValue::ExternalWeakLinkage:
312 Out << "GlobalValue::ExternalWeakLinkage"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000313 case GlobalValue::GhostLinkage:
314 Out << "GlobalValue::GhostLinkage"; break;
Duncan Sands4dc2b392009-03-11 20:14:15 +0000315 case GlobalValue::CommonLinkage:
316 Out << "GlobalValue::CommonLinkage"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000317 }
318 }
319
320 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
321 switch (VisType) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000322 default: llvm_unreachable("Unknown GVar visibility");
Anton Korobeynikov50276522008-04-23 22:29:24 +0000323 case GlobalValue::DefaultVisibility:
324 Out << "GlobalValue::DefaultVisibility";
325 break;
326 case GlobalValue::HiddenVisibility:
327 Out << "GlobalValue::HiddenVisibility";
328 break;
329 case GlobalValue::ProtectedVisibility:
330 Out << "GlobalValue::ProtectedVisibility";
331 break;
332 }
333 }
334
335 // printEscapedString - Print each character of the specified string, escaping
336 // it if it is not printable or if it is an escape char.
337 void CppWriter::printEscapedString(const std::string &Str) {
338 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
339 unsigned char C = Str[i];
340 if (isprint(C) && C != '"' && C != '\\') {
341 Out << C;
342 } else {
343 Out << "\\x"
344 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
345 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
346 }
347 }
348 }
349
350 std::string CppWriter::getCppName(const Type* Ty) {
351 // First, handle the primitive types .. easy
352 if (Ty->isPrimitiveType() || Ty->isInteger()) {
353 switch (Ty->getTypeID()) {
354 case Type::VoidTyID: return "Type::VoidTy";
355 case Type::IntegerTyID: {
356 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
357 return "IntegerType::get(" + utostr(BitWidth) + ")";
358 }
Chris Lattnerc650f1f2009-05-01 23:54:26 +0000359 case Type::X86_FP80TyID: return "Type::X86_FP80Ty";
360 case Type::FloatTyID: return "Type::FloatTy";
361 case Type::DoubleTyID: return "Type::DoubleTy";
362 case Type::LabelTyID: return "Type::LabelTy";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000363 default:
364 error("Invalid primitive type");
365 break;
366 }
367 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
368 }
369
370 // Now, see if we've seen the type before and return that
371 TypeMap::iterator I = TypeNames.find(Ty);
372 if (I != TypeNames.end())
373 return I->second;
374
375 // Okay, let's build a new name for this type. Start with a prefix
376 const char* prefix = 0;
377 switch (Ty->getTypeID()) {
378 case Type::FunctionTyID: prefix = "FuncTy_"; break;
379 case Type::StructTyID: prefix = "StructTy_"; break;
380 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
381 case Type::PointerTyID: prefix = "PointerTy_"; break;
382 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
383 case Type::VectorTyID: prefix = "VectorTy_"; break;
384 default: prefix = "OtherTy_"; break; // prevent breakage
385 }
386
387 // See if the type has a name in the symboltable and build accordingly
388 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
389 std::string name;
390 if (tName)
391 name = std::string(prefix) + *tName;
392 else
393 name = std::string(prefix) + utostr(uniqueNum++);
394 sanitize(name);
395
396 // Save the name
397 return TypeNames[Ty] = name;
398 }
399
400 void CppWriter::printCppName(const Type* Ty) {
401 printEscapedString(getCppName(Ty));
402 }
403
404 std::string CppWriter::getCppName(const Value* val) {
405 std::string name;
406 ValueMap::iterator I = ValueNames.find(val);
407 if (I != ValueNames.end() && I->first == val)
408 return I->second;
409
410 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
411 name = std::string("gvar_") +
412 getTypePrefix(GV->getType()->getElementType());
413 } else if (isa<Function>(val)) {
414 name = std::string("func_");
415 } else if (const Constant* C = dyn_cast<Constant>(val)) {
416 name = std::string("const_") + getTypePrefix(C->getType());
417 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
418 if (is_inline) {
419 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
420 Function::const_arg_iterator(Arg)) + 1;
421 name = std::string("arg_") + utostr(argNum);
422 NameSet::iterator NI = UsedNames.find(name);
423 if (NI != UsedNames.end())
424 name += std::string("_") + utostr(uniqueNum++);
425 UsedNames.insert(name);
426 return ValueNames[val] = name;
427 } else {
428 name = getTypePrefix(val->getType());
429 }
430 } else {
431 name = getTypePrefix(val->getType());
432 }
433 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
434 sanitize(name);
435 NameSet::iterator NI = UsedNames.find(name);
436 if (NI != UsedNames.end())
437 name += std::string("_") + utostr(uniqueNum++);
438 UsedNames.insert(name);
439 return ValueNames[val] = name;
440 }
441
442 void CppWriter::printCppName(const Value* val) {
443 printEscapedString(getCppName(val));
444 }
445
Devang Patel05988662008-09-25 21:00:45 +0000446 void CppWriter::printAttributes(const AttrListPtr &PAL,
Anton Korobeynikov50276522008-04-23 22:29:24 +0000447 const std::string &name) {
Devang Patel05988662008-09-25 21:00:45 +0000448 Out << "AttrListPtr " << name << "_PAL;";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000449 nl(Out);
450 if (!PAL.isEmpty()) {
451 Out << '{'; in(); nl(Out);
Devang Patel05988662008-09-25 21:00:45 +0000452 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
453 Out << "AttributeWithIndex PAWI;"; nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000454 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
Nicolas Geoffrayd9afb4d2008-11-08 15:36:01 +0000455 unsigned index = PAL.getSlot(i).Index;
Devang Pateleaf42ab2008-09-23 23:03:40 +0000456 Attributes attrs = PAL.getSlot(i).Attrs;
Nicolas Geoffrayd9afb4d2008-11-08 15:36:01 +0000457 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
Chris Lattneracca9552009-01-13 07:22:22 +0000458#define HANDLE_ATTR(X) \
459 if (attrs & Attribute::X) \
460 Out << " | Attribute::" #X; \
461 attrs &= ~Attribute::X;
462
463 HANDLE_ATTR(SExt);
464 HANDLE_ATTR(ZExt);
Chris Lattneracca9552009-01-13 07:22:22 +0000465 HANDLE_ATTR(NoReturn);
Jeffrey Yasskin2d92c712009-05-28 03:16:17 +0000466 HANDLE_ATTR(InReg);
467 HANDLE_ATTR(StructRet);
Chris Lattneracca9552009-01-13 07:22:22 +0000468 HANDLE_ATTR(NoUnwind);
Chris Lattneracca9552009-01-13 07:22:22 +0000469 HANDLE_ATTR(NoAlias);
Jeffrey Yasskin2d92c712009-05-28 03:16:17 +0000470 HANDLE_ATTR(ByVal);
Chris Lattneracca9552009-01-13 07:22:22 +0000471 HANDLE_ATTR(Nest);
472 HANDLE_ATTR(ReadNone);
473 HANDLE_ATTR(ReadOnly);
Jeffrey Yasskin2d92c712009-05-28 03:16:17 +0000474 HANDLE_ATTR(NoInline);
475 HANDLE_ATTR(AlwaysInline);
476 HANDLE_ATTR(OptimizeForSize);
477 HANDLE_ATTR(StackProtect);
478 HANDLE_ATTR(StackProtectReq);
Chris Lattneracca9552009-01-13 07:22:22 +0000479 HANDLE_ATTR(NoCapture);
480#undef HANDLE_ATTR
481 assert(attrs == 0 && "Unhandled attribute!");
Anton Korobeynikov50276522008-04-23 22:29:24 +0000482 Out << ";";
483 nl(Out);
484 Out << "Attrs.push_back(PAWI);";
485 nl(Out);
486 }
Devang Patel05988662008-09-25 21:00:45 +0000487 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000488 nl(Out);
489 out(); nl(Out);
490 Out << '}'; nl(Out);
491 }
492 }
493
494 bool CppWriter::printTypeInternal(const Type* Ty) {
495 // We don't print definitions for primitive types
496 if (Ty->isPrimitiveType() || Ty->isInteger())
497 return false;
498
499 // If we already defined this type, we don't need to define it again.
500 if (DefinedTypes.find(Ty) != DefinedTypes.end())
501 return false;
502
503 // Everything below needs the name for the type so get it now.
504 std::string typeName(getCppName(Ty));
505
506 // Search the type stack for recursion. If we find it, then generate this
507 // as an OpaqueType, but make sure not to do this multiple times because
508 // the type could appear in multiple places on the stack. Once the opaque
509 // definition is issued, it must not be re-issued. Consequently we have to
510 // check the UnresolvedTypes list as well.
511 TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
512 Ty);
513 if (TI != TypeStack.end()) {
514 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
515 if (I == UnresolvedTypes.end()) {
516 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
517 nl(Out);
518 UnresolvedTypes[Ty] = typeName;
519 }
520 return true;
521 }
522
523 // We're going to print a derived type which, by definition, contains other
524 // types. So, push this one we're printing onto the type stack to assist with
525 // recursive definitions.
526 TypeStack.push_back(Ty);
527
528 // Print the type definition
529 switch (Ty->getTypeID()) {
530 case Type::FunctionTyID: {
531 const FunctionType* FT = cast<FunctionType>(Ty);
532 Out << "std::vector<const Type*>" << typeName << "_args;";
533 nl(Out);
534 FunctionType::param_iterator PI = FT->param_begin();
535 FunctionType::param_iterator PE = FT->param_end();
536 for (; PI != PE; ++PI) {
537 const Type* argTy = static_cast<const Type*>(*PI);
538 bool isForward = printTypeInternal(argTy);
539 std::string argName(getCppName(argTy));
540 Out << typeName << "_args.push_back(" << argName;
541 if (isForward)
542 Out << "_fwd";
543 Out << ");";
544 nl(Out);
545 }
546 bool isForward = printTypeInternal(FT->getReturnType());
547 std::string retTypeName(getCppName(FT->getReturnType()));
548 Out << "FunctionType* " << typeName << " = FunctionType::get(";
549 in(); nl(Out) << "/*Result=*/" << retTypeName;
550 if (isForward)
551 Out << "_fwd";
552 Out << ",";
553 nl(Out) << "/*Params=*/" << typeName << "_args,";
554 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
555 out();
556 nl(Out);
557 break;
558 }
559 case Type::StructTyID: {
560 const StructType* ST = cast<StructType>(Ty);
561 Out << "std::vector<const Type*>" << typeName << "_fields;";
562 nl(Out);
563 StructType::element_iterator EI = ST->element_begin();
564 StructType::element_iterator EE = ST->element_end();
565 for (; EI != EE; ++EI) {
566 const Type* fieldTy = static_cast<const Type*>(*EI);
567 bool isForward = printTypeInternal(fieldTy);
568 std::string fieldName(getCppName(fieldTy));
569 Out << typeName << "_fields.push_back(" << fieldName;
570 if (isForward)
571 Out << "_fwd";
572 Out << ");";
573 nl(Out);
574 }
575 Out << "StructType* " << typeName << " = StructType::get("
576 << typeName << "_fields, /*isPacked=*/"
577 << (ST->isPacked() ? "true" : "false") << ");";
578 nl(Out);
579 break;
580 }
581 case Type::ArrayTyID: {
582 const ArrayType* AT = cast<ArrayType>(Ty);
583 const Type* ET = AT->getElementType();
584 bool isForward = printTypeInternal(ET);
585 std::string elemName(getCppName(ET));
586 Out << "ArrayType* " << typeName << " = ArrayType::get("
587 << elemName << (isForward ? "_fwd" : "")
588 << ", " << utostr(AT->getNumElements()) << ");";
589 nl(Out);
590 break;
591 }
592 case Type::PointerTyID: {
593 const PointerType* PT = cast<PointerType>(Ty);
594 const Type* ET = PT->getElementType();
595 bool isForward = printTypeInternal(ET);
596 std::string elemName(getCppName(ET));
597 Out << "PointerType* " << typeName << " = PointerType::get("
598 << elemName << (isForward ? "_fwd" : "")
599 << ", " << utostr(PT->getAddressSpace()) << ");";
600 nl(Out);
601 break;
602 }
603 case Type::VectorTyID: {
604 const VectorType* PT = cast<VectorType>(Ty);
605 const Type* ET = PT->getElementType();
606 bool isForward = printTypeInternal(ET);
607 std::string elemName(getCppName(ET));
608 Out << "VectorType* " << typeName << " = VectorType::get("
609 << elemName << (isForward ? "_fwd" : "")
610 << ", " << utostr(PT->getNumElements()) << ");";
611 nl(Out);
612 break;
613 }
614 case Type::OpaqueTyID: {
615 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
616 nl(Out);
617 break;
618 }
619 default:
620 error("Invalid TypeID");
621 }
622
623 // If the type had a name, make sure we recreate it.
624 const std::string* progTypeName =
625 findTypeName(TheModule->getTypeSymbolTable(),Ty);
626 if (progTypeName) {
627 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
628 << typeName << ");";
629 nl(Out);
630 }
631
632 // Pop us off the type stack
633 TypeStack.pop_back();
634
635 // Indicate that this type is now defined.
636 DefinedTypes.insert(Ty);
637
638 // Early resolve as many unresolved types as possible. Search the unresolved
639 // types map for the type we just printed. Now that its definition is complete
640 // we can resolve any previous references to it. This prevents a cascade of
641 // unresolved types.
642 TypeMap::iterator I = UnresolvedTypes.find(Ty);
643 if (I != UnresolvedTypes.end()) {
644 Out << "cast<OpaqueType>(" << I->second
645 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
646 nl(Out);
647 Out << I->second << " = cast<";
648 switch (Ty->getTypeID()) {
649 case Type::FunctionTyID: Out << "FunctionType"; break;
650 case Type::ArrayTyID: Out << "ArrayType"; break;
651 case Type::StructTyID: Out << "StructType"; break;
652 case Type::VectorTyID: Out << "VectorType"; break;
653 case Type::PointerTyID: Out << "PointerType"; break;
654 case Type::OpaqueTyID: Out << "OpaqueType"; break;
655 default: Out << "NoSuchDerivedType"; break;
656 }
657 Out << ">(" << I->second << "_fwd.get());";
658 nl(Out); nl(Out);
659 UnresolvedTypes.erase(I);
660 }
661
662 // Finally, separate the type definition from other with a newline.
663 nl(Out);
664
665 // We weren't a recursive type
666 return false;
667 }
668
669 // Prints a type definition. Returns true if it could not resolve all the
670 // types in the definition but had to use a forward reference.
671 void CppWriter::printType(const Type* Ty) {
672 assert(TypeStack.empty());
673 TypeStack.clear();
674 printTypeInternal(Ty);
675 assert(TypeStack.empty());
676 }
677
678 void CppWriter::printTypes(const Module* M) {
679 // Walk the symbol table and print out all its types
680 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
681 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
682 TI != TE; ++TI) {
683
684 // For primitive types and types already defined, just add a name
685 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
686 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
687 TNI != TypeNames.end()) {
688 Out << "mod->addTypeName(\"";
689 printEscapedString(TI->first);
690 Out << "\", " << getCppName(TI->second) << ");";
691 nl(Out);
692 // For everything else, define the type
693 } else {
694 printType(TI->second);
695 }
696 }
697
698 // Add all of the global variables to the value table...
699 for (Module::const_global_iterator I = TheModule->global_begin(),
700 E = TheModule->global_end(); I != E; ++I) {
701 if (I->hasInitializer())
702 printType(I->getInitializer()->getType());
703 printType(I->getType());
704 }
705
706 // Add all the functions to the table
707 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
708 FI != FE; ++FI) {
709 printType(FI->getReturnType());
710 printType(FI->getFunctionType());
711 // Add all the function arguments
712 for (Function::const_arg_iterator AI = FI->arg_begin(),
713 AE = FI->arg_end(); AI != AE; ++AI) {
714 printType(AI->getType());
715 }
716
717 // Add all of the basic blocks and instructions
718 for (Function::const_iterator BB = FI->begin(),
719 E = FI->end(); BB != E; ++BB) {
720 printType(BB->getType());
721 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
722 ++I) {
723 printType(I->getType());
724 for (unsigned i = 0; i < I->getNumOperands(); ++i)
725 printType(I->getOperand(i)->getType());
726 }
727 }
728 }
729 }
730
731
732 // printConstant - Print out a constant pool entry...
733 void CppWriter::printConstant(const Constant *CV) {
734 // First, if the constant is actually a GlobalValue (variable or function)
735 // or its already in the constant list then we've printed it already and we
736 // can just return.
737 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
738 return;
739
740 std::string constName(getCppName(CV));
741 std::string typeName(getCppName(CV->getType()));
Anton Korobeynikovff4ca2e2008-10-05 15:07:06 +0000742
Anton Korobeynikov50276522008-04-23 22:29:24 +0000743 if (isa<GlobalValue>(CV)) {
744 // Skip variables and functions, we emit them elsewhere
745 return;
746 }
Anton Korobeynikovff4ca2e2008-10-05 15:07:06 +0000747
Anton Korobeynikov50276522008-04-23 22:29:24 +0000748 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
Anton Korobeynikov70053c32008-08-18 20:03:45 +0000749 std::string constValue = CI->getValue().toString(10, true);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000750 Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
Chris Lattnerfad86b02008-08-17 07:19:36 +0000751 << cast<IntegerType>(CI->getType())->getBitWidth() << ", \""
Anton Korobeynikov70053c32008-08-18 20:03:45 +0000752 << constValue << "\", " << constValue.length() << ", 10));";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000753 } else if (isa<ConstantAggregateZero>(CV)) {
754 Out << "ConstantAggregateZero* " << constName
755 << " = ConstantAggregateZero::get(" << typeName << ");";
756 } else if (isa<ConstantPointerNull>(CV)) {
757 Out << "ConstantPointerNull* " << constName
Anton Korobeynikovff4ca2e2008-10-05 15:07:06 +0000758 << " = ConstantPointerNull::get(" << typeName << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000759 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
760 Out << "ConstantFP* " << constName << " = ";
761 printCFP(CFP);
762 Out << ";";
763 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
764 if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
765 Out << "Constant* " << constName << " = ConstantArray::get(\"";
766 std::string tmp = CA->getAsString();
767 bool nullTerminate = false;
768 if (tmp[tmp.length()-1] == 0) {
769 tmp.erase(tmp.length()-1);
770 nullTerminate = true;
771 }
772 printEscapedString(tmp);
773 // Determine if we want null termination or not.
774 if (nullTerminate)
775 Out << "\", true"; // Indicate that the null terminator should be
776 // added.
777 else
778 Out << "\", false";// No null terminator
779 Out << ");";
780 } else {
781 Out << "std::vector<Constant*> " << constName << "_elems;";
782 nl(Out);
783 unsigned N = CA->getNumOperands();
784 for (unsigned i = 0; i < N; ++i) {
785 printConstant(CA->getOperand(i)); // recurse to print operands
786 Out << constName << "_elems.push_back("
787 << getCppName(CA->getOperand(i)) << ");";
788 nl(Out);
789 }
790 Out << "Constant* " << constName << " = ConstantArray::get("
791 << typeName << ", " << constName << "_elems);";
792 }
793 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
794 Out << "std::vector<Constant*> " << constName << "_fields;";
795 nl(Out);
796 unsigned N = CS->getNumOperands();
797 for (unsigned i = 0; i < N; i++) {
798 printConstant(CS->getOperand(i));
799 Out << constName << "_fields.push_back("
800 << getCppName(CS->getOperand(i)) << ");";
801 nl(Out);
802 }
803 Out << "Constant* " << constName << " = ConstantStruct::get("
804 << typeName << ", " << constName << "_fields);";
805 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
806 Out << "std::vector<Constant*> " << constName << "_elems;";
807 nl(Out);
808 unsigned N = CP->getNumOperands();
809 for (unsigned i = 0; i < N; ++i) {
810 printConstant(CP->getOperand(i));
811 Out << constName << "_elems.push_back("
812 << getCppName(CP->getOperand(i)) << ");";
813 nl(Out);
814 }
815 Out << "Constant* " << constName << " = ConstantVector::get("
816 << typeName << ", " << constName << "_elems);";
817 } else if (isa<UndefValue>(CV)) {
818 Out << "UndefValue* " << constName << " = UndefValue::get("
819 << typeName << ");";
820 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
821 if (CE->getOpcode() == Instruction::GetElementPtr) {
822 Out << "std::vector<Constant*> " << constName << "_indices;";
823 nl(Out);
824 printConstant(CE->getOperand(0));
825 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
826 printConstant(CE->getOperand(i));
827 Out << constName << "_indices.push_back("
828 << getCppName(CE->getOperand(i)) << ");";
829 nl(Out);
830 }
831 Out << "Constant* " << constName
832 << " = ConstantExpr::getGetElementPtr("
833 << getCppName(CE->getOperand(0)) << ", "
834 << "&" << constName << "_indices[0], "
835 << constName << "_indices.size()"
836 << " );";
837 } else if (CE->isCast()) {
838 printConstant(CE->getOperand(0));
839 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
840 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000841 default: llvm_unreachable("Invalid cast opcode");
Anton Korobeynikov50276522008-04-23 22:29:24 +0000842 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
843 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
844 case Instruction::SExt: Out << "Instruction::SExt"; break;
845 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
846 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
847 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
848 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
849 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
850 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
851 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
852 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
853 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
854 }
855 Out << ", " << getCppName(CE->getOperand(0)) << ", "
856 << getCppName(CE->getType()) << ");";
857 } else {
858 unsigned N = CE->getNumOperands();
859 for (unsigned i = 0; i < N; ++i ) {
860 printConstant(CE->getOperand(i));
861 }
862 Out << "Constant* " << constName << " = ConstantExpr::";
863 switch (CE->getOpcode()) {
864 case Instruction::Add: Out << "getAdd("; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000865 case Instruction::FAdd: Out << "getFAdd("; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000866 case Instruction::Sub: Out << "getSub("; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000867 case Instruction::FSub: Out << "getFSub("; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000868 case Instruction::Mul: Out << "getMul("; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000869 case Instruction::FMul: Out << "getFMul("; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000870 case Instruction::UDiv: Out << "getUDiv("; break;
871 case Instruction::SDiv: Out << "getSDiv("; break;
872 case Instruction::FDiv: Out << "getFDiv("; break;
873 case Instruction::URem: Out << "getURem("; break;
874 case Instruction::SRem: Out << "getSRem("; break;
875 case Instruction::FRem: Out << "getFRem("; break;
876 case Instruction::And: Out << "getAnd("; break;
877 case Instruction::Or: Out << "getOr("; break;
878 case Instruction::Xor: Out << "getXor("; break;
879 case Instruction::ICmp:
880 Out << "getICmp(ICmpInst::ICMP_";
881 switch (CE->getPredicate()) {
882 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
883 case ICmpInst::ICMP_NE: Out << "NE"; break;
884 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
885 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
886 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
887 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
888 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
889 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
890 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
891 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
892 default: error("Invalid ICmp Predicate");
893 }
894 break;
895 case Instruction::FCmp:
896 Out << "getFCmp(FCmpInst::FCMP_";
897 switch (CE->getPredicate()) {
898 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
899 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
900 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
901 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
902 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
903 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
904 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
905 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
906 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
907 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
908 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
909 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
910 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
911 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
912 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
913 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
914 default: error("Invalid FCmp Predicate");
915 }
916 break;
917 case Instruction::Shl: Out << "getShl("; break;
918 case Instruction::LShr: Out << "getLShr("; break;
919 case Instruction::AShr: Out << "getAShr("; break;
920 case Instruction::Select: Out << "getSelect("; break;
921 case Instruction::ExtractElement: Out << "getExtractElement("; break;
922 case Instruction::InsertElement: Out << "getInsertElement("; break;
923 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
924 default:
925 error("Invalid constant expression");
926 break;
927 }
928 Out << getCppName(CE->getOperand(0));
929 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
930 Out << ", " << getCppName(CE->getOperand(i));
931 Out << ");";
932 }
933 } else {
934 error("Bad Constant");
935 Out << "Constant* " << constName << " = 0; ";
936 }
937 nl(Out);
938 }
939
940 void CppWriter::printConstants(const Module* M) {
941 // Traverse all the global variables looking for constant initializers
942 for (Module::const_global_iterator I = TheModule->global_begin(),
943 E = TheModule->global_end(); I != E; ++I)
944 if (I->hasInitializer())
945 printConstant(I->getInitializer());
946
947 // Traverse the LLVM functions looking for constants
948 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
949 FI != FE; ++FI) {
950 // Add all of the basic blocks and instructions
951 for (Function::const_iterator BB = FI->begin(),
952 E = FI->end(); BB != E; ++BB) {
953 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
954 ++I) {
955 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
956 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
957 printConstant(C);
958 }
959 }
960 }
961 }
962 }
963 }
964
965 void CppWriter::printVariableUses(const GlobalVariable *GV) {
966 nl(Out) << "// Type Definitions";
967 nl(Out);
968 printType(GV->getType());
969 if (GV->hasInitializer()) {
970 Constant* Init = GV->getInitializer();
971 printType(Init->getType());
972 if (Function* F = dyn_cast<Function>(Init)) {
973 nl(Out)<< "/ Function Declarations"; nl(Out);
974 printFunctionHead(F);
975 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
976 nl(Out) << "// Global Variable Declarations"; nl(Out);
977 printVariableHead(gv);
978 } else {
979 nl(Out) << "// Constant Definitions"; nl(Out);
980 printConstant(gv);
981 }
982 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
983 nl(Out) << "// Global Variable Definitions"; nl(Out);
984 printVariableBody(gv);
985 }
986 }
987 }
988
989 void CppWriter::printVariableHead(const GlobalVariable *GV) {
990 nl(Out) << "GlobalVariable* " << getCppName(GV);
991 if (is_inline) {
992 Out << " = mod->getGlobalVariable(";
993 printEscapedString(GV->getName());
994 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
995 nl(Out) << "if (!" << getCppName(GV) << ") {";
996 in(); nl(Out) << getCppName(GV);
997 }
Owen Anderson16a412e2009-07-10 16:42:19 +0000998 Out << " = new GlobalVariable(/*Module=*/*mod";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000999 nl(Out) << "/*Type=*/";
1000 printCppName(GV->getType()->getElementType());
1001 Out << ",";
1002 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
1003 Out << ",";
1004 nl(Out) << "/*Linkage=*/";
1005 printLinkageType(GV->getLinkage());
1006 Out << ",";
1007 nl(Out) << "/*Initializer=*/0, ";
1008 if (GV->hasInitializer()) {
1009 Out << "// has initializer, specified below";
1010 }
1011 nl(Out) << "/*Name=*/\"";
1012 printEscapedString(GV->getName());
Owen Anderson16a412e2009-07-10 16:42:19 +00001013 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001014 nl(Out);
1015
1016 if (GV->hasSection()) {
1017 printCppName(GV);
1018 Out << "->setSection(\"";
1019 printEscapedString(GV->getSection());
1020 Out << "\");";
1021 nl(Out);
1022 }
1023 if (GV->getAlignment()) {
1024 printCppName(GV);
1025 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1026 nl(Out);
1027 }
1028 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1029 printCppName(GV);
1030 Out << "->setVisibility(";
1031 printVisibilityType(GV->getVisibility());
1032 Out << ");";
1033 nl(Out);
1034 }
1035 if (is_inline) {
1036 out(); Out << "}"; nl(Out);
1037 }
1038 }
1039
1040 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1041 if (GV->hasInitializer()) {
1042 printCppName(GV);
1043 Out << "->setInitializer(";
1044 Out << getCppName(GV->getInitializer()) << ");";
1045 nl(Out);
1046 }
1047 }
1048
1049 std::string CppWriter::getOpName(Value* V) {
1050 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1051 return getCppName(V);
1052
1053 // See if its alread in the map of forward references, if so just return the
1054 // name we already set up for it
1055 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1056 if (I != ForwardRefs.end())
1057 return I->second;
1058
1059 // This is a new forward reference. Generate a unique name for it
1060 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1061
1062 // Yes, this is a hack. An Argument is the smallest instantiable value that
1063 // we can make as a placeholder for the real value. We'll replace these
1064 // Argument instances later.
1065 Out << "Argument* " << result << " = new Argument("
1066 << getCppName(V->getType()) << ");";
1067 nl(Out);
1068 ForwardRefs[V] = result;
1069 return result;
1070 }
1071
1072 // printInstruction - This member is called for each Instruction in a function.
1073 void CppWriter::printInstruction(const Instruction *I,
1074 const std::string& bbname) {
1075 std::string iName(getCppName(I));
1076
1077 // Before we emit this instruction, we need to take care of generating any
1078 // forward references. So, we get the names of all the operands in advance
1079 std::string* opNames = new std::string[I->getNumOperands()];
1080 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1081 opNames[i] = getOpName(I->getOperand(i));
1082 }
1083
1084 switch (I->getOpcode()) {
Dan Gohman26825a82008-06-09 14:09:13 +00001085 default:
1086 error("Invalid instruction");
1087 break;
1088
Anton Korobeynikov50276522008-04-23 22:29:24 +00001089 case Instruction::Ret: {
1090 const ReturnInst* ret = cast<ReturnInst>(I);
1091 Out << "ReturnInst::Create("
1092 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1093 break;
1094 }
1095 case Instruction::Br: {
1096 const BranchInst* br = cast<BranchInst>(I);
1097 Out << "BranchInst::Create(" ;
1098 if (br->getNumOperands() == 3 ) {
Anton Korobeynikovcffb5282009-05-04 19:10:38 +00001099 Out << opNames[2] << ", "
Anton Korobeynikov50276522008-04-23 22:29:24 +00001100 << opNames[1] << ", "
Anton Korobeynikovcffb5282009-05-04 19:10:38 +00001101 << opNames[0] << ", ";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001102
1103 } else if (br->getNumOperands() == 1) {
1104 Out << opNames[0] << ", ";
1105 } else {
1106 error("Branch with 2 operands?");
1107 }
1108 Out << bbname << ");";
1109 break;
1110 }
1111 case Instruction::Switch: {
1112 const SwitchInst* sw = cast<SwitchInst>(I);
1113 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1114 << opNames[0] << ", "
1115 << opNames[1] << ", "
1116 << sw->getNumCases() << ", " << bbname << ");";
1117 nl(Out);
1118 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1119 Out << iName << "->addCase("
1120 << opNames[i] << ", "
1121 << opNames[i+1] << ");";
1122 nl(Out);
1123 }
1124 break;
1125 }
1126 case Instruction::Invoke: {
1127 const InvokeInst* inv = cast<InvokeInst>(I);
1128 Out << "std::vector<Value*> " << iName << "_params;";
1129 nl(Out);
1130 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1131 Out << iName << "_params.push_back("
1132 << opNames[i] << ");";
1133 nl(Out);
1134 }
1135 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1136 << opNames[0] << ", "
1137 << opNames[1] << ", "
1138 << opNames[2] << ", "
1139 << iName << "_params.begin(), " << iName << "_params.end(), \"";
1140 printEscapedString(inv->getName());
1141 Out << "\", " << bbname << ");";
1142 nl(Out) << iName << "->setCallingConv(";
1143 printCallingConv(inv->getCallingConv());
1144 Out << ");";
Devang Patel05988662008-09-25 21:00:45 +00001145 printAttributes(inv->getAttributes(), iName);
1146 Out << iName << "->setAttributes(" << iName << "_PAL);";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001147 nl(Out);
1148 break;
1149 }
1150 case Instruction::Unwind: {
1151 Out << "new UnwindInst("
1152 << bbname << ");";
1153 break;
1154 }
1155 case Instruction::Unreachable:{
1156 Out << "new UnreachableInst("
1157 << bbname << ");";
1158 break;
1159 }
1160 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001161 case Instruction::FAdd:
Anton Korobeynikov50276522008-04-23 22:29:24 +00001162 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001163 case Instruction::FSub:
Anton Korobeynikov50276522008-04-23 22:29:24 +00001164 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001165 case Instruction::FMul:
Anton Korobeynikov50276522008-04-23 22:29:24 +00001166 case Instruction::UDiv:
1167 case Instruction::SDiv:
1168 case Instruction::FDiv:
1169 case Instruction::URem:
1170 case Instruction::SRem:
1171 case Instruction::FRem:
1172 case Instruction::And:
1173 case Instruction::Or:
1174 case Instruction::Xor:
1175 case Instruction::Shl:
1176 case Instruction::LShr:
1177 case Instruction::AShr:{
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001178 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001179 switch (I->getOpcode()) {
1180 case Instruction::Add: Out << "Instruction::Add"; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001181 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001182 case Instruction::Sub: Out << "Instruction::Sub"; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001183 case Instruction::FSub: Out << "Instruction::FSub"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001184 case Instruction::Mul: Out << "Instruction::Mul"; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001185 case Instruction::FMul: Out << "Instruction::FMul"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001186 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1187 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1188 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1189 case Instruction::URem:Out << "Instruction::URem"; break;
1190 case Instruction::SRem:Out << "Instruction::SRem"; break;
1191 case Instruction::FRem:Out << "Instruction::FRem"; break;
1192 case Instruction::And: Out << "Instruction::And"; break;
1193 case Instruction::Or: Out << "Instruction::Or"; break;
1194 case Instruction::Xor: Out << "Instruction::Xor"; break;
1195 case Instruction::Shl: Out << "Instruction::Shl"; break;
1196 case Instruction::LShr:Out << "Instruction::LShr"; break;
1197 case Instruction::AShr:Out << "Instruction::AShr"; break;
1198 default: Out << "Instruction::BadOpCode"; break;
1199 }
1200 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1201 printEscapedString(I->getName());
1202 Out << "\", " << bbname << ");";
1203 break;
1204 }
1205 case Instruction::FCmp: {
1206 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1207 switch (cast<FCmpInst>(I)->getPredicate()) {
1208 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1209 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1210 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1211 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1212 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1213 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1214 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1215 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1216 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1217 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1218 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1219 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1220 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1221 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1222 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1223 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1224 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1225 }
1226 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1227 printEscapedString(I->getName());
1228 Out << "\", " << bbname << ");";
1229 break;
1230 }
1231 case Instruction::ICmp: {
1232 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1233 switch (cast<ICmpInst>(I)->getPredicate()) {
1234 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1235 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1236 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1237 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1238 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1239 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1240 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1241 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1242 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1243 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1244 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1245 }
1246 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1247 printEscapedString(I->getName());
1248 Out << "\", " << bbname << ");";
1249 break;
1250 }
1251 case Instruction::Malloc: {
1252 const MallocInst* mallocI = cast<MallocInst>(I);
1253 Out << "MallocInst* " << iName << " = new MallocInst("
1254 << getCppName(mallocI->getAllocatedType()) << ", ";
1255 if (mallocI->isArrayAllocation())
1256 Out << opNames[0] << ", " ;
1257 Out << "\"";
1258 printEscapedString(mallocI->getName());
1259 Out << "\", " << bbname << ");";
1260 if (mallocI->getAlignment())
1261 nl(Out) << iName << "->setAlignment("
1262 << mallocI->getAlignment() << ");";
1263 break;
1264 }
1265 case Instruction::Free: {
1266 Out << "FreeInst* " << iName << " = new FreeInst("
1267 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1268 break;
1269 }
1270 case Instruction::Alloca: {
1271 const AllocaInst* allocaI = cast<AllocaInst>(I);
1272 Out << "AllocaInst* " << iName << " = new AllocaInst("
1273 << getCppName(allocaI->getAllocatedType()) << ", ";
1274 if (allocaI->isArrayAllocation())
1275 Out << opNames[0] << ", ";
1276 Out << "\"";
1277 printEscapedString(allocaI->getName());
1278 Out << "\", " << bbname << ");";
1279 if (allocaI->getAlignment())
1280 nl(Out) << iName << "->setAlignment("
1281 << allocaI->getAlignment() << ");";
1282 break;
1283 }
1284 case Instruction::Load:{
1285 const LoadInst* load = cast<LoadInst>(I);
1286 Out << "LoadInst* " << iName << " = new LoadInst("
1287 << opNames[0] << ", \"";
1288 printEscapedString(load->getName());
1289 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1290 << ", " << bbname << ");";
1291 break;
1292 }
1293 case Instruction::Store: {
1294 const StoreInst* store = cast<StoreInst>(I);
Anton Korobeynikovb0714db2008-11-09 02:54:13 +00001295 Out << " new StoreInst("
Anton Korobeynikov50276522008-04-23 22:29:24 +00001296 << opNames[0] << ", "
1297 << opNames[1] << ", "
1298 << (store->isVolatile() ? "true" : "false")
1299 << ", " << bbname << ");";
1300 break;
1301 }
1302 case Instruction::GetElementPtr: {
1303 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1304 if (gep->getNumOperands() <= 2) {
1305 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1306 << opNames[0];
1307 if (gep->getNumOperands() == 2)
1308 Out << ", " << opNames[1];
1309 } else {
1310 Out << "std::vector<Value*> " << iName << "_indices;";
1311 nl(Out);
1312 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1313 Out << iName << "_indices.push_back("
1314 << opNames[i] << ");";
1315 nl(Out);
1316 }
1317 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1318 << opNames[0] << ", " << iName << "_indices.begin(), "
1319 << iName << "_indices.end()";
1320 }
1321 Out << ", \"";
1322 printEscapedString(gep->getName());
1323 Out << "\", " << bbname << ");";
1324 break;
1325 }
1326 case Instruction::PHI: {
1327 const PHINode* phi = cast<PHINode>(I);
1328
1329 Out << "PHINode* " << iName << " = PHINode::Create("
1330 << getCppName(phi->getType()) << ", \"";
1331 printEscapedString(phi->getName());
1332 Out << "\", " << bbname << ");";
1333 nl(Out) << iName << "->reserveOperandSpace("
1334 << phi->getNumIncomingValues()
1335 << ");";
1336 nl(Out);
1337 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1338 Out << iName << "->addIncoming("
1339 << opNames[i] << ", " << opNames[i+1] << ");";
1340 nl(Out);
1341 }
1342 break;
1343 }
1344 case Instruction::Trunc:
1345 case Instruction::ZExt:
1346 case Instruction::SExt:
1347 case Instruction::FPTrunc:
1348 case Instruction::FPExt:
1349 case Instruction::FPToUI:
1350 case Instruction::FPToSI:
1351 case Instruction::UIToFP:
1352 case Instruction::SIToFP:
1353 case Instruction::PtrToInt:
1354 case Instruction::IntToPtr:
1355 case Instruction::BitCast: {
1356 const CastInst* cst = cast<CastInst>(I);
1357 Out << "CastInst* " << iName << " = new ";
1358 switch (I->getOpcode()) {
1359 case Instruction::Trunc: Out << "TruncInst"; break;
1360 case Instruction::ZExt: Out << "ZExtInst"; break;
1361 case Instruction::SExt: Out << "SExtInst"; break;
1362 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1363 case Instruction::FPExt: Out << "FPExtInst"; break;
1364 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1365 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1366 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1367 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1368 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1369 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1370 case Instruction::BitCast: Out << "BitCastInst"; break;
1371 default: assert(!"Unreachable"); break;
1372 }
1373 Out << "(" << opNames[0] << ", "
1374 << getCppName(cst->getType()) << ", \"";
1375 printEscapedString(cst->getName());
1376 Out << "\", " << bbname << ");";
1377 break;
1378 }
1379 case Instruction::Call:{
1380 const CallInst* call = cast<CallInst>(I);
Gabor Greif0c8f7dc2009-03-25 06:32:59 +00001381 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001382 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1383 << getCppName(ila->getFunctionType()) << ", \""
1384 << ila->getAsmString() << "\", \""
1385 << ila->getConstraintString() << "\","
1386 << (ila->hasSideEffects() ? "true" : "false") << ");";
1387 nl(Out);
1388 }
1389 if (call->getNumOperands() > 2) {
1390 Out << "std::vector<Value*> " << iName << "_params;";
1391 nl(Out);
1392 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1393 Out << iName << "_params.push_back(" << opNames[i] << ");";
1394 nl(Out);
1395 }
1396 Out << "CallInst* " << iName << " = CallInst::Create("
1397 << opNames[0] << ", " << iName << "_params.begin(), "
1398 << iName << "_params.end(), \"";
1399 } else if (call->getNumOperands() == 2) {
1400 Out << "CallInst* " << iName << " = CallInst::Create("
1401 << opNames[0] << ", " << opNames[1] << ", \"";
1402 } else {
1403 Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
1404 << ", \"";
1405 }
1406 printEscapedString(call->getName());
1407 Out << "\", " << bbname << ");";
1408 nl(Out) << iName << "->setCallingConv(";
1409 printCallingConv(call->getCallingConv());
1410 Out << ");";
1411 nl(Out) << iName << "->setTailCall("
1412 << (call->isTailCall() ? "true":"false");
1413 Out << ");";
Devang Patel05988662008-09-25 21:00:45 +00001414 printAttributes(call->getAttributes(), iName);
1415 Out << iName << "->setAttributes(" << iName << "_PAL);";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001416 nl(Out);
1417 break;
1418 }
1419 case Instruction::Select: {
1420 const SelectInst* sel = cast<SelectInst>(I);
1421 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1422 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1423 printEscapedString(sel->getName());
1424 Out << "\", " << bbname << ");";
1425 break;
1426 }
1427 case Instruction::UserOp1:
1428 /// FALL THROUGH
1429 case Instruction::UserOp2: {
1430 /// FIXME: What should be done here?
1431 break;
1432 }
1433 case Instruction::VAArg: {
1434 const VAArgInst* va = cast<VAArgInst>(I);
1435 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1436 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1437 printEscapedString(va->getName());
1438 Out << "\", " << bbname << ");";
1439 break;
1440 }
1441 case Instruction::ExtractElement: {
1442 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1443 Out << "ExtractElementInst* " << getCppName(eei)
1444 << " = new ExtractElementInst(" << opNames[0]
1445 << ", " << opNames[1] << ", \"";
1446 printEscapedString(eei->getName());
1447 Out << "\", " << bbname << ");";
1448 break;
1449 }
1450 case Instruction::InsertElement: {
1451 const InsertElementInst* iei = cast<InsertElementInst>(I);
1452 Out << "InsertElementInst* " << getCppName(iei)
1453 << " = InsertElementInst::Create(" << opNames[0]
1454 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1455 printEscapedString(iei->getName());
1456 Out << "\", " << bbname << ");";
1457 break;
1458 }
1459 case Instruction::ShuffleVector: {
1460 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1461 Out << "ShuffleVectorInst* " << getCppName(svi)
1462 << " = new ShuffleVectorInst(" << opNames[0]
1463 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1464 printEscapedString(svi->getName());
1465 Out << "\", " << bbname << ");";
1466 break;
1467 }
Dan Gohman75146a62008-06-09 14:12:10 +00001468 case Instruction::ExtractValue: {
1469 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1470 Out << "std::vector<unsigned> " << iName << "_indices;";
1471 nl(Out);
1472 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1473 Out << iName << "_indices.push_back("
1474 << evi->idx_begin()[i] << ");";
1475 nl(Out);
1476 }
1477 Out << "ExtractValueInst* " << getCppName(evi)
1478 << " = ExtractValueInst::Create(" << opNames[0]
1479 << ", "
1480 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1481 printEscapedString(evi->getName());
1482 Out << "\", " << bbname << ");";
1483 break;
1484 }
1485 case Instruction::InsertValue: {
1486 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1487 Out << "std::vector<unsigned> " << iName << "_indices;";
1488 nl(Out);
1489 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1490 Out << iName << "_indices.push_back("
1491 << ivi->idx_begin()[i] << ");";
1492 nl(Out);
1493 }
1494 Out << "InsertValueInst* " << getCppName(ivi)
1495 << " = InsertValueInst::Create(" << opNames[0]
1496 << ", " << opNames[1] << ", "
1497 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1498 printEscapedString(ivi->getName());
1499 Out << "\", " << bbname << ");";
1500 break;
1501 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001502 }
1503 DefinedValues.insert(I);
1504 nl(Out);
1505 delete [] opNames;
1506}
1507
1508 // Print out the types, constants and declarations needed by one function
1509 void CppWriter::printFunctionUses(const Function* F) {
1510 nl(Out) << "// Type Definitions"; nl(Out);
1511 if (!is_inline) {
1512 // Print the function's return type
1513 printType(F->getReturnType());
1514
1515 // Print the function's function type
1516 printType(F->getFunctionType());
1517
1518 // Print the types of each of the function's arguments
1519 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1520 AI != AE; ++AI) {
1521 printType(AI->getType());
1522 }
1523 }
1524
1525 // Print type definitions for every type referenced by an instruction and
1526 // make a note of any global values or constants that are referenced
1527 SmallPtrSet<GlobalValue*,64> gvs;
1528 SmallPtrSet<Constant*,64> consts;
1529 for (Function::const_iterator BB = F->begin(), BE = F->end();
1530 BB != BE; ++BB){
1531 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1532 I != E; ++I) {
1533 // Print the type of the instruction itself
1534 printType(I->getType());
1535
1536 // Print the type of each of the instruction's operands
1537 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1538 Value* operand = I->getOperand(i);
1539 printType(operand->getType());
1540
1541 // If the operand references a GVal or Constant, make a note of it
1542 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1543 gvs.insert(GV);
1544 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1545 if (GVar->hasInitializer())
1546 consts.insert(GVar->getInitializer());
1547 } else if (Constant* C = dyn_cast<Constant>(operand))
1548 consts.insert(C);
1549 }
1550 }
1551 }
1552
1553 // Print the function declarations for any functions encountered
1554 nl(Out) << "// Function Declarations"; nl(Out);
1555 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1556 I != E; ++I) {
1557 if (Function* Fun = dyn_cast<Function>(*I)) {
1558 if (!is_inline || Fun != F)
1559 printFunctionHead(Fun);
1560 }
1561 }
1562
1563 // Print the global variable declarations for any variables encountered
1564 nl(Out) << "// Global Variable Declarations"; nl(Out);
1565 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1566 I != E; ++I) {
1567 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1568 printVariableHead(F);
1569 }
1570
1571 // Print the constants found
1572 nl(Out) << "// Constant Definitions"; nl(Out);
1573 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1574 E = consts.end(); I != E; ++I) {
1575 printConstant(*I);
1576 }
1577
1578 // Process the global variables definitions now that all the constants have
1579 // been emitted. These definitions just couple the gvars with their constant
1580 // initializers.
1581 nl(Out) << "// Global Variable Definitions"; nl(Out);
1582 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1583 I != E; ++I) {
1584 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1585 printVariableBody(GV);
1586 }
1587 }
1588
1589 void CppWriter::printFunctionHead(const Function* F) {
1590 nl(Out) << "Function* " << getCppName(F);
1591 if (is_inline) {
1592 Out << " = mod->getFunction(\"";
1593 printEscapedString(F->getName());
1594 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1595 nl(Out) << "if (!" << getCppName(F) << ") {";
1596 nl(Out) << getCppName(F);
1597 }
1598 Out<< " = Function::Create(";
1599 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1600 nl(Out) << "/*Linkage=*/";
1601 printLinkageType(F->getLinkage());
1602 Out << ",";
1603 nl(Out) << "/*Name=*/\"";
1604 printEscapedString(F->getName());
1605 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1606 nl(Out,-1);
1607 printCppName(F);
1608 Out << "->setCallingConv(";
1609 printCallingConv(F->getCallingConv());
1610 Out << ");";
1611 nl(Out);
1612 if (F->hasSection()) {
1613 printCppName(F);
1614 Out << "->setSection(\"" << F->getSection() << "\");";
1615 nl(Out);
1616 }
1617 if (F->getAlignment()) {
1618 printCppName(F);
1619 Out << "->setAlignment(" << F->getAlignment() << ");";
1620 nl(Out);
1621 }
1622 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1623 printCppName(F);
1624 Out << "->setVisibility(";
1625 printVisibilityType(F->getVisibility());
1626 Out << ");";
1627 nl(Out);
1628 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001629 if (F->hasGC()) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001630 printCppName(F);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001631 Out << "->setGC(\"" << F->getGC() << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001632 nl(Out);
1633 }
1634 if (is_inline) {
1635 Out << "}";
1636 nl(Out);
1637 }
Devang Patel05988662008-09-25 21:00:45 +00001638 printAttributes(F->getAttributes(), getCppName(F));
Anton Korobeynikov50276522008-04-23 22:29:24 +00001639 printCppName(F);
Devang Patel05988662008-09-25 21:00:45 +00001640 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001641 nl(Out);
1642 }
1643
1644 void CppWriter::printFunctionBody(const Function *F) {
1645 if (F->isDeclaration())
1646 return; // external functions have no bodies.
1647
1648 // Clear the DefinedValues and ForwardRefs maps because we can't have
1649 // cross-function forward refs
1650 ForwardRefs.clear();
1651 DefinedValues.clear();
1652
1653 // Create all the argument values
1654 if (!is_inline) {
1655 if (!F->arg_empty()) {
1656 Out << "Function::arg_iterator args = " << getCppName(F)
1657 << "->arg_begin();";
1658 nl(Out);
1659 }
1660 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1661 AI != AE; ++AI) {
1662 Out << "Value* " << getCppName(AI) << " = args++;";
1663 nl(Out);
1664 if (AI->hasName()) {
1665 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1666 nl(Out);
1667 }
1668 }
1669 }
1670
1671 // Create all the basic blocks
1672 nl(Out);
1673 for (Function::const_iterator BI = F->begin(), BE = F->end();
1674 BI != BE; ++BI) {
1675 std::string bbname(getCppName(BI));
1676 Out << "BasicBlock* " << bbname << " = BasicBlock::Create(\"";
1677 if (BI->hasName())
1678 printEscapedString(BI->getName());
1679 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1680 nl(Out);
1681 }
1682
1683 // Output all of its basic blocks... for the function
1684 for (Function::const_iterator BI = F->begin(), BE = F->end();
1685 BI != BE; ++BI) {
1686 std::string bbname(getCppName(BI));
1687 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1688 nl(Out);
1689
1690 // Output all of the instructions in the basic block...
1691 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1692 I != E; ++I) {
1693 printInstruction(I,bbname);
1694 }
1695 }
1696
1697 // Loop over the ForwardRefs and resolve them now that all instructions
1698 // are generated.
1699 if (!ForwardRefs.empty()) {
1700 nl(Out) << "// Resolve Forward References";
1701 nl(Out);
1702 }
1703
1704 while (!ForwardRefs.empty()) {
1705 ForwardRefMap::iterator I = ForwardRefs.begin();
1706 Out << I->second << "->replaceAllUsesWith("
1707 << getCppName(I->first) << "); delete " << I->second << ";";
1708 nl(Out);
1709 ForwardRefs.erase(I);
1710 }
1711 }
1712
1713 void CppWriter::printInline(const std::string& fname,
1714 const std::string& func) {
1715 const Function* F = TheModule->getFunction(func);
1716 if (!F) {
1717 error(std::string("Function '") + func + "' not found in input module");
1718 return;
1719 }
1720 if (F->isDeclaration()) {
1721 error(std::string("Function '") + func + "' is external!");
1722 return;
1723 }
1724 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1725 << getCppName(F);
1726 unsigned arg_count = 1;
1727 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1728 AI != AE; ++AI) {
1729 Out << ", Value* arg_" << arg_count;
1730 }
1731 Out << ") {";
1732 nl(Out);
1733 is_inline = true;
1734 printFunctionUses(F);
1735 printFunctionBody(F);
1736 is_inline = false;
1737 Out << "return " << getCppName(F->begin()) << ";";
1738 nl(Out) << "}";
1739 nl(Out);
1740 }
1741
1742 void CppWriter::printModuleBody() {
1743 // Print out all the type definitions
1744 nl(Out) << "// Type Definitions"; nl(Out);
1745 printTypes(TheModule);
1746
1747 // Functions can call each other and global variables can reference them so
1748 // define all the functions first before emitting their function bodies.
1749 nl(Out) << "// Function Declarations"; nl(Out);
1750 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1751 I != E; ++I)
1752 printFunctionHead(I);
1753
1754 // Process the global variables declarations. We can't initialze them until
1755 // after the constants are printed so just print a header for each global
1756 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1757 for (Module::const_global_iterator I = TheModule->global_begin(),
1758 E = TheModule->global_end(); I != E; ++I) {
1759 printVariableHead(I);
1760 }
1761
1762 // Print out all the constants definitions. Constants don't recurse except
1763 // through GlobalValues. All GlobalValues have been declared at this point
1764 // so we can proceed to generate the constants.
1765 nl(Out) << "// Constant Definitions"; nl(Out);
1766 printConstants(TheModule);
1767
1768 // Process the global variables definitions now that all the constants have
1769 // been emitted. These definitions just couple the gvars with their constant
1770 // initializers.
1771 nl(Out) << "// Global Variable Definitions"; nl(Out);
1772 for (Module::const_global_iterator I = TheModule->global_begin(),
1773 E = TheModule->global_end(); I != E; ++I) {
1774 printVariableBody(I);
1775 }
1776
1777 // Finally, we can safely put out all of the function bodies.
1778 nl(Out) << "// Function Definitions"; nl(Out);
1779 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1780 I != E; ++I) {
1781 if (!I->isDeclaration()) {
1782 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1783 << ")";
1784 nl(Out) << "{";
1785 nl(Out,1);
1786 printFunctionBody(I);
1787 nl(Out,-1) << "}";
1788 nl(Out);
1789 }
1790 }
1791 }
1792
1793 void CppWriter::printProgram(const std::string& fname,
1794 const std::string& mName) {
1795 Out << "#include <llvm/Module.h>\n";
1796 Out << "#include <llvm/DerivedTypes.h>\n";
1797 Out << "#include <llvm/Constants.h>\n";
1798 Out << "#include <llvm/GlobalVariable.h>\n";
1799 Out << "#include <llvm/Function.h>\n";
1800 Out << "#include <llvm/CallingConv.h>\n";
1801 Out << "#include <llvm/BasicBlock.h>\n";
1802 Out << "#include <llvm/Instructions.h>\n";
1803 Out << "#include <llvm/InlineAsm.h>\n";
David Greene71847812009-07-14 20:18:05 +00001804 Out << "#include <llvm/Support/FormattedStream.h>\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001805 Out << "#include <llvm/Support/MathExtras.h>\n";
1806 Out << "#include <llvm/Pass.h>\n";
1807 Out << "#include <llvm/PassManager.h>\n";
Nicolas Geoffray9474ede2008-05-14 07:52:03 +00001808 Out << "#include <llvm/ADT/SmallVector.h>\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001809 Out << "#include <llvm/Analysis/Verifier.h>\n";
1810 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1811 Out << "#include <algorithm>\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001812 Out << "using namespace llvm;\n\n";
1813 Out << "Module* " << fname << "();\n\n";
1814 Out << "int main(int argc, char**argv) {\n";
1815 Out << " Module* Mod = " << fname << "();\n";
1816 Out << " verifyModule(*Mod, PrintMessageAction);\n";
Dan Gohmanf9231292008-12-08 07:07:24 +00001817 Out << " outs().flush();\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001818 Out << " PassManager PM;\n";
Dan Gohmanf9231292008-12-08 07:07:24 +00001819 Out << " PM.add(createPrintModulePass(&outs()));\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001820 Out << " PM.run(*Mod);\n";
1821 Out << " return 0;\n";
1822 Out << "}\n\n";
1823 printModule(fname,mName);
1824 }
1825
1826 void CppWriter::printModule(const std::string& fname,
1827 const std::string& mName) {
1828 nl(Out) << "Module* " << fname << "() {";
1829 nl(Out,1) << "// Module Construction";
Nick Lewyckyb8b73472009-06-26 04:33:37 +00001830 nl(Out) << "Module* mod = new Module(\"";
1831 printEscapedString(mName);
1832 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001833 if (!TheModule->getTargetTriple().empty()) {
1834 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1835 }
1836 if (!TheModule->getTargetTriple().empty()) {
1837 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1838 << "\");";
1839 }
1840
1841 if (!TheModule->getModuleInlineAsm().empty()) {
1842 nl(Out) << "mod->setModuleInlineAsm(\"";
1843 printEscapedString(TheModule->getModuleInlineAsm());
1844 Out << "\");";
1845 }
1846 nl(Out);
1847
1848 // Loop over the dependent libraries and emit them.
1849 Module::lib_iterator LI = TheModule->lib_begin();
1850 Module::lib_iterator LE = TheModule->lib_end();
1851 while (LI != LE) {
1852 Out << "mod->addLibrary(\"" << *LI << "\");";
1853 nl(Out);
1854 ++LI;
1855 }
1856 printModuleBody();
1857 nl(Out) << "return mod;";
1858 nl(Out,-1) << "}";
1859 nl(Out);
1860 }
1861
1862 void CppWriter::printContents(const std::string& fname,
1863 const std::string& mName) {
1864 Out << "\nModule* " << fname << "(Module *mod) {\n";
Nick Lewyckyb8b73472009-06-26 04:33:37 +00001865 Out << "\nmod->setModuleIdentifier(\"";
1866 printEscapedString(mName);
1867 Out << "\");\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001868 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,
David Greene71847812009-07-14 20:18:05 +00002010 formatted_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}