blob: 69f0ff87eda0e195e3964d28d555e285ece8ee44 [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>
Benjamin Kramer901b8582012-03-23 11:35:30 +000036#include <cstdio>
Chris Lattner1afcace2011-07-09 17:41:24 +000037#include <map>
Benjamin Kramer901b8582012-03-23 11:35:30 +000038#include <set>
Anton Korobeynikov50276522008-04-23 22:29:24 +000039using namespace llvm;
40
41static cl::opt<std::string>
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000042FuncName("cppfname", cl::desc("Specify the name of the generated function"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000043 cl::value_desc("function name"));
44
45enum WhatToGenerate {
46 GenProgram,
47 GenModule,
48 GenContents,
49 GenFunction,
50 GenFunctions,
51 GenInline,
52 GenVariable,
53 GenType
54};
55
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000056static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000057 cl::desc("Choose what kind of output to generate"),
58 cl::init(GenProgram),
59 cl::values(
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000060 clEnumValN(GenProgram, "program", "Generate a complete program"),
61 clEnumValN(GenModule, "module", "Generate a module definition"),
62 clEnumValN(GenContents, "contents", "Generate contents of a module"),
63 clEnumValN(GenFunction, "function", "Generate a function definition"),
64 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
65 clEnumValN(GenInline, "inline", "Generate an inline function"),
66 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
67 clEnumValN(GenType, "type", "Generate a type definition"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000068 clEnumValEnd
69 )
70);
71
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000072static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000073 cl::desc("Specify the name of the thing to generate"),
74 cl::init("!bad!"));
75
Daniel Dunbar0c795d62009-07-25 06:49:55 +000076extern "C" void LLVMInitializeCppBackendTarget() {
77 // Register the target.
Daniel Dunbar214e2232009-08-04 04:02:45 +000078 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
Daniel Dunbar0c795d62009-07-25 06:49:55 +000079}
Douglas Gregor1555a232009-06-16 20:12:29 +000080
Dan Gohman844731a2008-05-13 00:00:25 +000081namespace {
Chris Lattnerdb125cf2011-07-18 04:54:35 +000082 typedef std::vector<Type*> TypeList;
83 typedef std::map<Type*,std::string> TypeMap;
Anton Korobeynikov50276522008-04-23 22:29:24 +000084 typedef std::map<const Value*,std::string> ValueMap;
85 typedef std::set<std::string> NameSet;
Chris Lattnerdb125cf2011-07-18 04:54:35 +000086 typedef std::set<Type*> TypeSet;
Anton Korobeynikov50276522008-04-23 22:29:24 +000087 typedef std::set<const Value*> ValueSet;
88 typedef std::map<const Value*,std::string> ForwardRefMap;
89
90 /// CppWriter - This class is the main chunk of code that converts an LLVM
91 /// module to a C++ translation unit.
92 class CppWriter : public ModulePass {
David Greene71847812009-07-14 20:18:05 +000093 formatted_raw_ostream &Out;
Anton Korobeynikov50276522008-04-23 22:29:24 +000094 const Module *TheModule;
95 uint64_t uniqueNum;
96 TypeMap TypeNames;
97 ValueMap ValueNames;
Anton Korobeynikov50276522008-04-23 22:29:24 +000098 NameSet UsedNames;
99 TypeSet DefinedTypes;
100 ValueSet DefinedValues;
101 ForwardRefMap ForwardRefs;
102 bool is_inline;
Chris Lattner1018c242010-06-21 23:14:47 +0000103 unsigned indent_level;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000104
105 public:
106 static char ID;
David Greene71847812009-07-14 20:18:05 +0000107 explicit CppWriter(formatted_raw_ostream &o) :
Owen Anderson90c579d2010-08-06 18:33:48 +0000108 ModulePass(ID), Out(o), uniqueNum(0), is_inline(false), indent_level(0){}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000109
110 virtual const char *getPassName() const { return "C++ backend"; }
111
112 bool runOnModule(Module &M);
113
Anton Korobeynikov50276522008-04-23 22:29:24 +0000114 void printProgram(const std::string& fname, const std::string& modName );
115 void printModule(const std::string& fname, const std::string& modName );
116 void printContents(const std::string& fname, const std::string& modName );
117 void printFunction(const std::string& fname, const std::string& funcName );
118 void printFunctions();
119 void printInline(const std::string& fname, const std::string& funcName );
120 void printVariable(const std::string& fname, const std::string& varName );
121 void printType(const std::string& fname, const std::string& typeName );
122
123 void error(const std::string& msg);
124
Chris Lattner1018c242010-06-21 23:14:47 +0000125
126 formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0);
127 inline void in() { indent_level++; }
128 inline void out() { if (indent_level >0) indent_level--; }
129
Anton Korobeynikov50276522008-04-23 22:29:24 +0000130 private:
131 void printLinkageType(GlobalValue::LinkageTypes LT);
132 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +0000133 void printCallingConv(CallingConv::ID cc);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000134 void printEscapedString(const std::string& str);
135 void printCFP(const ConstantFP* CFP);
136
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000137 std::string getCppName(Type* val);
138 inline void printCppName(Type* val);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000139
140 std::string getCppName(const Value* val);
141 inline void printCppName(const Value* val);
142
Devang Patel05988662008-09-25 21:00:45 +0000143 void printAttributes(const AttrListPtr &PAL, const std::string &name);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000144 void printType(Type* Ty);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000145 void printTypes(const Module* M);
146
147 void printConstant(const Constant *CPV);
148 void printConstants(const Module* M);
149
150 void printVariableUses(const GlobalVariable *GV);
151 void printVariableHead(const GlobalVariable *GV);
152 void printVariableBody(const GlobalVariable *GV);
153
154 void printFunctionUses(const Function *F);
155 void printFunctionHead(const Function *F);
156 void printFunctionBody(const Function *F);
157 void printInstruction(const Instruction *I, const std::string& bbname);
Eli Friedmanbb5a7442011-09-29 20:21:17 +0000158 std::string getOpName(const Value*);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000159
160 void printModuleBody();
161 };
Chris Lattner7e6d7452010-06-21 23:12:56 +0000162} // end anonymous namespace.
Anton Korobeynikov50276522008-04-23 22:29:24 +0000163
Chris Lattner1018c242010-06-21 23:14:47 +0000164formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
165 Out << '\n';
Chris Lattner7e6d7452010-06-21 23:12:56 +0000166 if (delta >= 0 || indent_level >= unsigned(-delta))
167 indent_level += delta;
Chris Lattner1018c242010-06-21 23:14:47 +0000168 Out.indent(indent_level);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000169 return Out;
170}
171
Chris Lattner7e6d7452010-06-21 23:12:56 +0000172static inline void sanitize(std::string &str) {
173 for (size_t i = 0; i < str.length(); ++i)
174 if (!isalnum(str[i]) && str[i] != '_')
175 str[i] = '_';
176}
177
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000178static std::string getTypePrefix(Type *Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000179 switch (Ty->getTypeID()) {
180 case Type::VoidTyID: return "void_";
181 case Type::IntegerTyID:
182 return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
183 case Type::FloatTyID: return "float_";
184 case Type::DoubleTyID: return "double_";
185 case Type::LabelTyID: return "label_";
186 case Type::FunctionTyID: return "func_";
187 case Type::StructTyID: return "struct_";
188 case Type::ArrayTyID: return "array_";
189 case Type::PointerTyID: return "ptr_";
190 case Type::VectorTyID: return "packed_";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000191 default: return "other_";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000192 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000193}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000194
Chris Lattner7e6d7452010-06-21 23:12:56 +0000195void CppWriter::error(const std::string& msg) {
196 report_fatal_error(msg);
197}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000198
Benjamin Kramere68e7752012-03-23 11:26:29 +0000199static inline std::string ftostr(const APFloat& V) {
200 std::string Buf;
201 if (&V.getSemantics() == &APFloat::IEEEdouble) {
202 raw_string_ostream(Buf) << V.convertToDouble();
203 return Buf;
204 } else if (&V.getSemantics() == &APFloat::IEEEsingle) {
205 raw_string_ostream(Buf) << (double)V.convertToFloat();
206 return Buf;
207 }
208 return "<unknown format in ftostr>"; // error
209}
210
Chris Lattner7e6d7452010-06-21 23:12:56 +0000211// printCFP - Print a floating point constant .. very carefully :)
212// This makes sure that conversion to/from floating yields the same binary
213// result so that we don't lose precision.
214void CppWriter::printCFP(const ConstantFP *CFP) {
215 bool ignored;
216 APFloat APF = APFloat(CFP->getValueAPF()); // copy
217 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
218 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
219 Out << "ConstantFP::get(mod->getContext(), ";
220 Out << "APFloat(";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000221#if HAVE_PRINTF_A
Chris Lattner7e6d7452010-06-21 23:12:56 +0000222 char Buffer[100];
223 sprintf(Buffer, "%A", APF.convertToDouble());
224 if ((!strncmp(Buffer, "0x", 2) ||
225 !strncmp(Buffer, "-0x", 3) ||
226 !strncmp(Buffer, "+0x", 3)) &&
227 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
228 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
229 Out << "BitsToDouble(" << Buffer << ")";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000230 else
Chris Lattner7e6d7452010-06-21 23:12:56 +0000231 Out << "BitsToFloat((float)" << Buffer << ")";
232 Out << ")";
233 } else {
234#endif
235 std::string StrVal = ftostr(CFP->getValueAPF());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000236
Chris Lattner7e6d7452010-06-21 23:12:56 +0000237 while (StrVal[0] == ' ')
238 StrVal.erase(StrVal.begin());
239
240 // Check to make sure that the stringized number is not some string like
241 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
242 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
243 ((StrVal[0] == '-' || StrVal[0] == '+') &&
244 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
245 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
246 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
247 Out << StrVal;
248 else
249 Out << StrVal << "f";
250 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
251 Out << "BitsToDouble(0x"
252 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
253 << "ULL) /* " << StrVal << " */";
254 else
255 Out << "BitsToFloat(0x"
256 << utohexstr((uint32_t)CFP->getValueAPF().
257 bitcastToAPInt().getZExtValue())
258 << "U) /* " << StrVal << " */";
259 Out << ")";
260#if HAVE_PRINTF_A
261 }
262#endif
263 Out << ")";
264}
265
266void CppWriter::printCallingConv(CallingConv::ID cc){
267 // Print the calling convention.
268 switch (cc) {
269 case CallingConv::C: Out << "CallingConv::C"; break;
270 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
271 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
272 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
273 default: Out << cc; break;
274 }
275}
276
277void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
278 switch (LT) {
279 case GlobalValue::InternalLinkage:
280 Out << "GlobalValue::InternalLinkage"; break;
281 case GlobalValue::PrivateLinkage:
282 Out << "GlobalValue::PrivateLinkage"; break;
283 case GlobalValue::LinkerPrivateLinkage:
284 Out << "GlobalValue::LinkerPrivateLinkage"; break;
Bill Wendling5e721d72010-07-01 21:55:59 +0000285 case GlobalValue::LinkerPrivateWeakLinkage:
286 Out << "GlobalValue::LinkerPrivateWeakLinkage"; break;
Bill Wendling55ae5152010-08-20 22:05:50 +0000287 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
288 Out << "GlobalValue::LinkerPrivateWeakDefAutoLinkage"; break;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000289 case GlobalValue::AvailableExternallyLinkage:
290 Out << "GlobalValue::AvailableExternallyLinkage "; break;
291 case GlobalValue::LinkOnceAnyLinkage:
292 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
293 case GlobalValue::LinkOnceODRLinkage:
294 Out << "GlobalValue::LinkOnceODRLinkage "; break;
295 case GlobalValue::WeakAnyLinkage:
296 Out << "GlobalValue::WeakAnyLinkage"; break;
297 case GlobalValue::WeakODRLinkage:
298 Out << "GlobalValue::WeakODRLinkage"; break;
299 case GlobalValue::AppendingLinkage:
300 Out << "GlobalValue::AppendingLinkage"; break;
301 case GlobalValue::ExternalLinkage:
302 Out << "GlobalValue::ExternalLinkage"; break;
303 case GlobalValue::DLLImportLinkage:
304 Out << "GlobalValue::DLLImportLinkage"; break;
305 case GlobalValue::DLLExportLinkage:
306 Out << "GlobalValue::DLLExportLinkage"; break;
307 case GlobalValue::ExternalWeakLinkage:
308 Out << "GlobalValue::ExternalWeakLinkage"; break;
309 case GlobalValue::CommonLinkage:
310 Out << "GlobalValue::CommonLinkage"; break;
311 }
312}
313
314void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
315 switch (VisType) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000316 case GlobalValue::DefaultVisibility:
317 Out << "GlobalValue::DefaultVisibility";
318 break;
319 case GlobalValue::HiddenVisibility:
320 Out << "GlobalValue::HiddenVisibility";
321 break;
322 case GlobalValue::ProtectedVisibility:
323 Out << "GlobalValue::ProtectedVisibility";
324 break;
325 }
326}
327
328// printEscapedString - Print each character of the specified string, escaping
329// it if it is not printable or if it is an escape char.
330void CppWriter::printEscapedString(const std::string &Str) {
331 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
332 unsigned char C = Str[i];
333 if (isprint(C) && C != '"' && C != '\\') {
334 Out << C;
335 } else {
336 Out << "\\x"
337 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
338 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
339 }
340 }
341}
342
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000343std::string CppWriter::getCppName(Type* Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000344 // First, handle the primitive types .. easy
345 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
346 switch (Ty->getTypeID()) {
347 case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())";
348 case Type::IntegerTyID: {
349 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
350 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
351 }
352 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
353 case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())";
354 case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())";
355 case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())";
Dale Johannesenbb811a22010-09-10 20:55:01 +0000356 case Type::X86_MMXTyID: return "Type::getX86_MMXTy(mod->getContext())";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000357 default:
358 error("Invalid primitive type");
359 break;
360 }
361 // shouldn't be returned, but make it sensible
362 return "Type::getVoidTy(mod->getContext())";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000363 }
364
Chris Lattner7e6d7452010-06-21 23:12:56 +0000365 // Now, see if we've seen the type before and return that
366 TypeMap::iterator I = TypeNames.find(Ty);
367 if (I != TypeNames.end())
368 return I->second;
369
370 // Okay, let's build a new name for this type. Start with a prefix
371 const char* prefix = 0;
372 switch (Ty->getTypeID()) {
373 case Type::FunctionTyID: prefix = "FuncTy_"; break;
374 case Type::StructTyID: prefix = "StructTy_"; break;
375 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
376 case Type::PointerTyID: prefix = "PointerTy_"; break;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000377 case Type::VectorTyID: prefix = "VectorTy_"; break;
378 default: prefix = "OtherTy_"; break; // prevent breakage
Anton Korobeynikov50276522008-04-23 22:29:24 +0000379 }
380
Chris Lattner7e6d7452010-06-21 23:12:56 +0000381 // See if the type has a name in the symboltable and build accordingly
Chris Lattner7e6d7452010-06-21 23:12:56 +0000382 std::string name;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000383 if (StructType *STy = dyn_cast<StructType>(Ty))
Chris Lattner1afcace2011-07-09 17:41:24 +0000384 if (STy->hasName())
385 name = STy->getName();
386
387 if (name.empty())
388 name = utostr(uniqueNum++);
389
390 name = std::string(prefix) + name;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000391 sanitize(name);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000392
Chris Lattner7e6d7452010-06-21 23:12:56 +0000393 // Save the name
394 return TypeNames[Ty] = name;
395}
396
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000397void CppWriter::printCppName(Type* Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000398 printEscapedString(getCppName(Ty));
399}
400
401std::string CppWriter::getCppName(const Value* val) {
402 std::string name;
403 ValueMap::iterator I = ValueNames.find(val);
404 if (I != ValueNames.end() && I->first == val)
405 return I->second;
406
407 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
408 name = std::string("gvar_") +
409 getTypePrefix(GV->getType()->getElementType());
410 } else if (isa<Function>(val)) {
411 name = std::string("func_");
412 } else if (const Constant* C = dyn_cast<Constant>(val)) {
413 name = std::string("const_") + getTypePrefix(C->getType());
414 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
415 if (is_inline) {
416 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
417 Function::const_arg_iterator(Arg)) + 1;
418 name = std::string("arg_") + utostr(argNum);
419 NameSet::iterator NI = UsedNames.find(name);
420 if (NI != UsedNames.end())
421 name += std::string("_") + utostr(uniqueNum++);
422 UsedNames.insert(name);
423 return ValueNames[val] = name;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000424 } else {
425 name = getTypePrefix(val->getType());
426 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000427 } else {
428 name = getTypePrefix(val->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000429 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000430 if (val->hasName())
431 name += val->getName();
432 else
433 name += utostr(uniqueNum++);
434 sanitize(name);
435 NameSet::iterator NI = UsedNames.find(name);
436 if (NI != UsedNames.end())
437 name += std::string("_") + utostr(uniqueNum++);
438 UsedNames.insert(name);
439 return ValueNames[val] = name;
440}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000441
Chris Lattner7e6d7452010-06-21 23:12:56 +0000442void CppWriter::printCppName(const Value* val) {
443 printEscapedString(getCppName(val));
444}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000445
Chris Lattner7e6d7452010-06-21 23:12:56 +0000446void CppWriter::printAttributes(const AttrListPtr &PAL,
447 const std::string &name) {
448 Out << "AttrListPtr " << name << "_PAL;";
449 nl(Out);
450 if (!PAL.isEmpty()) {
451 Out << '{'; in(); nl(Out);
452 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
453 Out << "AttributeWithIndex PAWI;"; nl(Out);
454 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
455 unsigned index = PAL.getSlot(i).Index;
456 Attributes attrs = PAL.getSlot(i).Attrs;
Nicolas Geoffray81946832012-01-22 20:05:26 +0000457 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = Attribute::None ";
Chris Lattneracca9552009-01-13 07:22:22 +0000458#define HANDLE_ATTR(X) \
Chris Lattner7e6d7452010-06-21 23:12:56 +0000459 if (attrs & Attribute::X) \
460 Out << " | Attribute::" #X; \
461 attrs &= ~Attribute::X;
462
463 HANDLE_ATTR(SExt);
464 HANDLE_ATTR(ZExt);
465 HANDLE_ATTR(NoReturn);
466 HANDLE_ATTR(InReg);
467 HANDLE_ATTR(StructRet);
468 HANDLE_ATTR(NoUnwind);
469 HANDLE_ATTR(NoAlias);
470 HANDLE_ATTR(ByVal);
471 HANDLE_ATTR(Nest);
472 HANDLE_ATTR(ReadNone);
473 HANDLE_ATTR(ReadOnly);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000474 HANDLE_ATTR(NoInline);
475 HANDLE_ATTR(AlwaysInline);
476 HANDLE_ATTR(OptimizeForSize);
477 HANDLE_ATTR(StackProtect);
478 HANDLE_ATTR(StackProtectReq);
479 HANDLE_ATTR(NoCapture);
Eli Friedman32bb4df2010-07-16 18:47:20 +0000480 HANDLE_ATTR(NoRedZone);
481 HANDLE_ATTR(NoImplicitFloat);
482 HANDLE_ATTR(Naked);
483 HANDLE_ATTR(InlineHint);
Rafael Espindola25456ef2011-10-03 14:45:37 +0000484 HANDLE_ATTR(ReturnsTwice);
Bill Wendling54f15362011-08-09 00:47:30 +0000485 HANDLE_ATTR(UWTable);
486 HANDLE_ATTR(NonLazyBind);
Chris Lattneracca9552009-01-13 07:22:22 +0000487#undef HANDLE_ATTR
Eli Friedman32bb4df2010-07-16 18:47:20 +0000488 if (attrs & Attribute::StackAlignment)
489 Out << " | Attribute::constructStackAlignmentFromInt("
490 << Attribute::getStackAlignmentFromAttrs(attrs)
491 << ")";
492 attrs &= ~Attribute::StackAlignment;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000493 assert(attrs == 0 && "Unhandled attribute!");
494 Out << ";";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000495 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000496 Out << "Attrs.push_back(PAWI);";
497 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000498 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000499 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
500 nl(Out);
501 out(); nl(Out);
502 Out << '}'; nl(Out);
503 }
504}
505
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000506void CppWriter::printType(Type* Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000507 // We don't print definitions for primitive types
508 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000509 return;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000510
511 // If we already defined this type, we don't need to define it again.
512 if (DefinedTypes.find(Ty) != DefinedTypes.end())
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000513 return;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000514
515 // Everything below needs the name for the type so get it now.
516 std::string typeName(getCppName(Ty));
517
Chris Lattner7e6d7452010-06-21 23:12:56 +0000518 // Print the type definition
519 switch (Ty->getTypeID()) {
520 case Type::FunctionTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000521 FunctionType* FT = cast<FunctionType>(Ty);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000522 Out << "std::vector<Type*>" << typeName << "_args;";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000523 nl(Out);
524 FunctionType::param_iterator PI = FT->param_begin();
525 FunctionType::param_iterator PE = FT->param_end();
526 for (; PI != PE; ++PI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000527 Type* argTy = static_cast<Type*>(*PI);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000528 printType(argTy);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000529 std::string argName(getCppName(argTy));
530 Out << typeName << "_args.push_back(" << argName;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000531 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000532 nl(Out);
533 }
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000534 printType(FT->getReturnType());
Chris Lattner7e6d7452010-06-21 23:12:56 +0000535 std::string retTypeName(getCppName(FT->getReturnType()));
536 Out << "FunctionType* " << typeName << " = FunctionType::get(";
537 in(); nl(Out) << "/*Result=*/" << retTypeName;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000538 Out << ",";
539 nl(Out) << "/*Params=*/" << typeName << "_args,";
540 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
541 out();
Anton Korobeynikov50276522008-04-23 22:29:24 +0000542 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000543 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000544 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000545 case Type::StructTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000546 StructType* ST = cast<StructType>(Ty);
Chris Lattnerc4d0e9f2011-08-12 18:07:07 +0000547 if (!ST->isLiteral()) {
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000548 Out << "StructType *" << typeName << " = mod->getTypeByName(\"";
549 printEscapedString(ST->getName());
550 Out << "\");";
551 nl(Out);
552 Out << "if (!" << typeName << ") {";
553 nl(Out);
554 Out << typeName << " = ";
Chris Lattnerc4d0e9f2011-08-12 18:07:07 +0000555 Out << "StructType::create(mod->getContext(), \"";
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000556 printEscapedString(ST->getName());
557 Out << "\");";
558 nl(Out);
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000559 Out << "}";
560 nl(Out);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000561 // Indicate that this type is now defined.
562 DefinedTypes.insert(Ty);
563 }
564
565 Out << "std::vector<Type*>" << typeName << "_fields;";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000566 nl(Out);
567 StructType::element_iterator EI = ST->element_begin();
568 StructType::element_iterator EE = ST->element_end();
569 for (; EI != EE; ++EI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000570 Type* fieldTy = static_cast<Type*>(*EI);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000571 printType(fieldTy);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000572 std::string fieldName(getCppName(fieldTy));
573 Out << typeName << "_fields.push_back(" << fieldName;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000574 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000575 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000576 }
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000577
Chris Lattnerc4d0e9f2011-08-12 18:07:07 +0000578 if (ST->isLiteral()) {
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000579 Out << "StructType *" << typeName << " = ";
Chris Lattner1afcace2011-07-09 17:41:24 +0000580 Out << "StructType::get(" << "mod->getContext(), ";
581 } else {
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000582 Out << "if (" << typeName << "->isOpaque()) {";
583 nl(Out);
Chris Lattner1afcace2011-07-09 17:41:24 +0000584 Out << typeName << "->setBody(";
585 }
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000586
Chris Lattner1afcace2011-07-09 17:41:24 +0000587 Out << typeName << "_fields, /*isPacked=*/"
Chris Lattner7e6d7452010-06-21 23:12:56 +0000588 << (ST->isPacked() ? "true" : "false") << ");";
589 nl(Out);
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000590 if (!ST->isLiteral()) {
591 Out << "}";
592 nl(Out);
593 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000594 break;
595 }
596 case Type::ArrayTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000597 ArrayType* AT = cast<ArrayType>(Ty);
598 Type* ET = AT->getElementType();
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000599 printType(ET);
600 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
601 std::string elemName(getCppName(ET));
602 Out << "ArrayType* " << typeName << " = ArrayType::get("
603 << elemName
604 << ", " << utostr(AT->getNumElements()) << ");";
605 nl(Out);
606 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000607 break;
608 }
609 case Type::PointerTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000610 PointerType* PT = cast<PointerType>(Ty);
611 Type* ET = PT->getElementType();
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000612 printType(ET);
613 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
614 std::string elemName(getCppName(ET));
615 Out << "PointerType* " << typeName << " = PointerType::get("
616 << elemName
617 << ", " << utostr(PT->getAddressSpace()) << ");";
618 nl(Out);
619 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000620 break;
621 }
622 case Type::VectorTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000623 VectorType* PT = cast<VectorType>(Ty);
624 Type* ET = PT->getElementType();
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000625 printType(ET);
626 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
627 std::string elemName(getCppName(ET));
628 Out << "VectorType* " << typeName << " = VectorType::get("
629 << elemName
630 << ", " << utostr(PT->getNumElements()) << ");";
631 nl(Out);
632 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000633 break;
634 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000635 default:
636 error("Invalid TypeID");
637 }
638
Chris Lattner7e6d7452010-06-21 23:12:56 +0000639 // Indicate that this type is now defined.
640 DefinedTypes.insert(Ty);
641
Chris Lattner7e6d7452010-06-21 23:12:56 +0000642 // Finally, separate the type definition from other with a newline.
643 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000644}
645
646void CppWriter::printTypes(const Module* M) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000647 // Add all of the global variables to the value table.
Chris Lattner7e6d7452010-06-21 23:12:56 +0000648 for (Module::const_global_iterator I = TheModule->global_begin(),
649 E = TheModule->global_end(); I != E; ++I) {
650 if (I->hasInitializer())
651 printType(I->getInitializer()->getType());
652 printType(I->getType());
653 }
654
655 // Add all the functions to the table
656 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
657 FI != FE; ++FI) {
658 printType(FI->getReturnType());
659 printType(FI->getFunctionType());
660 // Add all the function arguments
661 for (Function::const_arg_iterator AI = FI->arg_begin(),
662 AE = FI->arg_end(); AI != AE; ++AI) {
663 printType(AI->getType());
664 }
665
666 // Add all of the basic blocks and instructions
667 for (Function::const_iterator BB = FI->begin(),
668 E = FI->end(); BB != E; ++BB) {
669 printType(BB->getType());
670 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
671 ++I) {
672 printType(I->getType());
673 for (unsigned i = 0; i < I->getNumOperands(); ++i)
674 printType(I->getOperand(i)->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000675 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000676 }
677 }
678}
679
680
681// printConstant - Print out a constant pool entry...
682void CppWriter::printConstant(const Constant *CV) {
683 // First, if the constant is actually a GlobalValue (variable or function)
684 // or its already in the constant list then we've printed it already and we
685 // can just return.
686 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
687 return;
688
689 std::string constName(getCppName(CV));
690 std::string typeName(getCppName(CV->getType()));
691
Chris Lattner7e6d7452010-06-21 23:12:56 +0000692 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
693 std::string constValue = CI->getValue().toString(10, true);
694 Out << "ConstantInt* " << constName
695 << " = ConstantInt::get(mod->getContext(), APInt("
696 << cast<IntegerType>(CI->getType())->getBitWidth()
697 << ", StringRef(\"" << constValue << "\"), 10));";
698 } else if (isa<ConstantAggregateZero>(CV)) {
699 Out << "ConstantAggregateZero* " << constName
700 << " = ConstantAggregateZero::get(" << typeName << ");";
701 } else if (isa<ConstantPointerNull>(CV)) {
702 Out << "ConstantPointerNull* " << constName
703 << " = ConstantPointerNull::get(" << typeName << ");";
704 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
705 Out << "ConstantFP* " << constName << " = ";
706 printCFP(CFP);
707 Out << ";";
708 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000709 Out << "std::vector<Constant*> " << constName << "_elems;";
710 nl(Out);
711 unsigned N = CA->getNumOperands();
712 for (unsigned i = 0; i < N; ++i) {
713 printConstant(CA->getOperand(i)); // recurse to print operands
714 Out << constName << "_elems.push_back("
715 << getCppName(CA->getOperand(i)) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000716 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000717 }
Chris Lattner18c7f802012-02-05 02:29:43 +0000718 Out << "Constant* " << constName << " = ConstantArray::get("
719 << typeName << ", " << constName << "_elems);";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000720 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
721 Out << "std::vector<Constant*> " << constName << "_fields;";
722 nl(Out);
723 unsigned N = CS->getNumOperands();
724 for (unsigned i = 0; i < N; i++) {
725 printConstant(CS->getOperand(i));
726 Out << constName << "_fields.push_back("
727 << getCppName(CS->getOperand(i)) << ");";
728 nl(Out);
729 }
730 Out << "Constant* " << constName << " = ConstantStruct::get("
731 << typeName << ", " << constName << "_fields);";
Duncan Sands853066a2012-02-05 14:16:09 +0000732 } else if (const ConstantVector *CVec = dyn_cast<ConstantVector>(CV)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000733 Out << "std::vector<Constant*> " << constName << "_elems;";
734 nl(Out);
Duncan Sands853066a2012-02-05 14:16:09 +0000735 unsigned N = CVec->getNumOperands();
Chris Lattner7e6d7452010-06-21 23:12:56 +0000736 for (unsigned i = 0; i < N; ++i) {
Duncan Sands853066a2012-02-05 14:16:09 +0000737 printConstant(CVec->getOperand(i));
Chris Lattner7e6d7452010-06-21 23:12:56 +0000738 Out << constName << "_elems.push_back("
Duncan Sands853066a2012-02-05 14:16:09 +0000739 << getCppName(CVec->getOperand(i)) << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000740 nl(Out);
741 }
742 Out << "Constant* " << constName << " = ConstantVector::get("
743 << typeName << ", " << constName << "_elems);";
744 } else if (isa<UndefValue>(CV)) {
745 Out << "UndefValue* " << constName << " = UndefValue::get("
746 << typeName << ");";
Chris Lattner29cc6cb2012-01-24 14:17:05 +0000747 } else if (const ConstantDataSequential *CDS =
748 dyn_cast<ConstantDataSequential>(CV)) {
749 if (CDS->isString()) {
750 Out << "Constant *" << constName <<
751 " = ConstantDataArray::getString(mod->getContext(), \"";
Chris Lattner18c7f802012-02-05 02:29:43 +0000752 StringRef Str = CDS->getAsString();
Chris Lattner29cc6cb2012-01-24 14:17:05 +0000753 bool nullTerminate = false;
754 if (Str.back() == 0) {
755 Str = Str.drop_back();
756 nullTerminate = true;
757 }
758 printEscapedString(Str);
759 // Determine if we want null termination or not.
760 if (nullTerminate)
761 Out << "\", true);";
762 else
763 Out << "\", false);";// No null terminator
764 } else {
765 // TODO: Could generate more efficient code generating CDS calls instead.
766 Out << "std::vector<Constant*> " << constName << "_elems;";
767 nl(Out);
768 for (unsigned i = 0; i != CDS->getNumElements(); ++i) {
769 Constant *Elt = CDS->getElementAsConstant(i);
770 printConstant(Elt);
771 Out << constName << "_elems.push_back(" << getCppName(Elt) << ");";
772 nl(Out);
773 }
774 Out << "Constant* " << constName;
775
776 if (isa<ArrayType>(CDS->getType()))
777 Out << " = ConstantArray::get(";
778 else
779 Out << " = ConstantVector::get(";
780 Out << typeName << ", " << constName << "_elems);";
781 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000782 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
783 if (CE->getOpcode() == Instruction::GetElementPtr) {
784 Out << "std::vector<Constant*> " << constName << "_indices;";
785 nl(Out);
786 printConstant(CE->getOperand(0));
787 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
788 printConstant(CE->getOperand(i));
789 Out << constName << "_indices.push_back("
790 << getCppName(CE->getOperand(i)) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000791 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000792 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000793 Out << "Constant* " << constName
794 << " = ConstantExpr::getGetElementPtr("
795 << getCppName(CE->getOperand(0)) << ", "
Nicolas Geoffraya056d202011-07-21 20:59:21 +0000796 << constName << "_indices);";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000797 } else if (CE->isCast()) {
798 printConstant(CE->getOperand(0));
799 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
800 switch (CE->getOpcode()) {
801 default: llvm_unreachable("Invalid cast opcode");
802 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
803 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
804 case Instruction::SExt: Out << "Instruction::SExt"; break;
805 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
806 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
807 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
808 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
809 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
810 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
811 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
812 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
813 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
814 }
815 Out << ", " << getCppName(CE->getOperand(0)) << ", "
816 << getCppName(CE->getType()) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000817 } else {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000818 unsigned N = CE->getNumOperands();
819 for (unsigned i = 0; i < N; ++i ) {
820 printConstant(CE->getOperand(i));
821 }
822 Out << "Constant* " << constName << " = ConstantExpr::";
823 switch (CE->getOpcode()) {
824 case Instruction::Add: Out << "getAdd("; break;
825 case Instruction::FAdd: Out << "getFAdd("; break;
826 case Instruction::Sub: Out << "getSub("; break;
827 case Instruction::FSub: Out << "getFSub("; break;
828 case Instruction::Mul: Out << "getMul("; break;
829 case Instruction::FMul: Out << "getFMul("; break;
830 case Instruction::UDiv: Out << "getUDiv("; break;
831 case Instruction::SDiv: Out << "getSDiv("; break;
832 case Instruction::FDiv: Out << "getFDiv("; break;
833 case Instruction::URem: Out << "getURem("; break;
834 case Instruction::SRem: Out << "getSRem("; break;
835 case Instruction::FRem: Out << "getFRem("; break;
836 case Instruction::And: Out << "getAnd("; break;
837 case Instruction::Or: Out << "getOr("; break;
838 case Instruction::Xor: Out << "getXor("; break;
839 case Instruction::ICmp:
840 Out << "getICmp(ICmpInst::ICMP_";
841 switch (CE->getPredicate()) {
842 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
843 case ICmpInst::ICMP_NE: Out << "NE"; break;
844 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
845 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
846 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
847 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
848 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
849 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
850 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
851 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
852 default: error("Invalid ICmp Predicate");
853 }
854 break;
855 case Instruction::FCmp:
856 Out << "getFCmp(FCmpInst::FCMP_";
857 switch (CE->getPredicate()) {
858 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
859 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
860 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
861 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
862 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
863 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
864 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
865 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
866 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
867 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
868 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
869 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
870 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
871 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
872 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
873 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
874 default: error("Invalid FCmp Predicate");
875 }
876 break;
877 case Instruction::Shl: Out << "getShl("; break;
878 case Instruction::LShr: Out << "getLShr("; break;
879 case Instruction::AShr: Out << "getAShr("; break;
880 case Instruction::Select: Out << "getSelect("; break;
881 case Instruction::ExtractElement: Out << "getExtractElement("; break;
882 case Instruction::InsertElement: Out << "getInsertElement("; break;
883 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
884 default:
885 error("Invalid constant expression");
886 break;
887 }
888 Out << getCppName(CE->getOperand(0));
889 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
890 Out << ", " << getCppName(CE->getOperand(i));
891 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000892 }
Chris Lattner32848772010-06-21 23:19:36 +0000893 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
894 Out << "Constant* " << constName << " = ";
895 Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000896 } else {
897 error("Bad Constant");
898 Out << "Constant* " << constName << " = 0; ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000899 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000900 nl(Out);
901}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000902
Chris Lattner7e6d7452010-06-21 23:12:56 +0000903void CppWriter::printConstants(const Module* M) {
904 // Traverse all the global variables looking for constant initializers
905 for (Module::const_global_iterator I = TheModule->global_begin(),
906 E = TheModule->global_end(); I != E; ++I)
907 if (I->hasInitializer())
908 printConstant(I->getInitializer());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000909
Chris Lattner7e6d7452010-06-21 23:12:56 +0000910 // Traverse the LLVM functions looking for constants
911 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
912 FI != FE; ++FI) {
913 // Add all of the basic blocks and instructions
914 for (Function::const_iterator BB = FI->begin(),
915 E = FI->end(); BB != E; ++BB) {
916 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
917 ++I) {
918 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
919 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
920 printConstant(C);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000921 }
922 }
923 }
924 }
925 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000926}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000927
Chris Lattner7e6d7452010-06-21 23:12:56 +0000928void CppWriter::printVariableUses(const GlobalVariable *GV) {
929 nl(Out) << "// Type Definitions";
930 nl(Out);
931 printType(GV->getType());
932 if (GV->hasInitializer()) {
Jay Foad7d715df2011-06-19 18:37:11 +0000933 const Constant *Init = GV->getInitializer();
Chris Lattner7e6d7452010-06-21 23:12:56 +0000934 printType(Init->getType());
Jay Foad7d715df2011-06-19 18:37:11 +0000935 if (const Function *F = dyn_cast<Function>(Init)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000936 nl(Out)<< "/ Function Declarations"; nl(Out);
937 printFunctionHead(F);
Jay Foad7d715df2011-06-19 18:37:11 +0000938 } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000939 nl(Out) << "// Global Variable Declarations"; nl(Out);
940 printVariableHead(gv);
941
942 nl(Out) << "// Global Variable Definitions"; nl(Out);
943 printVariableBody(gv);
944 } else {
945 nl(Out) << "// Constant Definitions"; nl(Out);
946 printConstant(Init);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000947 }
948 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000949}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000950
Chris Lattner7e6d7452010-06-21 23:12:56 +0000951void CppWriter::printVariableHead(const GlobalVariable *GV) {
952 nl(Out) << "GlobalVariable* " << getCppName(GV);
953 if (is_inline) {
954 Out << " = mod->getGlobalVariable(mod->getContext(), ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000955 printEscapedString(GV->getName());
Chris Lattner7e6d7452010-06-21 23:12:56 +0000956 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
957 nl(Out) << "if (!" << getCppName(GV) << ") {";
958 in(); nl(Out) << getCppName(GV);
959 }
960 Out << " = new GlobalVariable(/*Module=*/*mod, ";
961 nl(Out) << "/*Type=*/";
962 printCppName(GV->getType()->getElementType());
963 Out << ",";
964 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
965 Out << ",";
966 nl(Out) << "/*Linkage=*/";
967 printLinkageType(GV->getLinkage());
968 Out << ",";
969 nl(Out) << "/*Initializer=*/0, ";
970 if (GV->hasInitializer()) {
971 Out << "// has initializer, specified below";
972 }
973 nl(Out) << "/*Name=*/\"";
974 printEscapedString(GV->getName());
975 Out << "\");";
976 nl(Out);
977
978 if (GV->hasSection()) {
979 printCppName(GV);
980 Out << "->setSection(\"";
981 printEscapedString(GV->getSection());
Owen Anderson16a412e2009-07-10 16:42:19 +0000982 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000983 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000984 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000985 if (GV->getAlignment()) {
986 printCppName(GV);
987 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000988 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000989 }
990 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
991 printCppName(GV);
992 Out << "->setVisibility(";
993 printVisibilityType(GV->getVisibility());
994 Out << ");";
995 nl(Out);
996 }
997 if (GV->isThreadLocal()) {
998 printCppName(GV);
999 Out << "->setThreadLocal(true);";
1000 nl(Out);
1001 }
1002 if (is_inline) {
1003 out(); Out << "}"; nl(Out);
1004 }
1005}
1006
1007void CppWriter::printVariableBody(const GlobalVariable *GV) {
1008 if (GV->hasInitializer()) {
1009 printCppName(GV);
1010 Out << "->setInitializer(";
1011 Out << getCppName(GV->getInitializer()) << ");";
1012 nl(Out);
1013 }
1014}
1015
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001016std::string CppWriter::getOpName(const Value* V) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001017 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1018 return getCppName(V);
1019
1020 // See if its alread in the map of forward references, if so just return the
1021 // name we already set up for it
1022 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1023 if (I != ForwardRefs.end())
1024 return I->second;
1025
1026 // This is a new forward reference. Generate a unique name for it
1027 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1028
1029 // Yes, this is a hack. An Argument is the smallest instantiable value that
1030 // we can make as a placeholder for the real value. We'll replace these
1031 // Argument instances later.
1032 Out << "Argument* " << result << " = new Argument("
1033 << getCppName(V->getType()) << ");";
1034 nl(Out);
1035 ForwardRefs[V] = result;
1036 return result;
1037}
1038
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001039static StringRef ConvertAtomicOrdering(AtomicOrdering Ordering) {
1040 switch (Ordering) {
1041 case NotAtomic: return "NotAtomic";
1042 case Unordered: return "Unordered";
1043 case Monotonic: return "Monotonic";
1044 case Acquire: return "Acquire";
1045 case Release: return "Release";
1046 case AcquireRelease: return "AcquireRelease";
1047 case SequentiallyConsistent: return "SequentiallyConsistent";
1048 }
1049 llvm_unreachable("Unknown ordering");
1050}
1051
1052static StringRef ConvertAtomicSynchScope(SynchronizationScope SynchScope) {
1053 switch (SynchScope) {
1054 case SingleThread: return "SingleThread";
1055 case CrossThread: return "CrossThread";
1056 }
1057 llvm_unreachable("Unknown synch scope");
1058}
1059
Chris Lattner7e6d7452010-06-21 23:12:56 +00001060// printInstruction - This member is called for each Instruction in a function.
1061void CppWriter::printInstruction(const Instruction *I,
1062 const std::string& bbname) {
1063 std::string iName(getCppName(I));
1064
1065 // Before we emit this instruction, we need to take care of generating any
1066 // forward references. So, we get the names of all the operands in advance
1067 const unsigned Ops(I->getNumOperands());
1068 std::string* opNames = new std::string[Ops];
Chris Lattner32848772010-06-21 23:19:36 +00001069 for (unsigned i = 0; i < Ops; i++)
Chris Lattner7e6d7452010-06-21 23:12:56 +00001070 opNames[i] = getOpName(I->getOperand(i));
Anton Korobeynikov50276522008-04-23 22:29:24 +00001071
Chris Lattner7e6d7452010-06-21 23:12:56 +00001072 switch (I->getOpcode()) {
1073 default:
1074 error("Invalid instruction");
1075 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001076
Chris Lattner7e6d7452010-06-21 23:12:56 +00001077 case Instruction::Ret: {
1078 const ReturnInst* ret = cast<ReturnInst>(I);
1079 Out << "ReturnInst::Create(mod->getContext(), "
1080 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1081 break;
1082 }
1083 case Instruction::Br: {
1084 const BranchInst* br = cast<BranchInst>(I);
1085 Out << "BranchInst::Create(" ;
Chris Lattner32848772010-06-21 23:19:36 +00001086 if (br->getNumOperands() == 3) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001087 Out << opNames[2] << ", "
Anton Korobeynikov50276522008-04-23 22:29:24 +00001088 << opNames[1] << ", "
Chris Lattner7e6d7452010-06-21 23:12:56 +00001089 << opNames[0] << ", ";
1090
1091 } else if (br->getNumOperands() == 1) {
1092 Out << opNames[0] << ", ";
1093 } else {
1094 error("Branch with 2 operands?");
1095 }
1096 Out << bbname << ");";
1097 break;
1098 }
1099 case Instruction::Switch: {
1100 const SwitchInst *SI = cast<SwitchInst>(I);
1101 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001102 << getOpName(SI->getCondition()) << ", "
1103 << getOpName(SI->getDefaultDest()) << ", "
Chris Lattner7e6d7452010-06-21 23:12:56 +00001104 << SI->getNumCases() << ", " << bbname << ");";
1105 nl(Out);
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00001106 for (SwitchInst::ConstCaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00001107 i != e; ++i) {
1108 const ConstantInt* CaseVal = i.getCaseValue();
1109 const BasicBlock *BB = i.getCaseSuccessor();
Chris Lattner7e6d7452010-06-21 23:12:56 +00001110 Out << iName << "->addCase("
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001111 << getOpName(CaseVal) << ", "
1112 << getOpName(BB) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001113 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001114 }
1115 break;
1116 }
1117 case Instruction::IndirectBr: {
1118 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1119 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1120 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1121 nl(Out);
1122 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1123 Out << iName << "->addDestination(" << opNames[i] << ");";
1124 nl(Out);
1125 }
1126 break;
1127 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00001128 case Instruction::Resume: {
1129 Out << "ResumeInst::Create(mod->getContext(), " << opNames[0]
1130 << ", " << bbname << ");";
1131 break;
1132 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001133 case Instruction::Invoke: {
1134 const InvokeInst* inv = cast<InvokeInst>(I);
1135 Out << "std::vector<Value*> " << iName << "_params;";
1136 nl(Out);
1137 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1138 Out << iName << "_params.push_back("
1139 << getOpName(inv->getArgOperand(i)) << ");";
1140 nl(Out);
1141 }
1142 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1143 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1144 << getOpName(inv->getCalledFunction()) << ", "
1145 << getOpName(inv->getNormalDest()) << ", "
1146 << getOpName(inv->getUnwindDest()) << ", "
Nick Lewycky3bca1012011-09-05 18:50:59 +00001147 << iName << "_params, \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001148 printEscapedString(inv->getName());
1149 Out << "\", " << bbname << ");";
1150 nl(Out) << iName << "->setCallingConv(";
1151 printCallingConv(inv->getCallingConv());
1152 Out << ");";
1153 printAttributes(inv->getAttributes(), iName);
1154 Out << iName << "->setAttributes(" << iName << "_PAL);";
1155 nl(Out);
1156 break;
1157 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001158 case Instruction::Unreachable: {
1159 Out << "new UnreachableInst("
1160 << "mod->getContext(), "
1161 << bbname << ");";
1162 break;
1163 }
1164 case Instruction::Add:
1165 case Instruction::FAdd:
1166 case Instruction::Sub:
1167 case Instruction::FSub:
1168 case Instruction::Mul:
1169 case Instruction::FMul:
1170 case Instruction::UDiv:
1171 case Instruction::SDiv:
1172 case Instruction::FDiv:
1173 case Instruction::URem:
1174 case Instruction::SRem:
1175 case Instruction::FRem:
1176 case Instruction::And:
1177 case Instruction::Or:
1178 case Instruction::Xor:
1179 case Instruction::Shl:
1180 case Instruction::LShr:
1181 case Instruction::AShr:{
1182 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1183 switch (I->getOpcode()) {
1184 case Instruction::Add: Out << "Instruction::Add"; break;
1185 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1186 case Instruction::Sub: Out << "Instruction::Sub"; break;
1187 case Instruction::FSub: Out << "Instruction::FSub"; break;
1188 case Instruction::Mul: Out << "Instruction::Mul"; break;
1189 case Instruction::FMul: Out << "Instruction::FMul"; break;
1190 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1191 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1192 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1193 case Instruction::URem:Out << "Instruction::URem"; break;
1194 case Instruction::SRem:Out << "Instruction::SRem"; break;
1195 case Instruction::FRem:Out << "Instruction::FRem"; break;
1196 case Instruction::And: Out << "Instruction::And"; break;
1197 case Instruction::Or: Out << "Instruction::Or"; break;
1198 case Instruction::Xor: Out << "Instruction::Xor"; break;
1199 case Instruction::Shl: Out << "Instruction::Shl"; break;
1200 case Instruction::LShr:Out << "Instruction::LShr"; break;
1201 case Instruction::AShr:Out << "Instruction::AShr"; break;
1202 default: Out << "Instruction::BadOpCode"; break;
1203 }
1204 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1205 printEscapedString(I->getName());
1206 Out << "\", " << bbname << ");";
1207 break;
1208 }
1209 case Instruction::FCmp: {
1210 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1211 switch (cast<FCmpInst>(I)->getPredicate()) {
1212 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1213 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1214 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1215 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1216 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1217 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1218 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1219 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1220 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1221 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1222 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1223 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1224 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1225 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1226 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1227 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1228 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1229 }
1230 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1231 printEscapedString(I->getName());
1232 Out << "\");";
1233 break;
1234 }
1235 case Instruction::ICmp: {
1236 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1237 switch (cast<ICmpInst>(I)->getPredicate()) {
1238 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1239 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1240 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1241 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1242 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1243 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1244 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1245 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1246 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1247 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1248 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1249 }
1250 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1251 printEscapedString(I->getName());
1252 Out << "\");";
1253 break;
1254 }
1255 case Instruction::Alloca: {
1256 const AllocaInst* allocaI = cast<AllocaInst>(I);
1257 Out << "AllocaInst* " << iName << " = new AllocaInst("
1258 << getCppName(allocaI->getAllocatedType()) << ", ";
1259 if (allocaI->isArrayAllocation())
1260 Out << opNames[0] << ", ";
1261 Out << "\"";
1262 printEscapedString(allocaI->getName());
1263 Out << "\", " << bbname << ");";
1264 if (allocaI->getAlignment())
1265 nl(Out) << iName << "->setAlignment("
1266 << allocaI->getAlignment() << ");";
1267 break;
1268 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001269 case Instruction::Load: {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001270 const LoadInst* load = cast<LoadInst>(I);
1271 Out << "LoadInst* " << iName << " = new LoadInst("
1272 << opNames[0] << ", \"";
1273 printEscapedString(load->getName());
1274 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1275 << ", " << bbname << ");";
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001276 if (load->getAlignment())
1277 nl(Out) << iName << "->setAlignment("
1278 << load->getAlignment() << ");";
1279 if (load->isAtomic()) {
1280 StringRef Ordering = ConvertAtomicOrdering(load->getOrdering());
1281 StringRef CrossThread = ConvertAtomicSynchScope(load->getSynchScope());
1282 nl(Out) << iName << "->setAtomic("
1283 << Ordering << ", " << CrossThread << ");";
1284 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001285 break;
1286 }
1287 case Instruction::Store: {
1288 const StoreInst* store = cast<StoreInst>(I);
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001289 Out << "StoreInst* " << iName << " = new StoreInst("
Chris Lattner7e6d7452010-06-21 23:12:56 +00001290 << opNames[0] << ", "
1291 << opNames[1] << ", "
1292 << (store->isVolatile() ? "true" : "false")
1293 << ", " << bbname << ");";
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001294 if (store->getAlignment())
1295 nl(Out) << iName << "->setAlignment("
1296 << store->getAlignment() << ");";
1297 if (store->isAtomic()) {
1298 StringRef Ordering = ConvertAtomicOrdering(store->getOrdering());
1299 StringRef CrossThread = ConvertAtomicSynchScope(store->getSynchScope());
1300 nl(Out) << iName << "->setAtomic("
1301 << Ordering << ", " << CrossThread << ");";
1302 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001303 break;
1304 }
1305 case Instruction::GetElementPtr: {
1306 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1307 if (gep->getNumOperands() <= 2) {
1308 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1309 << opNames[0];
1310 if (gep->getNumOperands() == 2)
1311 Out << ", " << opNames[1];
1312 } else {
1313 Out << "std::vector<Value*> " << iName << "_indices;";
1314 nl(Out);
1315 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1316 Out << iName << "_indices.push_back("
1317 << opNames[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001318 nl(Out);
1319 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001320 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
Nicolas Geoffray45c8d2b2011-07-26 20:52:25 +00001321 << opNames[0] << ", " << iName << "_indices";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001322 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001323 Out << ", \"";
1324 printEscapedString(gep->getName());
1325 Out << "\", " << bbname << ");";
1326 break;
1327 }
1328 case Instruction::PHI: {
1329 const PHINode* phi = cast<PHINode>(I);
1330
1331 Out << "PHINode* " << iName << " = PHINode::Create("
Nicolas Geoffrayc6cf1972011-04-10 17:39:40 +00001332 << getCppName(phi->getType()) << ", "
Jay Foad3ecfc862011-03-30 11:28:46 +00001333 << phi->getNumIncomingValues() << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001334 printEscapedString(phi->getName());
1335 Out << "\", " << bbname << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001336 nl(Out);
Jay Foadc1371202011-06-20 14:18:48 +00001337 for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001338 Out << iName << "->addIncoming("
Jay Foadc1371202011-06-20 14:18:48 +00001339 << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
Jay Foad95c3e482011-06-23 09:09:15 +00001340 << getOpName(phi->getIncomingBlock(i)) << ");";
Chris Lattner627b4702009-10-27 21:24:48 +00001341 nl(Out);
Chris Lattner627b4702009-10-27 21:24:48 +00001342 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001343 break;
1344 }
1345 case Instruction::Trunc:
1346 case Instruction::ZExt:
1347 case Instruction::SExt:
1348 case Instruction::FPTrunc:
1349 case Instruction::FPExt:
1350 case Instruction::FPToUI:
1351 case Instruction::FPToSI:
1352 case Instruction::UIToFP:
1353 case Instruction::SIToFP:
1354 case Instruction::PtrToInt:
1355 case Instruction::IntToPtr:
1356 case Instruction::BitCast: {
1357 const CastInst* cst = cast<CastInst>(I);
1358 Out << "CastInst* " << iName << " = new ";
1359 switch (I->getOpcode()) {
1360 case Instruction::Trunc: Out << "TruncInst"; break;
1361 case Instruction::ZExt: Out << "ZExtInst"; break;
1362 case Instruction::SExt: Out << "SExtInst"; break;
1363 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1364 case Instruction::FPExt: Out << "FPExtInst"; break;
1365 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1366 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1367 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1368 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1369 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1370 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1371 case Instruction::BitCast: Out << "BitCastInst"; break;
Craig Topperbc219812012-02-07 02:50:20 +00001372 default: llvm_unreachable("Unreachable");
Chris Lattner7e6d7452010-06-21 23:12:56 +00001373 }
1374 Out << "(" << opNames[0] << ", "
1375 << getCppName(cst->getType()) << ", \"";
1376 printEscapedString(cst->getName());
1377 Out << "\", " << bbname << ");";
1378 break;
1379 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001380 case Instruction::Call: {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001381 const CallInst* call = cast<CallInst>(I);
1382 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1383 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1384 << getCppName(ila->getFunctionType()) << ", \""
1385 << ila->getAsmString() << "\", \""
1386 << ila->getConstraintString() << "\","
1387 << (ila->hasSideEffects() ? "true" : "false") << ");";
1388 nl(Out);
1389 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001390 if (call->getNumArgOperands() > 1) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001391 Out << "std::vector<Value*> " << iName << "_params;";
1392 nl(Out);
Gabor Greif53ba5502010-07-02 19:08:46 +00001393 for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
Gabor Greif63d024f2010-07-13 15:31:36 +00001394 Out << iName << "_params.push_back(" << opNames[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001395 nl(Out);
1396 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001397 Out << "CallInst* " << iName << " = CallInst::Create("
Gabor Greifa3997812010-07-22 10:37:47 +00001398 << opNames[call->getNumArgOperands()] << ", "
Nicolas Geoffraya056d202011-07-21 20:59:21 +00001399 << iName << "_params, \"";
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001400 } else if (call->getNumArgOperands() == 1) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001401 Out << "CallInst* " << iName << " = CallInst::Create("
Gabor Greif63d024f2010-07-13 15:31:36 +00001402 << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001403 } else {
Gabor Greif63d024f2010-07-13 15:31:36 +00001404 Out << "CallInst* " << iName << " = CallInst::Create("
1405 << opNames[call->getNumArgOperands()] << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001406 }
1407 printEscapedString(call->getName());
1408 Out << "\", " << bbname << ");";
1409 nl(Out) << iName << "->setCallingConv(";
1410 printCallingConv(call->getCallingConv());
1411 Out << ");";
1412 nl(Out) << iName << "->setTailCall("
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001413 << (call->isTailCall() ? "true" : "false");
Chris Lattner7e6d7452010-06-21 23:12:56 +00001414 Out << ");";
Gabor Greif135d7fe2010-07-02 19:26:28 +00001415 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001416 printAttributes(call->getAttributes(), iName);
1417 Out << iName << "->setAttributes(" << iName << "_PAL);";
1418 nl(Out);
1419 break;
1420 }
1421 case Instruction::Select: {
1422 const SelectInst* sel = cast<SelectInst>(I);
1423 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1424 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1425 printEscapedString(sel->getName());
1426 Out << "\", " << bbname << ");";
1427 break;
1428 }
1429 case Instruction::UserOp1:
1430 /// FALL THROUGH
1431 case Instruction::UserOp2: {
1432 /// FIXME: What should be done here?
1433 break;
1434 }
1435 case Instruction::VAArg: {
1436 const VAArgInst* va = cast<VAArgInst>(I);
1437 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1438 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1439 printEscapedString(va->getName());
1440 Out << "\", " << bbname << ");";
1441 break;
1442 }
1443 case Instruction::ExtractElement: {
1444 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1445 Out << "ExtractElementInst* " << getCppName(eei)
1446 << " = new ExtractElementInst(" << opNames[0]
1447 << ", " << opNames[1] << ", \"";
1448 printEscapedString(eei->getName());
1449 Out << "\", " << bbname << ");";
1450 break;
1451 }
1452 case Instruction::InsertElement: {
1453 const InsertElementInst* iei = cast<InsertElementInst>(I);
1454 Out << "InsertElementInst* " << getCppName(iei)
1455 << " = InsertElementInst::Create(" << opNames[0]
1456 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1457 printEscapedString(iei->getName());
1458 Out << "\", " << bbname << ");";
1459 break;
1460 }
1461 case Instruction::ShuffleVector: {
1462 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1463 Out << "ShuffleVectorInst* " << getCppName(svi)
1464 << " = new ShuffleVectorInst(" << opNames[0]
1465 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1466 printEscapedString(svi->getName());
1467 Out << "\", " << bbname << ");";
1468 break;
1469 }
1470 case Instruction::ExtractValue: {
1471 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1472 Out << "std::vector<unsigned> " << iName << "_indices;";
1473 nl(Out);
1474 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1475 Out << iName << "_indices.push_back("
1476 << evi->idx_begin()[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001477 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001478 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001479 Out << "ExtractValueInst* " << getCppName(evi)
1480 << " = ExtractValueInst::Create(" << opNames[0]
1481 << ", "
Nick Lewycky3bca1012011-09-05 18:50:59 +00001482 << iName << "_indices, \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001483 printEscapedString(evi->getName());
1484 Out << "\", " << bbname << ");";
1485 break;
1486 }
1487 case Instruction::InsertValue: {
1488 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1489 Out << "std::vector<unsigned> " << iName << "_indices;";
1490 nl(Out);
1491 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1492 Out << iName << "_indices.push_back("
1493 << ivi->idx_begin()[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001494 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001495 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001496 Out << "InsertValueInst* " << getCppName(ivi)
1497 << " = InsertValueInst::Create(" << opNames[0]
1498 << ", " << opNames[1] << ", "
Nick Lewycky3bca1012011-09-05 18:50:59 +00001499 << iName << "_indices, \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001500 printEscapedString(ivi->getName());
1501 Out << "\", " << bbname << ");";
1502 break;
1503 }
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001504 case Instruction::Fence: {
1505 const FenceInst *fi = cast<FenceInst>(I);
1506 StringRef Ordering = ConvertAtomicOrdering(fi->getOrdering());
1507 StringRef CrossThread = ConvertAtomicSynchScope(fi->getSynchScope());
1508 Out << "FenceInst* " << iName
1509 << " = new FenceInst(mod->getContext(), "
Eli Friedman5b7cc332011-11-04 17:29:35 +00001510 << Ordering << ", " << CrossThread << ", " << bbname
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001511 << ");";
1512 break;
1513 }
1514 case Instruction::AtomicCmpXchg: {
1515 const AtomicCmpXchgInst *cxi = cast<AtomicCmpXchgInst>(I);
1516 StringRef Ordering = ConvertAtomicOrdering(cxi->getOrdering());
1517 StringRef CrossThread = ConvertAtomicSynchScope(cxi->getSynchScope());
1518 Out << "AtomicCmpXchgInst* " << iName
1519 << " = new AtomicCmpXchgInst("
1520 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", "
Eli Friedman5b7cc332011-11-04 17:29:35 +00001521 << Ordering << ", " << CrossThread << ", " << bbname
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001522 << ");";
1523 nl(Out) << iName << "->setName(\"";
1524 printEscapedString(cxi->getName());
1525 Out << "\");";
1526 break;
1527 }
1528 case Instruction::AtomicRMW: {
1529 const AtomicRMWInst *rmwi = cast<AtomicRMWInst>(I);
1530 StringRef Ordering = ConvertAtomicOrdering(rmwi->getOrdering());
1531 StringRef CrossThread = ConvertAtomicSynchScope(rmwi->getSynchScope());
1532 StringRef Operation;
1533 switch (rmwi->getOperation()) {
1534 case AtomicRMWInst::Xchg: Operation = "AtomicRMWInst::Xchg"; break;
1535 case AtomicRMWInst::Add: Operation = "AtomicRMWInst::Add"; break;
1536 case AtomicRMWInst::Sub: Operation = "AtomicRMWInst::Sub"; break;
1537 case AtomicRMWInst::And: Operation = "AtomicRMWInst::And"; break;
1538 case AtomicRMWInst::Nand: Operation = "AtomicRMWInst::Nand"; break;
1539 case AtomicRMWInst::Or: Operation = "AtomicRMWInst::Or"; break;
1540 case AtomicRMWInst::Xor: Operation = "AtomicRMWInst::Xor"; break;
1541 case AtomicRMWInst::Max: Operation = "AtomicRMWInst::Max"; break;
1542 case AtomicRMWInst::Min: Operation = "AtomicRMWInst::Min"; break;
1543 case AtomicRMWInst::UMax: Operation = "AtomicRMWInst::UMax"; break;
1544 case AtomicRMWInst::UMin: Operation = "AtomicRMWInst::UMin"; break;
1545 case AtomicRMWInst::BAD_BINOP: llvm_unreachable("Bad atomic operation");
1546 }
1547 Out << "AtomicRMWInst* " << iName
1548 << " = new AtomicRMWInst("
1549 << Operation << ", "
1550 << opNames[0] << ", " << opNames[1] << ", "
Eli Friedman5b7cc332011-11-04 17:29:35 +00001551 << Ordering << ", " << CrossThread << ", " << bbname
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001552 << ");";
1553 nl(Out) << iName << "->setName(\"";
1554 printEscapedString(rmwi->getName());
1555 Out << "\");";
1556 break;
1557 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001558 }
1559 DefinedValues.insert(I);
1560 nl(Out);
1561 delete [] opNames;
1562}
1563
Chris Lattner7e6d7452010-06-21 23:12:56 +00001564// Print out the types, constants and declarations needed by one function
1565void CppWriter::printFunctionUses(const Function* F) {
1566 nl(Out) << "// Type Definitions"; nl(Out);
1567 if (!is_inline) {
1568 // Print the function's return type
1569 printType(F->getReturnType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001570
Chris Lattner7e6d7452010-06-21 23:12:56 +00001571 // Print the function's function type
1572 printType(F->getFunctionType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001573
Chris Lattner7e6d7452010-06-21 23:12:56 +00001574 // Print the types of each of the function's arguments
Anton Korobeynikov50276522008-04-23 22:29:24 +00001575 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1576 AI != AE; ++AI) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001577 printType(AI->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001578 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001579 }
1580
Chris Lattner7e6d7452010-06-21 23:12:56 +00001581 // Print type definitions for every type referenced by an instruction and
1582 // make a note of any global values or constants that are referenced
1583 SmallPtrSet<GlobalValue*,64> gvs;
1584 SmallPtrSet<Constant*,64> consts;
1585 for (Function::const_iterator BB = F->begin(), BE = F->end();
1586 BB != BE; ++BB){
1587 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
Anton Korobeynikov50276522008-04-23 22:29:24 +00001588 I != E; ++I) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001589 // Print the type of the instruction itself
1590 printType(I->getType());
1591
1592 // Print the type of each of the instruction's operands
1593 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1594 Value* operand = I->getOperand(i);
1595 printType(operand->getType());
1596
1597 // If the operand references a GVal or Constant, make a note of it
1598 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1599 gvs.insert(GV);
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001600 if (GenerationType != GenFunction)
1601 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1602 if (GVar->hasInitializer())
1603 consts.insert(GVar->getInitializer());
1604 } else if (Constant* C = dyn_cast<Constant>(operand)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001605 consts.insert(C);
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001606 for (unsigned j = 0; j < C->getNumOperands(); ++j) {
1607 // If the operand references a GVal or Constant, make a note of it
1608 Value* operand = C->getOperand(j);
1609 printType(operand->getType());
1610 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1611 gvs.insert(GV);
1612 if (GenerationType != GenFunction)
1613 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1614 if (GVar->hasInitializer())
1615 consts.insert(GVar->getInitializer());
1616 }
1617 }
1618 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001619 }
1620 }
1621 }
1622
1623 // Print the function declarations for any functions encountered
1624 nl(Out) << "// Function Declarations"; nl(Out);
1625 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1626 I != E; ++I) {
1627 if (Function* Fun = dyn_cast<Function>(*I)) {
1628 if (!is_inline || Fun != F)
1629 printFunctionHead(Fun);
1630 }
1631 }
1632
1633 // Print the global variable declarations for any variables encountered
1634 nl(Out) << "// Global Variable Declarations"; nl(Out);
1635 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1636 I != E; ++I) {
1637 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1638 printVariableHead(F);
1639 }
1640
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001641 // Print the constants found
Chris Lattner7e6d7452010-06-21 23:12:56 +00001642 nl(Out) << "// Constant Definitions"; nl(Out);
1643 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1644 E = consts.end(); I != E; ++I) {
1645 printConstant(*I);
1646 }
1647
1648 // Process the global variables definitions now that all the constants have
1649 // been emitted. These definitions just couple the gvars with their constant
1650 // initializers.
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001651 if (GenerationType != GenFunction) {
1652 nl(Out) << "// Global Variable Definitions"; nl(Out);
1653 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1654 I != E; ++I) {
1655 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1656 printVariableBody(GV);
1657 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001658 }
1659}
1660
1661void CppWriter::printFunctionHead(const Function* F) {
1662 nl(Out) << "Function* " << getCppName(F);
Nicolas Geoffrayf8557952011-10-08 11:56:36 +00001663 Out << " = mod->getFunction(\"";
1664 printEscapedString(F->getName());
1665 Out << "\");";
1666 nl(Out) << "if (!" << getCppName(F) << ") {";
1667 nl(Out) << getCppName(F);
1668
Chris Lattner7e6d7452010-06-21 23:12:56 +00001669 Out<< " = Function::Create(";
1670 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1671 nl(Out) << "/*Linkage=*/";
1672 printLinkageType(F->getLinkage());
1673 Out << ",";
1674 nl(Out) << "/*Name=*/\"";
1675 printEscapedString(F->getName());
1676 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1677 nl(Out,-1);
1678 printCppName(F);
1679 Out << "->setCallingConv(";
1680 printCallingConv(F->getCallingConv());
1681 Out << ");";
1682 nl(Out);
1683 if (F->hasSection()) {
1684 printCppName(F);
1685 Out << "->setSection(\"" << F->getSection() << "\");";
1686 nl(Out);
1687 }
1688 if (F->getAlignment()) {
1689 printCppName(F);
1690 Out << "->setAlignment(" << F->getAlignment() << ");";
1691 nl(Out);
1692 }
1693 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1694 printCppName(F);
1695 Out << "->setVisibility(";
1696 printVisibilityType(F->getVisibility());
1697 Out << ");";
1698 nl(Out);
1699 }
1700 if (F->hasGC()) {
1701 printCppName(F);
1702 Out << "->setGC(\"" << F->getGC() << "\");";
1703 nl(Out);
1704 }
Nicolas Geoffrayf8557952011-10-08 11:56:36 +00001705 Out << "}";
1706 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001707 printAttributes(F->getAttributes(), getCppName(F));
1708 printCppName(F);
1709 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1710 nl(Out);
1711}
1712
1713void CppWriter::printFunctionBody(const Function *F) {
1714 if (F->isDeclaration())
1715 return; // external functions have no bodies.
1716
1717 // Clear the DefinedValues and ForwardRefs maps because we can't have
1718 // cross-function forward refs
1719 ForwardRefs.clear();
1720 DefinedValues.clear();
1721
1722 // Create all the argument values
1723 if (!is_inline) {
1724 if (!F->arg_empty()) {
1725 Out << "Function::arg_iterator args = " << getCppName(F)
1726 << "->arg_begin();";
1727 nl(Out);
1728 }
1729 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1730 AI != AE; ++AI) {
1731 Out << "Value* " << getCppName(AI) << " = args++;";
1732 nl(Out);
1733 if (AI->hasName()) {
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001734 Out << getCppName(AI) << "->setName(\"";
1735 printEscapedString(AI->getName());
1736 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001737 nl(Out);
1738 }
1739 }
1740 }
1741
Chris Lattner7e6d7452010-06-21 23:12:56 +00001742 // Create all the basic blocks
1743 nl(Out);
1744 for (Function::const_iterator BI = F->begin(), BE = F->end();
1745 BI != BE; ++BI) {
1746 std::string bbname(getCppName(BI));
1747 Out << "BasicBlock* " << bbname <<
1748 " = BasicBlock::Create(mod->getContext(), \"";
1749 if (BI->hasName())
1750 printEscapedString(BI->getName());
1751 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1752 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001753 }
1754
Chris Lattner7e6d7452010-06-21 23:12:56 +00001755 // Output all of its basic blocks... for the function
1756 for (Function::const_iterator BI = F->begin(), BE = F->end();
1757 BI != BE; ++BI) {
1758 std::string bbname(getCppName(BI));
1759 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001760 nl(Out);
1761
Chris Lattner7e6d7452010-06-21 23:12:56 +00001762 // Output all of the instructions in the basic block...
1763 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1764 I != E; ++I) {
1765 printInstruction(I,bbname);
1766 }
1767 }
1768
1769 // Loop over the ForwardRefs and resolve them now that all instructions
1770 // are generated.
1771 if (!ForwardRefs.empty()) {
1772 nl(Out) << "// Resolve Forward References";
1773 nl(Out);
1774 }
1775
1776 while (!ForwardRefs.empty()) {
1777 ForwardRefMap::iterator I = ForwardRefs.begin();
1778 Out << I->second << "->replaceAllUsesWith("
1779 << getCppName(I->first) << "); delete " << I->second << ";";
1780 nl(Out);
1781 ForwardRefs.erase(I);
1782 }
1783}
1784
1785void CppWriter::printInline(const std::string& fname,
1786 const std::string& func) {
1787 const Function* F = TheModule->getFunction(func);
1788 if (!F) {
1789 error(std::string("Function '") + func + "' not found in input module");
1790 return;
1791 }
1792 if (F->isDeclaration()) {
1793 error(std::string("Function '") + func + "' is external!");
1794 return;
1795 }
1796 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1797 << getCppName(F);
1798 unsigned arg_count = 1;
1799 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1800 AI != AE; ++AI) {
1801 Out << ", Value* arg_" << arg_count;
1802 }
1803 Out << ") {";
1804 nl(Out);
1805 is_inline = true;
1806 printFunctionUses(F);
1807 printFunctionBody(F);
1808 is_inline = false;
1809 Out << "return " << getCppName(F->begin()) << ";";
1810 nl(Out) << "}";
1811 nl(Out);
1812}
1813
1814void CppWriter::printModuleBody() {
1815 // Print out all the type definitions
1816 nl(Out) << "// Type Definitions"; nl(Out);
1817 printTypes(TheModule);
1818
1819 // Functions can call each other and global variables can reference them so
1820 // define all the functions first before emitting their function bodies.
1821 nl(Out) << "// Function Declarations"; nl(Out);
1822 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1823 I != E; ++I)
1824 printFunctionHead(I);
1825
1826 // Process the global variables declarations. We can't initialze them until
1827 // after the constants are printed so just print a header for each global
1828 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1829 for (Module::const_global_iterator I = TheModule->global_begin(),
1830 E = TheModule->global_end(); I != E; ++I) {
1831 printVariableHead(I);
1832 }
1833
1834 // Print out all the constants definitions. Constants don't recurse except
1835 // through GlobalValues. All GlobalValues have been declared at this point
1836 // so we can proceed to generate the constants.
1837 nl(Out) << "// Constant Definitions"; nl(Out);
1838 printConstants(TheModule);
1839
1840 // Process the global variables definitions now that all the constants have
1841 // been emitted. These definitions just couple the gvars with their constant
1842 // initializers.
1843 nl(Out) << "// Global Variable Definitions"; nl(Out);
1844 for (Module::const_global_iterator I = TheModule->global_begin(),
1845 E = TheModule->global_end(); I != E; ++I) {
1846 printVariableBody(I);
1847 }
1848
1849 // Finally, we can safely put out all of the function bodies.
1850 nl(Out) << "// Function Definitions"; nl(Out);
1851 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1852 I != E; ++I) {
1853 if (!I->isDeclaration()) {
1854 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1855 << ")";
1856 nl(Out) << "{";
1857 nl(Out,1);
1858 printFunctionBody(I);
1859 nl(Out,-1) << "}";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001860 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001861 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001862 }
1863}
1864
1865void CppWriter::printProgram(const std::string& fname,
1866 const std::string& mName) {
1867 Out << "#include <llvm/LLVMContext.h>\n";
1868 Out << "#include <llvm/Module.h>\n";
1869 Out << "#include <llvm/DerivedTypes.h>\n";
1870 Out << "#include <llvm/Constants.h>\n";
1871 Out << "#include <llvm/GlobalVariable.h>\n";
1872 Out << "#include <llvm/Function.h>\n";
1873 Out << "#include <llvm/CallingConv.h>\n";
1874 Out << "#include <llvm/BasicBlock.h>\n";
1875 Out << "#include <llvm/Instructions.h>\n";
1876 Out << "#include <llvm/InlineAsm.h>\n";
1877 Out << "#include <llvm/Support/FormattedStream.h>\n";
1878 Out << "#include <llvm/Support/MathExtras.h>\n";
1879 Out << "#include <llvm/Pass.h>\n";
1880 Out << "#include <llvm/PassManager.h>\n";
1881 Out << "#include <llvm/ADT/SmallVector.h>\n";
1882 Out << "#include <llvm/Analysis/Verifier.h>\n";
1883 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1884 Out << "#include <algorithm>\n";
1885 Out << "using namespace llvm;\n\n";
1886 Out << "Module* " << fname << "();\n\n";
1887 Out << "int main(int argc, char**argv) {\n";
1888 Out << " Module* Mod = " << fname << "();\n";
1889 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1890 Out << " PassManager PM;\n";
1891 Out << " PM.add(createPrintModulePass(&outs()));\n";
1892 Out << " PM.run(*Mod);\n";
1893 Out << " return 0;\n";
1894 Out << "}\n\n";
1895 printModule(fname,mName);
1896}
1897
1898void CppWriter::printModule(const std::string& fname,
1899 const std::string& mName) {
1900 nl(Out) << "Module* " << fname << "() {";
1901 nl(Out,1) << "// Module Construction";
1902 nl(Out) << "Module* mod = new Module(\"";
1903 printEscapedString(mName);
1904 Out << "\", getGlobalContext());";
1905 if (!TheModule->getTargetTriple().empty()) {
1906 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1907 }
1908 if (!TheModule->getTargetTriple().empty()) {
1909 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1910 << "\");";
1911 }
1912
1913 if (!TheModule->getModuleInlineAsm().empty()) {
1914 nl(Out) << "mod->setModuleInlineAsm(\"";
1915 printEscapedString(TheModule->getModuleInlineAsm());
1916 Out << "\");";
1917 }
1918 nl(Out);
1919
1920 // Loop over the dependent libraries and emit them.
1921 Module::lib_iterator LI = TheModule->lib_begin();
1922 Module::lib_iterator LE = TheModule->lib_end();
1923 while (LI != LE) {
1924 Out << "mod->addLibrary(\"" << *LI << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001925 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001926 ++LI;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001927 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001928 printModuleBody();
1929 nl(Out) << "return mod;";
1930 nl(Out,-1) << "}";
1931 nl(Out);
1932}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001933
Chris Lattner7e6d7452010-06-21 23:12:56 +00001934void CppWriter::printContents(const std::string& fname,
1935 const std::string& mName) {
1936 Out << "\nModule* " << fname << "(Module *mod) {\n";
1937 Out << "\nmod->setModuleIdentifier(\"";
1938 printEscapedString(mName);
1939 Out << "\");\n";
1940 printModuleBody();
1941 Out << "\nreturn mod;\n";
1942 Out << "\n}\n";
1943}
1944
1945void CppWriter::printFunction(const std::string& fname,
1946 const std::string& funcName) {
1947 const Function* F = TheModule->getFunction(funcName);
1948 if (!F) {
1949 error(std::string("Function '") + funcName + "' not found in input module");
1950 return;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001951 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001952 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1953 printFunctionUses(F);
1954 printFunctionHead(F);
1955 printFunctionBody(F);
1956 Out << "return " << getCppName(F) << ";\n";
1957 Out << "}\n";
1958}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001959
Chris Lattner7e6d7452010-06-21 23:12:56 +00001960void CppWriter::printFunctions() {
1961 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1962 Module::const_iterator I = funcs.begin();
1963 Module::const_iterator IE = funcs.end();
Anton Korobeynikov50276522008-04-23 22:29:24 +00001964
Chris Lattner7e6d7452010-06-21 23:12:56 +00001965 for (; I != IE; ++I) {
1966 const Function &func = *I;
1967 if (!func.isDeclaration()) {
1968 std::string name("define_");
1969 name += func.getName();
1970 printFunction(name, func.getName());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001971 }
1972 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001973}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001974
Chris Lattner7e6d7452010-06-21 23:12:56 +00001975void CppWriter::printVariable(const std::string& fname,
1976 const std::string& varName) {
1977 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001978
Chris Lattner7e6d7452010-06-21 23:12:56 +00001979 if (!GV) {
1980 error(std::string("Variable '") + varName + "' not found in input module");
1981 return;
1982 }
1983 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1984 printVariableUses(GV);
1985 printVariableHead(GV);
1986 printVariableBody(GV);
1987 Out << "return " << getCppName(GV) << ";\n";
1988 Out << "}\n";
1989}
1990
Chris Lattner1afcace2011-07-09 17:41:24 +00001991void CppWriter::printType(const std::string &fname,
1992 const std::string &typeName) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001993 Type* Ty = TheModule->getTypeByName(typeName);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001994 if (!Ty) {
1995 error(std::string("Type '") + typeName + "' not found in input module");
1996 return;
1997 }
1998 Out << "\nType* " << fname << "(Module *mod) {\n";
1999 printType(Ty);
2000 Out << "return " << getCppName(Ty) << ";\n";
2001 Out << "}\n";
2002}
2003
2004bool CppWriter::runOnModule(Module &M) {
2005 TheModule = &M;
2006
2007 // Emit a header
2008 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
2009
2010 // Get the name of the function we're supposed to generate
2011 std::string fname = FuncName.getValue();
2012
2013 // Get the name of the thing we are to generate
2014 std::string tgtname = NameToGenerate.getValue();
2015 if (GenerationType == GenModule ||
2016 GenerationType == GenContents ||
2017 GenerationType == GenProgram ||
2018 GenerationType == GenFunctions) {
2019 if (tgtname == "!bad!") {
2020 if (M.getModuleIdentifier() == "-")
2021 tgtname = "<stdin>";
2022 else
2023 tgtname = M.getModuleIdentifier();
Anton Korobeynikov50276522008-04-23 22:29:24 +00002024 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00002025 } else if (tgtname == "!bad!")
2026 error("You must use the -for option with -gen-{function,variable,type}");
2027
2028 switch (WhatToGenerate(GenerationType)) {
2029 case GenProgram:
2030 if (fname.empty())
2031 fname = "makeLLVMModule";
2032 printProgram(fname,tgtname);
2033 break;
2034 case GenModule:
2035 if (fname.empty())
2036 fname = "makeLLVMModule";
2037 printModule(fname,tgtname);
2038 break;
2039 case GenContents:
2040 if (fname.empty())
2041 fname = "makeLLVMModuleContents";
2042 printContents(fname,tgtname);
2043 break;
2044 case GenFunction:
2045 if (fname.empty())
2046 fname = "makeLLVMFunction";
2047 printFunction(fname,tgtname);
2048 break;
2049 case GenFunctions:
2050 printFunctions();
2051 break;
2052 case GenInline:
2053 if (fname.empty())
2054 fname = "makeLLVMInline";
2055 printInline(fname,tgtname);
2056 break;
2057 case GenVariable:
2058 if (fname.empty())
2059 fname = "makeLLVMVariable";
2060 printVariable(fname,tgtname);
2061 break;
2062 case GenType:
2063 if (fname.empty())
2064 fname = "makeLLVMType";
2065 printType(fname,tgtname);
2066 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002067 }
2068
Chris Lattner7e6d7452010-06-21 23:12:56 +00002069 return false;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002070}
2071
2072char CppWriter::ID = 0;
2073
2074//===----------------------------------------------------------------------===//
2075// External Interface declaration
2076//===----------------------------------------------------------------------===//
2077
Dan Gohman99dca4f2010-05-11 19:57:55 +00002078bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
2079 formatted_raw_ostream &o,
2080 CodeGenFileType FileType,
Dan Gohman99dca4f2010-05-11 19:57:55 +00002081 bool DisableVerify) {
Chris Lattner211edae2010-02-02 21:06:45 +00002082 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002083 PM.add(new CppWriter(o));
2084 return false;
2085}