blob: efa54d20885a778fd58a757102b4cc45768c5e63 [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"
Evan Cheng1abf2cb2011-07-14 23:50:31 +000025#include "llvm/MC/MCAsmInfo.h"
Evan Cheng59ee62d2011-07-11 03:57:24 +000026#include "llvm/MC/MCInstrInfo.h"
Evan Chengffc0e732011-07-09 05:47:46 +000027#include "llvm/MC/MCSubtargetInfo.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000028#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/Support/CommandLine.h"
Torok Edwin30464702009-07-08 20:55:50 +000030#include "llvm/Support/ErrorHandling.h"
David Greene71847812009-07-14 20:18:05 +000031#include "llvm/Support/FormattedStream.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000032#include "llvm/Support/TargetRegistry.h"
Chris Lattner23132b12009-08-24 03:52:50 +000033#include "llvm/ADT/StringExtras.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>
Chris Lattner1afcace2011-07-09 17:41:24 +000037#include <map>
Anton Korobeynikov50276522008-04-23 22:29:24 +000038using 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
Daniel Dunbar0c795d62009-07-25 06:49:55 +000075extern "C" void LLVMInitializeCppBackendTarget() {
76 // Register the target.
Daniel Dunbar214e2232009-08-04 04:02:45 +000077 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
Daniel Dunbar0c795d62009-07-25 06:49:55 +000078}
Douglas Gregor1555a232009-06-16 20:12:29 +000079
Dan Gohman844731a2008-05-13 00:00:25 +000080namespace {
Chris Lattnerdb125cf2011-07-18 04:54:35 +000081 typedef std::vector<Type*> TypeList;
82 typedef std::map<Type*,std::string> TypeMap;
Anton Korobeynikov50276522008-04-23 22:29:24 +000083 typedef std::map<const Value*,std::string> ValueMap;
84 typedef std::set<std::string> NameSet;
Chris Lattnerdb125cf2011-07-18 04:54:35 +000085 typedef std::set<Type*> TypeSet;
Anton Korobeynikov50276522008-04-23 22:29:24 +000086 typedef std::set<const Value*> ValueSet;
87 typedef std::map<const Value*,std::string> ForwardRefMap;
88
89 /// CppWriter - This class is the main chunk of code that converts an LLVM
90 /// module to a C++ translation unit.
91 class CppWriter : public ModulePass {
David Greene71847812009-07-14 20:18:05 +000092 formatted_raw_ostream &Out;
Anton Korobeynikov50276522008-04-23 22:29:24 +000093 const Module *TheModule;
94 uint64_t uniqueNum;
95 TypeMap TypeNames;
96 ValueMap ValueNames;
Anton Korobeynikov50276522008-04-23 22:29:24 +000097 NameSet UsedNames;
98 TypeSet DefinedTypes;
99 ValueSet DefinedValues;
100 ForwardRefMap ForwardRefs;
101 bool is_inline;
Chris Lattner1018c242010-06-21 23:14:47 +0000102 unsigned indent_level;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000103
104 public:
105 static char ID;
David Greene71847812009-07-14 20:18:05 +0000106 explicit CppWriter(formatted_raw_ostream &o) :
Owen Anderson90c579d2010-08-06 18:33:48 +0000107 ModulePass(ID), Out(o), uniqueNum(0), is_inline(false), indent_level(0){}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000108
109 virtual const char *getPassName() const { return "C++ backend"; }
110
111 bool runOnModule(Module &M);
112
Anton Korobeynikov50276522008-04-23 22:29:24 +0000113 void printProgram(const std::string& fname, const std::string& modName );
114 void printModule(const std::string& fname, const std::string& modName );
115 void printContents(const std::string& fname, const std::string& modName );
116 void printFunction(const std::string& fname, const std::string& funcName );
117 void printFunctions();
118 void printInline(const std::string& fname, const std::string& funcName );
119 void printVariable(const std::string& fname, const std::string& varName );
120 void printType(const std::string& fname, const std::string& typeName );
121
122 void error(const std::string& msg);
123
Chris Lattner1018c242010-06-21 23:14:47 +0000124
125 formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0);
126 inline void in() { indent_level++; }
127 inline void out() { if (indent_level >0) indent_level--; }
128
Anton Korobeynikov50276522008-04-23 22:29:24 +0000129 private:
130 void printLinkageType(GlobalValue::LinkageTypes LT);
131 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +0000132 void printCallingConv(CallingConv::ID cc);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000133 void printEscapedString(const std::string& str);
134 void printCFP(const ConstantFP* CFP);
135
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000136 std::string getCppName(Type* val);
137 inline void printCppName(Type* val);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000138
139 std::string getCppName(const Value* val);
140 inline void printCppName(const Value* val);
141
Devang Patel05988662008-09-25 21:00:45 +0000142 void printAttributes(const AttrListPtr &PAL, const std::string &name);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000143 void printType(Type* Ty);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000144 void printTypes(const Module* M);
145
146 void printConstant(const Constant *CPV);
147 void printConstants(const Module* M);
148
149 void printVariableUses(const GlobalVariable *GV);
150 void printVariableHead(const GlobalVariable *GV);
151 void printVariableBody(const GlobalVariable *GV);
152
153 void printFunctionUses(const Function *F);
154 void printFunctionHead(const Function *F);
155 void printFunctionBody(const Function *F);
156 void printInstruction(const Instruction *I, const std::string& bbname);
Eli Friedmanbb5a7442011-09-29 20:21:17 +0000157 std::string getOpName(const Value*);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000158
159 void printModuleBody();
160 };
Chris Lattner7e6d7452010-06-21 23:12:56 +0000161} // end anonymous namespace.
Anton Korobeynikov50276522008-04-23 22:29:24 +0000162
Chris Lattner1018c242010-06-21 23:14:47 +0000163formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
164 Out << '\n';
Chris Lattner7e6d7452010-06-21 23:12:56 +0000165 if (delta >= 0 || indent_level >= unsigned(-delta))
166 indent_level += delta;
Chris Lattner1018c242010-06-21 23:14:47 +0000167 Out.indent(indent_level);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000168 return Out;
169}
170
Chris Lattner7e6d7452010-06-21 23:12:56 +0000171static inline void sanitize(std::string &str) {
172 for (size_t i = 0; i < str.length(); ++i)
173 if (!isalnum(str[i]) && str[i] != '_')
174 str[i] = '_';
175}
176
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000177static std::string getTypePrefix(Type *Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000178 switch (Ty->getTypeID()) {
179 case Type::VoidTyID: return "void_";
180 case Type::IntegerTyID:
181 return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
182 case Type::FloatTyID: return "float_";
183 case Type::DoubleTyID: return "double_";
184 case Type::LabelTyID: return "label_";
185 case Type::FunctionTyID: return "func_";
186 case Type::StructTyID: return "struct_";
187 case Type::ArrayTyID: return "array_";
188 case Type::PointerTyID: return "ptr_";
189 case Type::VectorTyID: return "packed_";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000190 default: return "other_";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000191 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000192}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000193
Chris Lattner7e6d7452010-06-21 23:12:56 +0000194void CppWriter::error(const std::string& msg) {
195 report_fatal_error(msg);
196}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000197
Benjamin Kramere68e7752012-03-23 11:26:29 +0000198static inline std::string ftostr(const APFloat& V) {
199 std::string Buf;
200 if (&V.getSemantics() == &APFloat::IEEEdouble) {
201 raw_string_ostream(Buf) << V.convertToDouble();
202 return Buf;
203 } else if (&V.getSemantics() == &APFloat::IEEEsingle) {
204 raw_string_ostream(Buf) << (double)V.convertToFloat();
205 return Buf;
206 }
207 return "<unknown format in ftostr>"; // error
208}
209
Chris Lattner7e6d7452010-06-21 23:12:56 +0000210// printCFP - Print a floating point constant .. very carefully :)
211// This makes sure that conversion to/from floating yields the same binary
212// result so that we don't lose precision.
213void CppWriter::printCFP(const ConstantFP *CFP) {
214 bool ignored;
215 APFloat APF = APFloat(CFP->getValueAPF()); // copy
216 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
217 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
218 Out << "ConstantFP::get(mod->getContext(), ";
219 Out << "APFloat(";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000220#if HAVE_PRINTF_A
Chris Lattner7e6d7452010-06-21 23:12:56 +0000221 char Buffer[100];
222 sprintf(Buffer, "%A", APF.convertToDouble());
223 if ((!strncmp(Buffer, "0x", 2) ||
224 !strncmp(Buffer, "-0x", 3) ||
225 !strncmp(Buffer, "+0x", 3)) &&
226 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
227 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
228 Out << "BitsToDouble(" << Buffer << ")";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000229 else
Chris Lattner7e6d7452010-06-21 23:12:56 +0000230 Out << "BitsToFloat((float)" << Buffer << ")";
231 Out << ")";
232 } else {
233#endif
234 std::string StrVal = ftostr(CFP->getValueAPF());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000235
Chris Lattner7e6d7452010-06-21 23:12:56 +0000236 while (StrVal[0] == ' ')
237 StrVal.erase(StrVal.begin());
238
239 // Check to make sure that the stringized number is not some string like
240 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
241 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
242 ((StrVal[0] == '-' || StrVal[0] == '+') &&
243 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
244 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
245 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
246 Out << StrVal;
247 else
248 Out << StrVal << "f";
249 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
250 Out << "BitsToDouble(0x"
251 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
252 << "ULL) /* " << StrVal << " */";
253 else
254 Out << "BitsToFloat(0x"
255 << utohexstr((uint32_t)CFP->getValueAPF().
256 bitcastToAPInt().getZExtValue())
257 << "U) /* " << StrVal << " */";
258 Out << ")";
259#if HAVE_PRINTF_A
260 }
261#endif
262 Out << ")";
263}
264
265void CppWriter::printCallingConv(CallingConv::ID cc){
266 // Print the calling convention.
267 switch (cc) {
268 case CallingConv::C: Out << "CallingConv::C"; break;
269 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
270 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
271 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
272 default: Out << cc; break;
273 }
274}
275
276void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
277 switch (LT) {
278 case GlobalValue::InternalLinkage:
279 Out << "GlobalValue::InternalLinkage"; break;
280 case GlobalValue::PrivateLinkage:
281 Out << "GlobalValue::PrivateLinkage"; break;
282 case GlobalValue::LinkerPrivateLinkage:
283 Out << "GlobalValue::LinkerPrivateLinkage"; break;
Bill Wendling5e721d72010-07-01 21:55:59 +0000284 case GlobalValue::LinkerPrivateWeakLinkage:
285 Out << "GlobalValue::LinkerPrivateWeakLinkage"; break;
Bill Wendling55ae5152010-08-20 22:05:50 +0000286 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
287 Out << "GlobalValue::LinkerPrivateWeakDefAutoLinkage"; break;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000288 case GlobalValue::AvailableExternallyLinkage:
289 Out << "GlobalValue::AvailableExternallyLinkage "; break;
290 case GlobalValue::LinkOnceAnyLinkage:
291 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
292 case GlobalValue::LinkOnceODRLinkage:
293 Out << "GlobalValue::LinkOnceODRLinkage "; break;
294 case GlobalValue::WeakAnyLinkage:
295 Out << "GlobalValue::WeakAnyLinkage"; break;
296 case GlobalValue::WeakODRLinkage:
297 Out << "GlobalValue::WeakODRLinkage"; break;
298 case GlobalValue::AppendingLinkage:
299 Out << "GlobalValue::AppendingLinkage"; break;
300 case GlobalValue::ExternalLinkage:
301 Out << "GlobalValue::ExternalLinkage"; break;
302 case GlobalValue::DLLImportLinkage:
303 Out << "GlobalValue::DLLImportLinkage"; break;
304 case GlobalValue::DLLExportLinkage:
305 Out << "GlobalValue::DLLExportLinkage"; break;
306 case GlobalValue::ExternalWeakLinkage:
307 Out << "GlobalValue::ExternalWeakLinkage"; break;
308 case GlobalValue::CommonLinkage:
309 Out << "GlobalValue::CommonLinkage"; break;
310 }
311}
312
313void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
314 switch (VisType) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000315 case GlobalValue::DefaultVisibility:
316 Out << "GlobalValue::DefaultVisibility";
317 break;
318 case GlobalValue::HiddenVisibility:
319 Out << "GlobalValue::HiddenVisibility";
320 break;
321 case GlobalValue::ProtectedVisibility:
322 Out << "GlobalValue::ProtectedVisibility";
323 break;
324 }
325}
326
327// printEscapedString - Print each character of the specified string, escaping
328// it if it is not printable or if it is an escape char.
329void CppWriter::printEscapedString(const std::string &Str) {
330 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
331 unsigned char C = Str[i];
332 if (isprint(C) && C != '"' && C != '\\') {
333 Out << C;
334 } else {
335 Out << "\\x"
336 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
337 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
338 }
339 }
340}
341
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000342std::string CppWriter::getCppName(Type* Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000343 // First, handle the primitive types .. easy
344 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
345 switch (Ty->getTypeID()) {
346 case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())";
347 case Type::IntegerTyID: {
348 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
349 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
350 }
351 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
352 case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())";
353 case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())";
354 case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())";
Dale Johannesenbb811a22010-09-10 20:55:01 +0000355 case Type::X86_MMXTyID: return "Type::getX86_MMXTy(mod->getContext())";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000356 default:
357 error("Invalid primitive type");
358 break;
359 }
360 // shouldn't be returned, but make it sensible
361 return "Type::getVoidTy(mod->getContext())";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000362 }
363
Chris Lattner7e6d7452010-06-21 23:12:56 +0000364 // Now, see if we've seen the type before and return that
365 TypeMap::iterator I = TypeNames.find(Ty);
366 if (I != TypeNames.end())
367 return I->second;
368
369 // Okay, let's build a new name for this type. Start with a prefix
370 const char* prefix = 0;
371 switch (Ty->getTypeID()) {
372 case Type::FunctionTyID: prefix = "FuncTy_"; break;
373 case Type::StructTyID: prefix = "StructTy_"; break;
374 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
375 case Type::PointerTyID: prefix = "PointerTy_"; break;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000376 case Type::VectorTyID: prefix = "VectorTy_"; break;
377 default: prefix = "OtherTy_"; break; // prevent breakage
Anton Korobeynikov50276522008-04-23 22:29:24 +0000378 }
379
Chris Lattner7e6d7452010-06-21 23:12:56 +0000380 // See if the type has a name in the symboltable and build accordingly
Chris Lattner7e6d7452010-06-21 23:12:56 +0000381 std::string name;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000382 if (StructType *STy = dyn_cast<StructType>(Ty))
Chris Lattner1afcace2011-07-09 17:41:24 +0000383 if (STy->hasName())
384 name = STy->getName();
385
386 if (name.empty())
387 name = utostr(uniqueNum++);
388
389 name = std::string(prefix) + name;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000390 sanitize(name);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000391
Chris Lattner7e6d7452010-06-21 23:12:56 +0000392 // Save the name
393 return TypeNames[Ty] = name;
394}
395
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000396void CppWriter::printCppName(Type* Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000397 printEscapedString(getCppName(Ty));
398}
399
400std::string CppWriter::getCppName(const Value* val) {
401 std::string name;
402 ValueMap::iterator I = ValueNames.find(val);
403 if (I != ValueNames.end() && I->first == val)
404 return I->second;
405
406 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
407 name = std::string("gvar_") +
408 getTypePrefix(GV->getType()->getElementType());
409 } else if (isa<Function>(val)) {
410 name = std::string("func_");
411 } else if (const Constant* C = dyn_cast<Constant>(val)) {
412 name = std::string("const_") + getTypePrefix(C->getType());
413 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
414 if (is_inline) {
415 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
416 Function::const_arg_iterator(Arg)) + 1;
417 name = std::string("arg_") + utostr(argNum);
418 NameSet::iterator NI = UsedNames.find(name);
419 if (NI != UsedNames.end())
420 name += std::string("_") + utostr(uniqueNum++);
421 UsedNames.insert(name);
422 return ValueNames[val] = name;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000423 } else {
424 name = getTypePrefix(val->getType());
425 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000426 } else {
427 name = getTypePrefix(val->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000428 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000429 if (val->hasName())
430 name += val->getName();
431 else
432 name += utostr(uniqueNum++);
433 sanitize(name);
434 NameSet::iterator NI = UsedNames.find(name);
435 if (NI != UsedNames.end())
436 name += std::string("_") + utostr(uniqueNum++);
437 UsedNames.insert(name);
438 return ValueNames[val] = name;
439}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000440
Chris Lattner7e6d7452010-06-21 23:12:56 +0000441void CppWriter::printCppName(const Value* val) {
442 printEscapedString(getCppName(val));
443}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000444
Chris Lattner7e6d7452010-06-21 23:12:56 +0000445void CppWriter::printAttributes(const AttrListPtr &PAL,
446 const std::string &name) {
447 Out << "AttrListPtr " << name << "_PAL;";
448 nl(Out);
449 if (!PAL.isEmpty()) {
450 Out << '{'; in(); nl(Out);
451 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
452 Out << "AttributeWithIndex PAWI;"; nl(Out);
453 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
454 unsigned index = PAL.getSlot(i).Index;
455 Attributes attrs = PAL.getSlot(i).Attrs;
Nicolas Geoffray81946832012-01-22 20:05:26 +0000456 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = Attribute::None ";
Chris Lattneracca9552009-01-13 07:22:22 +0000457#define HANDLE_ATTR(X) \
Chris Lattner7e6d7452010-06-21 23:12:56 +0000458 if (attrs & Attribute::X) \
459 Out << " | Attribute::" #X; \
460 attrs &= ~Attribute::X;
461
462 HANDLE_ATTR(SExt);
463 HANDLE_ATTR(ZExt);
464 HANDLE_ATTR(NoReturn);
465 HANDLE_ATTR(InReg);
466 HANDLE_ATTR(StructRet);
467 HANDLE_ATTR(NoUnwind);
468 HANDLE_ATTR(NoAlias);
469 HANDLE_ATTR(ByVal);
470 HANDLE_ATTR(Nest);
471 HANDLE_ATTR(ReadNone);
472 HANDLE_ATTR(ReadOnly);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000473 HANDLE_ATTR(NoInline);
474 HANDLE_ATTR(AlwaysInline);
475 HANDLE_ATTR(OptimizeForSize);
476 HANDLE_ATTR(StackProtect);
477 HANDLE_ATTR(StackProtectReq);
478 HANDLE_ATTR(NoCapture);
Eli Friedman32bb4df2010-07-16 18:47:20 +0000479 HANDLE_ATTR(NoRedZone);
480 HANDLE_ATTR(NoImplicitFloat);
481 HANDLE_ATTR(Naked);
482 HANDLE_ATTR(InlineHint);
Rafael Espindola25456ef2011-10-03 14:45:37 +0000483 HANDLE_ATTR(ReturnsTwice);
Bill Wendling54f15362011-08-09 00:47:30 +0000484 HANDLE_ATTR(UWTable);
485 HANDLE_ATTR(NonLazyBind);
Chris Lattneracca9552009-01-13 07:22:22 +0000486#undef HANDLE_ATTR
Eli Friedman32bb4df2010-07-16 18:47:20 +0000487 if (attrs & Attribute::StackAlignment)
488 Out << " | Attribute::constructStackAlignmentFromInt("
489 << Attribute::getStackAlignmentFromAttrs(attrs)
490 << ")";
491 attrs &= ~Attribute::StackAlignment;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000492 assert(attrs == 0 && "Unhandled attribute!");
493 Out << ";";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000494 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000495 Out << "Attrs.push_back(PAWI);";
496 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000497 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000498 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
499 nl(Out);
500 out(); nl(Out);
501 Out << '}'; nl(Out);
502 }
503}
504
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000505void CppWriter::printType(Type* Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000506 // We don't print definitions for primitive types
507 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000508 return;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000509
510 // If we already defined this type, we don't need to define it again.
511 if (DefinedTypes.find(Ty) != DefinedTypes.end())
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000512 return;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000513
514 // Everything below needs the name for the type so get it now.
515 std::string typeName(getCppName(Ty));
516
Chris Lattner7e6d7452010-06-21 23:12:56 +0000517 // Print the type definition
518 switch (Ty->getTypeID()) {
519 case Type::FunctionTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000520 FunctionType* FT = cast<FunctionType>(Ty);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000521 Out << "std::vector<Type*>" << typeName << "_args;";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000522 nl(Out);
523 FunctionType::param_iterator PI = FT->param_begin();
524 FunctionType::param_iterator PE = FT->param_end();
525 for (; PI != PE; ++PI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000526 Type* argTy = static_cast<Type*>(*PI);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000527 printType(argTy);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000528 std::string argName(getCppName(argTy));
529 Out << typeName << "_args.push_back(" << argName;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000530 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000531 nl(Out);
532 }
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000533 printType(FT->getReturnType());
Chris Lattner7e6d7452010-06-21 23:12:56 +0000534 std::string retTypeName(getCppName(FT->getReturnType()));
535 Out << "FunctionType* " << typeName << " = FunctionType::get(";
536 in(); nl(Out) << "/*Result=*/" << retTypeName;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000537 Out << ",";
538 nl(Out) << "/*Params=*/" << typeName << "_args,";
539 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
540 out();
Anton Korobeynikov50276522008-04-23 22:29:24 +0000541 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000542 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000543 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000544 case Type::StructTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000545 StructType* ST = cast<StructType>(Ty);
Chris Lattnerc4d0e9f2011-08-12 18:07:07 +0000546 if (!ST->isLiteral()) {
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000547 Out << "StructType *" << typeName << " = mod->getTypeByName(\"";
548 printEscapedString(ST->getName());
549 Out << "\");";
550 nl(Out);
551 Out << "if (!" << typeName << ") {";
552 nl(Out);
553 Out << typeName << " = ";
Chris Lattnerc4d0e9f2011-08-12 18:07:07 +0000554 Out << "StructType::create(mod->getContext(), \"";
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000555 printEscapedString(ST->getName());
556 Out << "\");";
557 nl(Out);
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000558 Out << "}";
559 nl(Out);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000560 // Indicate that this type is now defined.
561 DefinedTypes.insert(Ty);
562 }
563
564 Out << "std::vector<Type*>" << typeName << "_fields;";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000565 nl(Out);
566 StructType::element_iterator EI = ST->element_begin();
567 StructType::element_iterator EE = ST->element_end();
568 for (; EI != EE; ++EI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000569 Type* fieldTy = static_cast<Type*>(*EI);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000570 printType(fieldTy);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000571 std::string fieldName(getCppName(fieldTy));
572 Out << typeName << "_fields.push_back(" << fieldName;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000573 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000574 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000575 }
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000576
Chris Lattnerc4d0e9f2011-08-12 18:07:07 +0000577 if (ST->isLiteral()) {
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000578 Out << "StructType *" << typeName << " = ";
Chris Lattner1afcace2011-07-09 17:41:24 +0000579 Out << "StructType::get(" << "mod->getContext(), ";
580 } else {
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000581 Out << "if (" << typeName << "->isOpaque()) {";
582 nl(Out);
Chris Lattner1afcace2011-07-09 17:41:24 +0000583 Out << typeName << "->setBody(";
584 }
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000585
Chris Lattner1afcace2011-07-09 17:41:24 +0000586 Out << typeName << "_fields, /*isPacked=*/"
Chris Lattner7e6d7452010-06-21 23:12:56 +0000587 << (ST->isPacked() ? "true" : "false") << ");";
588 nl(Out);
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000589 if (!ST->isLiteral()) {
590 Out << "}";
591 nl(Out);
592 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000593 break;
594 }
595 case Type::ArrayTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000596 ArrayType* AT = cast<ArrayType>(Ty);
597 Type* ET = AT->getElementType();
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000598 printType(ET);
599 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
600 std::string elemName(getCppName(ET));
601 Out << "ArrayType* " << typeName << " = ArrayType::get("
602 << elemName
603 << ", " << utostr(AT->getNumElements()) << ");";
604 nl(Out);
605 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000606 break;
607 }
608 case Type::PointerTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000609 PointerType* PT = cast<PointerType>(Ty);
610 Type* ET = PT->getElementType();
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000611 printType(ET);
612 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
613 std::string elemName(getCppName(ET));
614 Out << "PointerType* " << typeName << " = PointerType::get("
615 << elemName
616 << ", " << utostr(PT->getAddressSpace()) << ");";
617 nl(Out);
618 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000619 break;
620 }
621 case Type::VectorTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000622 VectorType* PT = cast<VectorType>(Ty);
623 Type* ET = PT->getElementType();
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000624 printType(ET);
625 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
626 std::string elemName(getCppName(ET));
627 Out << "VectorType* " << typeName << " = VectorType::get("
628 << elemName
629 << ", " << utostr(PT->getNumElements()) << ");";
630 nl(Out);
631 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000632 break;
633 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000634 default:
635 error("Invalid TypeID");
636 }
637
Chris Lattner7e6d7452010-06-21 23:12:56 +0000638 // Indicate that this type is now defined.
639 DefinedTypes.insert(Ty);
640
Chris Lattner7e6d7452010-06-21 23:12:56 +0000641 // Finally, separate the type definition from other with a newline.
642 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000643}
644
645void CppWriter::printTypes(const Module* M) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000646 // Add all of the global variables to the value table.
Chris Lattner7e6d7452010-06-21 23:12:56 +0000647 for (Module::const_global_iterator I = TheModule->global_begin(),
648 E = TheModule->global_end(); I != E; ++I) {
649 if (I->hasInitializer())
650 printType(I->getInitializer()->getType());
651 printType(I->getType());
652 }
653
654 // Add all the functions to the table
655 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
656 FI != FE; ++FI) {
657 printType(FI->getReturnType());
658 printType(FI->getFunctionType());
659 // Add all the function arguments
660 for (Function::const_arg_iterator AI = FI->arg_begin(),
661 AE = FI->arg_end(); AI != AE; ++AI) {
662 printType(AI->getType());
663 }
664
665 // Add all of the basic blocks and instructions
666 for (Function::const_iterator BB = FI->begin(),
667 E = FI->end(); BB != E; ++BB) {
668 printType(BB->getType());
669 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
670 ++I) {
671 printType(I->getType());
672 for (unsigned i = 0; i < I->getNumOperands(); ++i)
673 printType(I->getOperand(i)->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000674 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000675 }
676 }
677}
678
679
680// printConstant - Print out a constant pool entry...
681void CppWriter::printConstant(const Constant *CV) {
682 // First, if the constant is actually a GlobalValue (variable or function)
683 // or its already in the constant list then we've printed it already and we
684 // can just return.
685 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
686 return;
687
688 std::string constName(getCppName(CV));
689 std::string typeName(getCppName(CV->getType()));
690
Chris Lattner7e6d7452010-06-21 23:12:56 +0000691 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
692 std::string constValue = CI->getValue().toString(10, true);
693 Out << "ConstantInt* " << constName
694 << " = ConstantInt::get(mod->getContext(), APInt("
695 << cast<IntegerType>(CI->getType())->getBitWidth()
696 << ", StringRef(\"" << constValue << "\"), 10));";
697 } else if (isa<ConstantAggregateZero>(CV)) {
698 Out << "ConstantAggregateZero* " << constName
699 << " = ConstantAggregateZero::get(" << typeName << ");";
700 } else if (isa<ConstantPointerNull>(CV)) {
701 Out << "ConstantPointerNull* " << constName
702 << " = ConstantPointerNull::get(" << typeName << ");";
703 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
704 Out << "ConstantFP* " << constName << " = ";
705 printCFP(CFP);
706 Out << ";";
707 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000708 Out << "std::vector<Constant*> " << constName << "_elems;";
709 nl(Out);
710 unsigned N = CA->getNumOperands();
711 for (unsigned i = 0; i < N; ++i) {
712 printConstant(CA->getOperand(i)); // recurse to print operands
713 Out << constName << "_elems.push_back("
714 << getCppName(CA->getOperand(i)) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000715 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000716 }
Chris Lattner18c7f802012-02-05 02:29:43 +0000717 Out << "Constant* " << constName << " = ConstantArray::get("
718 << typeName << ", " << constName << "_elems);";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000719 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
720 Out << "std::vector<Constant*> " << constName << "_fields;";
721 nl(Out);
722 unsigned N = CS->getNumOperands();
723 for (unsigned i = 0; i < N; i++) {
724 printConstant(CS->getOperand(i));
725 Out << constName << "_fields.push_back("
726 << getCppName(CS->getOperand(i)) << ");";
727 nl(Out);
728 }
729 Out << "Constant* " << constName << " = ConstantStruct::get("
730 << typeName << ", " << constName << "_fields);";
Duncan Sands853066a2012-02-05 14:16:09 +0000731 } else if (const ConstantVector *CVec = dyn_cast<ConstantVector>(CV)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000732 Out << "std::vector<Constant*> " << constName << "_elems;";
733 nl(Out);
Duncan Sands853066a2012-02-05 14:16:09 +0000734 unsigned N = CVec->getNumOperands();
Chris Lattner7e6d7452010-06-21 23:12:56 +0000735 for (unsigned i = 0; i < N; ++i) {
Duncan Sands853066a2012-02-05 14:16:09 +0000736 printConstant(CVec->getOperand(i));
Chris Lattner7e6d7452010-06-21 23:12:56 +0000737 Out << constName << "_elems.push_back("
Duncan Sands853066a2012-02-05 14:16:09 +0000738 << getCppName(CVec->getOperand(i)) << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000739 nl(Out);
740 }
741 Out << "Constant* " << constName << " = ConstantVector::get("
742 << typeName << ", " << constName << "_elems);";
743 } else if (isa<UndefValue>(CV)) {
744 Out << "UndefValue* " << constName << " = UndefValue::get("
745 << typeName << ");";
Chris Lattner29cc6cb2012-01-24 14:17:05 +0000746 } else if (const ConstantDataSequential *CDS =
747 dyn_cast<ConstantDataSequential>(CV)) {
748 if (CDS->isString()) {
749 Out << "Constant *" << constName <<
750 " = ConstantDataArray::getString(mod->getContext(), \"";
Chris Lattner18c7f802012-02-05 02:29:43 +0000751 StringRef Str = CDS->getAsString();
Chris Lattner29cc6cb2012-01-24 14:17:05 +0000752 bool nullTerminate = false;
753 if (Str.back() == 0) {
754 Str = Str.drop_back();
755 nullTerminate = true;
756 }
757 printEscapedString(Str);
758 // Determine if we want null termination or not.
759 if (nullTerminate)
760 Out << "\", true);";
761 else
762 Out << "\", false);";// No null terminator
763 } else {
764 // TODO: Could generate more efficient code generating CDS calls instead.
765 Out << "std::vector<Constant*> " << constName << "_elems;";
766 nl(Out);
767 for (unsigned i = 0; i != CDS->getNumElements(); ++i) {
768 Constant *Elt = CDS->getElementAsConstant(i);
769 printConstant(Elt);
770 Out << constName << "_elems.push_back(" << getCppName(Elt) << ");";
771 nl(Out);
772 }
773 Out << "Constant* " << constName;
774
775 if (isa<ArrayType>(CDS->getType()))
776 Out << " = ConstantArray::get(";
777 else
778 Out << " = ConstantVector::get(";
779 Out << typeName << ", " << constName << "_elems);";
780 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000781 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
782 if (CE->getOpcode() == Instruction::GetElementPtr) {
783 Out << "std::vector<Constant*> " << constName << "_indices;";
784 nl(Out);
785 printConstant(CE->getOperand(0));
786 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
787 printConstant(CE->getOperand(i));
788 Out << constName << "_indices.push_back("
789 << getCppName(CE->getOperand(i)) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000790 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000791 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000792 Out << "Constant* " << constName
793 << " = ConstantExpr::getGetElementPtr("
794 << getCppName(CE->getOperand(0)) << ", "
Nicolas Geoffraya056d202011-07-21 20:59:21 +0000795 << constName << "_indices);";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000796 } else if (CE->isCast()) {
797 printConstant(CE->getOperand(0));
798 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
799 switch (CE->getOpcode()) {
800 default: llvm_unreachable("Invalid cast opcode");
801 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
802 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
803 case Instruction::SExt: Out << "Instruction::SExt"; break;
804 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
805 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
806 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
807 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
808 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
809 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
810 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
811 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
812 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
813 }
814 Out << ", " << getCppName(CE->getOperand(0)) << ", "
815 << getCppName(CE->getType()) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000816 } else {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000817 unsigned N = CE->getNumOperands();
818 for (unsigned i = 0; i < N; ++i ) {
819 printConstant(CE->getOperand(i));
820 }
821 Out << "Constant* " << constName << " = ConstantExpr::";
822 switch (CE->getOpcode()) {
823 case Instruction::Add: Out << "getAdd("; break;
824 case Instruction::FAdd: Out << "getFAdd("; break;
825 case Instruction::Sub: Out << "getSub("; break;
826 case Instruction::FSub: Out << "getFSub("; break;
827 case Instruction::Mul: Out << "getMul("; break;
828 case Instruction::FMul: Out << "getFMul("; break;
829 case Instruction::UDiv: Out << "getUDiv("; break;
830 case Instruction::SDiv: Out << "getSDiv("; break;
831 case Instruction::FDiv: Out << "getFDiv("; break;
832 case Instruction::URem: Out << "getURem("; break;
833 case Instruction::SRem: Out << "getSRem("; break;
834 case Instruction::FRem: Out << "getFRem("; break;
835 case Instruction::And: Out << "getAnd("; break;
836 case Instruction::Or: Out << "getOr("; break;
837 case Instruction::Xor: Out << "getXor("; break;
838 case Instruction::ICmp:
839 Out << "getICmp(ICmpInst::ICMP_";
840 switch (CE->getPredicate()) {
841 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
842 case ICmpInst::ICMP_NE: Out << "NE"; break;
843 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
844 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
845 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
846 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
847 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
848 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
849 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
850 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
851 default: error("Invalid ICmp Predicate");
852 }
853 break;
854 case Instruction::FCmp:
855 Out << "getFCmp(FCmpInst::FCMP_";
856 switch (CE->getPredicate()) {
857 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
858 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
859 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
860 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
861 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
862 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
863 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
864 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
865 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
866 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
867 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
868 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
869 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
870 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
871 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
872 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
873 default: error("Invalid FCmp Predicate");
874 }
875 break;
876 case Instruction::Shl: Out << "getShl("; break;
877 case Instruction::LShr: Out << "getLShr("; break;
878 case Instruction::AShr: Out << "getAShr("; break;
879 case Instruction::Select: Out << "getSelect("; break;
880 case Instruction::ExtractElement: Out << "getExtractElement("; break;
881 case Instruction::InsertElement: Out << "getInsertElement("; break;
882 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
883 default:
884 error("Invalid constant expression");
885 break;
886 }
887 Out << getCppName(CE->getOperand(0));
888 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
889 Out << ", " << getCppName(CE->getOperand(i));
890 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000891 }
Chris Lattner32848772010-06-21 23:19:36 +0000892 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
893 Out << "Constant* " << constName << " = ";
894 Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000895 } else {
896 error("Bad Constant");
897 Out << "Constant* " << constName << " = 0; ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000898 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000899 nl(Out);
900}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000901
Chris Lattner7e6d7452010-06-21 23:12:56 +0000902void CppWriter::printConstants(const Module* M) {
903 // Traverse all the global variables looking for constant initializers
904 for (Module::const_global_iterator I = TheModule->global_begin(),
905 E = TheModule->global_end(); I != E; ++I)
906 if (I->hasInitializer())
907 printConstant(I->getInitializer());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000908
Chris Lattner7e6d7452010-06-21 23:12:56 +0000909 // Traverse the LLVM functions looking for constants
910 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
911 FI != FE; ++FI) {
912 // Add all of the basic blocks and instructions
913 for (Function::const_iterator BB = FI->begin(),
914 E = FI->end(); BB != E; ++BB) {
915 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
916 ++I) {
917 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
918 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
919 printConstant(C);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000920 }
921 }
922 }
923 }
924 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000925}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000926
Chris Lattner7e6d7452010-06-21 23:12:56 +0000927void CppWriter::printVariableUses(const GlobalVariable *GV) {
928 nl(Out) << "// Type Definitions";
929 nl(Out);
930 printType(GV->getType());
931 if (GV->hasInitializer()) {
Jay Foad7d715df2011-06-19 18:37:11 +0000932 const Constant *Init = GV->getInitializer();
Chris Lattner7e6d7452010-06-21 23:12:56 +0000933 printType(Init->getType());
Jay Foad7d715df2011-06-19 18:37:11 +0000934 if (const Function *F = dyn_cast<Function>(Init)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000935 nl(Out)<< "/ Function Declarations"; nl(Out);
936 printFunctionHead(F);
Jay Foad7d715df2011-06-19 18:37:11 +0000937 } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000938 nl(Out) << "// Global Variable Declarations"; nl(Out);
939 printVariableHead(gv);
940
941 nl(Out) << "// Global Variable Definitions"; nl(Out);
942 printVariableBody(gv);
943 } else {
944 nl(Out) << "// Constant Definitions"; nl(Out);
945 printConstant(Init);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000946 }
947 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000948}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000949
Chris Lattner7e6d7452010-06-21 23:12:56 +0000950void CppWriter::printVariableHead(const GlobalVariable *GV) {
951 nl(Out) << "GlobalVariable* " << getCppName(GV);
952 if (is_inline) {
953 Out << " = mod->getGlobalVariable(mod->getContext(), ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000954 printEscapedString(GV->getName());
Chris Lattner7e6d7452010-06-21 23:12:56 +0000955 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
956 nl(Out) << "if (!" << getCppName(GV) << ") {";
957 in(); nl(Out) << getCppName(GV);
958 }
959 Out << " = new GlobalVariable(/*Module=*/*mod, ";
960 nl(Out) << "/*Type=*/";
961 printCppName(GV->getType()->getElementType());
962 Out << ",";
963 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
964 Out << ",";
965 nl(Out) << "/*Linkage=*/";
966 printLinkageType(GV->getLinkage());
967 Out << ",";
968 nl(Out) << "/*Initializer=*/0, ";
969 if (GV->hasInitializer()) {
970 Out << "// has initializer, specified below";
971 }
972 nl(Out) << "/*Name=*/\"";
973 printEscapedString(GV->getName());
974 Out << "\");";
975 nl(Out);
976
977 if (GV->hasSection()) {
978 printCppName(GV);
979 Out << "->setSection(\"";
980 printEscapedString(GV->getSection());
Owen Anderson16a412e2009-07-10 16:42:19 +0000981 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000982 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000983 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000984 if (GV->getAlignment()) {
985 printCppName(GV);
986 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000987 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000988 }
989 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
990 printCppName(GV);
991 Out << "->setVisibility(";
992 printVisibilityType(GV->getVisibility());
993 Out << ");";
994 nl(Out);
995 }
996 if (GV->isThreadLocal()) {
997 printCppName(GV);
998 Out << "->setThreadLocal(true);";
999 nl(Out);
1000 }
1001 if (is_inline) {
1002 out(); Out << "}"; nl(Out);
1003 }
1004}
1005
1006void CppWriter::printVariableBody(const GlobalVariable *GV) {
1007 if (GV->hasInitializer()) {
1008 printCppName(GV);
1009 Out << "->setInitializer(";
1010 Out << getCppName(GV->getInitializer()) << ");";
1011 nl(Out);
1012 }
1013}
1014
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001015std::string CppWriter::getOpName(const Value* V) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001016 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1017 return getCppName(V);
1018
1019 // See if its alread in the map of forward references, if so just return the
1020 // name we already set up for it
1021 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1022 if (I != ForwardRefs.end())
1023 return I->second;
1024
1025 // This is a new forward reference. Generate a unique name for it
1026 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1027
1028 // Yes, this is a hack. An Argument is the smallest instantiable value that
1029 // we can make as a placeholder for the real value. We'll replace these
1030 // Argument instances later.
1031 Out << "Argument* " << result << " = new Argument("
1032 << getCppName(V->getType()) << ");";
1033 nl(Out);
1034 ForwardRefs[V] = result;
1035 return result;
1036}
1037
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001038static StringRef ConvertAtomicOrdering(AtomicOrdering Ordering) {
1039 switch (Ordering) {
1040 case NotAtomic: return "NotAtomic";
1041 case Unordered: return "Unordered";
1042 case Monotonic: return "Monotonic";
1043 case Acquire: return "Acquire";
1044 case Release: return "Release";
1045 case AcquireRelease: return "AcquireRelease";
1046 case SequentiallyConsistent: return "SequentiallyConsistent";
1047 }
1048 llvm_unreachable("Unknown ordering");
1049}
1050
1051static StringRef ConvertAtomicSynchScope(SynchronizationScope SynchScope) {
1052 switch (SynchScope) {
1053 case SingleThread: return "SingleThread";
1054 case CrossThread: return "CrossThread";
1055 }
1056 llvm_unreachable("Unknown synch scope");
1057}
1058
Chris Lattner7e6d7452010-06-21 23:12:56 +00001059// printInstruction - This member is called for each Instruction in a function.
1060void CppWriter::printInstruction(const Instruction *I,
1061 const std::string& bbname) {
1062 std::string iName(getCppName(I));
1063
1064 // Before we emit this instruction, we need to take care of generating any
1065 // forward references. So, we get the names of all the operands in advance
1066 const unsigned Ops(I->getNumOperands());
1067 std::string* opNames = new std::string[Ops];
Chris Lattner32848772010-06-21 23:19:36 +00001068 for (unsigned i = 0; i < Ops; i++)
Chris Lattner7e6d7452010-06-21 23:12:56 +00001069 opNames[i] = getOpName(I->getOperand(i));
Anton Korobeynikov50276522008-04-23 22:29:24 +00001070
Chris Lattner7e6d7452010-06-21 23:12:56 +00001071 switch (I->getOpcode()) {
1072 default:
1073 error("Invalid instruction");
1074 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001075
Chris Lattner7e6d7452010-06-21 23:12:56 +00001076 case Instruction::Ret: {
1077 const ReturnInst* ret = cast<ReturnInst>(I);
1078 Out << "ReturnInst::Create(mod->getContext(), "
1079 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1080 break;
1081 }
1082 case Instruction::Br: {
1083 const BranchInst* br = cast<BranchInst>(I);
1084 Out << "BranchInst::Create(" ;
Chris Lattner32848772010-06-21 23:19:36 +00001085 if (br->getNumOperands() == 3) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001086 Out << opNames[2] << ", "
Anton Korobeynikov50276522008-04-23 22:29:24 +00001087 << opNames[1] << ", "
Chris Lattner7e6d7452010-06-21 23:12:56 +00001088 << opNames[0] << ", ";
1089
1090 } else if (br->getNumOperands() == 1) {
1091 Out << opNames[0] << ", ";
1092 } else {
1093 error("Branch with 2 operands?");
1094 }
1095 Out << bbname << ");";
1096 break;
1097 }
1098 case Instruction::Switch: {
1099 const SwitchInst *SI = cast<SwitchInst>(I);
1100 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001101 << getOpName(SI->getCondition()) << ", "
1102 << getOpName(SI->getDefaultDest()) << ", "
Chris Lattner7e6d7452010-06-21 23:12:56 +00001103 << SI->getNumCases() << ", " << bbname << ");";
1104 nl(Out);
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00001105 for (SwitchInst::ConstCaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00001106 i != e; ++i) {
1107 const ConstantInt* CaseVal = i.getCaseValue();
1108 const BasicBlock *BB = i.getCaseSuccessor();
Chris Lattner7e6d7452010-06-21 23:12:56 +00001109 Out << iName << "->addCase("
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001110 << getOpName(CaseVal) << ", "
1111 << getOpName(BB) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001112 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001113 }
1114 break;
1115 }
1116 case Instruction::IndirectBr: {
1117 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1118 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1119 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1120 nl(Out);
1121 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1122 Out << iName << "->addDestination(" << opNames[i] << ");";
1123 nl(Out);
1124 }
1125 break;
1126 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00001127 case Instruction::Resume: {
1128 Out << "ResumeInst::Create(mod->getContext(), " << opNames[0]
1129 << ", " << bbname << ");";
1130 break;
1131 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001132 case Instruction::Invoke: {
1133 const InvokeInst* inv = cast<InvokeInst>(I);
1134 Out << "std::vector<Value*> " << iName << "_params;";
1135 nl(Out);
1136 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1137 Out << iName << "_params.push_back("
1138 << getOpName(inv->getArgOperand(i)) << ");";
1139 nl(Out);
1140 }
1141 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1142 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1143 << getOpName(inv->getCalledFunction()) << ", "
1144 << getOpName(inv->getNormalDest()) << ", "
1145 << getOpName(inv->getUnwindDest()) << ", "
Nick Lewycky3bca1012011-09-05 18:50:59 +00001146 << iName << "_params, \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001147 printEscapedString(inv->getName());
1148 Out << "\", " << bbname << ");";
1149 nl(Out) << iName << "->setCallingConv(";
1150 printCallingConv(inv->getCallingConv());
1151 Out << ");";
1152 printAttributes(inv->getAttributes(), iName);
1153 Out << iName << "->setAttributes(" << iName << "_PAL);";
1154 nl(Out);
1155 break;
1156 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001157 case Instruction::Unreachable: {
1158 Out << "new UnreachableInst("
1159 << "mod->getContext(), "
1160 << bbname << ");";
1161 break;
1162 }
1163 case Instruction::Add:
1164 case Instruction::FAdd:
1165 case Instruction::Sub:
1166 case Instruction::FSub:
1167 case Instruction::Mul:
1168 case Instruction::FMul:
1169 case Instruction::UDiv:
1170 case Instruction::SDiv:
1171 case Instruction::FDiv:
1172 case Instruction::URem:
1173 case Instruction::SRem:
1174 case Instruction::FRem:
1175 case Instruction::And:
1176 case Instruction::Or:
1177 case Instruction::Xor:
1178 case Instruction::Shl:
1179 case Instruction::LShr:
1180 case Instruction::AShr:{
1181 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1182 switch (I->getOpcode()) {
1183 case Instruction::Add: Out << "Instruction::Add"; break;
1184 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1185 case Instruction::Sub: Out << "Instruction::Sub"; break;
1186 case Instruction::FSub: Out << "Instruction::FSub"; break;
1187 case Instruction::Mul: Out << "Instruction::Mul"; break;
1188 case Instruction::FMul: Out << "Instruction::FMul"; break;
1189 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1190 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1191 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1192 case Instruction::URem:Out << "Instruction::URem"; break;
1193 case Instruction::SRem:Out << "Instruction::SRem"; break;
1194 case Instruction::FRem:Out << "Instruction::FRem"; break;
1195 case Instruction::And: Out << "Instruction::And"; break;
1196 case Instruction::Or: Out << "Instruction::Or"; break;
1197 case Instruction::Xor: Out << "Instruction::Xor"; break;
1198 case Instruction::Shl: Out << "Instruction::Shl"; break;
1199 case Instruction::LShr:Out << "Instruction::LShr"; break;
1200 case Instruction::AShr:Out << "Instruction::AShr"; break;
1201 default: Out << "Instruction::BadOpCode"; break;
1202 }
1203 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1204 printEscapedString(I->getName());
1205 Out << "\", " << bbname << ");";
1206 break;
1207 }
1208 case Instruction::FCmp: {
1209 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1210 switch (cast<FCmpInst>(I)->getPredicate()) {
1211 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1212 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1213 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1214 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1215 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1216 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1217 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1218 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1219 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1220 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1221 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1222 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1223 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1224 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1225 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1226 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1227 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1228 }
1229 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1230 printEscapedString(I->getName());
1231 Out << "\");";
1232 break;
1233 }
1234 case Instruction::ICmp: {
1235 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1236 switch (cast<ICmpInst>(I)->getPredicate()) {
1237 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1238 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1239 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1240 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1241 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1242 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1243 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1244 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1245 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1246 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1247 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1248 }
1249 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1250 printEscapedString(I->getName());
1251 Out << "\");";
1252 break;
1253 }
1254 case Instruction::Alloca: {
1255 const AllocaInst* allocaI = cast<AllocaInst>(I);
1256 Out << "AllocaInst* " << iName << " = new AllocaInst("
1257 << getCppName(allocaI->getAllocatedType()) << ", ";
1258 if (allocaI->isArrayAllocation())
1259 Out << opNames[0] << ", ";
1260 Out << "\"";
1261 printEscapedString(allocaI->getName());
1262 Out << "\", " << bbname << ");";
1263 if (allocaI->getAlignment())
1264 nl(Out) << iName << "->setAlignment("
1265 << allocaI->getAlignment() << ");";
1266 break;
1267 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001268 case Instruction::Load: {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001269 const LoadInst* load = cast<LoadInst>(I);
1270 Out << "LoadInst* " << iName << " = new LoadInst("
1271 << opNames[0] << ", \"";
1272 printEscapedString(load->getName());
1273 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1274 << ", " << bbname << ");";
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001275 if (load->getAlignment())
1276 nl(Out) << iName << "->setAlignment("
1277 << load->getAlignment() << ");";
1278 if (load->isAtomic()) {
1279 StringRef Ordering = ConvertAtomicOrdering(load->getOrdering());
1280 StringRef CrossThread = ConvertAtomicSynchScope(load->getSynchScope());
1281 nl(Out) << iName << "->setAtomic("
1282 << Ordering << ", " << CrossThread << ");";
1283 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001284 break;
1285 }
1286 case Instruction::Store: {
1287 const StoreInst* store = cast<StoreInst>(I);
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001288 Out << "StoreInst* " << iName << " = new StoreInst("
Chris Lattner7e6d7452010-06-21 23:12:56 +00001289 << opNames[0] << ", "
1290 << opNames[1] << ", "
1291 << (store->isVolatile() ? "true" : "false")
1292 << ", " << bbname << ");";
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001293 if (store->getAlignment())
1294 nl(Out) << iName << "->setAlignment("
1295 << store->getAlignment() << ");";
1296 if (store->isAtomic()) {
1297 StringRef Ordering = ConvertAtomicOrdering(store->getOrdering());
1298 StringRef CrossThread = ConvertAtomicSynchScope(store->getSynchScope());
1299 nl(Out) << iName << "->setAtomic("
1300 << Ordering << ", " << CrossThread << ");";
1301 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001302 break;
1303 }
1304 case Instruction::GetElementPtr: {
1305 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1306 if (gep->getNumOperands() <= 2) {
1307 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1308 << opNames[0];
1309 if (gep->getNumOperands() == 2)
1310 Out << ", " << opNames[1];
1311 } else {
1312 Out << "std::vector<Value*> " << iName << "_indices;";
1313 nl(Out);
1314 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1315 Out << iName << "_indices.push_back("
1316 << opNames[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001317 nl(Out);
1318 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001319 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
Nicolas Geoffray45c8d2b2011-07-26 20:52:25 +00001320 << opNames[0] << ", " << iName << "_indices";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001321 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001322 Out << ", \"";
1323 printEscapedString(gep->getName());
1324 Out << "\", " << bbname << ");";
1325 break;
1326 }
1327 case Instruction::PHI: {
1328 const PHINode* phi = cast<PHINode>(I);
1329
1330 Out << "PHINode* " << iName << " = PHINode::Create("
Nicolas Geoffrayc6cf1972011-04-10 17:39:40 +00001331 << getCppName(phi->getType()) << ", "
Jay Foad3ecfc862011-03-30 11:28:46 +00001332 << phi->getNumIncomingValues() << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001333 printEscapedString(phi->getName());
1334 Out << "\", " << bbname << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001335 nl(Out);
Jay Foadc1371202011-06-20 14:18:48 +00001336 for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001337 Out << iName << "->addIncoming("
Jay Foadc1371202011-06-20 14:18:48 +00001338 << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
Jay Foad95c3e482011-06-23 09:09:15 +00001339 << getOpName(phi->getIncomingBlock(i)) << ");";
Chris Lattner627b4702009-10-27 21:24:48 +00001340 nl(Out);
Chris Lattner627b4702009-10-27 21:24:48 +00001341 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001342 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;
Craig Topperbc219812012-02-07 02:50:20 +00001371 default: llvm_unreachable("Unreachable");
Chris Lattner7e6d7452010-06-21 23:12:56 +00001372 }
1373 Out << "(" << opNames[0] << ", "
1374 << getCppName(cst->getType()) << ", \"";
1375 printEscapedString(cst->getName());
1376 Out << "\", " << bbname << ");";
1377 break;
1378 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001379 case Instruction::Call: {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001380 const CallInst* call = cast<CallInst>(I);
1381 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1382 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 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001389 if (call->getNumArgOperands() > 1) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001390 Out << "std::vector<Value*> " << iName << "_params;";
1391 nl(Out);
Gabor Greif53ba5502010-07-02 19:08:46 +00001392 for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
Gabor Greif63d024f2010-07-13 15:31:36 +00001393 Out << iName << "_params.push_back(" << opNames[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001394 nl(Out);
1395 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001396 Out << "CallInst* " << iName << " = CallInst::Create("
Gabor Greifa3997812010-07-22 10:37:47 +00001397 << opNames[call->getNumArgOperands()] << ", "
Nicolas Geoffraya056d202011-07-21 20:59:21 +00001398 << iName << "_params, \"";
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001399 } else if (call->getNumArgOperands() == 1) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001400 Out << "CallInst* " << iName << " = CallInst::Create("
Gabor Greif63d024f2010-07-13 15:31:36 +00001401 << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001402 } else {
Gabor Greif63d024f2010-07-13 15:31:36 +00001403 Out << "CallInst* " << iName << " = CallInst::Create("
1404 << opNames[call->getNumArgOperands()] << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001405 }
1406 printEscapedString(call->getName());
1407 Out << "\", " << bbname << ");";
1408 nl(Out) << iName << "->setCallingConv(";
1409 printCallingConv(call->getCallingConv());
1410 Out << ");";
1411 nl(Out) << iName << "->setTailCall("
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001412 << (call->isTailCall() ? "true" : "false");
Chris Lattner7e6d7452010-06-21 23:12:56 +00001413 Out << ");";
Gabor Greif135d7fe2010-07-02 19:26:28 +00001414 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001415 printAttributes(call->getAttributes(), iName);
1416 Out << iName << "->setAttributes(" << iName << "_PAL);";
1417 nl(Out);
1418 break;
1419 }
1420 case Instruction::Select: {
1421 const SelectInst* sel = cast<SelectInst>(I);
1422 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1423 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1424 printEscapedString(sel->getName());
1425 Out << "\", " << bbname << ");";
1426 break;
1427 }
1428 case Instruction::UserOp1:
1429 /// FALL THROUGH
1430 case Instruction::UserOp2: {
1431 /// FIXME: What should be done here?
1432 break;
1433 }
1434 case Instruction::VAArg: {
1435 const VAArgInst* va = cast<VAArgInst>(I);
1436 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1437 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1438 printEscapedString(va->getName());
1439 Out << "\", " << bbname << ");";
1440 break;
1441 }
1442 case Instruction::ExtractElement: {
1443 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1444 Out << "ExtractElementInst* " << getCppName(eei)
1445 << " = new ExtractElementInst(" << opNames[0]
1446 << ", " << opNames[1] << ", \"";
1447 printEscapedString(eei->getName());
1448 Out << "\", " << bbname << ");";
1449 break;
1450 }
1451 case Instruction::InsertElement: {
1452 const InsertElementInst* iei = cast<InsertElementInst>(I);
1453 Out << "InsertElementInst* " << getCppName(iei)
1454 << " = InsertElementInst::Create(" << opNames[0]
1455 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1456 printEscapedString(iei->getName());
1457 Out << "\", " << bbname << ");";
1458 break;
1459 }
1460 case Instruction::ShuffleVector: {
1461 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1462 Out << "ShuffleVectorInst* " << getCppName(svi)
1463 << " = new ShuffleVectorInst(" << opNames[0]
1464 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1465 printEscapedString(svi->getName());
1466 Out << "\", " << bbname << ");";
1467 break;
1468 }
1469 case Instruction::ExtractValue: {
1470 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1471 Out << "std::vector<unsigned> " << iName << "_indices;";
1472 nl(Out);
1473 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1474 Out << iName << "_indices.push_back("
1475 << evi->idx_begin()[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001476 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001477 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001478 Out << "ExtractValueInst* " << getCppName(evi)
1479 << " = ExtractValueInst::Create(" << opNames[0]
1480 << ", "
Nick Lewycky3bca1012011-09-05 18:50:59 +00001481 << iName << "_indices, \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001482 printEscapedString(evi->getName());
1483 Out << "\", " << bbname << ");";
1484 break;
1485 }
1486 case Instruction::InsertValue: {
1487 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1488 Out << "std::vector<unsigned> " << iName << "_indices;";
1489 nl(Out);
1490 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1491 Out << iName << "_indices.push_back("
1492 << ivi->idx_begin()[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001493 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001494 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001495 Out << "InsertValueInst* " << getCppName(ivi)
1496 << " = InsertValueInst::Create(" << opNames[0]
1497 << ", " << opNames[1] << ", "
Nick Lewycky3bca1012011-09-05 18:50:59 +00001498 << iName << "_indices, \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001499 printEscapedString(ivi->getName());
1500 Out << "\", " << bbname << ");";
1501 break;
1502 }
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001503 case Instruction::Fence: {
1504 const FenceInst *fi = cast<FenceInst>(I);
1505 StringRef Ordering = ConvertAtomicOrdering(fi->getOrdering());
1506 StringRef CrossThread = ConvertAtomicSynchScope(fi->getSynchScope());
1507 Out << "FenceInst* " << iName
1508 << " = new FenceInst(mod->getContext(), "
Eli Friedman5b7cc332011-11-04 17:29:35 +00001509 << Ordering << ", " << CrossThread << ", " << bbname
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001510 << ");";
1511 break;
1512 }
1513 case Instruction::AtomicCmpXchg: {
1514 const AtomicCmpXchgInst *cxi = cast<AtomicCmpXchgInst>(I);
1515 StringRef Ordering = ConvertAtomicOrdering(cxi->getOrdering());
1516 StringRef CrossThread = ConvertAtomicSynchScope(cxi->getSynchScope());
1517 Out << "AtomicCmpXchgInst* " << iName
1518 << " = new AtomicCmpXchgInst("
1519 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", "
Eli Friedman5b7cc332011-11-04 17:29:35 +00001520 << Ordering << ", " << CrossThread << ", " << bbname
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001521 << ");";
1522 nl(Out) << iName << "->setName(\"";
1523 printEscapedString(cxi->getName());
1524 Out << "\");";
1525 break;
1526 }
1527 case Instruction::AtomicRMW: {
1528 const AtomicRMWInst *rmwi = cast<AtomicRMWInst>(I);
1529 StringRef Ordering = ConvertAtomicOrdering(rmwi->getOrdering());
1530 StringRef CrossThread = ConvertAtomicSynchScope(rmwi->getSynchScope());
1531 StringRef Operation;
1532 switch (rmwi->getOperation()) {
1533 case AtomicRMWInst::Xchg: Operation = "AtomicRMWInst::Xchg"; break;
1534 case AtomicRMWInst::Add: Operation = "AtomicRMWInst::Add"; break;
1535 case AtomicRMWInst::Sub: Operation = "AtomicRMWInst::Sub"; break;
1536 case AtomicRMWInst::And: Operation = "AtomicRMWInst::And"; break;
1537 case AtomicRMWInst::Nand: Operation = "AtomicRMWInst::Nand"; break;
1538 case AtomicRMWInst::Or: Operation = "AtomicRMWInst::Or"; break;
1539 case AtomicRMWInst::Xor: Operation = "AtomicRMWInst::Xor"; break;
1540 case AtomicRMWInst::Max: Operation = "AtomicRMWInst::Max"; break;
1541 case AtomicRMWInst::Min: Operation = "AtomicRMWInst::Min"; break;
1542 case AtomicRMWInst::UMax: Operation = "AtomicRMWInst::UMax"; break;
1543 case AtomicRMWInst::UMin: Operation = "AtomicRMWInst::UMin"; break;
1544 case AtomicRMWInst::BAD_BINOP: llvm_unreachable("Bad atomic operation");
1545 }
1546 Out << "AtomicRMWInst* " << iName
1547 << " = new AtomicRMWInst("
1548 << Operation << ", "
1549 << opNames[0] << ", " << opNames[1] << ", "
Eli Friedman5b7cc332011-11-04 17:29:35 +00001550 << Ordering << ", " << CrossThread << ", " << bbname
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001551 << ");";
1552 nl(Out) << iName << "->setName(\"";
1553 printEscapedString(rmwi->getName());
1554 Out << "\");";
1555 break;
1556 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001557 }
1558 DefinedValues.insert(I);
1559 nl(Out);
1560 delete [] opNames;
1561}
1562
Chris Lattner7e6d7452010-06-21 23:12:56 +00001563// Print out the types, constants and declarations needed by one function
1564void CppWriter::printFunctionUses(const Function* F) {
1565 nl(Out) << "// Type Definitions"; nl(Out);
1566 if (!is_inline) {
1567 // Print the function's return type
1568 printType(F->getReturnType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001569
Chris Lattner7e6d7452010-06-21 23:12:56 +00001570 // Print the function's function type
1571 printType(F->getFunctionType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001572
Chris Lattner7e6d7452010-06-21 23:12:56 +00001573 // Print the types of each of the function's arguments
Anton Korobeynikov50276522008-04-23 22:29:24 +00001574 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1575 AI != AE; ++AI) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001576 printType(AI->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001577 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001578 }
1579
Chris Lattner7e6d7452010-06-21 23:12:56 +00001580 // Print type definitions for every type referenced by an instruction and
1581 // make a note of any global values or constants that are referenced
1582 SmallPtrSet<GlobalValue*,64> gvs;
1583 SmallPtrSet<Constant*,64> consts;
1584 for (Function::const_iterator BB = F->begin(), BE = F->end();
1585 BB != BE; ++BB){
1586 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
Anton Korobeynikov50276522008-04-23 22:29:24 +00001587 I != E; ++I) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001588 // Print the type of the instruction itself
1589 printType(I->getType());
1590
1591 // Print the type of each of the instruction's operands
1592 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1593 Value* operand = I->getOperand(i);
1594 printType(operand->getType());
1595
1596 // If the operand references a GVal or Constant, make a note of it
1597 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1598 gvs.insert(GV);
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001599 if (GenerationType != GenFunction)
1600 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1601 if (GVar->hasInitializer())
1602 consts.insert(GVar->getInitializer());
1603 } else if (Constant* C = dyn_cast<Constant>(operand)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001604 consts.insert(C);
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001605 for (unsigned j = 0; j < C->getNumOperands(); ++j) {
1606 // If the operand references a GVal or Constant, make a note of it
1607 Value* operand = C->getOperand(j);
1608 printType(operand->getType());
1609 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1610 gvs.insert(GV);
1611 if (GenerationType != GenFunction)
1612 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1613 if (GVar->hasInitializer())
1614 consts.insert(GVar->getInitializer());
1615 }
1616 }
1617 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001618 }
1619 }
1620 }
1621
1622 // Print the function declarations for any functions encountered
1623 nl(Out) << "// Function Declarations"; nl(Out);
1624 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1625 I != E; ++I) {
1626 if (Function* Fun = dyn_cast<Function>(*I)) {
1627 if (!is_inline || Fun != F)
1628 printFunctionHead(Fun);
1629 }
1630 }
1631
1632 // Print the global variable declarations for any variables encountered
1633 nl(Out) << "// Global Variable Declarations"; nl(Out);
1634 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1635 I != E; ++I) {
1636 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1637 printVariableHead(F);
1638 }
1639
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001640 // Print the constants found
Chris Lattner7e6d7452010-06-21 23:12:56 +00001641 nl(Out) << "// Constant Definitions"; nl(Out);
1642 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1643 E = consts.end(); I != E; ++I) {
1644 printConstant(*I);
1645 }
1646
1647 // Process the global variables definitions now that all the constants have
1648 // been emitted. These definitions just couple the gvars with their constant
1649 // initializers.
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001650 if (GenerationType != GenFunction) {
1651 nl(Out) << "// Global Variable Definitions"; nl(Out);
1652 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1653 I != E; ++I) {
1654 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1655 printVariableBody(GV);
1656 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001657 }
1658}
1659
1660void CppWriter::printFunctionHead(const Function* F) {
1661 nl(Out) << "Function* " << getCppName(F);
Nicolas Geoffrayf8557952011-10-08 11:56:36 +00001662 Out << " = mod->getFunction(\"";
1663 printEscapedString(F->getName());
1664 Out << "\");";
1665 nl(Out) << "if (!" << getCppName(F) << ") {";
1666 nl(Out) << getCppName(F);
1667
Chris Lattner7e6d7452010-06-21 23:12:56 +00001668 Out<< " = Function::Create(";
1669 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1670 nl(Out) << "/*Linkage=*/";
1671 printLinkageType(F->getLinkage());
1672 Out << ",";
1673 nl(Out) << "/*Name=*/\"";
1674 printEscapedString(F->getName());
1675 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1676 nl(Out,-1);
1677 printCppName(F);
1678 Out << "->setCallingConv(";
1679 printCallingConv(F->getCallingConv());
1680 Out << ");";
1681 nl(Out);
1682 if (F->hasSection()) {
1683 printCppName(F);
1684 Out << "->setSection(\"" << F->getSection() << "\");";
1685 nl(Out);
1686 }
1687 if (F->getAlignment()) {
1688 printCppName(F);
1689 Out << "->setAlignment(" << F->getAlignment() << ");";
1690 nl(Out);
1691 }
1692 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1693 printCppName(F);
1694 Out << "->setVisibility(";
1695 printVisibilityType(F->getVisibility());
1696 Out << ");";
1697 nl(Out);
1698 }
1699 if (F->hasGC()) {
1700 printCppName(F);
1701 Out << "->setGC(\"" << F->getGC() << "\");";
1702 nl(Out);
1703 }
Nicolas Geoffrayf8557952011-10-08 11:56:36 +00001704 Out << "}";
1705 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001706 printAttributes(F->getAttributes(), getCppName(F));
1707 printCppName(F);
1708 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1709 nl(Out);
1710}
1711
1712void CppWriter::printFunctionBody(const Function *F) {
1713 if (F->isDeclaration())
1714 return; // external functions have no bodies.
1715
1716 // Clear the DefinedValues and ForwardRefs maps because we can't have
1717 // cross-function forward refs
1718 ForwardRefs.clear();
1719 DefinedValues.clear();
1720
1721 // Create all the argument values
1722 if (!is_inline) {
1723 if (!F->arg_empty()) {
1724 Out << "Function::arg_iterator args = " << getCppName(F)
1725 << "->arg_begin();";
1726 nl(Out);
1727 }
1728 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1729 AI != AE; ++AI) {
1730 Out << "Value* " << getCppName(AI) << " = args++;";
1731 nl(Out);
1732 if (AI->hasName()) {
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001733 Out << getCppName(AI) << "->setName(\"";
1734 printEscapedString(AI->getName());
1735 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001736 nl(Out);
1737 }
1738 }
1739 }
1740
Chris Lattner7e6d7452010-06-21 23:12:56 +00001741 // Create all the basic blocks
1742 nl(Out);
1743 for (Function::const_iterator BI = F->begin(), BE = F->end();
1744 BI != BE; ++BI) {
1745 std::string bbname(getCppName(BI));
1746 Out << "BasicBlock* " << bbname <<
1747 " = BasicBlock::Create(mod->getContext(), \"";
1748 if (BI->hasName())
1749 printEscapedString(BI->getName());
1750 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1751 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001752 }
1753
Chris Lattner7e6d7452010-06-21 23:12:56 +00001754 // Output all of its basic blocks... for the function
1755 for (Function::const_iterator BI = F->begin(), BE = F->end();
1756 BI != BE; ++BI) {
1757 std::string bbname(getCppName(BI));
1758 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001759 nl(Out);
1760
Chris Lattner7e6d7452010-06-21 23:12:56 +00001761 // Output all of the instructions in the basic block...
1762 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1763 I != E; ++I) {
1764 printInstruction(I,bbname);
1765 }
1766 }
1767
1768 // Loop over the ForwardRefs and resolve them now that all instructions
1769 // are generated.
1770 if (!ForwardRefs.empty()) {
1771 nl(Out) << "// Resolve Forward References";
1772 nl(Out);
1773 }
1774
1775 while (!ForwardRefs.empty()) {
1776 ForwardRefMap::iterator I = ForwardRefs.begin();
1777 Out << I->second << "->replaceAllUsesWith("
1778 << getCppName(I->first) << "); delete " << I->second << ";";
1779 nl(Out);
1780 ForwardRefs.erase(I);
1781 }
1782}
1783
1784void CppWriter::printInline(const std::string& fname,
1785 const std::string& func) {
1786 const Function* F = TheModule->getFunction(func);
1787 if (!F) {
1788 error(std::string("Function '") + func + "' not found in input module");
1789 return;
1790 }
1791 if (F->isDeclaration()) {
1792 error(std::string("Function '") + func + "' is external!");
1793 return;
1794 }
1795 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1796 << getCppName(F);
1797 unsigned arg_count = 1;
1798 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1799 AI != AE; ++AI) {
1800 Out << ", Value* arg_" << arg_count;
1801 }
1802 Out << ") {";
1803 nl(Out);
1804 is_inline = true;
1805 printFunctionUses(F);
1806 printFunctionBody(F);
1807 is_inline = false;
1808 Out << "return " << getCppName(F->begin()) << ";";
1809 nl(Out) << "}";
1810 nl(Out);
1811}
1812
1813void CppWriter::printModuleBody() {
1814 // Print out all the type definitions
1815 nl(Out) << "// Type Definitions"; nl(Out);
1816 printTypes(TheModule);
1817
1818 // Functions can call each other and global variables can reference them so
1819 // define all the functions first before emitting their function bodies.
1820 nl(Out) << "// Function Declarations"; nl(Out);
1821 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1822 I != E; ++I)
1823 printFunctionHead(I);
1824
1825 // Process the global variables declarations. We can't initialze them until
1826 // after the constants are printed so just print a header for each global
1827 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1828 for (Module::const_global_iterator I = TheModule->global_begin(),
1829 E = TheModule->global_end(); I != E; ++I) {
1830 printVariableHead(I);
1831 }
1832
1833 // Print out all the constants definitions. Constants don't recurse except
1834 // through GlobalValues. All GlobalValues have been declared at this point
1835 // so we can proceed to generate the constants.
1836 nl(Out) << "// Constant Definitions"; nl(Out);
1837 printConstants(TheModule);
1838
1839 // Process the global variables definitions now that all the constants have
1840 // been emitted. These definitions just couple the gvars with their constant
1841 // initializers.
1842 nl(Out) << "// Global Variable Definitions"; nl(Out);
1843 for (Module::const_global_iterator I = TheModule->global_begin(),
1844 E = TheModule->global_end(); I != E; ++I) {
1845 printVariableBody(I);
1846 }
1847
1848 // Finally, we can safely put out all of the function bodies.
1849 nl(Out) << "// Function Definitions"; nl(Out);
1850 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1851 I != E; ++I) {
1852 if (!I->isDeclaration()) {
1853 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1854 << ")";
1855 nl(Out) << "{";
1856 nl(Out,1);
1857 printFunctionBody(I);
1858 nl(Out,-1) << "}";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001859 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001860 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001861 }
1862}
1863
1864void CppWriter::printProgram(const std::string& fname,
1865 const std::string& mName) {
1866 Out << "#include <llvm/LLVMContext.h>\n";
1867 Out << "#include <llvm/Module.h>\n";
1868 Out << "#include <llvm/DerivedTypes.h>\n";
1869 Out << "#include <llvm/Constants.h>\n";
1870 Out << "#include <llvm/GlobalVariable.h>\n";
1871 Out << "#include <llvm/Function.h>\n";
1872 Out << "#include <llvm/CallingConv.h>\n";
1873 Out << "#include <llvm/BasicBlock.h>\n";
1874 Out << "#include <llvm/Instructions.h>\n";
1875 Out << "#include <llvm/InlineAsm.h>\n";
1876 Out << "#include <llvm/Support/FormattedStream.h>\n";
1877 Out << "#include <llvm/Support/MathExtras.h>\n";
1878 Out << "#include <llvm/Pass.h>\n";
1879 Out << "#include <llvm/PassManager.h>\n";
1880 Out << "#include <llvm/ADT/SmallVector.h>\n";
1881 Out << "#include <llvm/Analysis/Verifier.h>\n";
1882 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1883 Out << "#include <algorithm>\n";
1884 Out << "using namespace llvm;\n\n";
1885 Out << "Module* " << fname << "();\n\n";
1886 Out << "int main(int argc, char**argv) {\n";
1887 Out << " Module* Mod = " << fname << "();\n";
1888 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1889 Out << " PassManager PM;\n";
1890 Out << " PM.add(createPrintModulePass(&outs()));\n";
1891 Out << " PM.run(*Mod);\n";
1892 Out << " return 0;\n";
1893 Out << "}\n\n";
1894 printModule(fname,mName);
1895}
1896
1897void CppWriter::printModule(const std::string& fname,
1898 const std::string& mName) {
1899 nl(Out) << "Module* " << fname << "() {";
1900 nl(Out,1) << "// Module Construction";
1901 nl(Out) << "Module* mod = new Module(\"";
1902 printEscapedString(mName);
1903 Out << "\", getGlobalContext());";
1904 if (!TheModule->getTargetTriple().empty()) {
1905 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1906 }
1907 if (!TheModule->getTargetTriple().empty()) {
1908 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1909 << "\");";
1910 }
1911
1912 if (!TheModule->getModuleInlineAsm().empty()) {
1913 nl(Out) << "mod->setModuleInlineAsm(\"";
1914 printEscapedString(TheModule->getModuleInlineAsm());
1915 Out << "\");";
1916 }
1917 nl(Out);
1918
1919 // Loop over the dependent libraries and emit them.
1920 Module::lib_iterator LI = TheModule->lib_begin();
1921 Module::lib_iterator LE = TheModule->lib_end();
1922 while (LI != LE) {
1923 Out << "mod->addLibrary(\"" << *LI << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001924 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001925 ++LI;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001926 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001927 printModuleBody();
1928 nl(Out) << "return mod;";
1929 nl(Out,-1) << "}";
1930 nl(Out);
1931}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001932
Chris Lattner7e6d7452010-06-21 23:12:56 +00001933void CppWriter::printContents(const std::string& fname,
1934 const std::string& mName) {
1935 Out << "\nModule* " << fname << "(Module *mod) {\n";
1936 Out << "\nmod->setModuleIdentifier(\"";
1937 printEscapedString(mName);
1938 Out << "\");\n";
1939 printModuleBody();
1940 Out << "\nreturn mod;\n";
1941 Out << "\n}\n";
1942}
1943
1944void CppWriter::printFunction(const std::string& fname,
1945 const std::string& funcName) {
1946 const Function* F = TheModule->getFunction(funcName);
1947 if (!F) {
1948 error(std::string("Function '") + funcName + "' not found in input module");
1949 return;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001950 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001951 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1952 printFunctionUses(F);
1953 printFunctionHead(F);
1954 printFunctionBody(F);
1955 Out << "return " << getCppName(F) << ";\n";
1956 Out << "}\n";
1957}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001958
Chris Lattner7e6d7452010-06-21 23:12:56 +00001959void CppWriter::printFunctions() {
1960 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1961 Module::const_iterator I = funcs.begin();
1962 Module::const_iterator IE = funcs.end();
Anton Korobeynikov50276522008-04-23 22:29:24 +00001963
Chris Lattner7e6d7452010-06-21 23:12:56 +00001964 for (; I != IE; ++I) {
1965 const Function &func = *I;
1966 if (!func.isDeclaration()) {
1967 std::string name("define_");
1968 name += func.getName();
1969 printFunction(name, func.getName());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001970 }
1971 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001972}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001973
Chris Lattner7e6d7452010-06-21 23:12:56 +00001974void CppWriter::printVariable(const std::string& fname,
1975 const std::string& varName) {
1976 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001977
Chris Lattner7e6d7452010-06-21 23:12:56 +00001978 if (!GV) {
1979 error(std::string("Variable '") + varName + "' not found in input module");
1980 return;
1981 }
1982 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1983 printVariableUses(GV);
1984 printVariableHead(GV);
1985 printVariableBody(GV);
1986 Out << "return " << getCppName(GV) << ";\n";
1987 Out << "}\n";
1988}
1989
Chris Lattner1afcace2011-07-09 17:41:24 +00001990void CppWriter::printType(const std::string &fname,
1991 const std::string &typeName) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001992 Type* Ty = TheModule->getTypeByName(typeName);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001993 if (!Ty) {
1994 error(std::string("Type '") + typeName + "' not found in input module");
1995 return;
1996 }
1997 Out << "\nType* " << fname << "(Module *mod) {\n";
1998 printType(Ty);
1999 Out << "return " << getCppName(Ty) << ";\n";
2000 Out << "}\n";
2001}
2002
2003bool CppWriter::runOnModule(Module &M) {
2004 TheModule = &M;
2005
2006 // Emit a header
2007 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
2008
2009 // Get the name of the function we're supposed to generate
2010 std::string fname = FuncName.getValue();
2011
2012 // Get the name of the thing we are to generate
2013 std::string tgtname = NameToGenerate.getValue();
2014 if (GenerationType == GenModule ||
2015 GenerationType == GenContents ||
2016 GenerationType == GenProgram ||
2017 GenerationType == GenFunctions) {
2018 if (tgtname == "!bad!") {
2019 if (M.getModuleIdentifier() == "-")
2020 tgtname = "<stdin>";
2021 else
2022 tgtname = M.getModuleIdentifier();
Anton Korobeynikov50276522008-04-23 22:29:24 +00002023 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00002024 } else if (tgtname == "!bad!")
2025 error("You must use the -for option with -gen-{function,variable,type}");
2026
2027 switch (WhatToGenerate(GenerationType)) {
2028 case GenProgram:
2029 if (fname.empty())
2030 fname = "makeLLVMModule";
2031 printProgram(fname,tgtname);
2032 break;
2033 case GenModule:
2034 if (fname.empty())
2035 fname = "makeLLVMModule";
2036 printModule(fname,tgtname);
2037 break;
2038 case GenContents:
2039 if (fname.empty())
2040 fname = "makeLLVMModuleContents";
2041 printContents(fname,tgtname);
2042 break;
2043 case GenFunction:
2044 if (fname.empty())
2045 fname = "makeLLVMFunction";
2046 printFunction(fname,tgtname);
2047 break;
2048 case GenFunctions:
2049 printFunctions();
2050 break;
2051 case GenInline:
2052 if (fname.empty())
2053 fname = "makeLLVMInline";
2054 printInline(fname,tgtname);
2055 break;
2056 case GenVariable:
2057 if (fname.empty())
2058 fname = "makeLLVMVariable";
2059 printVariable(fname,tgtname);
2060 break;
2061 case GenType:
2062 if (fname.empty())
2063 fname = "makeLLVMType";
2064 printType(fname,tgtname);
2065 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002066 }
2067
Chris Lattner7e6d7452010-06-21 23:12:56 +00002068 return false;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002069}
2070
2071char CppWriter::ID = 0;
2072
2073//===----------------------------------------------------------------------===//
2074// External Interface declaration
2075//===----------------------------------------------------------------------===//
2076
Dan Gohman99dca4f2010-05-11 19:57:55 +00002077bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
2078 formatted_raw_ostream &o,
2079 CodeGenFileType FileType,
Dan Gohman99dca4f2010-05-11 19:57:55 +00002080 bool DisableVerify) {
Chris Lattner211edae2010-02-02 21:06:45 +00002081 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002082 PM.add(new CppWriter(o));
2083 return false;
2084}