blob: c5bd13c05b84399ef18b6cfa7e5afe7398cc0429 [file] [log] [blame]
Anton Korobeynikov78695032008-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 Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/SmallPtrSet.h"
17#include "llvm/ADT/StringExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/Config/config.h"
Chandler Carruth9fb823b2013-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 Cheng1705ab02011-07-14 23:50:31 +000026#include "llvm/MC/MCAsmInfo.h"
Evan Chengc5e6d2f2011-07-11 03:57:24 +000027#include "llvm/MC/MCInstrInfo.h"
Evan Cheng91111d22011-07-09 05:47:46 +000028#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/Pass.h"
30#include "llvm/PassManager.h"
Anton Korobeynikov78695032008-04-23 22:29:24 +000031#include "llvm/Support/CommandLine.h"
Torok Edwinf8d479c2009-07-08 20:55:50 +000032#include "llvm/Support/ErrorHandling.h"
David Greenea31f96c2009-07-14 20:18:05 +000033#include "llvm/Support/FormattedStream.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000034#include "llvm/Support/TargetRegistry.h"
Anton Korobeynikov78695032008-04-23 22:29:24 +000035#include <algorithm>
Will Dietz981af002013-10-12 00:55:57 +000036#include <cctype>
Benjamin Kramerb0640db2012-03-23 11:35:30 +000037#include <cstdio>
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000038#include <map>
Benjamin Kramerb0640db2012-03-23 11:35:30 +000039#include <set>
Anton Korobeynikov78695032008-04-23 22:29:24 +000040using namespace llvm;
41
42static cl::opt<std::string>
Anton Korobeynikov9dcc3e92008-04-23 22:37:03 +000043FuncName("cppfname", cl::desc("Specify the name of the generated function"),
Anton Korobeynikov78695032008-04-23 22:29:24 +000044 cl::value_desc("function name"));
45
46enum WhatToGenerate {
47 GenProgram,
48 GenModule,
49 GenContents,
50 GenFunction,
51 GenFunctions,
52 GenInline,
53 GenVariable,
54 GenType
55};
56
Anton Korobeynikov9dcc3e92008-04-23 22:37:03 +000057static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
Anton Korobeynikov78695032008-04-23 22:29:24 +000058 cl::desc("Choose what kind of output to generate"),
59 cl::init(GenProgram),
60 cl::values(
Anton Korobeynikov9dcc3e92008-04-23 22:37:03 +000061 clEnumValN(GenProgram, "program", "Generate a complete program"),
62 clEnumValN(GenModule, "module", "Generate a module definition"),
63 clEnumValN(GenContents, "contents", "Generate contents of a module"),
64 clEnumValN(GenFunction, "function", "Generate a function definition"),
65 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
66 clEnumValN(GenInline, "inline", "Generate an inline function"),
67 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
68 clEnumValN(GenType, "type", "Generate a type definition"),
Anton Korobeynikov78695032008-04-23 22:29:24 +000069 clEnumValEnd
70 )
71);
72
Anton Korobeynikov9dcc3e92008-04-23 22:37:03 +000073static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
Anton Korobeynikov78695032008-04-23 22:29:24 +000074 cl::desc("Specify the name of the thing to generate"),
75 cl::init("!bad!"));
76
Daniel Dunbar5680b4f2009-07-25 06:49:55 +000077extern "C" void LLVMInitializeCppBackendTarget() {
78 // Register the target.
Daniel Dunbar09c1d002009-08-04 04:02:45 +000079 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
Daniel Dunbar5680b4f2009-07-25 06:49:55 +000080}
Douglas Gregor1b731d52009-06-16 20:12:29 +000081
Dan Gohmand78c4002008-05-13 00:00:25 +000082namespace {
Chris Lattner229907c2011-07-18 04:54:35 +000083 typedef std::vector<Type*> TypeList;
84 typedef std::map<Type*,std::string> TypeMap;
Anton Korobeynikov78695032008-04-23 22:29:24 +000085 typedef std::map<const Value*,std::string> ValueMap;
86 typedef std::set<std::string> NameSet;
Chris Lattner229907c2011-07-18 04:54:35 +000087 typedef std::set<Type*> TypeSet;
Anton Korobeynikov78695032008-04-23 22:29:24 +000088 typedef std::set<const Value*> ValueSet;
89 typedef std::map<const Value*,std::string> ForwardRefMap;
90
91 /// CppWriter - This class is the main chunk of code that converts an LLVM
92 /// module to a C++ translation unit.
93 class CppWriter : public ModulePass {
David Greenea31f96c2009-07-14 20:18:05 +000094 formatted_raw_ostream &Out;
Anton Korobeynikov78695032008-04-23 22:29:24 +000095 const Module *TheModule;
96 uint64_t uniqueNum;
97 TypeMap TypeNames;
98 ValueMap ValueNames;
Anton Korobeynikov78695032008-04-23 22:29:24 +000099 NameSet UsedNames;
100 TypeSet DefinedTypes;
101 ValueSet DefinedValues;
102 ForwardRefMap ForwardRefs;
103 bool is_inline;
Chris Lattnerbb45b962010-06-21 23:14:47 +0000104 unsigned indent_level;
Anton Korobeynikov78695032008-04-23 22:29:24 +0000105
106 public:
107 static char ID;
David Greenea31f96c2009-07-14 20:18:05 +0000108 explicit CppWriter(formatted_raw_ostream &o) :
Owen Andersona7aed182010-08-06 18:33:48 +0000109 ModulePass(ID), Out(o), uniqueNum(0), is_inline(false), indent_level(0){}
Anton Korobeynikov78695032008-04-23 22:29:24 +0000110
111 virtual const char *getPassName() const { return "C++ backend"; }
112
113 bool runOnModule(Module &M);
114
Anton Korobeynikov78695032008-04-23 22:29:24 +0000115 void printProgram(const std::string& fname, const std::string& modName );
116 void printModule(const std::string& fname, const std::string& modName );
117 void printContents(const std::string& fname, const std::string& modName );
118 void printFunction(const std::string& fname, const std::string& funcName );
119 void printFunctions();
120 void printInline(const std::string& fname, const std::string& funcName );
121 void printVariable(const std::string& fname, const std::string& varName );
122 void printType(const std::string& fname, const std::string& typeName );
123
124 void error(const std::string& msg);
125
Chris Lattnerbb45b962010-06-21 23:14:47 +0000126
127 formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0);
128 inline void in() { indent_level++; }
129 inline void out() { if (indent_level >0) indent_level--; }
130
Anton Korobeynikov78695032008-04-23 22:29:24 +0000131 private:
132 void printLinkageType(GlobalValue::LinkageTypes LT);
133 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000134 void printThreadLocalMode(GlobalVariable::ThreadLocalMode TLM);
Sandeep Patel68c5f472009-09-02 08:44:58 +0000135 void printCallingConv(CallingConv::ID cc);
Anton Korobeynikov78695032008-04-23 22:29:24 +0000136 void printEscapedString(const std::string& str);
137 void printCFP(const ConstantFP* CFP);
138
Chris Lattner229907c2011-07-18 04:54:35 +0000139 std::string getCppName(Type* val);
140 inline void printCppName(Type* val);
Anton Korobeynikov78695032008-04-23 22:29:24 +0000141
142 std::string getCppName(const Value* val);
143 inline void printCppName(const Value* val);
144
Bill Wendlinge94d8432012-12-07 23:16:57 +0000145 void printAttributes(const AttributeSet &PAL, const std::string &name);
Chris Lattner229907c2011-07-18 04:54:35 +0000146 void printType(Type* Ty);
Anton Korobeynikov78695032008-04-23 22:29:24 +0000147 void printTypes(const Module* M);
148
149 void printConstant(const Constant *CPV);
150 void printConstants(const Module* M);
151
152 void printVariableUses(const GlobalVariable *GV);
153 void printVariableHead(const GlobalVariable *GV);
154 void printVariableBody(const GlobalVariable *GV);
155
156 void printFunctionUses(const Function *F);
157 void printFunctionHead(const Function *F);
158 void printFunctionBody(const Function *F);
159 void printInstruction(const Instruction *I, const std::string& bbname);
Eli Friedman95031ed2011-09-29 20:21:17 +0000160 std::string getOpName(const Value*);
Anton Korobeynikov78695032008-04-23 22:29:24 +0000161
162 void printModuleBody();
163 };
Chris Lattnera0b8c902010-06-21 23:12:56 +0000164} // end anonymous namespace.
Anton Korobeynikov78695032008-04-23 22:29:24 +0000165
Chris Lattnerbb45b962010-06-21 23:14:47 +0000166formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
167 Out << '\n';
Chris Lattnera0b8c902010-06-21 23:12:56 +0000168 if (delta >= 0 || indent_level >= unsigned(-delta))
169 indent_level += delta;
Chris Lattnerbb45b962010-06-21 23:14:47 +0000170 Out.indent(indent_level);
Chris Lattnera0b8c902010-06-21 23:12:56 +0000171 return Out;
172}
173
Chris Lattnera0b8c902010-06-21 23:12:56 +0000174static inline void sanitize(std::string &str) {
175 for (size_t i = 0; i < str.length(); ++i)
176 if (!isalnum(str[i]) && str[i] != '_')
177 str[i] = '_';
178}
179
Chris Lattner229907c2011-07-18 04:54:35 +0000180static std::string getTypePrefix(Type *Ty) {
Chris Lattnera0b8c902010-06-21 23:12:56 +0000181 switch (Ty->getTypeID()) {
182 case Type::VoidTyID: return "void_";
183 case Type::IntegerTyID:
184 return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
185 case Type::FloatTyID: return "float_";
186 case Type::DoubleTyID: return "double_";
187 case Type::LabelTyID: return "label_";
188 case Type::FunctionTyID: return "func_";
189 case Type::StructTyID: return "struct_";
190 case Type::ArrayTyID: return "array_";
191 case Type::PointerTyID: return "ptr_";
192 case Type::VectorTyID: return "packed_";
Chris Lattnera0b8c902010-06-21 23:12:56 +0000193 default: return "other_";
Anton Korobeynikov78695032008-04-23 22:29:24 +0000194 }
Chris Lattnera0b8c902010-06-21 23:12:56 +0000195}
Anton Korobeynikov78695032008-04-23 22:29:24 +0000196
Chris Lattnera0b8c902010-06-21 23:12:56 +0000197void CppWriter::error(const std::string& msg) {
198 report_fatal_error(msg);
199}
Anton Korobeynikov78695032008-04-23 22:29:24 +0000200
Benjamin Kramercbf108e2012-03-23 11:26:29 +0000201static inline std::string ftostr(const APFloat& V) {
202 std::string Buf;
203 if (&V.getSemantics() == &APFloat::IEEEdouble) {
204 raw_string_ostream(Buf) << V.convertToDouble();
205 return Buf;
206 } else if (&V.getSemantics() == &APFloat::IEEEsingle) {
207 raw_string_ostream(Buf) << (double)V.convertToFloat();
208 return Buf;
209 }
210 return "<unknown format in ftostr>"; // error
211}
212
Chris Lattnera0b8c902010-06-21 23:12:56 +0000213// printCFP - Print a floating point constant .. very carefully :)
214// This makes sure that conversion to/from floating yields the same binary
215// result so that we don't lose precision.
216void CppWriter::printCFP(const ConstantFP *CFP) {
217 bool ignored;
218 APFloat APF = APFloat(CFP->getValueAPF()); // copy
219 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
220 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
221 Out << "ConstantFP::get(mod->getContext(), ";
222 Out << "APFloat(";
Anton Korobeynikov78695032008-04-23 22:29:24 +0000223#if HAVE_PRINTF_A
Chris Lattnera0b8c902010-06-21 23:12:56 +0000224 char Buffer[100];
225 sprintf(Buffer, "%A", APF.convertToDouble());
226 if ((!strncmp(Buffer, "0x", 2) ||
227 !strncmp(Buffer, "-0x", 3) ||
228 !strncmp(Buffer, "+0x", 3)) &&
229 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
230 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
231 Out << "BitsToDouble(" << Buffer << ")";
Anton Korobeynikov78695032008-04-23 22:29:24 +0000232 else
Chris Lattnera0b8c902010-06-21 23:12:56 +0000233 Out << "BitsToFloat((float)" << Buffer << ")";
234 Out << ")";
235 } else {
236#endif
237 std::string StrVal = ftostr(CFP->getValueAPF());
Anton Korobeynikov78695032008-04-23 22:29:24 +0000238
Chris Lattnera0b8c902010-06-21 23:12:56 +0000239 while (StrVal[0] == ' ')
240 StrVal.erase(StrVal.begin());
241
242 // Check to make sure that the stringized number is not some string like
243 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
244 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
245 ((StrVal[0] == '-' || StrVal[0] == '+') &&
246 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
247 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
248 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
249 Out << StrVal;
250 else
251 Out << StrVal << "f";
252 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
253 Out << "BitsToDouble(0x"
254 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
255 << "ULL) /* " << StrVal << " */";
256 else
257 Out << "BitsToFloat(0x"
258 << utohexstr((uint32_t)CFP->getValueAPF().
259 bitcastToAPInt().getZExtValue())
260 << "U) /* " << StrVal << " */";
261 Out << ")";
262#if HAVE_PRINTF_A
263 }
264#endif
265 Out << ")";
266}
267
268void CppWriter::printCallingConv(CallingConv::ID cc){
269 // Print the calling convention.
270 switch (cc) {
271 case CallingConv::C: Out << "CallingConv::C"; break;
272 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
273 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
274 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
275 default: Out << cc; break;
276 }
277}
278
279void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
280 switch (LT) {
281 case GlobalValue::InternalLinkage:
282 Out << "GlobalValue::InternalLinkage"; break;
283 case GlobalValue::PrivateLinkage:
284 Out << "GlobalValue::PrivateLinkage"; break;
285 case GlobalValue::LinkerPrivateLinkage:
286 Out << "GlobalValue::LinkerPrivateLinkage"; break;
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000287 case GlobalValue::LinkerPrivateWeakLinkage:
288 Out << "GlobalValue::LinkerPrivateWeakLinkage"; break;
Chris Lattnera0b8c902010-06-21 23:12:56 +0000289 case GlobalValue::AvailableExternallyLinkage:
290 Out << "GlobalValue::AvailableExternallyLinkage "; break;
291 case GlobalValue::LinkOnceAnyLinkage:
292 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
293 case GlobalValue::LinkOnceODRLinkage:
294 Out << "GlobalValue::LinkOnceODRLinkage "; break;
Bill Wendling34bc34e2012-08-17 18:33:14 +0000295 case GlobalValue::LinkOnceODRAutoHideLinkage:
296 Out << "GlobalValue::LinkOnceODRAutoHideLinkage"; break;
Chris Lattnera0b8c902010-06-21 23:12:56 +0000297 case GlobalValue::WeakAnyLinkage:
298 Out << "GlobalValue::WeakAnyLinkage"; break;
299 case GlobalValue::WeakODRLinkage:
300 Out << "GlobalValue::WeakODRLinkage"; break;
301 case GlobalValue::AppendingLinkage:
302 Out << "GlobalValue::AppendingLinkage"; break;
303 case GlobalValue::ExternalLinkage:
304 Out << "GlobalValue::ExternalLinkage"; break;
305 case GlobalValue::DLLImportLinkage:
306 Out << "GlobalValue::DLLImportLinkage"; break;
307 case GlobalValue::DLLExportLinkage:
308 Out << "GlobalValue::DLLExportLinkage"; break;
309 case GlobalValue::ExternalWeakLinkage:
310 Out << "GlobalValue::ExternalWeakLinkage"; break;
311 case GlobalValue::CommonLinkage:
312 Out << "GlobalValue::CommonLinkage"; break;
313 }
314}
315
316void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
317 switch (VisType) {
Chris Lattnera0b8c902010-06-21 23:12:56 +0000318 case GlobalValue::DefaultVisibility:
319 Out << "GlobalValue::DefaultVisibility";
320 break;
321 case GlobalValue::HiddenVisibility:
322 Out << "GlobalValue::HiddenVisibility";
323 break;
324 case GlobalValue::ProtectedVisibility:
325 Out << "GlobalValue::ProtectedVisibility";
326 break;
327 }
328}
329
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000330void CppWriter::printThreadLocalMode(GlobalVariable::ThreadLocalMode TLM) {
331 switch (TLM) {
332 case GlobalVariable::NotThreadLocal:
333 Out << "GlobalVariable::NotThreadLocal";
334 break;
335 case GlobalVariable::GeneralDynamicTLSModel:
336 Out << "GlobalVariable::GeneralDynamicTLSModel";
337 break;
338 case GlobalVariable::LocalDynamicTLSModel:
339 Out << "GlobalVariable::LocalDynamicTLSModel";
340 break;
341 case GlobalVariable::InitialExecTLSModel:
342 Out << "GlobalVariable::InitialExecTLSModel";
343 break;
344 case GlobalVariable::LocalExecTLSModel:
345 Out << "GlobalVariable::LocalExecTLSModel";
346 break;
347 }
348}
349
Chris Lattnera0b8c902010-06-21 23:12:56 +0000350// printEscapedString - Print each character of the specified string, escaping
351// it if it is not printable or if it is an escape char.
352void CppWriter::printEscapedString(const std::string &Str) {
353 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
354 unsigned char C = Str[i];
355 if (isprint(C) && C != '"' && C != '\\') {
356 Out << C;
357 } else {
358 Out << "\\x"
359 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
360 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
361 }
362 }
363}
364
Chris Lattner229907c2011-07-18 04:54:35 +0000365std::string CppWriter::getCppName(Type* Ty) {
Chris Lattnera0b8c902010-06-21 23:12:56 +0000366 // First, handle the primitive types .. easy
367 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
368 switch (Ty->getTypeID()) {
369 case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())";
370 case Type::IntegerTyID: {
371 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
372 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
373 }
374 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
375 case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())";
376 case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())";
377 case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())";
Dale Johannesenbaa5d042010-09-10 20:55:01 +0000378 case Type::X86_MMXTyID: return "Type::getX86_MMXTy(mod->getContext())";
Chris Lattnera0b8c902010-06-21 23:12:56 +0000379 default:
380 error("Invalid primitive type");
381 break;
382 }
383 // shouldn't be returned, but make it sensible
384 return "Type::getVoidTy(mod->getContext())";
Anton Korobeynikov78695032008-04-23 22:29:24 +0000385 }
386
Chris Lattnera0b8c902010-06-21 23:12:56 +0000387 // Now, see if we've seen the type before and return that
388 TypeMap::iterator I = TypeNames.find(Ty);
389 if (I != TypeNames.end())
390 return I->second;
391
392 // Okay, let's build a new name for this type. Start with a prefix
393 const char* prefix = 0;
394 switch (Ty->getTypeID()) {
395 case Type::FunctionTyID: prefix = "FuncTy_"; break;
396 case Type::StructTyID: prefix = "StructTy_"; break;
397 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
398 case Type::PointerTyID: prefix = "PointerTy_"; break;
Chris Lattnera0b8c902010-06-21 23:12:56 +0000399 case Type::VectorTyID: prefix = "VectorTy_"; break;
400 default: prefix = "OtherTy_"; break; // prevent breakage
Anton Korobeynikov78695032008-04-23 22:29:24 +0000401 }
402
Chris Lattnera0b8c902010-06-21 23:12:56 +0000403 // See if the type has a name in the symboltable and build accordingly
Chris Lattnera0b8c902010-06-21 23:12:56 +0000404 std::string name;
Chris Lattner229907c2011-07-18 04:54:35 +0000405 if (StructType *STy = dyn_cast<StructType>(Ty))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000406 if (STy->hasName())
407 name = STy->getName();
408
409 if (name.empty())
410 name = utostr(uniqueNum++);
411
412 name = std::string(prefix) + name;
Chris Lattnera0b8c902010-06-21 23:12:56 +0000413 sanitize(name);
Anton Korobeynikov78695032008-04-23 22:29:24 +0000414
Chris Lattnera0b8c902010-06-21 23:12:56 +0000415 // Save the name
416 return TypeNames[Ty] = name;
417}
418
Chris Lattner229907c2011-07-18 04:54:35 +0000419void CppWriter::printCppName(Type* Ty) {
Chris Lattnera0b8c902010-06-21 23:12:56 +0000420 printEscapedString(getCppName(Ty));
421}
422
423std::string CppWriter::getCppName(const Value* val) {
424 std::string name;
425 ValueMap::iterator I = ValueNames.find(val);
426 if (I != ValueNames.end() && I->first == val)
427 return I->second;
428
429 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
430 name = std::string("gvar_") +
431 getTypePrefix(GV->getType()->getElementType());
432 } else if (isa<Function>(val)) {
433 name = std::string("func_");
434 } else if (const Constant* C = dyn_cast<Constant>(val)) {
435 name = std::string("const_") + getTypePrefix(C->getType());
436 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
437 if (is_inline) {
438 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
439 Function::const_arg_iterator(Arg)) + 1;
440 name = std::string("arg_") + utostr(argNum);
441 NameSet::iterator NI = UsedNames.find(name);
442 if (NI != UsedNames.end())
443 name += std::string("_") + utostr(uniqueNum++);
444 UsedNames.insert(name);
445 return ValueNames[val] = name;
Anton Korobeynikov78695032008-04-23 22:29:24 +0000446 } else {
447 name = getTypePrefix(val->getType());
448 }
Chris Lattnera0b8c902010-06-21 23:12:56 +0000449 } else {
450 name = getTypePrefix(val->getType());
Anton Korobeynikov78695032008-04-23 22:29:24 +0000451 }
Chris Lattnera0b8c902010-06-21 23:12:56 +0000452 if (val->hasName())
453 name += val->getName();
454 else
455 name += utostr(uniqueNum++);
456 sanitize(name);
457 NameSet::iterator NI = UsedNames.find(name);
458 if (NI != UsedNames.end())
459 name += std::string("_") + utostr(uniqueNum++);
460 UsedNames.insert(name);
461 return ValueNames[val] = name;
462}
Anton Korobeynikov78695032008-04-23 22:29:24 +0000463
Chris Lattnera0b8c902010-06-21 23:12:56 +0000464void CppWriter::printCppName(const Value* val) {
465 printEscapedString(getCppName(val));
466}
Anton Korobeynikov78695032008-04-23 22:29:24 +0000467
Bill Wendlinge94d8432012-12-07 23:16:57 +0000468void CppWriter::printAttributes(const AttributeSet &PAL,
Chris Lattnera0b8c902010-06-21 23:12:56 +0000469 const std::string &name) {
Bill Wendlinge94d8432012-12-07 23:16:57 +0000470 Out << "AttributeSet " << name << "_PAL;";
Chris Lattnera0b8c902010-06-21 23:12:56 +0000471 nl(Out);
472 if (!PAL.isEmpty()) {
473 Out << '{'; in(); nl(Out);
Bill Wendlingcc1fc942013-01-27 01:22:51 +0000474 Out << "SmallVector<AttributeSet, 4> Attrs;"; nl(Out);
475 Out << "AttributeSet PAS;"; in(); nl(Out);
Chris Lattnera0b8c902010-06-21 23:12:56 +0000476 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
Bill Wendling86492832013-01-25 21:46:52 +0000477 unsigned index = PAL.getSlotIndex(i);
Bill Wendling57625a42013-01-25 23:09:36 +0000478 AttrBuilder attrs(PAL.getSlotAttributes(i), index);
Bill Wendlingcc1fc942013-01-27 01:22:51 +0000479 Out << "{"; in(); nl(Out);
480 Out << "AttrBuilder B;"; nl(Out);
Bill Wendlingbbcdf4e2012-10-10 07:36:45 +0000481
Bill Wendlingcc1fc942013-01-27 01:22:51 +0000482#define HANDLE_ATTR(X) \
483 if (attrs.contains(Attribute::X)) { \
484 Out << "B.addAttribute(Attribute::" #X ");"; nl(Out); \
485 attrs.removeAttribute(Attribute::X); \
486 }
Bill Wendlingbbcdf4e2012-10-10 07:36:45 +0000487
Chris Lattnera0b8c902010-06-21 23:12:56 +0000488 HANDLE_ATTR(SExt);
489 HANDLE_ATTR(ZExt);
490 HANDLE_ATTR(NoReturn);
491 HANDLE_ATTR(InReg);
492 HANDLE_ATTR(StructRet);
493 HANDLE_ATTR(NoUnwind);
494 HANDLE_ATTR(NoAlias);
495 HANDLE_ATTR(ByVal);
496 HANDLE_ATTR(Nest);
497 HANDLE_ATTR(ReadNone);
498 HANDLE_ATTR(ReadOnly);
Chris Lattnera0b8c902010-06-21 23:12:56 +0000499 HANDLE_ATTR(NoInline);
500 HANDLE_ATTR(AlwaysInline);
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000501 HANDLE_ATTR(OptimizeNone);
Chris Lattnera0b8c902010-06-21 23:12:56 +0000502 HANDLE_ATTR(OptimizeForSize);
503 HANDLE_ATTR(StackProtect);
504 HANDLE_ATTR(StackProtectReq);
Bill Wendlingd154e2832013-01-23 06:41:41 +0000505 HANDLE_ATTR(StackProtectStrong);
Chris Lattnera0b8c902010-06-21 23:12:56 +0000506 HANDLE_ATTR(NoCapture);
Eli Friedmanba9b25a2010-07-16 18:47:20 +0000507 HANDLE_ATTR(NoRedZone);
508 HANDLE_ATTR(NoImplicitFloat);
509 HANDLE_ATTR(Naked);
510 HANDLE_ATTR(InlineHint);
Rafael Espindolacc349c82011-10-03 14:45:37 +0000511 HANDLE_ATTR(ReturnsTwice);
Bill Wendling413bff12011-08-09 00:47:30 +0000512 HANDLE_ATTR(UWTable);
513 HANDLE_ATTR(NonLazyBind);
Quentin Colombet5799e9f2012-10-30 16:32:52 +0000514 HANDLE_ATTR(MinSize);
Chris Lattner1a579352009-01-13 07:22:22 +0000515#undef HANDLE_ATTR
Bill Wendlingcc1fc942013-01-27 01:22:51 +0000516
517 if (attrs.contains(Attribute::StackAlignment)) {
518 Out << "B.addStackAlignmentAttr(" << attrs.getStackAlignment()<<')';
519 nl(Out);
520 attrs.removeAttribute(Attribute::StackAlignment);
521 }
522
Bill Wendlingcc1fc942013-01-27 01:22:51 +0000523 Out << "PAS = AttributeSet::get(mod->getContext(), ";
524 if (index == ~0U)
525 Out << "~0U,";
526 else
527 Out << index << "U,";
528 Out << " B);"; out(); nl(Out);
529 Out << "}"; out(); nl(Out);
Anton Korobeynikov78695032008-04-23 22:29:24 +0000530 nl(Out);
Bill Wendlingcc1fc942013-01-27 01:22:51 +0000531 Out << "Attrs.push_back(PAS);"; nl(Out);
Anton Korobeynikov78695032008-04-23 22:29:24 +0000532 }
Bill Wendlinge94d8432012-12-07 23:16:57 +0000533 Out << name << "_PAL = AttributeSet::get(mod->getContext(), Attrs);";
Chris Lattnera0b8c902010-06-21 23:12:56 +0000534 nl(Out);
535 out(); nl(Out);
536 Out << '}'; nl(Out);
537 }
538}
539
Chris Lattner229907c2011-07-18 04:54:35 +0000540void CppWriter::printType(Type* Ty) {
Chris Lattnera0b8c902010-06-21 23:12:56 +0000541 // We don't print definitions for primitive types
542 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
Nicolas Geoffrayf470b5b2011-07-14 21:04:35 +0000543 return;
Chris Lattnera0b8c902010-06-21 23:12:56 +0000544
545 // If we already defined this type, we don't need to define it again.
546 if (DefinedTypes.find(Ty) != DefinedTypes.end())
Nicolas Geoffrayf470b5b2011-07-14 21:04:35 +0000547 return;
Chris Lattnera0b8c902010-06-21 23:12:56 +0000548
549 // Everything below needs the name for the type so get it now.
550 std::string typeName(getCppName(Ty));
551
Chris Lattnera0b8c902010-06-21 23:12:56 +0000552 // Print the type definition
553 switch (Ty->getTypeID()) {
554 case Type::FunctionTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000555 FunctionType* FT = cast<FunctionType>(Ty);
Nicolas Geoffrayf470b5b2011-07-14 21:04:35 +0000556 Out << "std::vector<Type*>" << typeName << "_args;";
Chris Lattnera0b8c902010-06-21 23:12:56 +0000557 nl(Out);
558 FunctionType::param_iterator PI = FT->param_begin();
559 FunctionType::param_iterator PE = FT->param_end();
560 for (; PI != PE; ++PI) {
Chris Lattner229907c2011-07-18 04:54:35 +0000561 Type* argTy = static_cast<Type*>(*PI);
Nicolas Geoffrayf470b5b2011-07-14 21:04:35 +0000562 printType(argTy);
Chris Lattnera0b8c902010-06-21 23:12:56 +0000563 std::string argName(getCppName(argTy));
564 Out << typeName << "_args.push_back(" << argName;
Chris Lattnera0b8c902010-06-21 23:12:56 +0000565 Out << ");";
Anton Korobeynikov78695032008-04-23 22:29:24 +0000566 nl(Out);
567 }
Nicolas Geoffrayf470b5b2011-07-14 21:04:35 +0000568 printType(FT->getReturnType());
Chris Lattnera0b8c902010-06-21 23:12:56 +0000569 std::string retTypeName(getCppName(FT->getReturnType()));
570 Out << "FunctionType* " << typeName << " = FunctionType::get(";
571 in(); nl(Out) << "/*Result=*/" << retTypeName;
Chris Lattnera0b8c902010-06-21 23:12:56 +0000572 Out << ",";
573 nl(Out) << "/*Params=*/" << typeName << "_args,";
574 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
575 out();
Anton Korobeynikov78695032008-04-23 22:29:24 +0000576 nl(Out);
Chris Lattnera0b8c902010-06-21 23:12:56 +0000577 break;
Anton Korobeynikov78695032008-04-23 22:29:24 +0000578 }
Chris Lattnera0b8c902010-06-21 23:12:56 +0000579 case Type::StructTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000580 StructType* ST = cast<StructType>(Ty);
Chris Lattner01beceb2011-08-12 18:07:07 +0000581 if (!ST->isLiteral()) {
Nicolas Geoffraya0263e72011-10-08 11:56:36 +0000582 Out << "StructType *" << typeName << " = mod->getTypeByName(\"";
583 printEscapedString(ST->getName());
584 Out << "\");";
585 nl(Out);
586 Out << "if (!" << typeName << ") {";
587 nl(Out);
588 Out << typeName << " = ";
Chris Lattner01beceb2011-08-12 18:07:07 +0000589 Out << "StructType::create(mod->getContext(), \"";
Nicolas Geoffrayf470b5b2011-07-14 21:04:35 +0000590 printEscapedString(ST->getName());
591 Out << "\");";
592 nl(Out);
Nicolas Geoffraya0263e72011-10-08 11:56:36 +0000593 Out << "}";
594 nl(Out);
Nicolas Geoffrayf470b5b2011-07-14 21:04:35 +0000595 // Indicate that this type is now defined.
596 DefinedTypes.insert(Ty);
597 }
598
599 Out << "std::vector<Type*>" << typeName << "_fields;";
Chris Lattnera0b8c902010-06-21 23:12:56 +0000600 nl(Out);
601 StructType::element_iterator EI = ST->element_begin();
602 StructType::element_iterator EE = ST->element_end();
603 for (; EI != EE; ++EI) {
Chris Lattner229907c2011-07-18 04:54:35 +0000604 Type* fieldTy = static_cast<Type*>(*EI);
Nicolas Geoffrayf470b5b2011-07-14 21:04:35 +0000605 printType(fieldTy);
Chris Lattnera0b8c902010-06-21 23:12:56 +0000606 std::string fieldName(getCppName(fieldTy));
607 Out << typeName << "_fields.push_back(" << fieldName;
Chris Lattnera0b8c902010-06-21 23:12:56 +0000608 Out << ");";
Anton Korobeynikov78695032008-04-23 22:29:24 +0000609 nl(Out);
Chris Lattnera0b8c902010-06-21 23:12:56 +0000610 }
Nicolas Geoffrayf470b5b2011-07-14 21:04:35 +0000611
Chris Lattner01beceb2011-08-12 18:07:07 +0000612 if (ST->isLiteral()) {
Nicolas Geoffrayf470b5b2011-07-14 21:04:35 +0000613 Out << "StructType *" << typeName << " = ";
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000614 Out << "StructType::get(" << "mod->getContext(), ";
615 } else {
Nicolas Geoffraya0263e72011-10-08 11:56:36 +0000616 Out << "if (" << typeName << "->isOpaque()) {";
617 nl(Out);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000618 Out << typeName << "->setBody(";
619 }
Nicolas Geoffrayf470b5b2011-07-14 21:04:35 +0000620
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000621 Out << typeName << "_fields, /*isPacked=*/"
Chris Lattnera0b8c902010-06-21 23:12:56 +0000622 << (ST->isPacked() ? "true" : "false") << ");";
623 nl(Out);
Nicolas Geoffraya0263e72011-10-08 11:56:36 +0000624 if (!ST->isLiteral()) {
625 Out << "}";
626 nl(Out);
627 }
Chris Lattnera0b8c902010-06-21 23:12:56 +0000628 break;
629 }
630 case Type::ArrayTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000631 ArrayType* AT = cast<ArrayType>(Ty);
632 Type* ET = AT->getElementType();
Nicolas Geoffrayf470b5b2011-07-14 21:04:35 +0000633 printType(ET);
634 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
635 std::string elemName(getCppName(ET));
636 Out << "ArrayType* " << typeName << " = ArrayType::get("
637 << elemName
638 << ", " << utostr(AT->getNumElements()) << ");";
639 nl(Out);
640 }
Chris Lattnera0b8c902010-06-21 23:12:56 +0000641 break;
642 }
643 case Type::PointerTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000644 PointerType* PT = cast<PointerType>(Ty);
645 Type* ET = PT->getElementType();
Nicolas Geoffrayf470b5b2011-07-14 21:04:35 +0000646 printType(ET);
647 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
648 std::string elemName(getCppName(ET));
649 Out << "PointerType* " << typeName << " = PointerType::get("
650 << elemName
651 << ", " << utostr(PT->getAddressSpace()) << ");";
652 nl(Out);
653 }
Chris Lattnera0b8c902010-06-21 23:12:56 +0000654 break;
655 }
656 case Type::VectorTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000657 VectorType* PT = cast<VectorType>(Ty);
658 Type* ET = PT->getElementType();
Nicolas Geoffrayf470b5b2011-07-14 21:04:35 +0000659 printType(ET);
660 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
661 std::string elemName(getCppName(ET));
662 Out << "VectorType* " << typeName << " = VectorType::get("
663 << elemName
664 << ", " << utostr(PT->getNumElements()) << ");";
665 nl(Out);
666 }
Chris Lattnera0b8c902010-06-21 23:12:56 +0000667 break;
668 }
Chris Lattnera0b8c902010-06-21 23:12:56 +0000669 default:
670 error("Invalid TypeID");
671 }
672
Chris Lattnera0b8c902010-06-21 23:12:56 +0000673 // Indicate that this type is now defined.
674 DefinedTypes.insert(Ty);
675
Chris Lattnera0b8c902010-06-21 23:12:56 +0000676 // Finally, separate the type definition from other with a newline.
677 nl(Out);
Chris Lattnera0b8c902010-06-21 23:12:56 +0000678}
679
680void CppWriter::printTypes(const Module* M) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000681 // Add all of the global variables to the value table.
Chris Lattnera0b8c902010-06-21 23:12:56 +0000682 for (Module::const_global_iterator I = TheModule->global_begin(),
683 E = TheModule->global_end(); I != E; ++I) {
684 if (I->hasInitializer())
685 printType(I->getInitializer()->getType());
686 printType(I->getType());
687 }
688
689 // Add all the functions to the table
690 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
691 FI != FE; ++FI) {
692 printType(FI->getReturnType());
693 printType(FI->getFunctionType());
694 // Add all the function arguments
695 for (Function::const_arg_iterator AI = FI->arg_begin(),
696 AE = FI->arg_end(); AI != AE; ++AI) {
697 printType(AI->getType());
698 }
699
700 // Add all of the basic blocks and instructions
701 for (Function::const_iterator BB = FI->begin(),
702 E = FI->end(); BB != E; ++BB) {
703 printType(BB->getType());
704 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
705 ++I) {
706 printType(I->getType());
707 for (unsigned i = 0; i < I->getNumOperands(); ++i)
708 printType(I->getOperand(i)->getType());
Anton Korobeynikov78695032008-04-23 22:29:24 +0000709 }
Chris Lattnera0b8c902010-06-21 23:12:56 +0000710 }
711 }
712}
713
714
715// printConstant - Print out a constant pool entry...
716void CppWriter::printConstant(const Constant *CV) {
717 // First, if the constant is actually a GlobalValue (variable or function)
718 // or its already in the constant list then we've printed it already and we
719 // can just return.
720 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
721 return;
722
723 std::string constName(getCppName(CV));
724 std::string typeName(getCppName(CV->getType()));
725
Chris Lattnera0b8c902010-06-21 23:12:56 +0000726 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
727 std::string constValue = CI->getValue().toString(10, true);
728 Out << "ConstantInt* " << constName
729 << " = ConstantInt::get(mod->getContext(), APInt("
730 << cast<IntegerType>(CI->getType())->getBitWidth()
731 << ", StringRef(\"" << constValue << "\"), 10));";
732 } else if (isa<ConstantAggregateZero>(CV)) {
733 Out << "ConstantAggregateZero* " << constName
734 << " = ConstantAggregateZero::get(" << typeName << ");";
735 } else if (isa<ConstantPointerNull>(CV)) {
736 Out << "ConstantPointerNull* " << constName
737 << " = ConstantPointerNull::get(" << typeName << ");";
738 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
739 Out << "ConstantFP* " << constName << " = ";
740 printCFP(CFP);
741 Out << ";";
742 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000743 Out << "std::vector<Constant*> " << constName << "_elems;";
744 nl(Out);
745 unsigned N = CA->getNumOperands();
746 for (unsigned i = 0; i < N; ++i) {
747 printConstant(CA->getOperand(i)); // recurse to print operands
748 Out << constName << "_elems.push_back("
749 << getCppName(CA->getOperand(i)) << ");";
Anton Korobeynikov78695032008-04-23 22:29:24 +0000750 nl(Out);
Chris Lattnera0b8c902010-06-21 23:12:56 +0000751 }
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000752 Out << "Constant* " << constName << " = ConstantArray::get("
753 << typeName << ", " << constName << "_elems);";
Chris Lattnera0b8c902010-06-21 23:12:56 +0000754 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
755 Out << "std::vector<Constant*> " << constName << "_fields;";
756 nl(Out);
757 unsigned N = CS->getNumOperands();
758 for (unsigned i = 0; i < N; i++) {
759 printConstant(CS->getOperand(i));
760 Out << constName << "_fields.push_back("
761 << getCppName(CS->getOperand(i)) << ");";
762 nl(Out);
763 }
764 Out << "Constant* " << constName << " = ConstantStruct::get("
765 << typeName << ", " << constName << "_fields);";
Duncan Sandsefabc252012-02-05 14:16:09 +0000766 } else if (const ConstantVector *CVec = dyn_cast<ConstantVector>(CV)) {
Chris Lattnera0b8c902010-06-21 23:12:56 +0000767 Out << "std::vector<Constant*> " << constName << "_elems;";
768 nl(Out);
Duncan Sandsefabc252012-02-05 14:16:09 +0000769 unsigned N = CVec->getNumOperands();
Chris Lattnera0b8c902010-06-21 23:12:56 +0000770 for (unsigned i = 0; i < N; ++i) {
Duncan Sandsefabc252012-02-05 14:16:09 +0000771 printConstant(CVec->getOperand(i));
Chris Lattnera0b8c902010-06-21 23:12:56 +0000772 Out << constName << "_elems.push_back("
Duncan Sandsefabc252012-02-05 14:16:09 +0000773 << getCppName(CVec->getOperand(i)) << ");";
Chris Lattnera0b8c902010-06-21 23:12:56 +0000774 nl(Out);
775 }
776 Out << "Constant* " << constName << " = ConstantVector::get("
777 << typeName << ", " << constName << "_elems);";
778 } else if (isa<UndefValue>(CV)) {
779 Out << "UndefValue* " << constName << " = UndefValue::get("
780 << typeName << ");";
Chris Lattner139822f2012-01-24 14:17:05 +0000781 } else if (const ConstantDataSequential *CDS =
782 dyn_cast<ConstantDataSequential>(CV)) {
783 if (CDS->isString()) {
784 Out << "Constant *" << constName <<
785 " = ConstantDataArray::getString(mod->getContext(), \"";
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000786 StringRef Str = CDS->getAsString();
Chris Lattner139822f2012-01-24 14:17:05 +0000787 bool nullTerminate = false;
788 if (Str.back() == 0) {
789 Str = Str.drop_back();
790 nullTerminate = true;
791 }
792 printEscapedString(Str);
793 // Determine if we want null termination or not.
794 if (nullTerminate)
795 Out << "\", true);";
796 else
797 Out << "\", false);";// No null terminator
798 } else {
799 // TODO: Could generate more efficient code generating CDS calls instead.
800 Out << "std::vector<Constant*> " << constName << "_elems;";
801 nl(Out);
802 for (unsigned i = 0; i != CDS->getNumElements(); ++i) {
803 Constant *Elt = CDS->getElementAsConstant(i);
804 printConstant(Elt);
805 Out << constName << "_elems.push_back(" << getCppName(Elt) << ");";
806 nl(Out);
807 }
808 Out << "Constant* " << constName;
809
810 if (isa<ArrayType>(CDS->getType()))
811 Out << " = ConstantArray::get(";
812 else
813 Out << " = ConstantVector::get(";
814 Out << typeName << ", " << constName << "_elems);";
815 }
Chris Lattnera0b8c902010-06-21 23:12:56 +0000816 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
817 if (CE->getOpcode() == Instruction::GetElementPtr) {
818 Out << "std::vector<Constant*> " << constName << "_indices;";
819 nl(Out);
820 printConstant(CE->getOperand(0));
821 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
822 printConstant(CE->getOperand(i));
823 Out << constName << "_indices.push_back("
824 << getCppName(CE->getOperand(i)) << ");";
Anton Korobeynikov78695032008-04-23 22:29:24 +0000825 nl(Out);
Anton Korobeynikov78695032008-04-23 22:29:24 +0000826 }
Chris Lattnera0b8c902010-06-21 23:12:56 +0000827 Out << "Constant* " << constName
828 << " = ConstantExpr::getGetElementPtr("
829 << getCppName(CE->getOperand(0)) << ", "
Nicolas Geoffray6820c1e2011-07-21 20:59:21 +0000830 << constName << "_indices);";
Chris Lattnera0b8c902010-06-21 23:12:56 +0000831 } else if (CE->isCast()) {
832 printConstant(CE->getOperand(0));
833 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
834 switch (CE->getOpcode()) {
835 default: llvm_unreachable("Invalid cast opcode");
836 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
837 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
838 case Instruction::SExt: Out << "Instruction::SExt"; break;
839 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
840 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
841 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
842 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
843 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
844 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
845 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
846 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
847 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
848 }
849 Out << ", " << getCppName(CE->getOperand(0)) << ", "
850 << getCppName(CE->getType()) << ");";
Anton Korobeynikov78695032008-04-23 22:29:24 +0000851 } else {
Chris Lattnera0b8c902010-06-21 23:12:56 +0000852 unsigned N = CE->getNumOperands();
853 for (unsigned i = 0; i < N; ++i ) {
854 printConstant(CE->getOperand(i));
855 }
856 Out << "Constant* " << constName << " = ConstantExpr::";
857 switch (CE->getOpcode()) {
858 case Instruction::Add: Out << "getAdd("; break;
859 case Instruction::FAdd: Out << "getFAdd("; break;
860 case Instruction::Sub: Out << "getSub("; break;
861 case Instruction::FSub: Out << "getFSub("; break;
862 case Instruction::Mul: Out << "getMul("; break;
863 case Instruction::FMul: Out << "getFMul("; break;
864 case Instruction::UDiv: Out << "getUDiv("; break;
865 case Instruction::SDiv: Out << "getSDiv("; break;
866 case Instruction::FDiv: Out << "getFDiv("; break;
867 case Instruction::URem: Out << "getURem("; break;
868 case Instruction::SRem: Out << "getSRem("; break;
869 case Instruction::FRem: Out << "getFRem("; break;
870 case Instruction::And: Out << "getAnd("; break;
871 case Instruction::Or: Out << "getOr("; break;
872 case Instruction::Xor: Out << "getXor("; break;
873 case Instruction::ICmp:
874 Out << "getICmp(ICmpInst::ICMP_";
875 switch (CE->getPredicate()) {
876 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
877 case ICmpInst::ICMP_NE: Out << "NE"; break;
878 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
879 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
880 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
881 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
882 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
883 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
884 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
885 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
886 default: error("Invalid ICmp Predicate");
887 }
888 break;
889 case Instruction::FCmp:
890 Out << "getFCmp(FCmpInst::FCMP_";
891 switch (CE->getPredicate()) {
892 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
893 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
894 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
895 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
896 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
897 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
898 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
899 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
900 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
901 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
902 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
903 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
904 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
905 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
906 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
907 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
908 default: error("Invalid FCmp Predicate");
909 }
910 break;
911 case Instruction::Shl: Out << "getShl("; break;
912 case Instruction::LShr: Out << "getLShr("; break;
913 case Instruction::AShr: Out << "getAShr("; break;
914 case Instruction::Select: Out << "getSelect("; break;
915 case Instruction::ExtractElement: Out << "getExtractElement("; break;
916 case Instruction::InsertElement: Out << "getInsertElement("; break;
917 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
918 default:
919 error("Invalid constant expression");
920 break;
921 }
922 Out << getCppName(CE->getOperand(0));
923 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
924 Out << ", " << getCppName(CE->getOperand(i));
925 Out << ");";
Anton Korobeynikov78695032008-04-23 22:29:24 +0000926 }
Chris Lattner64960f52010-06-21 23:19:36 +0000927 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
928 Out << "Constant* " << constName << " = ";
929 Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
Chris Lattnera0b8c902010-06-21 23:12:56 +0000930 } else {
931 error("Bad Constant");
932 Out << "Constant* " << constName << " = 0; ";
Anton Korobeynikov78695032008-04-23 22:29:24 +0000933 }
Chris Lattnera0b8c902010-06-21 23:12:56 +0000934 nl(Out);
935}
Anton Korobeynikov78695032008-04-23 22:29:24 +0000936
Chris Lattnera0b8c902010-06-21 23:12:56 +0000937void CppWriter::printConstants(const Module* M) {
938 // Traverse all the global variables looking for constant initializers
939 for (Module::const_global_iterator I = TheModule->global_begin(),
940 E = TheModule->global_end(); I != E; ++I)
941 if (I->hasInitializer())
942 printConstant(I->getInitializer());
Anton Korobeynikov78695032008-04-23 22:29:24 +0000943
Chris Lattnera0b8c902010-06-21 23:12:56 +0000944 // Traverse the LLVM functions looking for constants
945 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
946 FI != FE; ++FI) {
947 // Add all of the basic blocks and instructions
948 for (Function::const_iterator BB = FI->begin(),
949 E = FI->end(); BB != E; ++BB) {
950 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
951 ++I) {
952 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
953 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
954 printConstant(C);
Anton Korobeynikov78695032008-04-23 22:29:24 +0000955 }
956 }
957 }
958 }
959 }
Chris Lattnera0b8c902010-06-21 23:12:56 +0000960}
Anton Korobeynikov78695032008-04-23 22:29:24 +0000961
Chris Lattnera0b8c902010-06-21 23:12:56 +0000962void CppWriter::printVariableUses(const GlobalVariable *GV) {
963 nl(Out) << "// Type Definitions";
964 nl(Out);
965 printType(GV->getType());
966 if (GV->hasInitializer()) {
Jay Foad60020682011-06-19 18:37:11 +0000967 const Constant *Init = GV->getInitializer();
Chris Lattnera0b8c902010-06-21 23:12:56 +0000968 printType(Init->getType());
Jay Foad60020682011-06-19 18:37:11 +0000969 if (const Function *F = dyn_cast<Function>(Init)) {
Chris Lattnera0b8c902010-06-21 23:12:56 +0000970 nl(Out)<< "/ Function Declarations"; nl(Out);
971 printFunctionHead(F);
Jay Foad60020682011-06-19 18:37:11 +0000972 } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
Chris Lattnera0b8c902010-06-21 23:12:56 +0000973 nl(Out) << "// Global Variable Declarations"; nl(Out);
974 printVariableHead(gv);
975
976 nl(Out) << "// Global Variable Definitions"; nl(Out);
977 printVariableBody(gv);
978 } else {
979 nl(Out) << "// Constant Definitions"; nl(Out);
980 printConstant(Init);
Anton Korobeynikov78695032008-04-23 22:29:24 +0000981 }
982 }
Chris Lattnera0b8c902010-06-21 23:12:56 +0000983}
Anton Korobeynikov78695032008-04-23 22:29:24 +0000984
Chris Lattnera0b8c902010-06-21 23:12:56 +0000985void CppWriter::printVariableHead(const GlobalVariable *GV) {
986 nl(Out) << "GlobalVariable* " << getCppName(GV);
987 if (is_inline) {
988 Out << " = mod->getGlobalVariable(mod->getContext(), ";
Anton Korobeynikov78695032008-04-23 22:29:24 +0000989 printEscapedString(GV->getName());
Chris Lattnera0b8c902010-06-21 23:12:56 +0000990 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
991 nl(Out) << "if (!" << getCppName(GV) << ") {";
992 in(); nl(Out) << getCppName(GV);
993 }
994 Out << " = new GlobalVariable(/*Module=*/*mod, ";
995 nl(Out) << "/*Type=*/";
996 printCppName(GV->getType()->getElementType());
997 Out << ",";
998 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
999 Out << ",";
1000 nl(Out) << "/*Linkage=*/";
1001 printLinkageType(GV->getLinkage());
1002 Out << ",";
1003 nl(Out) << "/*Initializer=*/0, ";
1004 if (GV->hasInitializer()) {
1005 Out << "// has initializer, specified below";
1006 }
1007 nl(Out) << "/*Name=*/\"";
1008 printEscapedString(GV->getName());
1009 Out << "\");";
1010 nl(Out);
1011
1012 if (GV->hasSection()) {
1013 printCppName(GV);
1014 Out << "->setSection(\"";
1015 printEscapedString(GV->getSection());
Owen Anderson96b491a2009-07-10 16:42:19 +00001016 Out << "\");";
Anton Korobeynikov78695032008-04-23 22:29:24 +00001017 nl(Out);
Anton Korobeynikov78695032008-04-23 22:29:24 +00001018 }
Chris Lattnera0b8c902010-06-21 23:12:56 +00001019 if (GV->getAlignment()) {
1020 printCppName(GV);
1021 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
Anton Korobeynikov78695032008-04-23 22:29:24 +00001022 nl(Out);
Chris Lattnera0b8c902010-06-21 23:12:56 +00001023 }
1024 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1025 printCppName(GV);
1026 Out << "->setVisibility(";
1027 printVisibilityType(GV->getVisibility());
1028 Out << ");";
1029 nl(Out);
1030 }
1031 if (GV->isThreadLocal()) {
1032 printCppName(GV);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001033 Out << "->setThreadLocalMode(";
1034 printThreadLocalMode(GV->getThreadLocalMode());
1035 Out << ");";
Chris Lattnera0b8c902010-06-21 23:12:56 +00001036 nl(Out);
1037 }
1038 if (is_inline) {
1039 out(); Out << "}"; nl(Out);
1040 }
1041}
1042
1043void CppWriter::printVariableBody(const GlobalVariable *GV) {
1044 if (GV->hasInitializer()) {
1045 printCppName(GV);
1046 Out << "->setInitializer(";
1047 Out << getCppName(GV->getInitializer()) << ");";
1048 nl(Out);
1049 }
1050}
1051
Eli Friedman95031ed2011-09-29 20:21:17 +00001052std::string CppWriter::getOpName(const Value* V) {
Chris Lattnera0b8c902010-06-21 23:12:56 +00001053 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1054 return getCppName(V);
1055
1056 // See if its alread in the map of forward references, if so just return the
1057 // name we already set up for it
1058 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1059 if (I != ForwardRefs.end())
1060 return I->second;
1061
1062 // This is a new forward reference. Generate a unique name for it
1063 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1064
1065 // Yes, this is a hack. An Argument is the smallest instantiable value that
1066 // we can make as a placeholder for the real value. We'll replace these
1067 // Argument instances later.
1068 Out << "Argument* " << result << " = new Argument("
1069 << getCppName(V->getType()) << ");";
1070 nl(Out);
1071 ForwardRefs[V] = result;
1072 return result;
1073}
1074
Eli Friedmand28ddbf2011-10-31 23:59:22 +00001075static StringRef ConvertAtomicOrdering(AtomicOrdering Ordering) {
1076 switch (Ordering) {
1077 case NotAtomic: return "NotAtomic";
1078 case Unordered: return "Unordered";
1079 case Monotonic: return "Monotonic";
1080 case Acquire: return "Acquire";
1081 case Release: return "Release";
1082 case AcquireRelease: return "AcquireRelease";
1083 case SequentiallyConsistent: return "SequentiallyConsistent";
1084 }
1085 llvm_unreachable("Unknown ordering");
1086}
1087
1088static StringRef ConvertAtomicSynchScope(SynchronizationScope SynchScope) {
1089 switch (SynchScope) {
1090 case SingleThread: return "SingleThread";
1091 case CrossThread: return "CrossThread";
1092 }
1093 llvm_unreachable("Unknown synch scope");
1094}
1095
Chris Lattnera0b8c902010-06-21 23:12:56 +00001096// printInstruction - This member is called for each Instruction in a function.
1097void CppWriter::printInstruction(const Instruction *I,
1098 const std::string& bbname) {
1099 std::string iName(getCppName(I));
1100
1101 // Before we emit this instruction, we need to take care of generating any
1102 // forward references. So, we get the names of all the operands in advance
1103 const unsigned Ops(I->getNumOperands());
1104 std::string* opNames = new std::string[Ops];
Chris Lattner64960f52010-06-21 23:19:36 +00001105 for (unsigned i = 0; i < Ops; i++)
Chris Lattnera0b8c902010-06-21 23:12:56 +00001106 opNames[i] = getOpName(I->getOperand(i));
Anton Korobeynikov78695032008-04-23 22:29:24 +00001107
Chris Lattnera0b8c902010-06-21 23:12:56 +00001108 switch (I->getOpcode()) {
1109 default:
1110 error("Invalid instruction");
1111 break;
Anton Korobeynikov78695032008-04-23 22:29:24 +00001112
Chris Lattnera0b8c902010-06-21 23:12:56 +00001113 case Instruction::Ret: {
1114 const ReturnInst* ret = cast<ReturnInst>(I);
1115 Out << "ReturnInst::Create(mod->getContext(), "
1116 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1117 break;
1118 }
1119 case Instruction::Br: {
1120 const BranchInst* br = cast<BranchInst>(I);
1121 Out << "BranchInst::Create(" ;
Chris Lattner64960f52010-06-21 23:19:36 +00001122 if (br->getNumOperands() == 3) {
Chris Lattnera0b8c902010-06-21 23:12:56 +00001123 Out << opNames[2] << ", "
Anton Korobeynikov78695032008-04-23 22:29:24 +00001124 << opNames[1] << ", "
Chris Lattnera0b8c902010-06-21 23:12:56 +00001125 << opNames[0] << ", ";
1126
1127 } else if (br->getNumOperands() == 1) {
1128 Out << opNames[0] << ", ";
1129 } else {
1130 error("Branch with 2 operands?");
1131 }
1132 Out << bbname << ");";
1133 break;
1134 }
1135 case Instruction::Switch: {
1136 const SwitchInst *SI = cast<SwitchInst>(I);
1137 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
Eli Friedman95031ed2011-09-29 20:21:17 +00001138 << getOpName(SI->getCondition()) << ", "
1139 << getOpName(SI->getDefaultDest()) << ", "
Chris Lattnera0b8c902010-06-21 23:12:56 +00001140 << SI->getNumCases() << ", " << bbname << ");";
1141 nl(Out);
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00001142 for (SwitchInst::ConstCaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001143 i != e; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00001144 const ConstantInt* CaseVal = i.getCaseValue();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001145 const BasicBlock *BB = i.getCaseSuccessor();
Chris Lattnera0b8c902010-06-21 23:12:56 +00001146 Out << iName << "->addCase("
Eli Friedman95031ed2011-09-29 20:21:17 +00001147 << getOpName(CaseVal) << ", "
1148 << getOpName(BB) << ");";
Anton Korobeynikov78695032008-04-23 22:29:24 +00001149 nl(Out);
Chris Lattnera0b8c902010-06-21 23:12:56 +00001150 }
1151 break;
1152 }
1153 case Instruction::IndirectBr: {
1154 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1155 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1156 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1157 nl(Out);
1158 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1159 Out << iName << "->addDestination(" << opNames[i] << ");";
1160 nl(Out);
1161 }
1162 break;
1163 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00001164 case Instruction::Resume: {
Eli Friedman410393a2013-09-24 00:36:09 +00001165 Out << "ResumeInst::Create(" << opNames[0] << ", " << bbname << ");";
Bill Wendlingf891bf82011-07-31 06:30:59 +00001166 break;
1167 }
Chris Lattnera0b8c902010-06-21 23:12:56 +00001168 case Instruction::Invoke: {
1169 const InvokeInst* inv = cast<InvokeInst>(I);
1170 Out << "std::vector<Value*> " << iName << "_params;";
1171 nl(Out);
1172 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1173 Out << iName << "_params.push_back("
1174 << getOpName(inv->getArgOperand(i)) << ");";
1175 nl(Out);
1176 }
1177 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1178 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
Eli Friedman410393a2013-09-24 00:36:09 +00001179 << getOpName(inv->getCalledValue()) << ", "
Chris Lattnera0b8c902010-06-21 23:12:56 +00001180 << getOpName(inv->getNormalDest()) << ", "
1181 << getOpName(inv->getUnwindDest()) << ", "
Nick Lewyckydf06b6e2011-09-05 18:50:59 +00001182 << iName << "_params, \"";
Chris Lattnera0b8c902010-06-21 23:12:56 +00001183 printEscapedString(inv->getName());
1184 Out << "\", " << bbname << ");";
1185 nl(Out) << iName << "->setCallingConv(";
1186 printCallingConv(inv->getCallingConv());
1187 Out << ");";
1188 printAttributes(inv->getAttributes(), iName);
1189 Out << iName << "->setAttributes(" << iName << "_PAL);";
1190 nl(Out);
1191 break;
1192 }
Chris Lattnera0b8c902010-06-21 23:12:56 +00001193 case Instruction::Unreachable: {
1194 Out << "new UnreachableInst("
1195 << "mod->getContext(), "
1196 << bbname << ");";
1197 break;
1198 }
1199 case Instruction::Add:
1200 case Instruction::FAdd:
1201 case Instruction::Sub:
1202 case Instruction::FSub:
1203 case Instruction::Mul:
1204 case Instruction::FMul:
1205 case Instruction::UDiv:
1206 case Instruction::SDiv:
1207 case Instruction::FDiv:
1208 case Instruction::URem:
1209 case Instruction::SRem:
1210 case Instruction::FRem:
1211 case Instruction::And:
1212 case Instruction::Or:
1213 case Instruction::Xor:
1214 case Instruction::Shl:
1215 case Instruction::LShr:
1216 case Instruction::AShr:{
1217 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1218 switch (I->getOpcode()) {
1219 case Instruction::Add: Out << "Instruction::Add"; break;
1220 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1221 case Instruction::Sub: Out << "Instruction::Sub"; break;
1222 case Instruction::FSub: Out << "Instruction::FSub"; break;
1223 case Instruction::Mul: Out << "Instruction::Mul"; break;
1224 case Instruction::FMul: Out << "Instruction::FMul"; break;
1225 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1226 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1227 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1228 case Instruction::URem:Out << "Instruction::URem"; break;
1229 case Instruction::SRem:Out << "Instruction::SRem"; break;
1230 case Instruction::FRem:Out << "Instruction::FRem"; break;
1231 case Instruction::And: Out << "Instruction::And"; break;
1232 case Instruction::Or: Out << "Instruction::Or"; break;
1233 case Instruction::Xor: Out << "Instruction::Xor"; break;
1234 case Instruction::Shl: Out << "Instruction::Shl"; break;
1235 case Instruction::LShr:Out << "Instruction::LShr"; break;
1236 case Instruction::AShr:Out << "Instruction::AShr"; break;
1237 default: Out << "Instruction::BadOpCode"; break;
1238 }
1239 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1240 printEscapedString(I->getName());
1241 Out << "\", " << bbname << ");";
1242 break;
1243 }
1244 case Instruction::FCmp: {
1245 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1246 switch (cast<FCmpInst>(I)->getPredicate()) {
1247 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1248 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1249 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1250 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1251 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1252 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1253 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1254 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1255 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1256 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1257 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1258 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1259 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1260 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1261 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1262 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1263 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1264 }
1265 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1266 printEscapedString(I->getName());
1267 Out << "\");";
1268 break;
1269 }
1270 case Instruction::ICmp: {
1271 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1272 switch (cast<ICmpInst>(I)->getPredicate()) {
1273 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1274 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1275 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1276 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1277 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1278 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1279 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1280 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1281 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1282 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1283 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1284 }
1285 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1286 printEscapedString(I->getName());
1287 Out << "\");";
1288 break;
1289 }
1290 case Instruction::Alloca: {
1291 const AllocaInst* allocaI = cast<AllocaInst>(I);
1292 Out << "AllocaInst* " << iName << " = new AllocaInst("
1293 << getCppName(allocaI->getAllocatedType()) << ", ";
1294 if (allocaI->isArrayAllocation())
1295 Out << opNames[0] << ", ";
1296 Out << "\"";
1297 printEscapedString(allocaI->getName());
1298 Out << "\", " << bbname << ");";
1299 if (allocaI->getAlignment())
1300 nl(Out) << iName << "->setAlignment("
1301 << allocaI->getAlignment() << ");";
1302 break;
1303 }
Gabor Greif7d4038dd2010-06-26 12:17:21 +00001304 case Instruction::Load: {
Chris Lattnera0b8c902010-06-21 23:12:56 +00001305 const LoadInst* load = cast<LoadInst>(I);
1306 Out << "LoadInst* " << iName << " = new LoadInst("
1307 << opNames[0] << ", \"";
1308 printEscapedString(load->getName());
1309 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1310 << ", " << bbname << ");";
Eli Friedmand28ddbf2011-10-31 23:59:22 +00001311 if (load->getAlignment())
1312 nl(Out) << iName << "->setAlignment("
1313 << load->getAlignment() << ");";
1314 if (load->isAtomic()) {
1315 StringRef Ordering = ConvertAtomicOrdering(load->getOrdering());
1316 StringRef CrossThread = ConvertAtomicSynchScope(load->getSynchScope());
1317 nl(Out) << iName << "->setAtomic("
1318 << Ordering << ", " << CrossThread << ");";
1319 }
Chris Lattnera0b8c902010-06-21 23:12:56 +00001320 break;
1321 }
1322 case Instruction::Store: {
1323 const StoreInst* store = cast<StoreInst>(I);
Eli Friedmand28ddbf2011-10-31 23:59:22 +00001324 Out << "StoreInst* " << iName << " = new StoreInst("
Chris Lattnera0b8c902010-06-21 23:12:56 +00001325 << opNames[0] << ", "
1326 << opNames[1] << ", "
1327 << (store->isVolatile() ? "true" : "false")
1328 << ", " << bbname << ");";
Eli Friedmand28ddbf2011-10-31 23:59:22 +00001329 if (store->getAlignment())
1330 nl(Out) << iName << "->setAlignment("
1331 << store->getAlignment() << ");";
1332 if (store->isAtomic()) {
1333 StringRef Ordering = ConvertAtomicOrdering(store->getOrdering());
1334 StringRef CrossThread = ConvertAtomicSynchScope(store->getSynchScope());
1335 nl(Out) << iName << "->setAtomic("
1336 << Ordering << ", " << CrossThread << ");";
1337 }
Chris Lattnera0b8c902010-06-21 23:12:56 +00001338 break;
1339 }
1340 case Instruction::GetElementPtr: {
1341 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1342 if (gep->getNumOperands() <= 2) {
1343 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1344 << opNames[0];
1345 if (gep->getNumOperands() == 2)
1346 Out << ", " << opNames[1];
1347 } else {
1348 Out << "std::vector<Value*> " << iName << "_indices;";
1349 nl(Out);
1350 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1351 Out << iName << "_indices.push_back("
1352 << opNames[i] << ");";
Anton Korobeynikov78695032008-04-23 22:29:24 +00001353 nl(Out);
1354 }
Chris Lattnera0b8c902010-06-21 23:12:56 +00001355 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
Nicolas Geoffray84c7b9e2011-07-26 20:52:25 +00001356 << opNames[0] << ", " << iName << "_indices";
Anton Korobeynikov78695032008-04-23 22:29:24 +00001357 }
Chris Lattnera0b8c902010-06-21 23:12:56 +00001358 Out << ", \"";
1359 printEscapedString(gep->getName());
1360 Out << "\", " << bbname << ");";
1361 break;
1362 }
1363 case Instruction::PHI: {
1364 const PHINode* phi = cast<PHINode>(I);
1365
1366 Out << "PHINode* " << iName << " = PHINode::Create("
Nicolas Geoffray9137ee82011-04-10 17:39:40 +00001367 << getCppName(phi->getType()) << ", "
Jay Foad52131342011-03-30 11:28:46 +00001368 << phi->getNumIncomingValues() << ", \"";
Chris Lattnera0b8c902010-06-21 23:12:56 +00001369 printEscapedString(phi->getName());
1370 Out << "\", " << bbname << ");";
Chris Lattnera0b8c902010-06-21 23:12:56 +00001371 nl(Out);
Jay Foad372ad642011-06-20 14:18:48 +00001372 for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
Chris Lattnera0b8c902010-06-21 23:12:56 +00001373 Out << iName << "->addIncoming("
Jay Foad372ad642011-06-20 14:18:48 +00001374 << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
Jay Foad61ea0e42011-06-23 09:09:15 +00001375 << getOpName(phi->getIncomingBlock(i)) << ");";
Chris Lattnere8628a02009-10-27 21:24:48 +00001376 nl(Out);
Chris Lattnere8628a02009-10-27 21:24:48 +00001377 }
Chris Lattnera0b8c902010-06-21 23:12:56 +00001378 break;
1379 }
1380 case Instruction::Trunc:
1381 case Instruction::ZExt:
1382 case Instruction::SExt:
1383 case Instruction::FPTrunc:
1384 case Instruction::FPExt:
1385 case Instruction::FPToUI:
1386 case Instruction::FPToSI:
1387 case Instruction::UIToFP:
1388 case Instruction::SIToFP:
1389 case Instruction::PtrToInt:
1390 case Instruction::IntToPtr:
1391 case Instruction::BitCast: {
1392 const CastInst* cst = cast<CastInst>(I);
1393 Out << "CastInst* " << iName << " = new ";
1394 switch (I->getOpcode()) {
1395 case Instruction::Trunc: Out << "TruncInst"; break;
1396 case Instruction::ZExt: Out << "ZExtInst"; break;
1397 case Instruction::SExt: Out << "SExtInst"; break;
1398 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1399 case Instruction::FPExt: Out << "FPExtInst"; break;
1400 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1401 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1402 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1403 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1404 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1405 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1406 case Instruction::BitCast: Out << "BitCastInst"; break;
Craig Toppere55c5562012-02-07 02:50:20 +00001407 default: llvm_unreachable("Unreachable");
Chris Lattnera0b8c902010-06-21 23:12:56 +00001408 }
1409 Out << "(" << opNames[0] << ", "
1410 << getCppName(cst->getType()) << ", \"";
1411 printEscapedString(cst->getName());
1412 Out << "\", " << bbname << ");";
1413 break;
1414 }
Gabor Greif7d4038dd2010-06-26 12:17:21 +00001415 case Instruction::Call: {
Chris Lattnera0b8c902010-06-21 23:12:56 +00001416 const CallInst* call = cast<CallInst>(I);
1417 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1418 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1419 << getCppName(ila->getFunctionType()) << ", \""
1420 << ila->getAsmString() << "\", \""
1421 << ila->getConstraintString() << "\","
1422 << (ila->hasSideEffects() ? "true" : "false") << ");";
1423 nl(Out);
1424 }
Gabor Greif7d4038dd2010-06-26 12:17:21 +00001425 if (call->getNumArgOperands() > 1) {
Anton Korobeynikov78695032008-04-23 22:29:24 +00001426 Out << "std::vector<Value*> " << iName << "_params;";
1427 nl(Out);
Gabor Greife537ddb2010-07-02 19:08:46 +00001428 for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
Gabor Greif03e7e682010-07-13 15:31:36 +00001429 Out << iName << "_params.push_back(" << opNames[i] << ");";
Anton Korobeynikov78695032008-04-23 22:29:24 +00001430 nl(Out);
1431 }
Chris Lattnera0b8c902010-06-21 23:12:56 +00001432 Out << "CallInst* " << iName << " = CallInst::Create("
Gabor Greif3e44ea12010-07-22 10:37:47 +00001433 << opNames[call->getNumArgOperands()] << ", "
Nicolas Geoffray6820c1e2011-07-21 20:59:21 +00001434 << iName << "_params, \"";
Gabor Greif7d4038dd2010-06-26 12:17:21 +00001435 } else if (call->getNumArgOperands() == 1) {
Chris Lattnera0b8c902010-06-21 23:12:56 +00001436 Out << "CallInst* " << iName << " = CallInst::Create("
Gabor Greif03e7e682010-07-13 15:31:36 +00001437 << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
Chris Lattnera0b8c902010-06-21 23:12:56 +00001438 } else {
Gabor Greif03e7e682010-07-13 15:31:36 +00001439 Out << "CallInst* " << iName << " = CallInst::Create("
1440 << opNames[call->getNumArgOperands()] << ", \"";
Chris Lattnera0b8c902010-06-21 23:12:56 +00001441 }
1442 printEscapedString(call->getName());
1443 Out << "\", " << bbname << ");";
1444 nl(Out) << iName << "->setCallingConv(";
1445 printCallingConv(call->getCallingConv());
1446 Out << ");";
1447 nl(Out) << iName << "->setTailCall("
Gabor Greif7d4038dd2010-06-26 12:17:21 +00001448 << (call->isTailCall() ? "true" : "false");
Chris Lattnera0b8c902010-06-21 23:12:56 +00001449 Out << ");";
Gabor Greif9da02a82010-07-02 19:26:28 +00001450 nl(Out);
Chris Lattnera0b8c902010-06-21 23:12:56 +00001451 printAttributes(call->getAttributes(), iName);
1452 Out << iName << "->setAttributes(" << iName << "_PAL);";
1453 nl(Out);
1454 break;
1455 }
1456 case Instruction::Select: {
1457 const SelectInst* sel = cast<SelectInst>(I);
1458 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1459 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1460 printEscapedString(sel->getName());
1461 Out << "\", " << bbname << ");";
1462 break;
1463 }
1464 case Instruction::UserOp1:
1465 /// FALL THROUGH
1466 case Instruction::UserOp2: {
1467 /// FIXME: What should be done here?
1468 break;
1469 }
1470 case Instruction::VAArg: {
1471 const VAArgInst* va = cast<VAArgInst>(I);
1472 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1473 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1474 printEscapedString(va->getName());
1475 Out << "\", " << bbname << ");";
1476 break;
1477 }
1478 case Instruction::ExtractElement: {
1479 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1480 Out << "ExtractElementInst* " << getCppName(eei)
1481 << " = new ExtractElementInst(" << opNames[0]
1482 << ", " << opNames[1] << ", \"";
1483 printEscapedString(eei->getName());
1484 Out << "\", " << bbname << ");";
1485 break;
1486 }
1487 case Instruction::InsertElement: {
1488 const InsertElementInst* iei = cast<InsertElementInst>(I);
1489 Out << "InsertElementInst* " << getCppName(iei)
1490 << " = InsertElementInst::Create(" << opNames[0]
1491 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1492 printEscapedString(iei->getName());
1493 Out << "\", " << bbname << ");";
1494 break;
1495 }
1496 case Instruction::ShuffleVector: {
1497 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1498 Out << "ShuffleVectorInst* " << getCppName(svi)
1499 << " = new ShuffleVectorInst(" << opNames[0]
1500 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1501 printEscapedString(svi->getName());
1502 Out << "\", " << bbname << ");";
1503 break;
1504 }
1505 case Instruction::ExtractValue: {
1506 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1507 Out << "std::vector<unsigned> " << iName << "_indices;";
1508 nl(Out);
1509 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1510 Out << iName << "_indices.push_back("
1511 << evi->idx_begin()[i] << ");";
Anton Korobeynikov78695032008-04-23 22:29:24 +00001512 nl(Out);
Anton Korobeynikov78695032008-04-23 22:29:24 +00001513 }
Chris Lattnera0b8c902010-06-21 23:12:56 +00001514 Out << "ExtractValueInst* " << getCppName(evi)
1515 << " = ExtractValueInst::Create(" << opNames[0]
1516 << ", "
Nick Lewyckydf06b6e2011-09-05 18:50:59 +00001517 << iName << "_indices, \"";
Chris Lattnera0b8c902010-06-21 23:12:56 +00001518 printEscapedString(evi->getName());
1519 Out << "\", " << bbname << ");";
1520 break;
1521 }
1522 case Instruction::InsertValue: {
1523 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1524 Out << "std::vector<unsigned> " << iName << "_indices;";
1525 nl(Out);
1526 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1527 Out << iName << "_indices.push_back("
1528 << ivi->idx_begin()[i] << ");";
Anton Korobeynikov78695032008-04-23 22:29:24 +00001529 nl(Out);
Anton Korobeynikov78695032008-04-23 22:29:24 +00001530 }
Chris Lattnera0b8c902010-06-21 23:12:56 +00001531 Out << "InsertValueInst* " << getCppName(ivi)
1532 << " = InsertValueInst::Create(" << opNames[0]
1533 << ", " << opNames[1] << ", "
Nick Lewyckydf06b6e2011-09-05 18:50:59 +00001534 << iName << "_indices, \"";
Chris Lattnera0b8c902010-06-21 23:12:56 +00001535 printEscapedString(ivi->getName());
1536 Out << "\", " << bbname << ");";
1537 break;
1538 }
Eli Friedmand28ddbf2011-10-31 23:59:22 +00001539 case Instruction::Fence: {
1540 const FenceInst *fi = cast<FenceInst>(I);
1541 StringRef Ordering = ConvertAtomicOrdering(fi->getOrdering());
1542 StringRef CrossThread = ConvertAtomicSynchScope(fi->getSynchScope());
1543 Out << "FenceInst* " << iName
1544 << " = new FenceInst(mod->getContext(), "
Eli Friedman5b693c22011-11-04 17:29:35 +00001545 << Ordering << ", " << CrossThread << ", " << bbname
Eli Friedmand28ddbf2011-10-31 23:59:22 +00001546 << ");";
1547 break;
1548 }
1549 case Instruction::AtomicCmpXchg: {
1550 const AtomicCmpXchgInst *cxi = cast<AtomicCmpXchgInst>(I);
1551 StringRef Ordering = ConvertAtomicOrdering(cxi->getOrdering());
1552 StringRef CrossThread = ConvertAtomicSynchScope(cxi->getSynchScope());
1553 Out << "AtomicCmpXchgInst* " << iName
1554 << " = new AtomicCmpXchgInst("
1555 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", "
Eli Friedman5b693c22011-11-04 17:29:35 +00001556 << Ordering << ", " << CrossThread << ", " << bbname
Eli Friedmand28ddbf2011-10-31 23:59:22 +00001557 << ");";
1558 nl(Out) << iName << "->setName(\"";
1559 printEscapedString(cxi->getName());
1560 Out << "\");";
1561 break;
1562 }
1563 case Instruction::AtomicRMW: {
1564 const AtomicRMWInst *rmwi = cast<AtomicRMWInst>(I);
1565 StringRef Ordering = ConvertAtomicOrdering(rmwi->getOrdering());
1566 StringRef CrossThread = ConvertAtomicSynchScope(rmwi->getSynchScope());
1567 StringRef Operation;
1568 switch (rmwi->getOperation()) {
1569 case AtomicRMWInst::Xchg: Operation = "AtomicRMWInst::Xchg"; break;
1570 case AtomicRMWInst::Add: Operation = "AtomicRMWInst::Add"; break;
1571 case AtomicRMWInst::Sub: Operation = "AtomicRMWInst::Sub"; break;
1572 case AtomicRMWInst::And: Operation = "AtomicRMWInst::And"; break;
1573 case AtomicRMWInst::Nand: Operation = "AtomicRMWInst::Nand"; break;
1574 case AtomicRMWInst::Or: Operation = "AtomicRMWInst::Or"; break;
1575 case AtomicRMWInst::Xor: Operation = "AtomicRMWInst::Xor"; break;
1576 case AtomicRMWInst::Max: Operation = "AtomicRMWInst::Max"; break;
1577 case AtomicRMWInst::Min: Operation = "AtomicRMWInst::Min"; break;
1578 case AtomicRMWInst::UMax: Operation = "AtomicRMWInst::UMax"; break;
1579 case AtomicRMWInst::UMin: Operation = "AtomicRMWInst::UMin"; break;
1580 case AtomicRMWInst::BAD_BINOP: llvm_unreachable("Bad atomic operation");
1581 }
1582 Out << "AtomicRMWInst* " << iName
1583 << " = new AtomicRMWInst("
1584 << Operation << ", "
1585 << opNames[0] << ", " << opNames[1] << ", "
Eli Friedman5b693c22011-11-04 17:29:35 +00001586 << Ordering << ", " << CrossThread << ", " << bbname
Eli Friedmand28ddbf2011-10-31 23:59:22 +00001587 << ");";
1588 nl(Out) << iName << "->setName(\"";
1589 printEscapedString(rmwi->getName());
1590 Out << "\");";
1591 break;
1592 }
Eli Friedman410393a2013-09-24 00:36:09 +00001593 case Instruction::LandingPad: {
1594 const LandingPadInst *lpi = cast<LandingPadInst>(I);
1595 Out << "LandingPadInst* " << iName << " = LandingPadInst::Create(";
1596 printCppName(lpi->getType());
1597 Out << ", " << opNames[0] << ", " << lpi->getNumClauses() << ", \"";
1598 printEscapedString(lpi->getName());
1599 Out << "\", " << bbname << ");";
1600 nl(Out) << iName << "->setCleanup("
1601 << (lpi->isCleanup() ? "true" : "false")
1602 << ");";
1603 for (unsigned i = 0, e = lpi->getNumClauses(); i != e; ++i)
1604 nl(Out) << iName << "->addClause(" << opNames[i+1] << ");";
1605 break;
1606 }
Anton Korobeynikov78695032008-04-23 22:29:24 +00001607 }
1608 DefinedValues.insert(I);
1609 nl(Out);
1610 delete [] opNames;
1611}
1612
Chris Lattnera0b8c902010-06-21 23:12:56 +00001613// Print out the types, constants and declarations needed by one function
1614void CppWriter::printFunctionUses(const Function* F) {
1615 nl(Out) << "// Type Definitions"; nl(Out);
1616 if (!is_inline) {
1617 // Print the function's return type
1618 printType(F->getReturnType());
Anton Korobeynikov78695032008-04-23 22:29:24 +00001619
Chris Lattnera0b8c902010-06-21 23:12:56 +00001620 // Print the function's function type
1621 printType(F->getFunctionType());
Anton Korobeynikov78695032008-04-23 22:29:24 +00001622
Chris Lattnera0b8c902010-06-21 23:12:56 +00001623 // Print the types of each of the function's arguments
Anton Korobeynikov78695032008-04-23 22:29:24 +00001624 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1625 AI != AE; ++AI) {
Chris Lattnera0b8c902010-06-21 23:12:56 +00001626 printType(AI->getType());
Anton Korobeynikov78695032008-04-23 22:29:24 +00001627 }
Anton Korobeynikov78695032008-04-23 22:29:24 +00001628 }
1629
Chris Lattnera0b8c902010-06-21 23:12:56 +00001630 // Print type definitions for every type referenced by an instruction and
1631 // make a note of any global values or constants that are referenced
1632 SmallPtrSet<GlobalValue*,64> gvs;
1633 SmallPtrSet<Constant*,64> consts;
1634 for (Function::const_iterator BB = F->begin(), BE = F->end();
1635 BB != BE; ++BB){
1636 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
Anton Korobeynikov78695032008-04-23 22:29:24 +00001637 I != E; ++I) {
Chris Lattnera0b8c902010-06-21 23:12:56 +00001638 // Print the type of the instruction itself
1639 printType(I->getType());
1640
1641 // Print the type of each of the instruction's operands
1642 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1643 Value* operand = I->getOperand(i);
1644 printType(operand->getType());
1645
1646 // If the operand references a GVal or Constant, make a note of it
1647 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1648 gvs.insert(GV);
Nicolas Geoffray235b66c2010-11-28 18:00:53 +00001649 if (GenerationType != GenFunction)
1650 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1651 if (GVar->hasInitializer())
1652 consts.insert(GVar->getInitializer());
1653 } else if (Constant* C = dyn_cast<Constant>(operand)) {
Chris Lattnera0b8c902010-06-21 23:12:56 +00001654 consts.insert(C);
Nicolas Geoffray235b66c2010-11-28 18:00:53 +00001655 for (unsigned j = 0; j < C->getNumOperands(); ++j) {
1656 // If the operand references a GVal or Constant, make a note of it
1657 Value* operand = C->getOperand(j);
1658 printType(operand->getType());
1659 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1660 gvs.insert(GV);
1661 if (GenerationType != GenFunction)
1662 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1663 if (GVar->hasInitializer())
1664 consts.insert(GVar->getInitializer());
1665 }
1666 }
1667 }
Chris Lattnera0b8c902010-06-21 23:12:56 +00001668 }
1669 }
1670 }
1671
1672 // Print the function declarations for any functions encountered
1673 nl(Out) << "// Function Declarations"; nl(Out);
1674 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1675 I != E; ++I) {
1676 if (Function* Fun = dyn_cast<Function>(*I)) {
1677 if (!is_inline || Fun != F)
1678 printFunctionHead(Fun);
1679 }
1680 }
1681
1682 // Print the global variable declarations for any variables encountered
1683 nl(Out) << "// Global Variable Declarations"; nl(Out);
1684 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1685 I != E; ++I) {
1686 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1687 printVariableHead(F);
1688 }
1689
Nicolas Geoffray235b66c2010-11-28 18:00:53 +00001690 // Print the constants found
Chris Lattnera0b8c902010-06-21 23:12:56 +00001691 nl(Out) << "// Constant Definitions"; nl(Out);
1692 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1693 E = consts.end(); I != E; ++I) {
1694 printConstant(*I);
1695 }
1696
1697 // Process the global variables definitions now that all the constants have
1698 // been emitted. These definitions just couple the gvars with their constant
1699 // initializers.
Nicolas Geoffray235b66c2010-11-28 18:00:53 +00001700 if (GenerationType != GenFunction) {
1701 nl(Out) << "// Global Variable Definitions"; nl(Out);
1702 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1703 I != E; ++I) {
1704 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1705 printVariableBody(GV);
1706 }
Chris Lattnera0b8c902010-06-21 23:12:56 +00001707 }
1708}
1709
1710void CppWriter::printFunctionHead(const Function* F) {
1711 nl(Out) << "Function* " << getCppName(F);
Nicolas Geoffraya0263e72011-10-08 11:56:36 +00001712 Out << " = mod->getFunction(\"";
1713 printEscapedString(F->getName());
1714 Out << "\");";
1715 nl(Out) << "if (!" << getCppName(F) << ") {";
1716 nl(Out) << getCppName(F);
1717
Chris Lattnera0b8c902010-06-21 23:12:56 +00001718 Out<< " = Function::Create(";
1719 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1720 nl(Out) << "/*Linkage=*/";
1721 printLinkageType(F->getLinkage());
1722 Out << ",";
1723 nl(Out) << "/*Name=*/\"";
1724 printEscapedString(F->getName());
1725 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1726 nl(Out,-1);
1727 printCppName(F);
1728 Out << "->setCallingConv(";
1729 printCallingConv(F->getCallingConv());
1730 Out << ");";
1731 nl(Out);
1732 if (F->hasSection()) {
1733 printCppName(F);
1734 Out << "->setSection(\"" << F->getSection() << "\");";
1735 nl(Out);
1736 }
1737 if (F->getAlignment()) {
1738 printCppName(F);
1739 Out << "->setAlignment(" << F->getAlignment() << ");";
1740 nl(Out);
1741 }
1742 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1743 printCppName(F);
1744 Out << "->setVisibility(";
1745 printVisibilityType(F->getVisibility());
1746 Out << ");";
1747 nl(Out);
1748 }
1749 if (F->hasGC()) {
1750 printCppName(F);
1751 Out << "->setGC(\"" << F->getGC() << "\");";
1752 nl(Out);
1753 }
Nicolas Geoffraya0263e72011-10-08 11:56:36 +00001754 Out << "}";
1755 nl(Out);
Chris Lattnera0b8c902010-06-21 23:12:56 +00001756 printAttributes(F->getAttributes(), getCppName(F));
1757 printCppName(F);
1758 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1759 nl(Out);
1760}
1761
1762void CppWriter::printFunctionBody(const Function *F) {
1763 if (F->isDeclaration())
1764 return; // external functions have no bodies.
1765
1766 // Clear the DefinedValues and ForwardRefs maps because we can't have
1767 // cross-function forward refs
1768 ForwardRefs.clear();
1769 DefinedValues.clear();
1770
1771 // Create all the argument values
1772 if (!is_inline) {
1773 if (!F->arg_empty()) {
1774 Out << "Function::arg_iterator args = " << getCppName(F)
1775 << "->arg_begin();";
1776 nl(Out);
1777 }
1778 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1779 AI != AE; ++AI) {
1780 Out << "Value* " << getCppName(AI) << " = args++;";
1781 nl(Out);
1782 if (AI->hasName()) {
Eli Friedmand28ddbf2011-10-31 23:59:22 +00001783 Out << getCppName(AI) << "->setName(\"";
1784 printEscapedString(AI->getName());
1785 Out << "\");";
Anton Korobeynikov78695032008-04-23 22:29:24 +00001786 nl(Out);
1787 }
1788 }
1789 }
1790
Chris Lattnera0b8c902010-06-21 23:12:56 +00001791 // Create all the basic blocks
1792 nl(Out);
1793 for (Function::const_iterator BI = F->begin(), BE = F->end();
1794 BI != BE; ++BI) {
1795 std::string bbname(getCppName(BI));
1796 Out << "BasicBlock* " << bbname <<
1797 " = BasicBlock::Create(mod->getContext(), \"";
1798 if (BI->hasName())
1799 printEscapedString(BI->getName());
1800 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1801 nl(Out);
Anton Korobeynikov78695032008-04-23 22:29:24 +00001802 }
1803
Chris Lattnera0b8c902010-06-21 23:12:56 +00001804 // Output all of its basic blocks... for the function
1805 for (Function::const_iterator BI = F->begin(), BE = F->end();
1806 BI != BE; ++BI) {
1807 std::string bbname(getCppName(BI));
1808 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
Anton Korobeynikov78695032008-04-23 22:29:24 +00001809 nl(Out);
1810
Chris Lattnera0b8c902010-06-21 23:12:56 +00001811 // Output all of the instructions in the basic block...
1812 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1813 I != E; ++I) {
1814 printInstruction(I,bbname);
1815 }
1816 }
1817
1818 // Loop over the ForwardRefs and resolve them now that all instructions
1819 // are generated.
1820 if (!ForwardRefs.empty()) {
1821 nl(Out) << "// Resolve Forward References";
1822 nl(Out);
1823 }
1824
1825 while (!ForwardRefs.empty()) {
1826 ForwardRefMap::iterator I = ForwardRefs.begin();
1827 Out << I->second << "->replaceAllUsesWith("
1828 << getCppName(I->first) << "); delete " << I->second << ";";
1829 nl(Out);
1830 ForwardRefs.erase(I);
1831 }
1832}
1833
1834void CppWriter::printInline(const std::string& fname,
1835 const std::string& func) {
1836 const Function* F = TheModule->getFunction(func);
1837 if (!F) {
1838 error(std::string("Function '") + func + "' not found in input module");
1839 return;
1840 }
1841 if (F->isDeclaration()) {
1842 error(std::string("Function '") + func + "' is external!");
1843 return;
1844 }
1845 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1846 << getCppName(F);
1847 unsigned arg_count = 1;
1848 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1849 AI != AE; ++AI) {
Craig Topper62cb2bc2013-07-31 03:22:07 +00001850 Out << ", Value* arg_" << arg_count++;
Chris Lattnera0b8c902010-06-21 23:12:56 +00001851 }
1852 Out << ") {";
1853 nl(Out);
1854 is_inline = true;
1855 printFunctionUses(F);
1856 printFunctionBody(F);
1857 is_inline = false;
1858 Out << "return " << getCppName(F->begin()) << ";";
1859 nl(Out) << "}";
1860 nl(Out);
1861}
1862
1863void CppWriter::printModuleBody() {
1864 // Print out all the type definitions
1865 nl(Out) << "// Type Definitions"; nl(Out);
1866 printTypes(TheModule);
1867
1868 // Functions can call each other and global variables can reference them so
1869 // define all the functions first before emitting their function bodies.
1870 nl(Out) << "// Function Declarations"; nl(Out);
1871 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1872 I != E; ++I)
1873 printFunctionHead(I);
1874
1875 // Process the global variables declarations. We can't initialze them until
1876 // after the constants are printed so just print a header for each global
1877 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1878 for (Module::const_global_iterator I = TheModule->global_begin(),
1879 E = TheModule->global_end(); I != E; ++I) {
1880 printVariableHead(I);
1881 }
1882
1883 // Print out all the constants definitions. Constants don't recurse except
1884 // through GlobalValues. All GlobalValues have been declared at this point
1885 // so we can proceed to generate the constants.
1886 nl(Out) << "// Constant Definitions"; nl(Out);
1887 printConstants(TheModule);
1888
1889 // Process the global variables definitions now that all the constants have
1890 // been emitted. These definitions just couple the gvars with their constant
1891 // initializers.
1892 nl(Out) << "// Global Variable Definitions"; nl(Out);
1893 for (Module::const_global_iterator I = TheModule->global_begin(),
1894 E = TheModule->global_end(); I != E; ++I) {
1895 printVariableBody(I);
1896 }
1897
1898 // Finally, we can safely put out all of the function bodies.
1899 nl(Out) << "// Function Definitions"; nl(Out);
1900 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1901 I != E; ++I) {
1902 if (!I->isDeclaration()) {
1903 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1904 << ")";
1905 nl(Out) << "{";
1906 nl(Out,1);
1907 printFunctionBody(I);
1908 nl(Out,-1) << "}";
Anton Korobeynikov78695032008-04-23 22:29:24 +00001909 nl(Out);
Anton Korobeynikov78695032008-04-23 22:29:24 +00001910 }
Chris Lattnera0b8c902010-06-21 23:12:56 +00001911 }
1912}
1913
1914void CppWriter::printProgram(const std::string& fname,
1915 const std::string& mName) {
Chris Lattnera0b8c902010-06-21 23:12:56 +00001916 Out << "#include <llvm/Pass.h>\n";
1917 Out << "#include <llvm/PassManager.h>\n";
Bill Wendlingcc1fc942013-01-27 01:22:51 +00001918
Chris Lattnera0b8c902010-06-21 23:12:56 +00001919 Out << "#include <llvm/ADT/SmallVector.h>\n";
1920 Out << "#include <llvm/Analysis/Verifier.h>\n";
1921 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
Bill Wendlingcc1fc942013-01-27 01:22:51 +00001922 Out << "#include <llvm/IR/BasicBlock.h>\n";
1923 Out << "#include <llvm/IR/CallingConv.h>\n";
1924 Out << "#include <llvm/IR/Constants.h>\n";
1925 Out << "#include <llvm/IR/DerivedTypes.h>\n";
1926 Out << "#include <llvm/IR/Function.h>\n";
1927 Out << "#include <llvm/IR/GlobalVariable.h>\n";
1928 Out << "#include <llvm/IR/InlineAsm.h>\n";
1929 Out << "#include <llvm/IR/Instructions.h>\n";
1930 Out << "#include <llvm/IR/LLVMContext.h>\n";
1931 Out << "#include <llvm/IR/Module.h>\n";
1932 Out << "#include <llvm/Support/FormattedStream.h>\n";
1933 Out << "#include <llvm/Support/MathExtras.h>\n";
Chris Lattnera0b8c902010-06-21 23:12:56 +00001934 Out << "#include <algorithm>\n";
1935 Out << "using namespace llvm;\n\n";
1936 Out << "Module* " << fname << "();\n\n";
1937 Out << "int main(int argc, char**argv) {\n";
1938 Out << " Module* Mod = " << fname << "();\n";
1939 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1940 Out << " PassManager PM;\n";
1941 Out << " PM.add(createPrintModulePass(&outs()));\n";
1942 Out << " PM.run(*Mod);\n";
1943 Out << " return 0;\n";
1944 Out << "}\n\n";
1945 printModule(fname,mName);
1946}
1947
1948void CppWriter::printModule(const std::string& fname,
1949 const std::string& mName) {
1950 nl(Out) << "Module* " << fname << "() {";
1951 nl(Out,1) << "// Module Construction";
1952 nl(Out) << "Module* mod = new Module(\"";
1953 printEscapedString(mName);
1954 Out << "\", getGlobalContext());";
1955 if (!TheModule->getTargetTriple().empty()) {
1956 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1957 }
1958 if (!TheModule->getTargetTriple().empty()) {
1959 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1960 << "\");";
1961 }
1962
1963 if (!TheModule->getModuleInlineAsm().empty()) {
1964 nl(Out) << "mod->setModuleInlineAsm(\"";
1965 printEscapedString(TheModule->getModuleInlineAsm());
1966 Out << "\");";
1967 }
1968 nl(Out);
1969
Chris Lattnera0b8c902010-06-21 23:12:56 +00001970 printModuleBody();
1971 nl(Out) << "return mod;";
1972 nl(Out,-1) << "}";
1973 nl(Out);
1974}
Anton Korobeynikov78695032008-04-23 22:29:24 +00001975
Chris Lattnera0b8c902010-06-21 23:12:56 +00001976void CppWriter::printContents(const std::string& fname,
1977 const std::string& mName) {
1978 Out << "\nModule* " << fname << "(Module *mod) {\n";
1979 Out << "\nmod->setModuleIdentifier(\"";
1980 printEscapedString(mName);
1981 Out << "\");\n";
1982 printModuleBody();
1983 Out << "\nreturn mod;\n";
1984 Out << "\n}\n";
1985}
1986
1987void CppWriter::printFunction(const std::string& fname,
1988 const std::string& funcName) {
1989 const Function* F = TheModule->getFunction(funcName);
1990 if (!F) {
1991 error(std::string("Function '") + funcName + "' not found in input module");
1992 return;
Anton Korobeynikov78695032008-04-23 22:29:24 +00001993 }
Chris Lattnera0b8c902010-06-21 23:12:56 +00001994 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1995 printFunctionUses(F);
1996 printFunctionHead(F);
1997 printFunctionBody(F);
1998 Out << "return " << getCppName(F) << ";\n";
1999 Out << "}\n";
2000}
Anton Korobeynikov78695032008-04-23 22:29:24 +00002001
Chris Lattnera0b8c902010-06-21 23:12:56 +00002002void CppWriter::printFunctions() {
2003 const Module::FunctionListType &funcs = TheModule->getFunctionList();
2004 Module::const_iterator I = funcs.begin();
2005 Module::const_iterator IE = funcs.end();
Anton Korobeynikov78695032008-04-23 22:29:24 +00002006
Chris Lattnera0b8c902010-06-21 23:12:56 +00002007 for (; I != IE; ++I) {
2008 const Function &func = *I;
2009 if (!func.isDeclaration()) {
2010 std::string name("define_");
2011 name += func.getName();
2012 printFunction(name, func.getName());
Anton Korobeynikov78695032008-04-23 22:29:24 +00002013 }
2014 }
Chris Lattnera0b8c902010-06-21 23:12:56 +00002015}
Anton Korobeynikov78695032008-04-23 22:29:24 +00002016
Chris Lattnera0b8c902010-06-21 23:12:56 +00002017void CppWriter::printVariable(const std::string& fname,
2018 const std::string& varName) {
2019 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
Anton Korobeynikov78695032008-04-23 22:29:24 +00002020
Chris Lattnera0b8c902010-06-21 23:12:56 +00002021 if (!GV) {
2022 error(std::string("Variable '") + varName + "' not found in input module");
2023 return;
2024 }
2025 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
2026 printVariableUses(GV);
2027 printVariableHead(GV);
2028 printVariableBody(GV);
2029 Out << "return " << getCppName(GV) << ";\n";
2030 Out << "}\n";
2031}
2032
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002033void CppWriter::printType(const std::string &fname,
2034 const std::string &typeName) {
Chris Lattner229907c2011-07-18 04:54:35 +00002035 Type* Ty = TheModule->getTypeByName(typeName);
Chris Lattnera0b8c902010-06-21 23:12:56 +00002036 if (!Ty) {
2037 error(std::string("Type '") + typeName + "' not found in input module");
2038 return;
2039 }
2040 Out << "\nType* " << fname << "(Module *mod) {\n";
2041 printType(Ty);
2042 Out << "return " << getCppName(Ty) << ";\n";
2043 Out << "}\n";
2044}
2045
2046bool CppWriter::runOnModule(Module &M) {
2047 TheModule = &M;
2048
2049 // Emit a header
2050 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
2051
2052 // Get the name of the function we're supposed to generate
2053 std::string fname = FuncName.getValue();
2054
2055 // Get the name of the thing we are to generate
2056 std::string tgtname = NameToGenerate.getValue();
2057 if (GenerationType == GenModule ||
2058 GenerationType == GenContents ||
2059 GenerationType == GenProgram ||
2060 GenerationType == GenFunctions) {
2061 if (tgtname == "!bad!") {
2062 if (M.getModuleIdentifier() == "-")
2063 tgtname = "<stdin>";
2064 else
2065 tgtname = M.getModuleIdentifier();
Anton Korobeynikov78695032008-04-23 22:29:24 +00002066 }
Chris Lattnera0b8c902010-06-21 23:12:56 +00002067 } else if (tgtname == "!bad!")
2068 error("You must use the -for option with -gen-{function,variable,type}");
2069
2070 switch (WhatToGenerate(GenerationType)) {
2071 case GenProgram:
2072 if (fname.empty())
2073 fname = "makeLLVMModule";
2074 printProgram(fname,tgtname);
2075 break;
2076 case GenModule:
2077 if (fname.empty())
2078 fname = "makeLLVMModule";
2079 printModule(fname,tgtname);
2080 break;
2081 case GenContents:
2082 if (fname.empty())
2083 fname = "makeLLVMModuleContents";
2084 printContents(fname,tgtname);
2085 break;
2086 case GenFunction:
2087 if (fname.empty())
2088 fname = "makeLLVMFunction";
2089 printFunction(fname,tgtname);
2090 break;
2091 case GenFunctions:
2092 printFunctions();
2093 break;
2094 case GenInline:
2095 if (fname.empty())
2096 fname = "makeLLVMInline";
2097 printInline(fname,tgtname);
2098 break;
2099 case GenVariable:
2100 if (fname.empty())
2101 fname = "makeLLVMVariable";
2102 printVariable(fname,tgtname);
2103 break;
2104 case GenType:
2105 if (fname.empty())
2106 fname = "makeLLVMType";
2107 printType(fname,tgtname);
2108 break;
Anton Korobeynikov78695032008-04-23 22:29:24 +00002109 }
2110
Chris Lattnera0b8c902010-06-21 23:12:56 +00002111 return false;
Anton Korobeynikov78695032008-04-23 22:29:24 +00002112}
2113
2114char CppWriter::ID = 0;
2115
2116//===----------------------------------------------------------------------===//
2117// External Interface declaration
2118//===----------------------------------------------------------------------===//
2119
Dan Gohman4cfccb82010-05-11 19:57:55 +00002120bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
2121 formatted_raw_ostream &o,
2122 CodeGenFileType FileType,
Bob Wilsoncac3b902012-07-02 19:48:45 +00002123 bool DisableVerify,
2124 AnalysisID StartAfter,
2125 AnalysisID StopAfter) {
Chris Lattnerf0cb12a2010-02-02 21:06:45 +00002126 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
Anton Korobeynikov78695032008-04-23 22:29:24 +00002127 PM.add(new CppWriter(o));
2128 return false;
2129}