blob: f46886143423aed13c6e866487e8748e15f9c3af [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"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "llvm/ADT/SmallPtrSet.h"
17#include "llvm/ADT/StringExtras.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/Config/config.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000019#include "llvm/IR/CallingConv.h"
20#include "llvm/IR/Constants.h"
21#include "llvm/IR/DerivedTypes.h"
22#include "llvm/IR/InlineAsm.h"
23#include "llvm/IR/Instruction.h"
24#include "llvm/IR/Instructions.h"
25#include "llvm/IR/Module.h"
Evan Cheng1abf2cb2011-07-14 23:50:31 +000026#include "llvm/MC/MCAsmInfo.h"
Evan Cheng59ee62d2011-07-11 03:57:24 +000027#include "llvm/MC/MCInstrInfo.h"
Evan Chengffc0e732011-07-09 05:47:46 +000028#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000029#include "llvm/Pass.h"
30#include "llvm/PassManager.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000031#include "llvm/Support/CommandLine.h"
Torok Edwin30464702009-07-08 20:55:50 +000032#include "llvm/Support/ErrorHandling.h"
David Greene71847812009-07-14 20:18:05 +000033#include "llvm/Support/FormattedStream.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000034#include "llvm/Support/TargetRegistry.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000035#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);
Hans Wennborgce718ff2012-06-23 11:37:03 +0000133 void printThreadLocalMode(GlobalVariable::ThreadLocalMode TLM);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +0000134 void printCallingConv(CallingConv::ID cc);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000135 void printEscapedString(const std::string& str);
136 void printCFP(const ConstantFP* CFP);
137
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000138 std::string getCppName(Type* val);
139 inline void printCppName(Type* val);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000140
141 std::string getCppName(const Value* val);
142 inline void printCppName(const Value* val);
143
Bill Wendling99faa3b2012-12-07 23:16:57 +0000144 void printAttributes(const AttributeSet &PAL, const std::string &name);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000145 void printType(Type* Ty);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000146 void printTypes(const Module* M);
147
148 void printConstant(const Constant *CPV);
149 void printConstants(const Module* M);
150
151 void printVariableUses(const GlobalVariable *GV);
152 void printVariableHead(const GlobalVariable *GV);
153 void printVariableBody(const GlobalVariable *GV);
154
155 void printFunctionUses(const Function *F);
156 void printFunctionHead(const Function *F);
157 void printFunctionBody(const Function *F);
158 void printInstruction(const Instruction *I, const std::string& bbname);
Eli Friedmanbb5a7442011-09-29 20:21:17 +0000159 std::string getOpName(const Value*);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000160
161 void printModuleBody();
162 };
Chris Lattner7e6d7452010-06-21 23:12:56 +0000163} // end anonymous namespace.
Anton Korobeynikov50276522008-04-23 22:29:24 +0000164
Chris Lattner1018c242010-06-21 23:14:47 +0000165formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
166 Out << '\n';
Chris Lattner7e6d7452010-06-21 23:12:56 +0000167 if (delta >= 0 || indent_level >= unsigned(-delta))
168 indent_level += delta;
Chris Lattner1018c242010-06-21 23:14:47 +0000169 Out.indent(indent_level);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000170 return Out;
171}
172
Chris Lattner7e6d7452010-06-21 23:12:56 +0000173static inline void sanitize(std::string &str) {
174 for (size_t i = 0; i < str.length(); ++i)
175 if (!isalnum(str[i]) && str[i] != '_')
176 str[i] = '_';
177}
178
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000179static std::string getTypePrefix(Type *Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000180 switch (Ty->getTypeID()) {
181 case Type::VoidTyID: return "void_";
182 case Type::IntegerTyID:
183 return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
184 case Type::FloatTyID: return "float_";
185 case Type::DoubleTyID: return "double_";
186 case Type::LabelTyID: return "label_";
187 case Type::FunctionTyID: return "func_";
188 case Type::StructTyID: return "struct_";
189 case Type::ArrayTyID: return "array_";
190 case Type::PointerTyID: return "ptr_";
191 case Type::VectorTyID: return "packed_";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000192 default: return "other_";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000193 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000194}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000195
Chris Lattner7e6d7452010-06-21 23:12:56 +0000196void CppWriter::error(const std::string& msg) {
197 report_fatal_error(msg);
198}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000199
Benjamin Kramere68e7752012-03-23 11:26:29 +0000200static inline std::string ftostr(const APFloat& V) {
201 std::string Buf;
202 if (&V.getSemantics() == &APFloat::IEEEdouble) {
203 raw_string_ostream(Buf) << V.convertToDouble();
204 return Buf;
205 } else if (&V.getSemantics() == &APFloat::IEEEsingle) {
206 raw_string_ostream(Buf) << (double)V.convertToFloat();
207 return Buf;
208 }
209 return "<unknown format in ftostr>"; // error
210}
211
Chris Lattner7e6d7452010-06-21 23:12:56 +0000212// printCFP - Print a floating point constant .. very carefully :)
213// This makes sure that conversion to/from floating yields the same binary
214// result so that we don't lose precision.
215void CppWriter::printCFP(const ConstantFP *CFP) {
216 bool ignored;
217 APFloat APF = APFloat(CFP->getValueAPF()); // copy
218 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
219 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
220 Out << "ConstantFP::get(mod->getContext(), ";
221 Out << "APFloat(";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000222#if HAVE_PRINTF_A
Chris Lattner7e6d7452010-06-21 23:12:56 +0000223 char Buffer[100];
224 sprintf(Buffer, "%A", APF.convertToDouble());
225 if ((!strncmp(Buffer, "0x", 2) ||
226 !strncmp(Buffer, "-0x", 3) ||
227 !strncmp(Buffer, "+0x", 3)) &&
228 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
229 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
230 Out << "BitsToDouble(" << Buffer << ")";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000231 else
Chris Lattner7e6d7452010-06-21 23:12:56 +0000232 Out << "BitsToFloat((float)" << Buffer << ")";
233 Out << ")";
234 } else {
235#endif
236 std::string StrVal = ftostr(CFP->getValueAPF());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000237
Chris Lattner7e6d7452010-06-21 23:12:56 +0000238 while (StrVal[0] == ' ')
239 StrVal.erase(StrVal.begin());
240
241 // Check to make sure that the stringized number is not some string like
242 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
243 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
244 ((StrVal[0] == '-' || StrVal[0] == '+') &&
245 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
246 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
247 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
248 Out << StrVal;
249 else
250 Out << StrVal << "f";
251 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
252 Out << "BitsToDouble(0x"
253 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
254 << "ULL) /* " << StrVal << " */";
255 else
256 Out << "BitsToFloat(0x"
257 << utohexstr((uint32_t)CFP->getValueAPF().
258 bitcastToAPInt().getZExtValue())
259 << "U) /* " << StrVal << " */";
260 Out << ")";
261#if HAVE_PRINTF_A
262 }
263#endif
264 Out << ")";
265}
266
267void CppWriter::printCallingConv(CallingConv::ID cc){
268 // Print the calling convention.
269 switch (cc) {
270 case CallingConv::C: Out << "CallingConv::C"; break;
271 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
272 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
273 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
274 default: Out << cc; break;
275 }
276}
277
278void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
279 switch (LT) {
280 case GlobalValue::InternalLinkage:
281 Out << "GlobalValue::InternalLinkage"; break;
282 case GlobalValue::PrivateLinkage:
283 Out << "GlobalValue::PrivateLinkage"; break;
284 case GlobalValue::LinkerPrivateLinkage:
285 Out << "GlobalValue::LinkerPrivateLinkage"; break;
Bill Wendling5e721d72010-07-01 21:55:59 +0000286 case GlobalValue::LinkerPrivateWeakLinkage:
287 Out << "GlobalValue::LinkerPrivateWeakLinkage"; break;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000288 case GlobalValue::AvailableExternallyLinkage:
289 Out << "GlobalValue::AvailableExternallyLinkage "; break;
290 case GlobalValue::LinkOnceAnyLinkage:
291 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
292 case GlobalValue::LinkOnceODRLinkage:
293 Out << "GlobalValue::LinkOnceODRLinkage "; break;
Bill Wendling32811be2012-08-17 18:33:14 +0000294 case GlobalValue::LinkOnceODRAutoHideLinkage:
295 Out << "GlobalValue::LinkOnceODRAutoHideLinkage"; break;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000296 case GlobalValue::WeakAnyLinkage:
297 Out << "GlobalValue::WeakAnyLinkage"; break;
298 case GlobalValue::WeakODRLinkage:
299 Out << "GlobalValue::WeakODRLinkage"; break;
300 case GlobalValue::AppendingLinkage:
301 Out << "GlobalValue::AppendingLinkage"; break;
302 case GlobalValue::ExternalLinkage:
303 Out << "GlobalValue::ExternalLinkage"; break;
304 case GlobalValue::DLLImportLinkage:
305 Out << "GlobalValue::DLLImportLinkage"; break;
306 case GlobalValue::DLLExportLinkage:
307 Out << "GlobalValue::DLLExportLinkage"; break;
308 case GlobalValue::ExternalWeakLinkage:
309 Out << "GlobalValue::ExternalWeakLinkage"; break;
310 case GlobalValue::CommonLinkage:
311 Out << "GlobalValue::CommonLinkage"; break;
312 }
313}
314
315void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
316 switch (VisType) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000317 case GlobalValue::DefaultVisibility:
318 Out << "GlobalValue::DefaultVisibility";
319 break;
320 case GlobalValue::HiddenVisibility:
321 Out << "GlobalValue::HiddenVisibility";
322 break;
323 case GlobalValue::ProtectedVisibility:
324 Out << "GlobalValue::ProtectedVisibility";
325 break;
326 }
327}
328
Hans Wennborgce718ff2012-06-23 11:37:03 +0000329void CppWriter::printThreadLocalMode(GlobalVariable::ThreadLocalMode TLM) {
330 switch (TLM) {
331 case GlobalVariable::NotThreadLocal:
332 Out << "GlobalVariable::NotThreadLocal";
333 break;
334 case GlobalVariable::GeneralDynamicTLSModel:
335 Out << "GlobalVariable::GeneralDynamicTLSModel";
336 break;
337 case GlobalVariable::LocalDynamicTLSModel:
338 Out << "GlobalVariable::LocalDynamicTLSModel";
339 break;
340 case GlobalVariable::InitialExecTLSModel:
341 Out << "GlobalVariable::InitialExecTLSModel";
342 break;
343 case GlobalVariable::LocalExecTLSModel:
344 Out << "GlobalVariable::LocalExecTLSModel";
345 break;
346 }
347}
348
Chris Lattner7e6d7452010-06-21 23:12:56 +0000349// printEscapedString - Print each character of the specified string, escaping
350// it if it is not printable or if it is an escape char.
351void CppWriter::printEscapedString(const std::string &Str) {
352 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
353 unsigned char C = Str[i];
354 if (isprint(C) && C != '"' && C != '\\') {
355 Out << C;
356 } else {
357 Out << "\\x"
358 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
359 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
360 }
361 }
362}
363
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000364std::string CppWriter::getCppName(Type* Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000365 // First, handle the primitive types .. easy
366 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
367 switch (Ty->getTypeID()) {
368 case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())";
369 case Type::IntegerTyID: {
370 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
371 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
372 }
373 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
374 case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())";
375 case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())";
376 case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())";
Dale Johannesenbb811a22010-09-10 20:55:01 +0000377 case Type::X86_MMXTyID: return "Type::getX86_MMXTy(mod->getContext())";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000378 default:
379 error("Invalid primitive type");
380 break;
381 }
382 // shouldn't be returned, but make it sensible
383 return "Type::getVoidTy(mod->getContext())";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000384 }
385
Chris Lattner7e6d7452010-06-21 23:12:56 +0000386 // Now, see if we've seen the type before and return that
387 TypeMap::iterator I = TypeNames.find(Ty);
388 if (I != TypeNames.end())
389 return I->second;
390
391 // Okay, let's build a new name for this type. Start with a prefix
392 const char* prefix = 0;
393 switch (Ty->getTypeID()) {
394 case Type::FunctionTyID: prefix = "FuncTy_"; break;
395 case Type::StructTyID: prefix = "StructTy_"; break;
396 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
397 case Type::PointerTyID: prefix = "PointerTy_"; break;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000398 case Type::VectorTyID: prefix = "VectorTy_"; break;
399 default: prefix = "OtherTy_"; break; // prevent breakage
Anton Korobeynikov50276522008-04-23 22:29:24 +0000400 }
401
Chris Lattner7e6d7452010-06-21 23:12:56 +0000402 // See if the type has a name in the symboltable and build accordingly
Chris Lattner7e6d7452010-06-21 23:12:56 +0000403 std::string name;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000404 if (StructType *STy = dyn_cast<StructType>(Ty))
Chris Lattner1afcace2011-07-09 17:41:24 +0000405 if (STy->hasName())
406 name = STy->getName();
407
408 if (name.empty())
409 name = utostr(uniqueNum++);
410
411 name = std::string(prefix) + name;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000412 sanitize(name);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000413
Chris Lattner7e6d7452010-06-21 23:12:56 +0000414 // Save the name
415 return TypeNames[Ty] = name;
416}
417
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000418void CppWriter::printCppName(Type* Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000419 printEscapedString(getCppName(Ty));
420}
421
422std::string CppWriter::getCppName(const Value* val) {
423 std::string name;
424 ValueMap::iterator I = ValueNames.find(val);
425 if (I != ValueNames.end() && I->first == val)
426 return I->second;
427
428 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
429 name = std::string("gvar_") +
430 getTypePrefix(GV->getType()->getElementType());
431 } else if (isa<Function>(val)) {
432 name = std::string("func_");
433 } else if (const Constant* C = dyn_cast<Constant>(val)) {
434 name = std::string("const_") + getTypePrefix(C->getType());
435 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
436 if (is_inline) {
437 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
438 Function::const_arg_iterator(Arg)) + 1;
439 name = std::string("arg_") + utostr(argNum);
440 NameSet::iterator NI = UsedNames.find(name);
441 if (NI != UsedNames.end())
442 name += std::string("_") + utostr(uniqueNum++);
443 UsedNames.insert(name);
444 return ValueNames[val] = name;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000445 } else {
446 name = getTypePrefix(val->getType());
447 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000448 } else {
449 name = getTypePrefix(val->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000450 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000451 if (val->hasName())
452 name += val->getName();
453 else
454 name += utostr(uniqueNum++);
455 sanitize(name);
456 NameSet::iterator NI = UsedNames.find(name);
457 if (NI != UsedNames.end())
458 name += std::string("_") + utostr(uniqueNum++);
459 UsedNames.insert(name);
460 return ValueNames[val] = name;
461}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000462
Chris Lattner7e6d7452010-06-21 23:12:56 +0000463void CppWriter::printCppName(const Value* val) {
464 printEscapedString(getCppName(val));
465}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000466
Bill Wendling99faa3b2012-12-07 23:16:57 +0000467void CppWriter::printAttributes(const AttributeSet &PAL,
Chris Lattner7e6d7452010-06-21 23:12:56 +0000468 const std::string &name) {
Bill Wendling99faa3b2012-12-07 23:16:57 +0000469 Out << "AttributeSet " << name << "_PAL;";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000470 nl(Out);
471 if (!PAL.isEmpty()) {
472 Out << '{'; in(); nl(Out);
473 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
474 Out << "AttributeWithIndex PAWI;"; nl(Out);
475 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
476 unsigned index = PAL.getSlot(i).Index;
Bill Wendling702cc912012-10-15 20:35:56 +0000477 AttrBuilder attrs(PAL.getSlot(i).Attrs);
Bill Wendling7d2f2492012-10-10 07:36:45 +0000478 Out << "PAWI.Index = " << index << "U;\n";
Nicolas Geoffray8b1b4132012-10-26 09:14:38 +0000479 Out << " {\n AttrBuilder B;\n";
Bill Wendling7d2f2492012-10-10 07:36:45 +0000480
481#define HANDLE_ATTR(X) \
Bill Wendling37766032012-12-30 09:17:46 +0000482 if (attrs.contains(Attribute::X)) \
Bill Wendling034b94b2012-12-19 07:18:57 +0000483 Out << " B.addAttribute(Attribute::" #X ");\n"; \
484 attrs.removeAttribute(Attribute::X);
Bill Wendling7d2f2492012-10-10 07:36:45 +0000485
Chris Lattner7e6d7452010-06-21 23:12:56 +0000486 HANDLE_ATTR(SExt);
487 HANDLE_ATTR(ZExt);
488 HANDLE_ATTR(NoReturn);
489 HANDLE_ATTR(InReg);
490 HANDLE_ATTR(StructRet);
491 HANDLE_ATTR(NoUnwind);
492 HANDLE_ATTR(NoAlias);
493 HANDLE_ATTR(ByVal);
494 HANDLE_ATTR(Nest);
495 HANDLE_ATTR(ReadNone);
496 HANDLE_ATTR(ReadOnly);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000497 HANDLE_ATTR(NoInline);
498 HANDLE_ATTR(AlwaysInline);
499 HANDLE_ATTR(OptimizeForSize);
500 HANDLE_ATTR(StackProtect);
501 HANDLE_ATTR(StackProtectReq);
502 HANDLE_ATTR(NoCapture);
Eli Friedman32bb4df2010-07-16 18:47:20 +0000503 HANDLE_ATTR(NoRedZone);
504 HANDLE_ATTR(NoImplicitFloat);
505 HANDLE_ATTR(Naked);
506 HANDLE_ATTR(InlineHint);
Rafael Espindola25456ef2011-10-03 14:45:37 +0000507 HANDLE_ATTR(ReturnsTwice);
Bill Wendling54f15362011-08-09 00:47:30 +0000508 HANDLE_ATTR(UWTable);
509 HANDLE_ATTR(NonLazyBind);
Quentin Colombet9a419f62012-10-30 16:32:52 +0000510 HANDLE_ATTR(MinSize);
Chris Lattneracca9552009-01-13 07:22:22 +0000511#undef HANDLE_ATTR
Bill Wendling37766032012-12-30 09:17:46 +0000512 if (attrs.contains(Attribute::StackAlignment))
Nicolas Geoffray8b1b4132012-10-26 09:14:38 +0000513 Out << " B.addStackAlignmentAttr(" << attrs.getStackAlignment() << ")\n";
Bill Wendling034b94b2012-12-19 07:18:57 +0000514 attrs.removeAttribute(Attribute::StackAlignment);
Bill Wendling7d2f2492012-10-10 07:36:45 +0000515 assert(!attrs.hasAttributes() && "Unhandled attribute!");
Bill Wendling034b94b2012-12-19 07:18:57 +0000516 Out << " PAWI.Attrs = Attribute::get(mod->getContext(), B);\n }";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000517 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000518 Out << "Attrs.push_back(PAWI);";
519 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000520 }
Bill Wendling99faa3b2012-12-07 23:16:57 +0000521 Out << name << "_PAL = AttributeSet::get(mod->getContext(), Attrs);";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000522 nl(Out);
523 out(); nl(Out);
524 Out << '}'; nl(Out);
525 }
526}
527
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000528void CppWriter::printType(Type* Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000529 // We don't print definitions for primitive types
530 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000531 return;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000532
533 // If we already defined this type, we don't need to define it again.
534 if (DefinedTypes.find(Ty) != DefinedTypes.end())
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000535 return;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000536
537 // Everything below needs the name for the type so get it now.
538 std::string typeName(getCppName(Ty));
539
Chris Lattner7e6d7452010-06-21 23:12:56 +0000540 // Print the type definition
541 switch (Ty->getTypeID()) {
542 case Type::FunctionTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000543 FunctionType* FT = cast<FunctionType>(Ty);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000544 Out << "std::vector<Type*>" << typeName << "_args;";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000545 nl(Out);
546 FunctionType::param_iterator PI = FT->param_begin();
547 FunctionType::param_iterator PE = FT->param_end();
548 for (; PI != PE; ++PI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000549 Type* argTy = static_cast<Type*>(*PI);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000550 printType(argTy);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000551 std::string argName(getCppName(argTy));
552 Out << typeName << "_args.push_back(" << argName;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000553 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000554 nl(Out);
555 }
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000556 printType(FT->getReturnType());
Chris Lattner7e6d7452010-06-21 23:12:56 +0000557 std::string retTypeName(getCppName(FT->getReturnType()));
558 Out << "FunctionType* " << typeName << " = FunctionType::get(";
559 in(); nl(Out) << "/*Result=*/" << retTypeName;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000560 Out << ",";
561 nl(Out) << "/*Params=*/" << typeName << "_args,";
562 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
563 out();
Anton Korobeynikov50276522008-04-23 22:29:24 +0000564 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000565 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000566 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000567 case Type::StructTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000568 StructType* ST = cast<StructType>(Ty);
Chris Lattnerc4d0e9f2011-08-12 18:07:07 +0000569 if (!ST->isLiteral()) {
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000570 Out << "StructType *" << typeName << " = mod->getTypeByName(\"";
571 printEscapedString(ST->getName());
572 Out << "\");";
573 nl(Out);
574 Out << "if (!" << typeName << ") {";
575 nl(Out);
576 Out << typeName << " = ";
Chris Lattnerc4d0e9f2011-08-12 18:07:07 +0000577 Out << "StructType::create(mod->getContext(), \"";
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000578 printEscapedString(ST->getName());
579 Out << "\");";
580 nl(Out);
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000581 Out << "}";
582 nl(Out);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000583 // Indicate that this type is now defined.
584 DefinedTypes.insert(Ty);
585 }
586
587 Out << "std::vector<Type*>" << typeName << "_fields;";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000588 nl(Out);
589 StructType::element_iterator EI = ST->element_begin();
590 StructType::element_iterator EE = ST->element_end();
591 for (; EI != EE; ++EI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000592 Type* fieldTy = static_cast<Type*>(*EI);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000593 printType(fieldTy);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000594 std::string fieldName(getCppName(fieldTy));
595 Out << typeName << "_fields.push_back(" << fieldName;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000596 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000597 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000598 }
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000599
Chris Lattnerc4d0e9f2011-08-12 18:07:07 +0000600 if (ST->isLiteral()) {
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000601 Out << "StructType *" << typeName << " = ";
Chris Lattner1afcace2011-07-09 17:41:24 +0000602 Out << "StructType::get(" << "mod->getContext(), ";
603 } else {
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000604 Out << "if (" << typeName << "->isOpaque()) {";
605 nl(Out);
Chris Lattner1afcace2011-07-09 17:41:24 +0000606 Out << typeName << "->setBody(";
607 }
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000608
Chris Lattner1afcace2011-07-09 17:41:24 +0000609 Out << typeName << "_fields, /*isPacked=*/"
Chris Lattner7e6d7452010-06-21 23:12:56 +0000610 << (ST->isPacked() ? "true" : "false") << ");";
611 nl(Out);
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000612 if (!ST->isLiteral()) {
613 Out << "}";
614 nl(Out);
615 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000616 break;
617 }
618 case Type::ArrayTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000619 ArrayType* AT = cast<ArrayType>(Ty);
620 Type* ET = AT->getElementType();
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000621 printType(ET);
622 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
623 std::string elemName(getCppName(ET));
624 Out << "ArrayType* " << typeName << " = ArrayType::get("
625 << elemName
626 << ", " << utostr(AT->getNumElements()) << ");";
627 nl(Out);
628 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000629 break;
630 }
631 case Type::PointerTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000632 PointerType* PT = cast<PointerType>(Ty);
633 Type* ET = PT->getElementType();
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000634 printType(ET);
635 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
636 std::string elemName(getCppName(ET));
637 Out << "PointerType* " << typeName << " = PointerType::get("
638 << elemName
639 << ", " << utostr(PT->getAddressSpace()) << ");";
640 nl(Out);
641 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000642 break;
643 }
644 case Type::VectorTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000645 VectorType* PT = cast<VectorType>(Ty);
646 Type* ET = PT->getElementType();
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000647 printType(ET);
648 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
649 std::string elemName(getCppName(ET));
650 Out << "VectorType* " << typeName << " = VectorType::get("
651 << elemName
652 << ", " << utostr(PT->getNumElements()) << ");";
653 nl(Out);
654 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000655 break;
656 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000657 default:
658 error("Invalid TypeID");
659 }
660
Chris Lattner7e6d7452010-06-21 23:12:56 +0000661 // Indicate that this type is now defined.
662 DefinedTypes.insert(Ty);
663
Chris Lattner7e6d7452010-06-21 23:12:56 +0000664 // Finally, separate the type definition from other with a newline.
665 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000666}
667
668void CppWriter::printTypes(const Module* M) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000669 // Add all of the global variables to the value table.
Chris Lattner7e6d7452010-06-21 23:12:56 +0000670 for (Module::const_global_iterator I = TheModule->global_begin(),
671 E = TheModule->global_end(); I != E; ++I) {
672 if (I->hasInitializer())
673 printType(I->getInitializer()->getType());
674 printType(I->getType());
675 }
676
677 // Add all the functions to the table
678 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
679 FI != FE; ++FI) {
680 printType(FI->getReturnType());
681 printType(FI->getFunctionType());
682 // Add all the function arguments
683 for (Function::const_arg_iterator AI = FI->arg_begin(),
684 AE = FI->arg_end(); AI != AE; ++AI) {
685 printType(AI->getType());
686 }
687
688 // Add all of the basic blocks and instructions
689 for (Function::const_iterator BB = FI->begin(),
690 E = FI->end(); BB != E; ++BB) {
691 printType(BB->getType());
692 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
693 ++I) {
694 printType(I->getType());
695 for (unsigned i = 0; i < I->getNumOperands(); ++i)
696 printType(I->getOperand(i)->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000697 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000698 }
699 }
700}
701
702
703// printConstant - Print out a constant pool entry...
704void CppWriter::printConstant(const Constant *CV) {
705 // First, if the constant is actually a GlobalValue (variable or function)
706 // or its already in the constant list then we've printed it already and we
707 // can just return.
708 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
709 return;
710
711 std::string constName(getCppName(CV));
712 std::string typeName(getCppName(CV->getType()));
713
Chris Lattner7e6d7452010-06-21 23:12:56 +0000714 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
715 std::string constValue = CI->getValue().toString(10, true);
716 Out << "ConstantInt* " << constName
717 << " = ConstantInt::get(mod->getContext(), APInt("
718 << cast<IntegerType>(CI->getType())->getBitWidth()
719 << ", StringRef(\"" << constValue << "\"), 10));";
720 } else if (isa<ConstantAggregateZero>(CV)) {
721 Out << "ConstantAggregateZero* " << constName
722 << " = ConstantAggregateZero::get(" << typeName << ");";
723 } else if (isa<ConstantPointerNull>(CV)) {
724 Out << "ConstantPointerNull* " << constName
725 << " = ConstantPointerNull::get(" << typeName << ");";
726 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
727 Out << "ConstantFP* " << constName << " = ";
728 printCFP(CFP);
729 Out << ";";
730 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000731 Out << "std::vector<Constant*> " << constName << "_elems;";
732 nl(Out);
733 unsigned N = CA->getNumOperands();
734 for (unsigned i = 0; i < N; ++i) {
735 printConstant(CA->getOperand(i)); // recurse to print operands
736 Out << constName << "_elems.push_back("
737 << getCppName(CA->getOperand(i)) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000738 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000739 }
Chris Lattner18c7f802012-02-05 02:29:43 +0000740 Out << "Constant* " << constName << " = ConstantArray::get("
741 << typeName << ", " << constName << "_elems);";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000742 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
743 Out << "std::vector<Constant*> " << constName << "_fields;";
744 nl(Out);
745 unsigned N = CS->getNumOperands();
746 for (unsigned i = 0; i < N; i++) {
747 printConstant(CS->getOperand(i));
748 Out << constName << "_fields.push_back("
749 << getCppName(CS->getOperand(i)) << ");";
750 nl(Out);
751 }
752 Out << "Constant* " << constName << " = ConstantStruct::get("
753 << typeName << ", " << constName << "_fields);";
Duncan Sands853066a2012-02-05 14:16:09 +0000754 } else if (const ConstantVector *CVec = dyn_cast<ConstantVector>(CV)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000755 Out << "std::vector<Constant*> " << constName << "_elems;";
756 nl(Out);
Duncan Sands853066a2012-02-05 14:16:09 +0000757 unsigned N = CVec->getNumOperands();
Chris Lattner7e6d7452010-06-21 23:12:56 +0000758 for (unsigned i = 0; i < N; ++i) {
Duncan Sands853066a2012-02-05 14:16:09 +0000759 printConstant(CVec->getOperand(i));
Chris Lattner7e6d7452010-06-21 23:12:56 +0000760 Out << constName << "_elems.push_back("
Duncan Sands853066a2012-02-05 14:16:09 +0000761 << getCppName(CVec->getOperand(i)) << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000762 nl(Out);
763 }
764 Out << "Constant* " << constName << " = ConstantVector::get("
765 << typeName << ", " << constName << "_elems);";
766 } else if (isa<UndefValue>(CV)) {
767 Out << "UndefValue* " << constName << " = UndefValue::get("
768 << typeName << ");";
Chris Lattner29cc6cb2012-01-24 14:17:05 +0000769 } else if (const ConstantDataSequential *CDS =
770 dyn_cast<ConstantDataSequential>(CV)) {
771 if (CDS->isString()) {
772 Out << "Constant *" << constName <<
773 " = ConstantDataArray::getString(mod->getContext(), \"";
Chris Lattner18c7f802012-02-05 02:29:43 +0000774 StringRef Str = CDS->getAsString();
Chris Lattner29cc6cb2012-01-24 14:17:05 +0000775 bool nullTerminate = false;
776 if (Str.back() == 0) {
777 Str = Str.drop_back();
778 nullTerminate = true;
779 }
780 printEscapedString(Str);
781 // Determine if we want null termination or not.
782 if (nullTerminate)
783 Out << "\", true);";
784 else
785 Out << "\", false);";// No null terminator
786 } else {
787 // TODO: Could generate more efficient code generating CDS calls instead.
788 Out << "std::vector<Constant*> " << constName << "_elems;";
789 nl(Out);
790 for (unsigned i = 0; i != CDS->getNumElements(); ++i) {
791 Constant *Elt = CDS->getElementAsConstant(i);
792 printConstant(Elt);
793 Out << constName << "_elems.push_back(" << getCppName(Elt) << ");";
794 nl(Out);
795 }
796 Out << "Constant* " << constName;
797
798 if (isa<ArrayType>(CDS->getType()))
799 Out << " = ConstantArray::get(";
800 else
801 Out << " = ConstantVector::get(";
802 Out << typeName << ", " << constName << "_elems);";
803 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000804 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
805 if (CE->getOpcode() == Instruction::GetElementPtr) {
806 Out << "std::vector<Constant*> " << constName << "_indices;";
807 nl(Out);
808 printConstant(CE->getOperand(0));
809 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
810 printConstant(CE->getOperand(i));
811 Out << constName << "_indices.push_back("
812 << getCppName(CE->getOperand(i)) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000813 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000814 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000815 Out << "Constant* " << constName
816 << " = ConstantExpr::getGetElementPtr("
817 << getCppName(CE->getOperand(0)) << ", "
Nicolas Geoffraya056d202011-07-21 20:59:21 +0000818 << constName << "_indices);";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000819 } else if (CE->isCast()) {
820 printConstant(CE->getOperand(0));
821 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
822 switch (CE->getOpcode()) {
823 default: llvm_unreachable("Invalid cast opcode");
824 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
825 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
826 case Instruction::SExt: Out << "Instruction::SExt"; break;
827 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
828 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
829 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
830 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
831 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
832 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
833 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
834 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
835 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
836 }
837 Out << ", " << getCppName(CE->getOperand(0)) << ", "
838 << getCppName(CE->getType()) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000839 } else {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000840 unsigned N = CE->getNumOperands();
841 for (unsigned i = 0; i < N; ++i ) {
842 printConstant(CE->getOperand(i));
843 }
844 Out << "Constant* " << constName << " = ConstantExpr::";
845 switch (CE->getOpcode()) {
846 case Instruction::Add: Out << "getAdd("; break;
847 case Instruction::FAdd: Out << "getFAdd("; break;
848 case Instruction::Sub: Out << "getSub("; break;
849 case Instruction::FSub: Out << "getFSub("; break;
850 case Instruction::Mul: Out << "getMul("; break;
851 case Instruction::FMul: Out << "getFMul("; break;
852 case Instruction::UDiv: Out << "getUDiv("; break;
853 case Instruction::SDiv: Out << "getSDiv("; break;
854 case Instruction::FDiv: Out << "getFDiv("; break;
855 case Instruction::URem: Out << "getURem("; break;
856 case Instruction::SRem: Out << "getSRem("; break;
857 case Instruction::FRem: Out << "getFRem("; break;
858 case Instruction::And: Out << "getAnd("; break;
859 case Instruction::Or: Out << "getOr("; break;
860 case Instruction::Xor: Out << "getXor("; break;
861 case Instruction::ICmp:
862 Out << "getICmp(ICmpInst::ICMP_";
863 switch (CE->getPredicate()) {
864 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
865 case ICmpInst::ICMP_NE: Out << "NE"; break;
866 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
867 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
868 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
869 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
870 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
871 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
872 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
873 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
874 default: error("Invalid ICmp Predicate");
875 }
876 break;
877 case Instruction::FCmp:
878 Out << "getFCmp(FCmpInst::FCMP_";
879 switch (CE->getPredicate()) {
880 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
881 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
882 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
883 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
884 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
885 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
886 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
887 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
888 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
889 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
890 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
891 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
892 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
893 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
894 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
895 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
896 default: error("Invalid FCmp Predicate");
897 }
898 break;
899 case Instruction::Shl: Out << "getShl("; break;
900 case Instruction::LShr: Out << "getLShr("; break;
901 case Instruction::AShr: Out << "getAShr("; break;
902 case Instruction::Select: Out << "getSelect("; break;
903 case Instruction::ExtractElement: Out << "getExtractElement("; break;
904 case Instruction::InsertElement: Out << "getInsertElement("; break;
905 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
906 default:
907 error("Invalid constant expression");
908 break;
909 }
910 Out << getCppName(CE->getOperand(0));
911 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
912 Out << ", " << getCppName(CE->getOperand(i));
913 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000914 }
Chris Lattner32848772010-06-21 23:19:36 +0000915 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
916 Out << "Constant* " << constName << " = ";
917 Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000918 } else {
919 error("Bad Constant");
920 Out << "Constant* " << constName << " = 0; ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000921 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000922 nl(Out);
923}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000924
Chris Lattner7e6d7452010-06-21 23:12:56 +0000925void CppWriter::printConstants(const Module* M) {
926 // Traverse all the global variables looking for constant initializers
927 for (Module::const_global_iterator I = TheModule->global_begin(),
928 E = TheModule->global_end(); I != E; ++I)
929 if (I->hasInitializer())
930 printConstant(I->getInitializer());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000931
Chris Lattner7e6d7452010-06-21 23:12:56 +0000932 // Traverse the LLVM functions looking for constants
933 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
934 FI != FE; ++FI) {
935 // Add all of the basic blocks and instructions
936 for (Function::const_iterator BB = FI->begin(),
937 E = FI->end(); BB != E; ++BB) {
938 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
939 ++I) {
940 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
941 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
942 printConstant(C);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000943 }
944 }
945 }
946 }
947 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000948}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000949
Chris Lattner7e6d7452010-06-21 23:12:56 +0000950void CppWriter::printVariableUses(const GlobalVariable *GV) {
951 nl(Out) << "// Type Definitions";
952 nl(Out);
953 printType(GV->getType());
954 if (GV->hasInitializer()) {
Jay Foad7d715df2011-06-19 18:37:11 +0000955 const Constant *Init = GV->getInitializer();
Chris Lattner7e6d7452010-06-21 23:12:56 +0000956 printType(Init->getType());
Jay Foad7d715df2011-06-19 18:37:11 +0000957 if (const Function *F = dyn_cast<Function>(Init)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000958 nl(Out)<< "/ Function Declarations"; nl(Out);
959 printFunctionHead(F);
Jay Foad7d715df2011-06-19 18:37:11 +0000960 } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000961 nl(Out) << "// Global Variable Declarations"; nl(Out);
962 printVariableHead(gv);
963
964 nl(Out) << "// Global Variable Definitions"; nl(Out);
965 printVariableBody(gv);
966 } else {
967 nl(Out) << "// Constant Definitions"; nl(Out);
968 printConstant(Init);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000969 }
970 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000971}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000972
Chris Lattner7e6d7452010-06-21 23:12:56 +0000973void CppWriter::printVariableHead(const GlobalVariable *GV) {
974 nl(Out) << "GlobalVariable* " << getCppName(GV);
975 if (is_inline) {
976 Out << " = mod->getGlobalVariable(mod->getContext(), ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000977 printEscapedString(GV->getName());
Chris Lattner7e6d7452010-06-21 23:12:56 +0000978 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
979 nl(Out) << "if (!" << getCppName(GV) << ") {";
980 in(); nl(Out) << getCppName(GV);
981 }
982 Out << " = new GlobalVariable(/*Module=*/*mod, ";
983 nl(Out) << "/*Type=*/";
984 printCppName(GV->getType()->getElementType());
985 Out << ",";
986 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
987 Out << ",";
988 nl(Out) << "/*Linkage=*/";
989 printLinkageType(GV->getLinkage());
990 Out << ",";
991 nl(Out) << "/*Initializer=*/0, ";
992 if (GV->hasInitializer()) {
993 Out << "// has initializer, specified below";
994 }
995 nl(Out) << "/*Name=*/\"";
996 printEscapedString(GV->getName());
997 Out << "\");";
998 nl(Out);
999
1000 if (GV->hasSection()) {
1001 printCppName(GV);
1002 Out << "->setSection(\"";
1003 printEscapedString(GV->getSection());
Owen Anderson16a412e2009-07-10 16:42:19 +00001004 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001005 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001006 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001007 if (GV->getAlignment()) {
1008 printCppName(GV);
1009 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001010 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001011 }
1012 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1013 printCppName(GV);
1014 Out << "->setVisibility(";
1015 printVisibilityType(GV->getVisibility());
1016 Out << ");";
1017 nl(Out);
1018 }
1019 if (GV->isThreadLocal()) {
1020 printCppName(GV);
Hans Wennborgce718ff2012-06-23 11:37:03 +00001021 Out << "->setThreadLocalMode(";
1022 printThreadLocalMode(GV->getThreadLocalMode());
1023 Out << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001024 nl(Out);
1025 }
1026 if (is_inline) {
1027 out(); Out << "}"; nl(Out);
1028 }
1029}
1030
1031void CppWriter::printVariableBody(const GlobalVariable *GV) {
1032 if (GV->hasInitializer()) {
1033 printCppName(GV);
1034 Out << "->setInitializer(";
1035 Out << getCppName(GV->getInitializer()) << ");";
1036 nl(Out);
1037 }
1038}
1039
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001040std::string CppWriter::getOpName(const Value* V) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001041 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1042 return getCppName(V);
1043
1044 // See if its alread in the map of forward references, if so just return the
1045 // name we already set up for it
1046 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1047 if (I != ForwardRefs.end())
1048 return I->second;
1049
1050 // This is a new forward reference. Generate a unique name for it
1051 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1052
1053 // Yes, this is a hack. An Argument is the smallest instantiable value that
1054 // we can make as a placeholder for the real value. We'll replace these
1055 // Argument instances later.
1056 Out << "Argument* " << result << " = new Argument("
1057 << getCppName(V->getType()) << ");";
1058 nl(Out);
1059 ForwardRefs[V] = result;
1060 return result;
1061}
1062
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001063static StringRef ConvertAtomicOrdering(AtomicOrdering Ordering) {
1064 switch (Ordering) {
1065 case NotAtomic: return "NotAtomic";
1066 case Unordered: return "Unordered";
1067 case Monotonic: return "Monotonic";
1068 case Acquire: return "Acquire";
1069 case Release: return "Release";
1070 case AcquireRelease: return "AcquireRelease";
1071 case SequentiallyConsistent: return "SequentiallyConsistent";
1072 }
1073 llvm_unreachable("Unknown ordering");
1074}
1075
1076static StringRef ConvertAtomicSynchScope(SynchronizationScope SynchScope) {
1077 switch (SynchScope) {
1078 case SingleThread: return "SingleThread";
1079 case CrossThread: return "CrossThread";
1080 }
1081 llvm_unreachable("Unknown synch scope");
1082}
1083
Chris Lattner7e6d7452010-06-21 23:12:56 +00001084// printInstruction - This member is called for each Instruction in a function.
1085void CppWriter::printInstruction(const Instruction *I,
1086 const std::string& bbname) {
1087 std::string iName(getCppName(I));
1088
1089 // Before we emit this instruction, we need to take care of generating any
1090 // forward references. So, we get the names of all the operands in advance
1091 const unsigned Ops(I->getNumOperands());
1092 std::string* opNames = new std::string[Ops];
Chris Lattner32848772010-06-21 23:19:36 +00001093 for (unsigned i = 0; i < Ops; i++)
Chris Lattner7e6d7452010-06-21 23:12:56 +00001094 opNames[i] = getOpName(I->getOperand(i));
Anton Korobeynikov50276522008-04-23 22:29:24 +00001095
Chris Lattner7e6d7452010-06-21 23:12:56 +00001096 switch (I->getOpcode()) {
1097 default:
1098 error("Invalid instruction");
1099 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001100
Chris Lattner7e6d7452010-06-21 23:12:56 +00001101 case Instruction::Ret: {
1102 const ReturnInst* ret = cast<ReturnInst>(I);
1103 Out << "ReturnInst::Create(mod->getContext(), "
1104 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1105 break;
1106 }
1107 case Instruction::Br: {
1108 const BranchInst* br = cast<BranchInst>(I);
1109 Out << "BranchInst::Create(" ;
Chris Lattner32848772010-06-21 23:19:36 +00001110 if (br->getNumOperands() == 3) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001111 Out << opNames[2] << ", "
Anton Korobeynikov50276522008-04-23 22:29:24 +00001112 << opNames[1] << ", "
Chris Lattner7e6d7452010-06-21 23:12:56 +00001113 << opNames[0] << ", ";
1114
1115 } else if (br->getNumOperands() == 1) {
1116 Out << opNames[0] << ", ";
1117 } else {
1118 error("Branch with 2 operands?");
1119 }
1120 Out << bbname << ");";
1121 break;
1122 }
1123 case Instruction::Switch: {
1124 const SwitchInst *SI = cast<SwitchInst>(I);
1125 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001126 << getOpName(SI->getCondition()) << ", "
1127 << getOpName(SI->getDefaultDest()) << ", "
Chris Lattner7e6d7452010-06-21 23:12:56 +00001128 << SI->getNumCases() << ", " << bbname << ");";
1129 nl(Out);
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00001130 for (SwitchInst::ConstCaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00001131 i != e; ++i) {
Stepan Dyatkovskiy0aa32d52012-05-29 12:26:47 +00001132 const IntegersSubset CaseVal = i.getCaseValueEx();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00001133 const BasicBlock *BB = i.getCaseSuccessor();
Chris Lattner7e6d7452010-06-21 23:12:56 +00001134 Out << iName << "->addCase("
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001135 << getOpName(CaseVal) << ", "
1136 << getOpName(BB) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001137 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001138 }
1139 break;
1140 }
1141 case Instruction::IndirectBr: {
1142 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1143 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1144 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1145 nl(Out);
1146 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1147 Out << iName << "->addDestination(" << opNames[i] << ");";
1148 nl(Out);
1149 }
1150 break;
1151 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00001152 case Instruction::Resume: {
1153 Out << "ResumeInst::Create(mod->getContext(), " << opNames[0]
1154 << ", " << bbname << ");";
1155 break;
1156 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001157 case Instruction::Invoke: {
1158 const InvokeInst* inv = cast<InvokeInst>(I);
1159 Out << "std::vector<Value*> " << iName << "_params;";
1160 nl(Out);
1161 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1162 Out << iName << "_params.push_back("
1163 << getOpName(inv->getArgOperand(i)) << ");";
1164 nl(Out);
1165 }
1166 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1167 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1168 << getOpName(inv->getCalledFunction()) << ", "
1169 << getOpName(inv->getNormalDest()) << ", "
1170 << getOpName(inv->getUnwindDest()) << ", "
Nick Lewycky3bca1012011-09-05 18:50:59 +00001171 << iName << "_params, \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001172 printEscapedString(inv->getName());
1173 Out << "\", " << bbname << ");";
1174 nl(Out) << iName << "->setCallingConv(";
1175 printCallingConv(inv->getCallingConv());
1176 Out << ");";
1177 printAttributes(inv->getAttributes(), iName);
1178 Out << iName << "->setAttributes(" << iName << "_PAL);";
1179 nl(Out);
1180 break;
1181 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001182 case Instruction::Unreachable: {
1183 Out << "new UnreachableInst("
1184 << "mod->getContext(), "
1185 << bbname << ");";
1186 break;
1187 }
1188 case Instruction::Add:
1189 case Instruction::FAdd:
1190 case Instruction::Sub:
1191 case Instruction::FSub:
1192 case Instruction::Mul:
1193 case Instruction::FMul:
1194 case Instruction::UDiv:
1195 case Instruction::SDiv:
1196 case Instruction::FDiv:
1197 case Instruction::URem:
1198 case Instruction::SRem:
1199 case Instruction::FRem:
1200 case Instruction::And:
1201 case Instruction::Or:
1202 case Instruction::Xor:
1203 case Instruction::Shl:
1204 case Instruction::LShr:
1205 case Instruction::AShr:{
1206 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1207 switch (I->getOpcode()) {
1208 case Instruction::Add: Out << "Instruction::Add"; break;
1209 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1210 case Instruction::Sub: Out << "Instruction::Sub"; break;
1211 case Instruction::FSub: Out << "Instruction::FSub"; break;
1212 case Instruction::Mul: Out << "Instruction::Mul"; break;
1213 case Instruction::FMul: Out << "Instruction::FMul"; break;
1214 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1215 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1216 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1217 case Instruction::URem:Out << "Instruction::URem"; break;
1218 case Instruction::SRem:Out << "Instruction::SRem"; break;
1219 case Instruction::FRem:Out << "Instruction::FRem"; break;
1220 case Instruction::And: Out << "Instruction::And"; break;
1221 case Instruction::Or: Out << "Instruction::Or"; break;
1222 case Instruction::Xor: Out << "Instruction::Xor"; break;
1223 case Instruction::Shl: Out << "Instruction::Shl"; break;
1224 case Instruction::LShr:Out << "Instruction::LShr"; break;
1225 case Instruction::AShr:Out << "Instruction::AShr"; break;
1226 default: Out << "Instruction::BadOpCode"; break;
1227 }
1228 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1229 printEscapedString(I->getName());
1230 Out << "\", " << bbname << ");";
1231 break;
1232 }
1233 case Instruction::FCmp: {
1234 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1235 switch (cast<FCmpInst>(I)->getPredicate()) {
1236 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1237 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1238 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1239 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1240 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1241 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1242 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1243 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1244 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1245 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1246 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1247 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1248 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1249 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1250 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1251 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1252 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1253 }
1254 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1255 printEscapedString(I->getName());
1256 Out << "\");";
1257 break;
1258 }
1259 case Instruction::ICmp: {
1260 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1261 switch (cast<ICmpInst>(I)->getPredicate()) {
1262 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1263 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1264 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1265 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1266 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1267 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1268 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1269 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1270 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1271 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1272 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1273 }
1274 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1275 printEscapedString(I->getName());
1276 Out << "\");";
1277 break;
1278 }
1279 case Instruction::Alloca: {
1280 const AllocaInst* allocaI = cast<AllocaInst>(I);
1281 Out << "AllocaInst* " << iName << " = new AllocaInst("
1282 << getCppName(allocaI->getAllocatedType()) << ", ";
1283 if (allocaI->isArrayAllocation())
1284 Out << opNames[0] << ", ";
1285 Out << "\"";
1286 printEscapedString(allocaI->getName());
1287 Out << "\", " << bbname << ");";
1288 if (allocaI->getAlignment())
1289 nl(Out) << iName << "->setAlignment("
1290 << allocaI->getAlignment() << ");";
1291 break;
1292 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001293 case Instruction::Load: {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001294 const LoadInst* load = cast<LoadInst>(I);
1295 Out << "LoadInst* " << iName << " = new LoadInst("
1296 << opNames[0] << ", \"";
1297 printEscapedString(load->getName());
1298 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1299 << ", " << bbname << ");";
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001300 if (load->getAlignment())
1301 nl(Out) << iName << "->setAlignment("
1302 << load->getAlignment() << ");";
1303 if (load->isAtomic()) {
1304 StringRef Ordering = ConvertAtomicOrdering(load->getOrdering());
1305 StringRef CrossThread = ConvertAtomicSynchScope(load->getSynchScope());
1306 nl(Out) << iName << "->setAtomic("
1307 << Ordering << ", " << CrossThread << ");";
1308 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001309 break;
1310 }
1311 case Instruction::Store: {
1312 const StoreInst* store = cast<StoreInst>(I);
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001313 Out << "StoreInst* " << iName << " = new StoreInst("
Chris Lattner7e6d7452010-06-21 23:12:56 +00001314 << opNames[0] << ", "
1315 << opNames[1] << ", "
1316 << (store->isVolatile() ? "true" : "false")
1317 << ", " << bbname << ");";
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001318 if (store->getAlignment())
1319 nl(Out) << iName << "->setAlignment("
1320 << store->getAlignment() << ");";
1321 if (store->isAtomic()) {
1322 StringRef Ordering = ConvertAtomicOrdering(store->getOrdering());
1323 StringRef CrossThread = ConvertAtomicSynchScope(store->getSynchScope());
1324 nl(Out) << iName << "->setAtomic("
1325 << Ordering << ", " << CrossThread << ");";
1326 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001327 break;
1328 }
1329 case Instruction::GetElementPtr: {
1330 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1331 if (gep->getNumOperands() <= 2) {
1332 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1333 << opNames[0];
1334 if (gep->getNumOperands() == 2)
1335 Out << ", " << opNames[1];
1336 } else {
1337 Out << "std::vector<Value*> " << iName << "_indices;";
1338 nl(Out);
1339 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1340 Out << iName << "_indices.push_back("
1341 << opNames[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001342 nl(Out);
1343 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001344 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
Nicolas Geoffray45c8d2b2011-07-26 20:52:25 +00001345 << opNames[0] << ", " << iName << "_indices";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001346 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001347 Out << ", \"";
1348 printEscapedString(gep->getName());
1349 Out << "\", " << bbname << ");";
1350 break;
1351 }
1352 case Instruction::PHI: {
1353 const PHINode* phi = cast<PHINode>(I);
1354
1355 Out << "PHINode* " << iName << " = PHINode::Create("
Nicolas Geoffrayc6cf1972011-04-10 17:39:40 +00001356 << getCppName(phi->getType()) << ", "
Jay Foad3ecfc862011-03-30 11:28:46 +00001357 << phi->getNumIncomingValues() << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001358 printEscapedString(phi->getName());
1359 Out << "\", " << bbname << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001360 nl(Out);
Jay Foadc1371202011-06-20 14:18:48 +00001361 for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001362 Out << iName << "->addIncoming("
Jay Foadc1371202011-06-20 14:18:48 +00001363 << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
Jay Foad95c3e482011-06-23 09:09:15 +00001364 << getOpName(phi->getIncomingBlock(i)) << ");";
Chris Lattner627b4702009-10-27 21:24:48 +00001365 nl(Out);
Chris Lattner627b4702009-10-27 21:24:48 +00001366 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001367 break;
1368 }
1369 case Instruction::Trunc:
1370 case Instruction::ZExt:
1371 case Instruction::SExt:
1372 case Instruction::FPTrunc:
1373 case Instruction::FPExt:
1374 case Instruction::FPToUI:
1375 case Instruction::FPToSI:
1376 case Instruction::UIToFP:
1377 case Instruction::SIToFP:
1378 case Instruction::PtrToInt:
1379 case Instruction::IntToPtr:
1380 case Instruction::BitCast: {
1381 const CastInst* cst = cast<CastInst>(I);
1382 Out << "CastInst* " << iName << " = new ";
1383 switch (I->getOpcode()) {
1384 case Instruction::Trunc: Out << "TruncInst"; break;
1385 case Instruction::ZExt: Out << "ZExtInst"; break;
1386 case Instruction::SExt: Out << "SExtInst"; break;
1387 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1388 case Instruction::FPExt: Out << "FPExtInst"; break;
1389 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1390 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1391 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1392 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1393 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1394 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1395 case Instruction::BitCast: Out << "BitCastInst"; break;
Craig Topperbc219812012-02-07 02:50:20 +00001396 default: llvm_unreachable("Unreachable");
Chris Lattner7e6d7452010-06-21 23:12:56 +00001397 }
1398 Out << "(" << opNames[0] << ", "
1399 << getCppName(cst->getType()) << ", \"";
1400 printEscapedString(cst->getName());
1401 Out << "\", " << bbname << ");";
1402 break;
1403 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001404 case Instruction::Call: {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001405 const CallInst* call = cast<CallInst>(I);
1406 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1407 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1408 << getCppName(ila->getFunctionType()) << ", \""
1409 << ila->getAsmString() << "\", \""
1410 << ila->getConstraintString() << "\","
1411 << (ila->hasSideEffects() ? "true" : "false") << ");";
1412 nl(Out);
1413 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001414 if (call->getNumArgOperands() > 1) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001415 Out << "std::vector<Value*> " << iName << "_params;";
1416 nl(Out);
Gabor Greif53ba5502010-07-02 19:08:46 +00001417 for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
Gabor Greif63d024f2010-07-13 15:31:36 +00001418 Out << iName << "_params.push_back(" << opNames[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001419 nl(Out);
1420 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001421 Out << "CallInst* " << iName << " = CallInst::Create("
Gabor Greifa3997812010-07-22 10:37:47 +00001422 << opNames[call->getNumArgOperands()] << ", "
Nicolas Geoffraya056d202011-07-21 20:59:21 +00001423 << iName << "_params, \"";
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001424 } else if (call->getNumArgOperands() == 1) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001425 Out << "CallInst* " << iName << " = CallInst::Create("
Gabor Greif63d024f2010-07-13 15:31:36 +00001426 << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001427 } else {
Gabor Greif63d024f2010-07-13 15:31:36 +00001428 Out << "CallInst* " << iName << " = CallInst::Create("
1429 << opNames[call->getNumArgOperands()] << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001430 }
1431 printEscapedString(call->getName());
1432 Out << "\", " << bbname << ");";
1433 nl(Out) << iName << "->setCallingConv(";
1434 printCallingConv(call->getCallingConv());
1435 Out << ");";
1436 nl(Out) << iName << "->setTailCall("
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001437 << (call->isTailCall() ? "true" : "false");
Chris Lattner7e6d7452010-06-21 23:12:56 +00001438 Out << ");";
Gabor Greif135d7fe2010-07-02 19:26:28 +00001439 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001440 printAttributes(call->getAttributes(), iName);
1441 Out << iName << "->setAttributes(" << iName << "_PAL);";
1442 nl(Out);
1443 break;
1444 }
1445 case Instruction::Select: {
1446 const SelectInst* sel = cast<SelectInst>(I);
1447 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1448 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1449 printEscapedString(sel->getName());
1450 Out << "\", " << bbname << ");";
1451 break;
1452 }
1453 case Instruction::UserOp1:
1454 /// FALL THROUGH
1455 case Instruction::UserOp2: {
1456 /// FIXME: What should be done here?
1457 break;
1458 }
1459 case Instruction::VAArg: {
1460 const VAArgInst* va = cast<VAArgInst>(I);
1461 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1462 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1463 printEscapedString(va->getName());
1464 Out << "\", " << bbname << ");";
1465 break;
1466 }
1467 case Instruction::ExtractElement: {
1468 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1469 Out << "ExtractElementInst* " << getCppName(eei)
1470 << " = new ExtractElementInst(" << opNames[0]
1471 << ", " << opNames[1] << ", \"";
1472 printEscapedString(eei->getName());
1473 Out << "\", " << bbname << ");";
1474 break;
1475 }
1476 case Instruction::InsertElement: {
1477 const InsertElementInst* iei = cast<InsertElementInst>(I);
1478 Out << "InsertElementInst* " << getCppName(iei)
1479 << " = InsertElementInst::Create(" << opNames[0]
1480 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1481 printEscapedString(iei->getName());
1482 Out << "\", " << bbname << ");";
1483 break;
1484 }
1485 case Instruction::ShuffleVector: {
1486 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1487 Out << "ShuffleVectorInst* " << getCppName(svi)
1488 << " = new ShuffleVectorInst(" << opNames[0]
1489 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1490 printEscapedString(svi->getName());
1491 Out << "\", " << bbname << ");";
1492 break;
1493 }
1494 case Instruction::ExtractValue: {
1495 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1496 Out << "std::vector<unsigned> " << iName << "_indices;";
1497 nl(Out);
1498 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1499 Out << iName << "_indices.push_back("
1500 << evi->idx_begin()[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001501 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001502 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001503 Out << "ExtractValueInst* " << getCppName(evi)
1504 << " = ExtractValueInst::Create(" << opNames[0]
1505 << ", "
Nick Lewycky3bca1012011-09-05 18:50:59 +00001506 << iName << "_indices, \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001507 printEscapedString(evi->getName());
1508 Out << "\", " << bbname << ");";
1509 break;
1510 }
1511 case Instruction::InsertValue: {
1512 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1513 Out << "std::vector<unsigned> " << iName << "_indices;";
1514 nl(Out);
1515 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1516 Out << iName << "_indices.push_back("
1517 << ivi->idx_begin()[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001518 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001519 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001520 Out << "InsertValueInst* " << getCppName(ivi)
1521 << " = InsertValueInst::Create(" << opNames[0]
1522 << ", " << opNames[1] << ", "
Nick Lewycky3bca1012011-09-05 18:50:59 +00001523 << iName << "_indices, \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001524 printEscapedString(ivi->getName());
1525 Out << "\", " << bbname << ");";
1526 break;
1527 }
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001528 case Instruction::Fence: {
1529 const FenceInst *fi = cast<FenceInst>(I);
1530 StringRef Ordering = ConvertAtomicOrdering(fi->getOrdering());
1531 StringRef CrossThread = ConvertAtomicSynchScope(fi->getSynchScope());
1532 Out << "FenceInst* " << iName
1533 << " = new FenceInst(mod->getContext(), "
Eli Friedman5b7cc332011-11-04 17:29:35 +00001534 << Ordering << ", " << CrossThread << ", " << bbname
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001535 << ");";
1536 break;
1537 }
1538 case Instruction::AtomicCmpXchg: {
1539 const AtomicCmpXchgInst *cxi = cast<AtomicCmpXchgInst>(I);
1540 StringRef Ordering = ConvertAtomicOrdering(cxi->getOrdering());
1541 StringRef CrossThread = ConvertAtomicSynchScope(cxi->getSynchScope());
1542 Out << "AtomicCmpXchgInst* " << iName
1543 << " = new AtomicCmpXchgInst("
1544 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", "
Eli Friedman5b7cc332011-11-04 17:29:35 +00001545 << Ordering << ", " << CrossThread << ", " << bbname
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001546 << ");";
1547 nl(Out) << iName << "->setName(\"";
1548 printEscapedString(cxi->getName());
1549 Out << "\");";
1550 break;
1551 }
1552 case Instruction::AtomicRMW: {
1553 const AtomicRMWInst *rmwi = cast<AtomicRMWInst>(I);
1554 StringRef Ordering = ConvertAtomicOrdering(rmwi->getOrdering());
1555 StringRef CrossThread = ConvertAtomicSynchScope(rmwi->getSynchScope());
1556 StringRef Operation;
1557 switch (rmwi->getOperation()) {
1558 case AtomicRMWInst::Xchg: Operation = "AtomicRMWInst::Xchg"; break;
1559 case AtomicRMWInst::Add: Operation = "AtomicRMWInst::Add"; break;
1560 case AtomicRMWInst::Sub: Operation = "AtomicRMWInst::Sub"; break;
1561 case AtomicRMWInst::And: Operation = "AtomicRMWInst::And"; break;
1562 case AtomicRMWInst::Nand: Operation = "AtomicRMWInst::Nand"; break;
1563 case AtomicRMWInst::Or: Operation = "AtomicRMWInst::Or"; break;
1564 case AtomicRMWInst::Xor: Operation = "AtomicRMWInst::Xor"; break;
1565 case AtomicRMWInst::Max: Operation = "AtomicRMWInst::Max"; break;
1566 case AtomicRMWInst::Min: Operation = "AtomicRMWInst::Min"; break;
1567 case AtomicRMWInst::UMax: Operation = "AtomicRMWInst::UMax"; break;
1568 case AtomicRMWInst::UMin: Operation = "AtomicRMWInst::UMin"; break;
1569 case AtomicRMWInst::BAD_BINOP: llvm_unreachable("Bad atomic operation");
1570 }
1571 Out << "AtomicRMWInst* " << iName
1572 << " = new AtomicRMWInst("
1573 << Operation << ", "
1574 << opNames[0] << ", " << opNames[1] << ", "
Eli Friedman5b7cc332011-11-04 17:29:35 +00001575 << Ordering << ", " << CrossThread << ", " << bbname
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001576 << ");";
1577 nl(Out) << iName << "->setName(\"";
1578 printEscapedString(rmwi->getName());
1579 Out << "\");";
1580 break;
1581 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001582 }
1583 DefinedValues.insert(I);
1584 nl(Out);
1585 delete [] opNames;
1586}
1587
Chris Lattner7e6d7452010-06-21 23:12:56 +00001588// Print out the types, constants and declarations needed by one function
1589void CppWriter::printFunctionUses(const Function* F) {
1590 nl(Out) << "// Type Definitions"; nl(Out);
1591 if (!is_inline) {
1592 // Print the function's return type
1593 printType(F->getReturnType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001594
Chris Lattner7e6d7452010-06-21 23:12:56 +00001595 // Print the function's function type
1596 printType(F->getFunctionType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001597
Chris Lattner7e6d7452010-06-21 23:12:56 +00001598 // Print the types of each of the function's arguments
Anton Korobeynikov50276522008-04-23 22:29:24 +00001599 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1600 AI != AE; ++AI) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001601 printType(AI->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001602 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001603 }
1604
Chris Lattner7e6d7452010-06-21 23:12:56 +00001605 // Print type definitions for every type referenced by an instruction and
1606 // make a note of any global values or constants that are referenced
1607 SmallPtrSet<GlobalValue*,64> gvs;
1608 SmallPtrSet<Constant*,64> consts;
1609 for (Function::const_iterator BB = F->begin(), BE = F->end();
1610 BB != BE; ++BB){
1611 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
Anton Korobeynikov50276522008-04-23 22:29:24 +00001612 I != E; ++I) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001613 // Print the type of the instruction itself
1614 printType(I->getType());
1615
1616 // Print the type of each of the instruction's operands
1617 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1618 Value* operand = I->getOperand(i);
1619 printType(operand->getType());
1620
1621 // If the operand references a GVal or Constant, make a note of it
1622 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1623 gvs.insert(GV);
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001624 if (GenerationType != GenFunction)
1625 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1626 if (GVar->hasInitializer())
1627 consts.insert(GVar->getInitializer());
1628 } else if (Constant* C = dyn_cast<Constant>(operand)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001629 consts.insert(C);
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001630 for (unsigned j = 0; j < C->getNumOperands(); ++j) {
1631 // If the operand references a GVal or Constant, make a note of it
1632 Value* operand = C->getOperand(j);
1633 printType(operand->getType());
1634 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1635 gvs.insert(GV);
1636 if (GenerationType != GenFunction)
1637 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1638 if (GVar->hasInitializer())
1639 consts.insert(GVar->getInitializer());
1640 }
1641 }
1642 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001643 }
1644 }
1645 }
1646
1647 // Print the function declarations for any functions encountered
1648 nl(Out) << "// Function Declarations"; nl(Out);
1649 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1650 I != E; ++I) {
1651 if (Function* Fun = dyn_cast<Function>(*I)) {
1652 if (!is_inline || Fun != F)
1653 printFunctionHead(Fun);
1654 }
1655 }
1656
1657 // Print the global variable declarations for any variables encountered
1658 nl(Out) << "// Global Variable Declarations"; nl(Out);
1659 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1660 I != E; ++I) {
1661 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1662 printVariableHead(F);
1663 }
1664
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001665 // Print the constants found
Chris Lattner7e6d7452010-06-21 23:12:56 +00001666 nl(Out) << "// Constant Definitions"; nl(Out);
1667 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1668 E = consts.end(); I != E; ++I) {
1669 printConstant(*I);
1670 }
1671
1672 // Process the global variables definitions now that all the constants have
1673 // been emitted. These definitions just couple the gvars with their constant
1674 // initializers.
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001675 if (GenerationType != GenFunction) {
1676 nl(Out) << "// Global Variable Definitions"; nl(Out);
1677 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1678 I != E; ++I) {
1679 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1680 printVariableBody(GV);
1681 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001682 }
1683}
1684
1685void CppWriter::printFunctionHead(const Function* F) {
1686 nl(Out) << "Function* " << getCppName(F);
Nicolas Geoffrayf8557952011-10-08 11:56:36 +00001687 Out << " = mod->getFunction(\"";
1688 printEscapedString(F->getName());
1689 Out << "\");";
1690 nl(Out) << "if (!" << getCppName(F) << ") {";
1691 nl(Out) << getCppName(F);
1692
Chris Lattner7e6d7452010-06-21 23:12:56 +00001693 Out<< " = Function::Create(";
1694 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1695 nl(Out) << "/*Linkage=*/";
1696 printLinkageType(F->getLinkage());
1697 Out << ",";
1698 nl(Out) << "/*Name=*/\"";
1699 printEscapedString(F->getName());
1700 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1701 nl(Out,-1);
1702 printCppName(F);
1703 Out << "->setCallingConv(";
1704 printCallingConv(F->getCallingConv());
1705 Out << ");";
1706 nl(Out);
1707 if (F->hasSection()) {
1708 printCppName(F);
1709 Out << "->setSection(\"" << F->getSection() << "\");";
1710 nl(Out);
1711 }
1712 if (F->getAlignment()) {
1713 printCppName(F);
1714 Out << "->setAlignment(" << F->getAlignment() << ");";
1715 nl(Out);
1716 }
1717 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1718 printCppName(F);
1719 Out << "->setVisibility(";
1720 printVisibilityType(F->getVisibility());
1721 Out << ");";
1722 nl(Out);
1723 }
1724 if (F->hasGC()) {
1725 printCppName(F);
1726 Out << "->setGC(\"" << F->getGC() << "\");";
1727 nl(Out);
1728 }
Nicolas Geoffrayf8557952011-10-08 11:56:36 +00001729 Out << "}";
1730 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001731 printAttributes(F->getAttributes(), getCppName(F));
1732 printCppName(F);
1733 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1734 nl(Out);
1735}
1736
1737void CppWriter::printFunctionBody(const Function *F) {
1738 if (F->isDeclaration())
1739 return; // external functions have no bodies.
1740
1741 // Clear the DefinedValues and ForwardRefs maps because we can't have
1742 // cross-function forward refs
1743 ForwardRefs.clear();
1744 DefinedValues.clear();
1745
1746 // Create all the argument values
1747 if (!is_inline) {
1748 if (!F->arg_empty()) {
1749 Out << "Function::arg_iterator args = " << getCppName(F)
1750 << "->arg_begin();";
1751 nl(Out);
1752 }
1753 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1754 AI != AE; ++AI) {
1755 Out << "Value* " << getCppName(AI) << " = args++;";
1756 nl(Out);
1757 if (AI->hasName()) {
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001758 Out << getCppName(AI) << "->setName(\"";
1759 printEscapedString(AI->getName());
1760 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001761 nl(Out);
1762 }
1763 }
1764 }
1765
Chris Lattner7e6d7452010-06-21 23:12:56 +00001766 // Create all the basic blocks
1767 nl(Out);
1768 for (Function::const_iterator BI = F->begin(), BE = F->end();
1769 BI != BE; ++BI) {
1770 std::string bbname(getCppName(BI));
1771 Out << "BasicBlock* " << bbname <<
1772 " = BasicBlock::Create(mod->getContext(), \"";
1773 if (BI->hasName())
1774 printEscapedString(BI->getName());
1775 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1776 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001777 }
1778
Chris Lattner7e6d7452010-06-21 23:12:56 +00001779 // Output all of its basic blocks... for the function
1780 for (Function::const_iterator BI = F->begin(), BE = F->end();
1781 BI != BE; ++BI) {
1782 std::string bbname(getCppName(BI));
1783 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001784 nl(Out);
1785
Chris Lattner7e6d7452010-06-21 23:12:56 +00001786 // Output all of the instructions in the basic block...
1787 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1788 I != E; ++I) {
1789 printInstruction(I,bbname);
1790 }
1791 }
1792
1793 // Loop over the ForwardRefs and resolve them now that all instructions
1794 // are generated.
1795 if (!ForwardRefs.empty()) {
1796 nl(Out) << "// Resolve Forward References";
1797 nl(Out);
1798 }
1799
1800 while (!ForwardRefs.empty()) {
1801 ForwardRefMap::iterator I = ForwardRefs.begin();
1802 Out << I->second << "->replaceAllUsesWith("
1803 << getCppName(I->first) << "); delete " << I->second << ";";
1804 nl(Out);
1805 ForwardRefs.erase(I);
1806 }
1807}
1808
1809void CppWriter::printInline(const std::string& fname,
1810 const std::string& func) {
1811 const Function* F = TheModule->getFunction(func);
1812 if (!F) {
1813 error(std::string("Function '") + func + "' not found in input module");
1814 return;
1815 }
1816 if (F->isDeclaration()) {
1817 error(std::string("Function '") + func + "' is external!");
1818 return;
1819 }
1820 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1821 << getCppName(F);
1822 unsigned arg_count = 1;
1823 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1824 AI != AE; ++AI) {
1825 Out << ", Value* arg_" << arg_count;
1826 }
1827 Out << ") {";
1828 nl(Out);
1829 is_inline = true;
1830 printFunctionUses(F);
1831 printFunctionBody(F);
1832 is_inline = false;
1833 Out << "return " << getCppName(F->begin()) << ";";
1834 nl(Out) << "}";
1835 nl(Out);
1836}
1837
1838void CppWriter::printModuleBody() {
1839 // Print out all the type definitions
1840 nl(Out) << "// Type Definitions"; nl(Out);
1841 printTypes(TheModule);
1842
1843 // Functions can call each other and global variables can reference them so
1844 // define all the functions first before emitting their function bodies.
1845 nl(Out) << "// Function Declarations"; nl(Out);
1846 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1847 I != E; ++I)
1848 printFunctionHead(I);
1849
1850 // Process the global variables declarations. We can't initialze them until
1851 // after the constants are printed so just print a header for each global
1852 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1853 for (Module::const_global_iterator I = TheModule->global_begin(),
1854 E = TheModule->global_end(); I != E; ++I) {
1855 printVariableHead(I);
1856 }
1857
1858 // Print out all the constants definitions. Constants don't recurse except
1859 // through GlobalValues. All GlobalValues have been declared at this point
1860 // so we can proceed to generate the constants.
1861 nl(Out) << "// Constant Definitions"; nl(Out);
1862 printConstants(TheModule);
1863
1864 // Process the global variables definitions now that all the constants have
1865 // been emitted. These definitions just couple the gvars with their constant
1866 // initializers.
1867 nl(Out) << "// Global Variable Definitions"; nl(Out);
1868 for (Module::const_global_iterator I = TheModule->global_begin(),
1869 E = TheModule->global_end(); I != E; ++I) {
1870 printVariableBody(I);
1871 }
1872
1873 // Finally, we can safely put out all of the function bodies.
1874 nl(Out) << "// Function Definitions"; nl(Out);
1875 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1876 I != E; ++I) {
1877 if (!I->isDeclaration()) {
1878 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1879 << ")";
1880 nl(Out) << "{";
1881 nl(Out,1);
1882 printFunctionBody(I);
1883 nl(Out,-1) << "}";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001884 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001885 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001886 }
1887}
1888
1889void CppWriter::printProgram(const std::string& fname,
1890 const std::string& mName) {
1891 Out << "#include <llvm/LLVMContext.h>\n";
1892 Out << "#include <llvm/Module.h>\n";
1893 Out << "#include <llvm/DerivedTypes.h>\n";
1894 Out << "#include <llvm/Constants.h>\n";
1895 Out << "#include <llvm/GlobalVariable.h>\n";
1896 Out << "#include <llvm/Function.h>\n";
1897 Out << "#include <llvm/CallingConv.h>\n";
1898 Out << "#include <llvm/BasicBlock.h>\n";
1899 Out << "#include <llvm/Instructions.h>\n";
1900 Out << "#include <llvm/InlineAsm.h>\n";
1901 Out << "#include <llvm/Support/FormattedStream.h>\n";
1902 Out << "#include <llvm/Support/MathExtras.h>\n";
1903 Out << "#include <llvm/Pass.h>\n";
1904 Out << "#include <llvm/PassManager.h>\n";
1905 Out << "#include <llvm/ADT/SmallVector.h>\n";
1906 Out << "#include <llvm/Analysis/Verifier.h>\n";
1907 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1908 Out << "#include <algorithm>\n";
1909 Out << "using namespace llvm;\n\n";
1910 Out << "Module* " << fname << "();\n\n";
1911 Out << "int main(int argc, char**argv) {\n";
1912 Out << " Module* Mod = " << fname << "();\n";
1913 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1914 Out << " PassManager PM;\n";
1915 Out << " PM.add(createPrintModulePass(&outs()));\n";
1916 Out << " PM.run(*Mod);\n";
1917 Out << " return 0;\n";
1918 Out << "}\n\n";
1919 printModule(fname,mName);
1920}
1921
1922void CppWriter::printModule(const std::string& fname,
1923 const std::string& mName) {
1924 nl(Out) << "Module* " << fname << "() {";
1925 nl(Out,1) << "// Module Construction";
1926 nl(Out) << "Module* mod = new Module(\"";
1927 printEscapedString(mName);
1928 Out << "\", getGlobalContext());";
1929 if (!TheModule->getTargetTriple().empty()) {
1930 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1931 }
1932 if (!TheModule->getTargetTriple().empty()) {
1933 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1934 << "\");";
1935 }
1936
1937 if (!TheModule->getModuleInlineAsm().empty()) {
1938 nl(Out) << "mod->setModuleInlineAsm(\"";
1939 printEscapedString(TheModule->getModuleInlineAsm());
1940 Out << "\");";
1941 }
1942 nl(Out);
1943
Chris Lattner7e6d7452010-06-21 23:12:56 +00001944 printModuleBody();
1945 nl(Out) << "return mod;";
1946 nl(Out,-1) << "}";
1947 nl(Out);
1948}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001949
Chris Lattner7e6d7452010-06-21 23:12:56 +00001950void CppWriter::printContents(const std::string& fname,
1951 const std::string& mName) {
1952 Out << "\nModule* " << fname << "(Module *mod) {\n";
1953 Out << "\nmod->setModuleIdentifier(\"";
1954 printEscapedString(mName);
1955 Out << "\");\n";
1956 printModuleBody();
1957 Out << "\nreturn mod;\n";
1958 Out << "\n}\n";
1959}
1960
1961void CppWriter::printFunction(const std::string& fname,
1962 const std::string& funcName) {
1963 const Function* F = TheModule->getFunction(funcName);
1964 if (!F) {
1965 error(std::string("Function '") + funcName + "' not found in input module");
1966 return;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001967 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001968 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1969 printFunctionUses(F);
1970 printFunctionHead(F);
1971 printFunctionBody(F);
1972 Out << "return " << getCppName(F) << ";\n";
1973 Out << "}\n";
1974}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001975
Chris Lattner7e6d7452010-06-21 23:12:56 +00001976void CppWriter::printFunctions() {
1977 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1978 Module::const_iterator I = funcs.begin();
1979 Module::const_iterator IE = funcs.end();
Anton Korobeynikov50276522008-04-23 22:29:24 +00001980
Chris Lattner7e6d7452010-06-21 23:12:56 +00001981 for (; I != IE; ++I) {
1982 const Function &func = *I;
1983 if (!func.isDeclaration()) {
1984 std::string name("define_");
1985 name += func.getName();
1986 printFunction(name, func.getName());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001987 }
1988 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001989}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001990
Chris Lattner7e6d7452010-06-21 23:12:56 +00001991void CppWriter::printVariable(const std::string& fname,
1992 const std::string& varName) {
1993 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001994
Chris Lattner7e6d7452010-06-21 23:12:56 +00001995 if (!GV) {
1996 error(std::string("Variable '") + varName + "' not found in input module");
1997 return;
1998 }
1999 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
2000 printVariableUses(GV);
2001 printVariableHead(GV);
2002 printVariableBody(GV);
2003 Out << "return " << getCppName(GV) << ";\n";
2004 Out << "}\n";
2005}
2006
Chris Lattner1afcace2011-07-09 17:41:24 +00002007void CppWriter::printType(const std::string &fname,
2008 const std::string &typeName) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002009 Type* Ty = TheModule->getTypeByName(typeName);
Chris Lattner7e6d7452010-06-21 23:12:56 +00002010 if (!Ty) {
2011 error(std::string("Type '") + typeName + "' not found in input module");
2012 return;
2013 }
2014 Out << "\nType* " << fname << "(Module *mod) {\n";
2015 printType(Ty);
2016 Out << "return " << getCppName(Ty) << ";\n";
2017 Out << "}\n";
2018}
2019
2020bool CppWriter::runOnModule(Module &M) {
2021 TheModule = &M;
2022
2023 // Emit a header
2024 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
2025
2026 // Get the name of the function we're supposed to generate
2027 std::string fname = FuncName.getValue();
2028
2029 // Get the name of the thing we are to generate
2030 std::string tgtname = NameToGenerate.getValue();
2031 if (GenerationType == GenModule ||
2032 GenerationType == GenContents ||
2033 GenerationType == GenProgram ||
2034 GenerationType == GenFunctions) {
2035 if (tgtname == "!bad!") {
2036 if (M.getModuleIdentifier() == "-")
2037 tgtname = "<stdin>";
2038 else
2039 tgtname = M.getModuleIdentifier();
Anton Korobeynikov50276522008-04-23 22:29:24 +00002040 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00002041 } else if (tgtname == "!bad!")
2042 error("You must use the -for option with -gen-{function,variable,type}");
2043
2044 switch (WhatToGenerate(GenerationType)) {
2045 case GenProgram:
2046 if (fname.empty())
2047 fname = "makeLLVMModule";
2048 printProgram(fname,tgtname);
2049 break;
2050 case GenModule:
2051 if (fname.empty())
2052 fname = "makeLLVMModule";
2053 printModule(fname,tgtname);
2054 break;
2055 case GenContents:
2056 if (fname.empty())
2057 fname = "makeLLVMModuleContents";
2058 printContents(fname,tgtname);
2059 break;
2060 case GenFunction:
2061 if (fname.empty())
2062 fname = "makeLLVMFunction";
2063 printFunction(fname,tgtname);
2064 break;
2065 case GenFunctions:
2066 printFunctions();
2067 break;
2068 case GenInline:
2069 if (fname.empty())
2070 fname = "makeLLVMInline";
2071 printInline(fname,tgtname);
2072 break;
2073 case GenVariable:
2074 if (fname.empty())
2075 fname = "makeLLVMVariable";
2076 printVariable(fname,tgtname);
2077 break;
2078 case GenType:
2079 if (fname.empty())
2080 fname = "makeLLVMType";
2081 printType(fname,tgtname);
2082 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002083 }
2084
Chris Lattner7e6d7452010-06-21 23:12:56 +00002085 return false;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002086}
2087
2088char CppWriter::ID = 0;
2089
2090//===----------------------------------------------------------------------===//
2091// External Interface declaration
2092//===----------------------------------------------------------------------===//
2093
Dan Gohman99dca4f2010-05-11 19:57:55 +00002094bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
2095 formatted_raw_ostream &o,
2096 CodeGenFileType FileType,
Bob Wilson30a507a2012-07-02 19:48:45 +00002097 bool DisableVerify,
2098 AnalysisID StartAfter,
2099 AnalysisID StopAfter) {
Chris Lattner211edae2010-02-02 21:06:45 +00002100 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002101 PM.add(new CppWriter(o));
2102 return false;
2103}