blob: 096e2bc13b09cf31a29b3bb6e330b098c07e801e [file] [log] [blame]
Anton Korobeynikov50276522008-04-23 22:29:24 +00001//===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the writing of the LLVM IR as a set of C++ calls to the
11// LLVM IR interface. The input module is assumed to be verified.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CPPTargetMachine.h"
16#include "llvm/CallingConv.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/InlineAsm.h"
20#include "llvm/Instruction.h"
21#include "llvm/Instructions.h"
22#include "llvm/Module.h"
23#include "llvm/Pass.h"
24#include "llvm/PassManager.h"
Evan Cheng1abf2cb2011-07-14 23:50:31 +000025#include "llvm/MC/MCAsmInfo.h"
Evan Cheng59ee62d2011-07-11 03:57:24 +000026#include "llvm/MC/MCInstrInfo.h"
Evan Chengffc0e732011-07-09 05:47:46 +000027#include "llvm/MC/MCSubtargetInfo.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000028#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/Support/CommandLine.h"
Torok Edwin30464702009-07-08 20:55:50 +000030#include "llvm/Support/ErrorHandling.h"
David Greene71847812009-07-14 20:18:05 +000031#include "llvm/Support/FormattedStream.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000032#include "llvm/Support/TargetRegistry.h"
Chris Lattner23132b12009-08-24 03:52:50 +000033#include "llvm/ADT/StringExtras.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000034#include "llvm/Config/config.h"
35#include <algorithm>
Benjamin Kramer901b8582012-03-23 11:35:30 +000036#include <cstdio>
Chris Lattner1afcace2011-07-09 17:41:24 +000037#include <map>
Benjamin Kramer901b8582012-03-23 11:35:30 +000038#include <set>
Anton Korobeynikov50276522008-04-23 22:29:24 +000039using namespace llvm;
40
41static cl::opt<std::string>
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000042FuncName("cppfname", cl::desc("Specify the name of the generated function"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000043 cl::value_desc("function name"));
44
45enum WhatToGenerate {
46 GenProgram,
47 GenModule,
48 GenContents,
49 GenFunction,
50 GenFunctions,
51 GenInline,
52 GenVariable,
53 GenType
54};
55
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000056static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000057 cl::desc("Choose what kind of output to generate"),
58 cl::init(GenProgram),
59 cl::values(
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000060 clEnumValN(GenProgram, "program", "Generate a complete program"),
61 clEnumValN(GenModule, "module", "Generate a module definition"),
62 clEnumValN(GenContents, "contents", "Generate contents of a module"),
63 clEnumValN(GenFunction, "function", "Generate a function definition"),
64 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
65 clEnumValN(GenInline, "inline", "Generate an inline function"),
66 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
67 clEnumValN(GenType, "type", "Generate a type definition"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000068 clEnumValEnd
69 )
70);
71
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000072static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000073 cl::desc("Specify the name of the thing to generate"),
74 cl::init("!bad!"));
75
Daniel Dunbar0c795d62009-07-25 06:49:55 +000076extern "C" void LLVMInitializeCppBackendTarget() {
77 // Register the target.
Daniel Dunbar214e2232009-08-04 04:02:45 +000078 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
Daniel Dunbar0c795d62009-07-25 06:49:55 +000079}
Douglas Gregor1555a232009-06-16 20:12:29 +000080
Dan Gohman844731a2008-05-13 00:00:25 +000081namespace {
Chris Lattnerdb125cf2011-07-18 04:54:35 +000082 typedef std::vector<Type*> TypeList;
83 typedef std::map<Type*,std::string> TypeMap;
Anton Korobeynikov50276522008-04-23 22:29:24 +000084 typedef std::map<const Value*,std::string> ValueMap;
85 typedef std::set<std::string> NameSet;
Chris Lattnerdb125cf2011-07-18 04:54:35 +000086 typedef std::set<Type*> TypeSet;
Anton Korobeynikov50276522008-04-23 22:29:24 +000087 typedef std::set<const Value*> ValueSet;
88 typedef std::map<const Value*,std::string> ForwardRefMap;
89
90 /// CppWriter - This class is the main chunk of code that converts an LLVM
91 /// module to a C++ translation unit.
92 class CppWriter : public ModulePass {
David Greene71847812009-07-14 20:18:05 +000093 formatted_raw_ostream &Out;
Anton Korobeynikov50276522008-04-23 22:29:24 +000094 const Module *TheModule;
95 uint64_t uniqueNum;
96 TypeMap TypeNames;
97 ValueMap ValueNames;
Anton Korobeynikov50276522008-04-23 22:29:24 +000098 NameSet UsedNames;
99 TypeSet DefinedTypes;
100 ValueSet DefinedValues;
101 ForwardRefMap ForwardRefs;
102 bool is_inline;
Chris Lattner1018c242010-06-21 23:14:47 +0000103 unsigned indent_level;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000104
105 public:
106 static char ID;
David Greene71847812009-07-14 20:18:05 +0000107 explicit CppWriter(formatted_raw_ostream &o) :
Owen Anderson90c579d2010-08-06 18:33:48 +0000108 ModulePass(ID), Out(o), uniqueNum(0), is_inline(false), indent_level(0){}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000109
110 virtual const char *getPassName() const { return "C++ backend"; }
111
112 bool runOnModule(Module &M);
113
Anton Korobeynikov50276522008-04-23 22:29:24 +0000114 void printProgram(const std::string& fname, const std::string& modName );
115 void printModule(const std::string& fname, const std::string& modName );
116 void printContents(const std::string& fname, const std::string& modName );
117 void printFunction(const std::string& fname, const std::string& funcName );
118 void printFunctions();
119 void printInline(const std::string& fname, const std::string& funcName );
120 void printVariable(const std::string& fname, const std::string& varName );
121 void printType(const std::string& fname, const std::string& typeName );
122
123 void error(const std::string& msg);
124
Chris Lattner1018c242010-06-21 23:14:47 +0000125
126 formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0);
127 inline void in() { indent_level++; }
128 inline void out() { if (indent_level >0) indent_level--; }
129
Anton Korobeynikov50276522008-04-23 22:29:24 +0000130 private:
131 void printLinkageType(GlobalValue::LinkageTypes LT);
132 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
Hans Wennborgce718ff2012-06-23 11:37:03 +0000133 void printThreadLocalMode(GlobalVariable::ThreadLocalMode TLM);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +0000134 void printCallingConv(CallingConv::ID cc);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000135 void printEscapedString(const std::string& str);
136 void printCFP(const ConstantFP* CFP);
137
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000138 std::string getCppName(Type* val);
139 inline void printCppName(Type* val);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000140
141 std::string getCppName(const Value* val);
142 inline void printCppName(const Value* val);
143
Devang Patel05988662008-09-25 21:00:45 +0000144 void printAttributes(const AttrListPtr &PAL, const std::string &name);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000145 void printType(Type* Ty);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000146 void printTypes(const Module* M);
147
148 void printConstant(const Constant *CPV);
149 void printConstants(const Module* M);
150
151 void printVariableUses(const GlobalVariable *GV);
152 void printVariableHead(const GlobalVariable *GV);
153 void printVariableBody(const GlobalVariable *GV);
154
155 void printFunctionUses(const Function *F);
156 void printFunctionHead(const Function *F);
157 void printFunctionBody(const Function *F);
158 void printInstruction(const Instruction *I, const std::string& bbname);
Eli Friedmanbb5a7442011-09-29 20:21:17 +0000159 std::string getOpName(const Value*);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000160
161 void printModuleBody();
162 };
Chris Lattner7e6d7452010-06-21 23:12:56 +0000163} // end anonymous namespace.
Anton Korobeynikov50276522008-04-23 22:29:24 +0000164
Chris Lattner1018c242010-06-21 23:14:47 +0000165formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
166 Out << '\n';
Chris Lattner7e6d7452010-06-21 23:12:56 +0000167 if (delta >= 0 || indent_level >= unsigned(-delta))
168 indent_level += delta;
Chris Lattner1018c242010-06-21 23:14:47 +0000169 Out.indent(indent_level);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000170 return Out;
171}
172
Chris Lattner7e6d7452010-06-21 23:12:56 +0000173static inline void sanitize(std::string &str) {
174 for (size_t i = 0; i < str.length(); ++i)
175 if (!isalnum(str[i]) && str[i] != '_')
176 str[i] = '_';
177}
178
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000179static std::string getTypePrefix(Type *Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000180 switch (Ty->getTypeID()) {
181 case Type::VoidTyID: return "void_";
182 case Type::IntegerTyID:
183 return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
184 case Type::FloatTyID: return "float_";
185 case Type::DoubleTyID: return "double_";
186 case Type::LabelTyID: return "label_";
187 case Type::FunctionTyID: return "func_";
188 case Type::StructTyID: return "struct_";
189 case Type::ArrayTyID: return "array_";
190 case Type::PointerTyID: return "ptr_";
191 case Type::VectorTyID: return "packed_";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000192 default: return "other_";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000193 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000194}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000195
Chris Lattner7e6d7452010-06-21 23:12:56 +0000196void CppWriter::error(const std::string& msg) {
197 report_fatal_error(msg);
198}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000199
Benjamin Kramere68e7752012-03-23 11:26:29 +0000200static inline std::string ftostr(const APFloat& V) {
201 std::string Buf;
202 if (&V.getSemantics() == &APFloat::IEEEdouble) {
203 raw_string_ostream(Buf) << V.convertToDouble();
204 return Buf;
205 } else if (&V.getSemantics() == &APFloat::IEEEsingle) {
206 raw_string_ostream(Buf) << (double)V.convertToFloat();
207 return Buf;
208 }
209 return "<unknown format in ftostr>"; // error
210}
211
Chris Lattner7e6d7452010-06-21 23:12:56 +0000212// printCFP - Print a floating point constant .. very carefully :)
213// This makes sure that conversion to/from floating yields the same binary
214// result so that we don't lose precision.
215void CppWriter::printCFP(const ConstantFP *CFP) {
216 bool ignored;
217 APFloat APF = APFloat(CFP->getValueAPF()); // copy
218 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
219 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
220 Out << "ConstantFP::get(mod->getContext(), ";
221 Out << "APFloat(";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000222#if HAVE_PRINTF_A
Chris Lattner7e6d7452010-06-21 23:12:56 +0000223 char Buffer[100];
224 sprintf(Buffer, "%A", APF.convertToDouble());
225 if ((!strncmp(Buffer, "0x", 2) ||
226 !strncmp(Buffer, "-0x", 3) ||
227 !strncmp(Buffer, "+0x", 3)) &&
228 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
229 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
230 Out << "BitsToDouble(" << Buffer << ")";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000231 else
Chris Lattner7e6d7452010-06-21 23:12:56 +0000232 Out << "BitsToFloat((float)" << Buffer << ")";
233 Out << ")";
234 } else {
235#endif
236 std::string StrVal = ftostr(CFP->getValueAPF());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000237
Chris Lattner7e6d7452010-06-21 23:12:56 +0000238 while (StrVal[0] == ' ')
239 StrVal.erase(StrVal.begin());
240
241 // Check to make sure that the stringized number is not some string like
242 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
243 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
244 ((StrVal[0] == '-' || StrVal[0] == '+') &&
245 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
246 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
247 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
248 Out << StrVal;
249 else
250 Out << StrVal << "f";
251 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
252 Out << "BitsToDouble(0x"
253 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
254 << "ULL) /* " << StrVal << " */";
255 else
256 Out << "BitsToFloat(0x"
257 << utohexstr((uint32_t)CFP->getValueAPF().
258 bitcastToAPInt().getZExtValue())
259 << "U) /* " << StrVal << " */";
260 Out << ")";
261#if HAVE_PRINTF_A
262 }
263#endif
264 Out << ")";
265}
266
267void CppWriter::printCallingConv(CallingConv::ID cc){
268 // Print the calling convention.
269 switch (cc) {
270 case CallingConv::C: Out << "CallingConv::C"; break;
271 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
272 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
273 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
274 default: Out << cc; break;
275 }
276}
277
278void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
279 switch (LT) {
280 case GlobalValue::InternalLinkage:
281 Out << "GlobalValue::InternalLinkage"; break;
282 case GlobalValue::PrivateLinkage:
283 Out << "GlobalValue::PrivateLinkage"; break;
284 case GlobalValue::LinkerPrivateLinkage:
285 Out << "GlobalValue::LinkerPrivateLinkage"; break;
Bill Wendling5e721d72010-07-01 21:55:59 +0000286 case GlobalValue::LinkerPrivateWeakLinkage:
287 Out << "GlobalValue::LinkerPrivateWeakLinkage"; break;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000288 case GlobalValue::AvailableExternallyLinkage:
289 Out << "GlobalValue::AvailableExternallyLinkage "; break;
290 case GlobalValue::LinkOnceAnyLinkage:
291 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
292 case GlobalValue::LinkOnceODRLinkage:
293 Out << "GlobalValue::LinkOnceODRLinkage "; break;
Bill Wendling32811be2012-08-17 18:33:14 +0000294 case GlobalValue::LinkOnceODRAutoHideLinkage:
295 Out << "GlobalValue::LinkOnceODRAutoHideLinkage"; break;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000296 case GlobalValue::WeakAnyLinkage:
297 Out << "GlobalValue::WeakAnyLinkage"; break;
298 case GlobalValue::WeakODRLinkage:
299 Out << "GlobalValue::WeakODRLinkage"; break;
300 case GlobalValue::AppendingLinkage:
301 Out << "GlobalValue::AppendingLinkage"; break;
302 case GlobalValue::ExternalLinkage:
303 Out << "GlobalValue::ExternalLinkage"; break;
304 case GlobalValue::DLLImportLinkage:
305 Out << "GlobalValue::DLLImportLinkage"; break;
306 case GlobalValue::DLLExportLinkage:
307 Out << "GlobalValue::DLLExportLinkage"; break;
308 case GlobalValue::ExternalWeakLinkage:
309 Out << "GlobalValue::ExternalWeakLinkage"; break;
310 case GlobalValue::CommonLinkage:
311 Out << "GlobalValue::CommonLinkage"; break;
312 }
313}
314
315void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
316 switch (VisType) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000317 case GlobalValue::DefaultVisibility:
318 Out << "GlobalValue::DefaultVisibility";
319 break;
320 case GlobalValue::HiddenVisibility:
321 Out << "GlobalValue::HiddenVisibility";
322 break;
323 case GlobalValue::ProtectedVisibility:
324 Out << "GlobalValue::ProtectedVisibility";
325 break;
326 }
327}
328
Hans Wennborgce718ff2012-06-23 11:37:03 +0000329void CppWriter::printThreadLocalMode(GlobalVariable::ThreadLocalMode TLM) {
330 switch (TLM) {
331 case GlobalVariable::NotThreadLocal:
332 Out << "GlobalVariable::NotThreadLocal";
333 break;
334 case GlobalVariable::GeneralDynamicTLSModel:
335 Out << "GlobalVariable::GeneralDynamicTLSModel";
336 break;
337 case GlobalVariable::LocalDynamicTLSModel:
338 Out << "GlobalVariable::LocalDynamicTLSModel";
339 break;
340 case GlobalVariable::InitialExecTLSModel:
341 Out << "GlobalVariable::InitialExecTLSModel";
342 break;
343 case GlobalVariable::LocalExecTLSModel:
344 Out << "GlobalVariable::LocalExecTLSModel";
345 break;
346 }
347}
348
Chris Lattner7e6d7452010-06-21 23:12:56 +0000349// printEscapedString - Print each character of the specified string, escaping
350// it if it is not printable or if it is an escape char.
351void CppWriter::printEscapedString(const std::string &Str) {
352 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
353 unsigned char C = Str[i];
354 if (isprint(C) && C != '"' && C != '\\') {
355 Out << C;
356 } else {
357 Out << "\\x"
358 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
359 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
360 }
361 }
362}
363
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000364std::string CppWriter::getCppName(Type* Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000365 // First, handle the primitive types .. easy
366 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
367 switch (Ty->getTypeID()) {
368 case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())";
369 case Type::IntegerTyID: {
370 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
371 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
372 }
373 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
374 case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())";
375 case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())";
376 case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())";
Dale Johannesenbb811a22010-09-10 20:55:01 +0000377 case Type::X86_MMXTyID: return "Type::getX86_MMXTy(mod->getContext())";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000378 default:
379 error("Invalid primitive type");
380 break;
381 }
382 // shouldn't be returned, but make it sensible
383 return "Type::getVoidTy(mod->getContext())";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000384 }
385
Chris Lattner7e6d7452010-06-21 23:12:56 +0000386 // Now, see if we've seen the type before and return that
387 TypeMap::iterator I = TypeNames.find(Ty);
388 if (I != TypeNames.end())
389 return I->second;
390
391 // Okay, let's build a new name for this type. Start with a prefix
392 const char* prefix = 0;
393 switch (Ty->getTypeID()) {
394 case Type::FunctionTyID: prefix = "FuncTy_"; break;
395 case Type::StructTyID: prefix = "StructTy_"; break;
396 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
397 case Type::PointerTyID: prefix = "PointerTy_"; break;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000398 case Type::VectorTyID: prefix = "VectorTy_"; break;
399 default: prefix = "OtherTy_"; break; // prevent breakage
Anton Korobeynikov50276522008-04-23 22:29:24 +0000400 }
401
Chris Lattner7e6d7452010-06-21 23:12:56 +0000402 // See if the type has a name in the symboltable and build accordingly
Chris Lattner7e6d7452010-06-21 23:12:56 +0000403 std::string name;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000404 if (StructType *STy = dyn_cast<StructType>(Ty))
Chris Lattner1afcace2011-07-09 17:41:24 +0000405 if (STy->hasName())
406 name = STy->getName();
407
408 if (name.empty())
409 name = utostr(uniqueNum++);
410
411 name = std::string(prefix) + name;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000412 sanitize(name);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000413
Chris Lattner7e6d7452010-06-21 23:12:56 +0000414 // Save the name
415 return TypeNames[Ty] = name;
416}
417
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000418void CppWriter::printCppName(Type* Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000419 printEscapedString(getCppName(Ty));
420}
421
422std::string CppWriter::getCppName(const Value* val) {
423 std::string name;
424 ValueMap::iterator I = ValueNames.find(val);
425 if (I != ValueNames.end() && I->first == val)
426 return I->second;
427
428 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
429 name = std::string("gvar_") +
430 getTypePrefix(GV->getType()->getElementType());
431 } else if (isa<Function>(val)) {
432 name = std::string("func_");
433 } else if (const Constant* C = dyn_cast<Constant>(val)) {
434 name = std::string("const_") + getTypePrefix(C->getType());
435 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
436 if (is_inline) {
437 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
438 Function::const_arg_iterator(Arg)) + 1;
439 name = std::string("arg_") + utostr(argNum);
440 NameSet::iterator NI = UsedNames.find(name);
441 if (NI != UsedNames.end())
442 name += std::string("_") + utostr(uniqueNum++);
443 UsedNames.insert(name);
444 return ValueNames[val] = name;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000445 } else {
446 name = getTypePrefix(val->getType());
447 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000448 } else {
449 name = getTypePrefix(val->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000450 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000451 if (val->hasName())
452 name += val->getName();
453 else
454 name += utostr(uniqueNum++);
455 sanitize(name);
456 NameSet::iterator NI = UsedNames.find(name);
457 if (NI != UsedNames.end())
458 name += std::string("_") + utostr(uniqueNum++);
459 UsedNames.insert(name);
460 return ValueNames[val] = name;
461}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000462
Chris Lattner7e6d7452010-06-21 23:12:56 +0000463void CppWriter::printCppName(const Value* val) {
464 printEscapedString(getCppName(val));
465}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000466
Chris Lattner7e6d7452010-06-21 23:12:56 +0000467void CppWriter::printAttributes(const AttrListPtr &PAL,
468 const std::string &name) {
469 Out << "AttrListPtr " << name << "_PAL;";
470 nl(Out);
471 if (!PAL.isEmpty()) {
472 Out << '{'; in(); nl(Out);
473 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
474 Out << "AttributeWithIndex PAWI;"; nl(Out);
475 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
476 unsigned index = PAL.getSlot(i).Index;
Bill Wendling7d2f2492012-10-10 07:36:45 +0000477 Attributes::Builder attrs(PAL.getSlot(i).Attrs);
478 Out << "PAWI.Index = " << index << "U;\n";
479 Out << " Attributes::Builder B;\n";
480
481#define HANDLE_ATTR(X) \
482 if (attrs.hasAttribute(Attributes::X)) \
483 Out << " B.addAttribute(Attributes::" #X ");\n"; \
484 attrs.removeAttribute(Attributes::X);
485
Chris Lattner7e6d7452010-06-21 23:12:56 +0000486 HANDLE_ATTR(SExt);
487 HANDLE_ATTR(ZExt);
488 HANDLE_ATTR(NoReturn);
489 HANDLE_ATTR(InReg);
490 HANDLE_ATTR(StructRet);
491 HANDLE_ATTR(NoUnwind);
492 HANDLE_ATTR(NoAlias);
493 HANDLE_ATTR(ByVal);
494 HANDLE_ATTR(Nest);
495 HANDLE_ATTR(ReadNone);
496 HANDLE_ATTR(ReadOnly);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000497 HANDLE_ATTR(NoInline);
498 HANDLE_ATTR(AlwaysInline);
499 HANDLE_ATTR(OptimizeForSize);
500 HANDLE_ATTR(StackProtect);
501 HANDLE_ATTR(StackProtectReq);
502 HANDLE_ATTR(NoCapture);
Eli Friedman32bb4df2010-07-16 18:47:20 +0000503 HANDLE_ATTR(NoRedZone);
504 HANDLE_ATTR(NoImplicitFloat);
505 HANDLE_ATTR(Naked);
506 HANDLE_ATTR(InlineHint);
Rafael Espindola25456ef2011-10-03 14:45:37 +0000507 HANDLE_ATTR(ReturnsTwice);
Bill Wendling54f15362011-08-09 00:47:30 +0000508 HANDLE_ATTR(UWTable);
509 HANDLE_ATTR(NonLazyBind);
Chris Lattneracca9552009-01-13 07:22:22 +0000510#undef HANDLE_ATTR
Bill Wendling7d2f2492012-10-10 07:36:45 +0000511 if (attrs.hasAttribute(Attributes::StackAlignment))
512 Out << "B.addStackAlignmentAttr(Attribute::constructStackAlignmentFromInt("
Bill Wendlingef99fe82012-09-21 15:26:31 +0000513 << attrs.getStackAlignment()
Bill Wendling7d2f2492012-10-10 07:36:45 +0000514 << "))";
515 nl(Out);
516 attrs.removeAttribute(Attributes::StackAlignment);
517 assert(!attrs.hasAttributes() && "Unhandled attribute!");
518 Out << "PAWI.Attrs = Attributes::get(B);";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000519 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000520 Out << "Attrs.push_back(PAWI);";
521 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000522 }
Nicolas Geoffraye2364292012-05-29 15:07:18 +0000523 Out << name << "_PAL = AttrListPtr::get(Attrs);";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000524 nl(Out);
525 out(); nl(Out);
526 Out << '}'; nl(Out);
527 }
528}
529
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000530void CppWriter::printType(Type* Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000531 // We don't print definitions for primitive types
532 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000533 return;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000534
535 // If we already defined this type, we don't need to define it again.
536 if (DefinedTypes.find(Ty) != DefinedTypes.end())
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000537 return;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000538
539 // Everything below needs the name for the type so get it now.
540 std::string typeName(getCppName(Ty));
541
Chris Lattner7e6d7452010-06-21 23:12:56 +0000542 // Print the type definition
543 switch (Ty->getTypeID()) {
544 case Type::FunctionTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000545 FunctionType* FT = cast<FunctionType>(Ty);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000546 Out << "std::vector<Type*>" << typeName << "_args;";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000547 nl(Out);
548 FunctionType::param_iterator PI = FT->param_begin();
549 FunctionType::param_iterator PE = FT->param_end();
550 for (; PI != PE; ++PI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000551 Type* argTy = static_cast<Type*>(*PI);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000552 printType(argTy);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000553 std::string argName(getCppName(argTy));
554 Out << typeName << "_args.push_back(" << argName;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000555 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000556 nl(Out);
557 }
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000558 printType(FT->getReturnType());
Chris Lattner7e6d7452010-06-21 23:12:56 +0000559 std::string retTypeName(getCppName(FT->getReturnType()));
560 Out << "FunctionType* " << typeName << " = FunctionType::get(";
561 in(); nl(Out) << "/*Result=*/" << retTypeName;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000562 Out << ",";
563 nl(Out) << "/*Params=*/" << typeName << "_args,";
564 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
565 out();
Anton Korobeynikov50276522008-04-23 22:29:24 +0000566 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000567 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000568 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000569 case Type::StructTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000570 StructType* ST = cast<StructType>(Ty);
Chris Lattnerc4d0e9f2011-08-12 18:07:07 +0000571 if (!ST->isLiteral()) {
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000572 Out << "StructType *" << typeName << " = mod->getTypeByName(\"";
573 printEscapedString(ST->getName());
574 Out << "\");";
575 nl(Out);
576 Out << "if (!" << typeName << ") {";
577 nl(Out);
578 Out << typeName << " = ";
Chris Lattnerc4d0e9f2011-08-12 18:07:07 +0000579 Out << "StructType::create(mod->getContext(), \"";
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000580 printEscapedString(ST->getName());
581 Out << "\");";
582 nl(Out);
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000583 Out << "}";
584 nl(Out);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000585 // Indicate that this type is now defined.
586 DefinedTypes.insert(Ty);
587 }
588
589 Out << "std::vector<Type*>" << typeName << "_fields;";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000590 nl(Out);
591 StructType::element_iterator EI = ST->element_begin();
592 StructType::element_iterator EE = ST->element_end();
593 for (; EI != EE; ++EI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000594 Type* fieldTy = static_cast<Type*>(*EI);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000595 printType(fieldTy);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000596 std::string fieldName(getCppName(fieldTy));
597 Out << typeName << "_fields.push_back(" << fieldName;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000598 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000599 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000600 }
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000601
Chris Lattnerc4d0e9f2011-08-12 18:07:07 +0000602 if (ST->isLiteral()) {
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000603 Out << "StructType *" << typeName << " = ";
Chris Lattner1afcace2011-07-09 17:41:24 +0000604 Out << "StructType::get(" << "mod->getContext(), ";
605 } else {
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000606 Out << "if (" << typeName << "->isOpaque()) {";
607 nl(Out);
Chris Lattner1afcace2011-07-09 17:41:24 +0000608 Out << typeName << "->setBody(";
609 }
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000610
Chris Lattner1afcace2011-07-09 17:41:24 +0000611 Out << typeName << "_fields, /*isPacked=*/"
Chris Lattner7e6d7452010-06-21 23:12:56 +0000612 << (ST->isPacked() ? "true" : "false") << ");";
613 nl(Out);
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000614 if (!ST->isLiteral()) {
615 Out << "}";
616 nl(Out);
617 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000618 break;
619 }
620 case Type::ArrayTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000621 ArrayType* AT = cast<ArrayType>(Ty);
622 Type* ET = AT->getElementType();
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000623 printType(ET);
624 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
625 std::string elemName(getCppName(ET));
626 Out << "ArrayType* " << typeName << " = ArrayType::get("
627 << elemName
628 << ", " << utostr(AT->getNumElements()) << ");";
629 nl(Out);
630 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000631 break;
632 }
633 case Type::PointerTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000634 PointerType* PT = cast<PointerType>(Ty);
635 Type* ET = PT->getElementType();
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000636 printType(ET);
637 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
638 std::string elemName(getCppName(ET));
639 Out << "PointerType* " << typeName << " = PointerType::get("
640 << elemName
641 << ", " << utostr(PT->getAddressSpace()) << ");";
642 nl(Out);
643 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000644 break;
645 }
646 case Type::VectorTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000647 VectorType* PT = cast<VectorType>(Ty);
648 Type* ET = PT->getElementType();
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000649 printType(ET);
650 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
651 std::string elemName(getCppName(ET));
652 Out << "VectorType* " << typeName << " = VectorType::get("
653 << elemName
654 << ", " << utostr(PT->getNumElements()) << ");";
655 nl(Out);
656 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000657 break;
658 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000659 default:
660 error("Invalid TypeID");
661 }
662
Chris Lattner7e6d7452010-06-21 23:12:56 +0000663 // Indicate that this type is now defined.
664 DefinedTypes.insert(Ty);
665
Chris Lattner7e6d7452010-06-21 23:12:56 +0000666 // Finally, separate the type definition from other with a newline.
667 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000668}
669
670void CppWriter::printTypes(const Module* M) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000671 // Add all of the global variables to the value table.
Chris Lattner7e6d7452010-06-21 23:12:56 +0000672 for (Module::const_global_iterator I = TheModule->global_begin(),
673 E = TheModule->global_end(); I != E; ++I) {
674 if (I->hasInitializer())
675 printType(I->getInitializer()->getType());
676 printType(I->getType());
677 }
678
679 // Add all the functions to the table
680 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
681 FI != FE; ++FI) {
682 printType(FI->getReturnType());
683 printType(FI->getFunctionType());
684 // Add all the function arguments
685 for (Function::const_arg_iterator AI = FI->arg_begin(),
686 AE = FI->arg_end(); AI != AE; ++AI) {
687 printType(AI->getType());
688 }
689
690 // Add all of the basic blocks and instructions
691 for (Function::const_iterator BB = FI->begin(),
692 E = FI->end(); BB != E; ++BB) {
693 printType(BB->getType());
694 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
695 ++I) {
696 printType(I->getType());
697 for (unsigned i = 0; i < I->getNumOperands(); ++i)
698 printType(I->getOperand(i)->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000699 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000700 }
701 }
702}
703
704
705// printConstant - Print out a constant pool entry...
706void CppWriter::printConstant(const Constant *CV) {
707 // First, if the constant is actually a GlobalValue (variable or function)
708 // or its already in the constant list then we've printed it already and we
709 // can just return.
710 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
711 return;
712
713 std::string constName(getCppName(CV));
714 std::string typeName(getCppName(CV->getType()));
715
Chris Lattner7e6d7452010-06-21 23:12:56 +0000716 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
717 std::string constValue = CI->getValue().toString(10, true);
718 Out << "ConstantInt* " << constName
719 << " = ConstantInt::get(mod->getContext(), APInt("
720 << cast<IntegerType>(CI->getType())->getBitWidth()
721 << ", StringRef(\"" << constValue << "\"), 10));";
722 } else if (isa<ConstantAggregateZero>(CV)) {
723 Out << "ConstantAggregateZero* " << constName
724 << " = ConstantAggregateZero::get(" << typeName << ");";
725 } else if (isa<ConstantPointerNull>(CV)) {
726 Out << "ConstantPointerNull* " << constName
727 << " = ConstantPointerNull::get(" << typeName << ");";
728 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
729 Out << "ConstantFP* " << constName << " = ";
730 printCFP(CFP);
731 Out << ";";
732 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000733 Out << "std::vector<Constant*> " << constName << "_elems;";
734 nl(Out);
735 unsigned N = CA->getNumOperands();
736 for (unsigned i = 0; i < N; ++i) {
737 printConstant(CA->getOperand(i)); // recurse to print operands
738 Out << constName << "_elems.push_back("
739 << getCppName(CA->getOperand(i)) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000740 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000741 }
Chris Lattner18c7f802012-02-05 02:29:43 +0000742 Out << "Constant* " << constName << " = ConstantArray::get("
743 << typeName << ", " << constName << "_elems);";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000744 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
745 Out << "std::vector<Constant*> " << constName << "_fields;";
746 nl(Out);
747 unsigned N = CS->getNumOperands();
748 for (unsigned i = 0; i < N; i++) {
749 printConstant(CS->getOperand(i));
750 Out << constName << "_fields.push_back("
751 << getCppName(CS->getOperand(i)) << ");";
752 nl(Out);
753 }
754 Out << "Constant* " << constName << " = ConstantStruct::get("
755 << typeName << ", " << constName << "_fields);";
Duncan Sands853066a2012-02-05 14:16:09 +0000756 } else if (const ConstantVector *CVec = dyn_cast<ConstantVector>(CV)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000757 Out << "std::vector<Constant*> " << constName << "_elems;";
758 nl(Out);
Duncan Sands853066a2012-02-05 14:16:09 +0000759 unsigned N = CVec->getNumOperands();
Chris Lattner7e6d7452010-06-21 23:12:56 +0000760 for (unsigned i = 0; i < N; ++i) {
Duncan Sands853066a2012-02-05 14:16:09 +0000761 printConstant(CVec->getOperand(i));
Chris Lattner7e6d7452010-06-21 23:12:56 +0000762 Out << constName << "_elems.push_back("
Duncan Sands853066a2012-02-05 14:16:09 +0000763 << getCppName(CVec->getOperand(i)) << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000764 nl(Out);
765 }
766 Out << "Constant* " << constName << " = ConstantVector::get("
767 << typeName << ", " << constName << "_elems);";
768 } else if (isa<UndefValue>(CV)) {
769 Out << "UndefValue* " << constName << " = UndefValue::get("
770 << typeName << ");";
Chris Lattner29cc6cb2012-01-24 14:17:05 +0000771 } else if (const ConstantDataSequential *CDS =
772 dyn_cast<ConstantDataSequential>(CV)) {
773 if (CDS->isString()) {
774 Out << "Constant *" << constName <<
775 " = ConstantDataArray::getString(mod->getContext(), \"";
Chris Lattner18c7f802012-02-05 02:29:43 +0000776 StringRef Str = CDS->getAsString();
Chris Lattner29cc6cb2012-01-24 14:17:05 +0000777 bool nullTerminate = false;
778 if (Str.back() == 0) {
779 Str = Str.drop_back();
780 nullTerminate = true;
781 }
782 printEscapedString(Str);
783 // Determine if we want null termination or not.
784 if (nullTerminate)
785 Out << "\", true);";
786 else
787 Out << "\", false);";// No null terminator
788 } else {
789 // TODO: Could generate more efficient code generating CDS calls instead.
790 Out << "std::vector<Constant*> " << constName << "_elems;";
791 nl(Out);
792 for (unsigned i = 0; i != CDS->getNumElements(); ++i) {
793 Constant *Elt = CDS->getElementAsConstant(i);
794 printConstant(Elt);
795 Out << constName << "_elems.push_back(" << getCppName(Elt) << ");";
796 nl(Out);
797 }
798 Out << "Constant* " << constName;
799
800 if (isa<ArrayType>(CDS->getType()))
801 Out << " = ConstantArray::get(";
802 else
803 Out << " = ConstantVector::get(";
804 Out << typeName << ", " << constName << "_elems);";
805 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000806 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
807 if (CE->getOpcode() == Instruction::GetElementPtr) {
808 Out << "std::vector<Constant*> " << constName << "_indices;";
809 nl(Out);
810 printConstant(CE->getOperand(0));
811 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
812 printConstant(CE->getOperand(i));
813 Out << constName << "_indices.push_back("
814 << getCppName(CE->getOperand(i)) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000815 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000816 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000817 Out << "Constant* " << constName
818 << " = ConstantExpr::getGetElementPtr("
819 << getCppName(CE->getOperand(0)) << ", "
Nicolas Geoffraya056d202011-07-21 20:59:21 +0000820 << constName << "_indices);";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000821 } else if (CE->isCast()) {
822 printConstant(CE->getOperand(0));
823 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
824 switch (CE->getOpcode()) {
825 default: llvm_unreachable("Invalid cast opcode");
826 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
827 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
828 case Instruction::SExt: Out << "Instruction::SExt"; break;
829 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
830 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
831 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
832 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
833 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
834 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
835 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
836 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
837 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
838 }
839 Out << ", " << getCppName(CE->getOperand(0)) << ", "
840 << getCppName(CE->getType()) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000841 } else {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000842 unsigned N = CE->getNumOperands();
843 for (unsigned i = 0; i < N; ++i ) {
844 printConstant(CE->getOperand(i));
845 }
846 Out << "Constant* " << constName << " = ConstantExpr::";
847 switch (CE->getOpcode()) {
848 case Instruction::Add: Out << "getAdd("; break;
849 case Instruction::FAdd: Out << "getFAdd("; break;
850 case Instruction::Sub: Out << "getSub("; break;
851 case Instruction::FSub: Out << "getFSub("; break;
852 case Instruction::Mul: Out << "getMul("; break;
853 case Instruction::FMul: Out << "getFMul("; break;
854 case Instruction::UDiv: Out << "getUDiv("; break;
855 case Instruction::SDiv: Out << "getSDiv("; break;
856 case Instruction::FDiv: Out << "getFDiv("; break;
857 case Instruction::URem: Out << "getURem("; break;
858 case Instruction::SRem: Out << "getSRem("; break;
859 case Instruction::FRem: Out << "getFRem("; break;
860 case Instruction::And: Out << "getAnd("; break;
861 case Instruction::Or: Out << "getOr("; break;
862 case Instruction::Xor: Out << "getXor("; break;
863 case Instruction::ICmp:
864 Out << "getICmp(ICmpInst::ICMP_";
865 switch (CE->getPredicate()) {
866 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
867 case ICmpInst::ICMP_NE: Out << "NE"; break;
868 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
869 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
870 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
871 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
872 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
873 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
874 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
875 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
876 default: error("Invalid ICmp Predicate");
877 }
878 break;
879 case Instruction::FCmp:
880 Out << "getFCmp(FCmpInst::FCMP_";
881 switch (CE->getPredicate()) {
882 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
883 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
884 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
885 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
886 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
887 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
888 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
889 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
890 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
891 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
892 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
893 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
894 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
895 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
896 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
897 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
898 default: error("Invalid FCmp Predicate");
899 }
900 break;
901 case Instruction::Shl: Out << "getShl("; break;
902 case Instruction::LShr: Out << "getLShr("; break;
903 case Instruction::AShr: Out << "getAShr("; break;
904 case Instruction::Select: Out << "getSelect("; break;
905 case Instruction::ExtractElement: Out << "getExtractElement("; break;
906 case Instruction::InsertElement: Out << "getInsertElement("; break;
907 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
908 default:
909 error("Invalid constant expression");
910 break;
911 }
912 Out << getCppName(CE->getOperand(0));
913 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
914 Out << ", " << getCppName(CE->getOperand(i));
915 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000916 }
Chris Lattner32848772010-06-21 23:19:36 +0000917 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
918 Out << "Constant* " << constName << " = ";
919 Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000920 } else {
921 error("Bad Constant");
922 Out << "Constant* " << constName << " = 0; ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000923 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000924 nl(Out);
925}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000926
Chris Lattner7e6d7452010-06-21 23:12:56 +0000927void CppWriter::printConstants(const Module* M) {
928 // Traverse all the global variables looking for constant initializers
929 for (Module::const_global_iterator I = TheModule->global_begin(),
930 E = TheModule->global_end(); I != E; ++I)
931 if (I->hasInitializer())
932 printConstant(I->getInitializer());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000933
Chris Lattner7e6d7452010-06-21 23:12:56 +0000934 // Traverse the LLVM functions looking for constants
935 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
936 FI != FE; ++FI) {
937 // Add all of the basic blocks and instructions
938 for (Function::const_iterator BB = FI->begin(),
939 E = FI->end(); BB != E; ++BB) {
940 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
941 ++I) {
942 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
943 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
944 printConstant(C);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000945 }
946 }
947 }
948 }
949 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000950}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000951
Chris Lattner7e6d7452010-06-21 23:12:56 +0000952void CppWriter::printVariableUses(const GlobalVariable *GV) {
953 nl(Out) << "// Type Definitions";
954 nl(Out);
955 printType(GV->getType());
956 if (GV->hasInitializer()) {
Jay Foad7d715df2011-06-19 18:37:11 +0000957 const Constant *Init = GV->getInitializer();
Chris Lattner7e6d7452010-06-21 23:12:56 +0000958 printType(Init->getType());
Jay Foad7d715df2011-06-19 18:37:11 +0000959 if (const Function *F = dyn_cast<Function>(Init)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000960 nl(Out)<< "/ Function Declarations"; nl(Out);
961 printFunctionHead(F);
Jay Foad7d715df2011-06-19 18:37:11 +0000962 } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000963 nl(Out) << "// Global Variable Declarations"; nl(Out);
964 printVariableHead(gv);
965
966 nl(Out) << "// Global Variable Definitions"; nl(Out);
967 printVariableBody(gv);
968 } else {
969 nl(Out) << "// Constant Definitions"; nl(Out);
970 printConstant(Init);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000971 }
972 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000973}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000974
Chris Lattner7e6d7452010-06-21 23:12:56 +0000975void CppWriter::printVariableHead(const GlobalVariable *GV) {
976 nl(Out) << "GlobalVariable* " << getCppName(GV);
977 if (is_inline) {
978 Out << " = mod->getGlobalVariable(mod->getContext(), ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000979 printEscapedString(GV->getName());
Chris Lattner7e6d7452010-06-21 23:12:56 +0000980 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
981 nl(Out) << "if (!" << getCppName(GV) << ") {";
982 in(); nl(Out) << getCppName(GV);
983 }
984 Out << " = new GlobalVariable(/*Module=*/*mod, ";
985 nl(Out) << "/*Type=*/";
986 printCppName(GV->getType()->getElementType());
987 Out << ",";
988 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
989 Out << ",";
990 nl(Out) << "/*Linkage=*/";
991 printLinkageType(GV->getLinkage());
992 Out << ",";
993 nl(Out) << "/*Initializer=*/0, ";
994 if (GV->hasInitializer()) {
995 Out << "// has initializer, specified below";
996 }
997 nl(Out) << "/*Name=*/\"";
998 printEscapedString(GV->getName());
999 Out << "\");";
1000 nl(Out);
1001
1002 if (GV->hasSection()) {
1003 printCppName(GV);
1004 Out << "->setSection(\"";
1005 printEscapedString(GV->getSection());
Owen Anderson16a412e2009-07-10 16:42:19 +00001006 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001007 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001008 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001009 if (GV->getAlignment()) {
1010 printCppName(GV);
1011 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001012 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001013 }
1014 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1015 printCppName(GV);
1016 Out << "->setVisibility(";
1017 printVisibilityType(GV->getVisibility());
1018 Out << ");";
1019 nl(Out);
1020 }
1021 if (GV->isThreadLocal()) {
1022 printCppName(GV);
Hans Wennborgce718ff2012-06-23 11:37:03 +00001023 Out << "->setThreadLocalMode(";
1024 printThreadLocalMode(GV->getThreadLocalMode());
1025 Out << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001026 nl(Out);
1027 }
1028 if (is_inline) {
1029 out(); Out << "}"; nl(Out);
1030 }
1031}
1032
1033void CppWriter::printVariableBody(const GlobalVariable *GV) {
1034 if (GV->hasInitializer()) {
1035 printCppName(GV);
1036 Out << "->setInitializer(";
1037 Out << getCppName(GV->getInitializer()) << ");";
1038 nl(Out);
1039 }
1040}
1041
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001042std::string CppWriter::getOpName(const Value* V) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001043 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1044 return getCppName(V);
1045
1046 // See if its alread in the map of forward references, if so just return the
1047 // name we already set up for it
1048 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1049 if (I != ForwardRefs.end())
1050 return I->second;
1051
1052 // This is a new forward reference. Generate a unique name for it
1053 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1054
1055 // Yes, this is a hack. An Argument is the smallest instantiable value that
1056 // we can make as a placeholder for the real value. We'll replace these
1057 // Argument instances later.
1058 Out << "Argument* " << result << " = new Argument("
1059 << getCppName(V->getType()) << ");";
1060 nl(Out);
1061 ForwardRefs[V] = result;
1062 return result;
1063}
1064
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001065static StringRef ConvertAtomicOrdering(AtomicOrdering Ordering) {
1066 switch (Ordering) {
1067 case NotAtomic: return "NotAtomic";
1068 case Unordered: return "Unordered";
1069 case Monotonic: return "Monotonic";
1070 case Acquire: return "Acquire";
1071 case Release: return "Release";
1072 case AcquireRelease: return "AcquireRelease";
1073 case SequentiallyConsistent: return "SequentiallyConsistent";
1074 }
1075 llvm_unreachable("Unknown ordering");
1076}
1077
1078static StringRef ConvertAtomicSynchScope(SynchronizationScope SynchScope) {
1079 switch (SynchScope) {
1080 case SingleThread: return "SingleThread";
1081 case CrossThread: return "CrossThread";
1082 }
1083 llvm_unreachable("Unknown synch scope");
1084}
1085
Chris Lattner7e6d7452010-06-21 23:12:56 +00001086// printInstruction - This member is called for each Instruction in a function.
1087void CppWriter::printInstruction(const Instruction *I,
1088 const std::string& bbname) {
1089 std::string iName(getCppName(I));
1090
1091 // Before we emit this instruction, we need to take care of generating any
1092 // forward references. So, we get the names of all the operands in advance
1093 const unsigned Ops(I->getNumOperands());
1094 std::string* opNames = new std::string[Ops];
Chris Lattner32848772010-06-21 23:19:36 +00001095 for (unsigned i = 0; i < Ops; i++)
Chris Lattner7e6d7452010-06-21 23:12:56 +00001096 opNames[i] = getOpName(I->getOperand(i));
Anton Korobeynikov50276522008-04-23 22:29:24 +00001097
Chris Lattner7e6d7452010-06-21 23:12:56 +00001098 switch (I->getOpcode()) {
1099 default:
1100 error("Invalid instruction");
1101 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001102
Chris Lattner7e6d7452010-06-21 23:12:56 +00001103 case Instruction::Ret: {
1104 const ReturnInst* ret = cast<ReturnInst>(I);
1105 Out << "ReturnInst::Create(mod->getContext(), "
1106 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1107 break;
1108 }
1109 case Instruction::Br: {
1110 const BranchInst* br = cast<BranchInst>(I);
1111 Out << "BranchInst::Create(" ;
Chris Lattner32848772010-06-21 23:19:36 +00001112 if (br->getNumOperands() == 3) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001113 Out << opNames[2] << ", "
Anton Korobeynikov50276522008-04-23 22:29:24 +00001114 << opNames[1] << ", "
Chris Lattner7e6d7452010-06-21 23:12:56 +00001115 << opNames[0] << ", ";
1116
1117 } else if (br->getNumOperands() == 1) {
1118 Out << opNames[0] << ", ";
1119 } else {
1120 error("Branch with 2 operands?");
1121 }
1122 Out << bbname << ");";
1123 break;
1124 }
1125 case Instruction::Switch: {
1126 const SwitchInst *SI = cast<SwitchInst>(I);
1127 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001128 << getOpName(SI->getCondition()) << ", "
1129 << getOpName(SI->getDefaultDest()) << ", "
Chris Lattner7e6d7452010-06-21 23:12:56 +00001130 << SI->getNumCases() << ", " << bbname << ");";
1131 nl(Out);
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00001132 for (SwitchInst::ConstCaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00001133 i != e; ++i) {
Stepan Dyatkovskiy0aa32d52012-05-29 12:26:47 +00001134 const IntegersSubset CaseVal = i.getCaseValueEx();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00001135 const BasicBlock *BB = i.getCaseSuccessor();
Chris Lattner7e6d7452010-06-21 23:12:56 +00001136 Out << iName << "->addCase("
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001137 << getOpName(CaseVal) << ", "
1138 << getOpName(BB) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001139 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001140 }
1141 break;
1142 }
1143 case Instruction::IndirectBr: {
1144 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1145 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1146 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1147 nl(Out);
1148 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1149 Out << iName << "->addDestination(" << opNames[i] << ");";
1150 nl(Out);
1151 }
1152 break;
1153 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00001154 case Instruction::Resume: {
1155 Out << "ResumeInst::Create(mod->getContext(), " << opNames[0]
1156 << ", " << bbname << ");";
1157 break;
1158 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001159 case Instruction::Invoke: {
1160 const InvokeInst* inv = cast<InvokeInst>(I);
1161 Out << "std::vector<Value*> " << iName << "_params;";
1162 nl(Out);
1163 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1164 Out << iName << "_params.push_back("
1165 << getOpName(inv->getArgOperand(i)) << ");";
1166 nl(Out);
1167 }
1168 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1169 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1170 << getOpName(inv->getCalledFunction()) << ", "
1171 << getOpName(inv->getNormalDest()) << ", "
1172 << getOpName(inv->getUnwindDest()) << ", "
Nick Lewycky3bca1012011-09-05 18:50:59 +00001173 << iName << "_params, \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001174 printEscapedString(inv->getName());
1175 Out << "\", " << bbname << ");";
1176 nl(Out) << iName << "->setCallingConv(";
1177 printCallingConv(inv->getCallingConv());
1178 Out << ");";
1179 printAttributes(inv->getAttributes(), iName);
1180 Out << iName << "->setAttributes(" << iName << "_PAL);";
1181 nl(Out);
1182 break;
1183 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001184 case Instruction::Unreachable: {
1185 Out << "new UnreachableInst("
1186 << "mod->getContext(), "
1187 << bbname << ");";
1188 break;
1189 }
1190 case Instruction::Add:
1191 case Instruction::FAdd:
1192 case Instruction::Sub:
1193 case Instruction::FSub:
1194 case Instruction::Mul:
1195 case Instruction::FMul:
1196 case Instruction::UDiv:
1197 case Instruction::SDiv:
1198 case Instruction::FDiv:
1199 case Instruction::URem:
1200 case Instruction::SRem:
1201 case Instruction::FRem:
1202 case Instruction::And:
1203 case Instruction::Or:
1204 case Instruction::Xor:
1205 case Instruction::Shl:
1206 case Instruction::LShr:
1207 case Instruction::AShr:{
1208 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1209 switch (I->getOpcode()) {
1210 case Instruction::Add: Out << "Instruction::Add"; break;
1211 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1212 case Instruction::Sub: Out << "Instruction::Sub"; break;
1213 case Instruction::FSub: Out << "Instruction::FSub"; break;
1214 case Instruction::Mul: Out << "Instruction::Mul"; break;
1215 case Instruction::FMul: Out << "Instruction::FMul"; break;
1216 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1217 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1218 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1219 case Instruction::URem:Out << "Instruction::URem"; break;
1220 case Instruction::SRem:Out << "Instruction::SRem"; break;
1221 case Instruction::FRem:Out << "Instruction::FRem"; break;
1222 case Instruction::And: Out << "Instruction::And"; break;
1223 case Instruction::Or: Out << "Instruction::Or"; break;
1224 case Instruction::Xor: Out << "Instruction::Xor"; break;
1225 case Instruction::Shl: Out << "Instruction::Shl"; break;
1226 case Instruction::LShr:Out << "Instruction::LShr"; break;
1227 case Instruction::AShr:Out << "Instruction::AShr"; break;
1228 default: Out << "Instruction::BadOpCode"; break;
1229 }
1230 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1231 printEscapedString(I->getName());
1232 Out << "\", " << bbname << ");";
1233 break;
1234 }
1235 case Instruction::FCmp: {
1236 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1237 switch (cast<FCmpInst>(I)->getPredicate()) {
1238 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1239 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1240 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1241 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1242 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1243 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1244 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1245 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1246 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1247 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1248 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1249 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1250 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1251 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1252 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1253 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1254 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1255 }
1256 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1257 printEscapedString(I->getName());
1258 Out << "\");";
1259 break;
1260 }
1261 case Instruction::ICmp: {
1262 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1263 switch (cast<ICmpInst>(I)->getPredicate()) {
1264 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1265 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1266 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1267 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1268 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1269 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1270 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1271 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1272 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1273 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1274 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1275 }
1276 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1277 printEscapedString(I->getName());
1278 Out << "\");";
1279 break;
1280 }
1281 case Instruction::Alloca: {
1282 const AllocaInst* allocaI = cast<AllocaInst>(I);
1283 Out << "AllocaInst* " << iName << " = new AllocaInst("
1284 << getCppName(allocaI->getAllocatedType()) << ", ";
1285 if (allocaI->isArrayAllocation())
1286 Out << opNames[0] << ", ";
1287 Out << "\"";
1288 printEscapedString(allocaI->getName());
1289 Out << "\", " << bbname << ");";
1290 if (allocaI->getAlignment())
1291 nl(Out) << iName << "->setAlignment("
1292 << allocaI->getAlignment() << ");";
1293 break;
1294 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001295 case Instruction::Load: {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001296 const LoadInst* load = cast<LoadInst>(I);
1297 Out << "LoadInst* " << iName << " = new LoadInst("
1298 << opNames[0] << ", \"";
1299 printEscapedString(load->getName());
1300 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1301 << ", " << bbname << ");";
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001302 if (load->getAlignment())
1303 nl(Out) << iName << "->setAlignment("
1304 << load->getAlignment() << ");";
1305 if (load->isAtomic()) {
1306 StringRef Ordering = ConvertAtomicOrdering(load->getOrdering());
1307 StringRef CrossThread = ConvertAtomicSynchScope(load->getSynchScope());
1308 nl(Out) << iName << "->setAtomic("
1309 << Ordering << ", " << CrossThread << ");";
1310 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001311 break;
1312 }
1313 case Instruction::Store: {
1314 const StoreInst* store = cast<StoreInst>(I);
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001315 Out << "StoreInst* " << iName << " = new StoreInst("
Chris Lattner7e6d7452010-06-21 23:12:56 +00001316 << opNames[0] << ", "
1317 << opNames[1] << ", "
1318 << (store->isVolatile() ? "true" : "false")
1319 << ", " << bbname << ");";
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001320 if (store->getAlignment())
1321 nl(Out) << iName << "->setAlignment("
1322 << store->getAlignment() << ");";
1323 if (store->isAtomic()) {
1324 StringRef Ordering = ConvertAtomicOrdering(store->getOrdering());
1325 StringRef CrossThread = ConvertAtomicSynchScope(store->getSynchScope());
1326 nl(Out) << iName << "->setAtomic("
1327 << Ordering << ", " << CrossThread << ");";
1328 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001329 break;
1330 }
1331 case Instruction::GetElementPtr: {
1332 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1333 if (gep->getNumOperands() <= 2) {
1334 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1335 << opNames[0];
1336 if (gep->getNumOperands() == 2)
1337 Out << ", " << opNames[1];
1338 } else {
1339 Out << "std::vector<Value*> " << iName << "_indices;";
1340 nl(Out);
1341 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1342 Out << iName << "_indices.push_back("
1343 << opNames[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001344 nl(Out);
1345 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001346 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
Nicolas Geoffray45c8d2b2011-07-26 20:52:25 +00001347 << opNames[0] << ", " << iName << "_indices";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001348 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001349 Out << ", \"";
1350 printEscapedString(gep->getName());
1351 Out << "\", " << bbname << ");";
1352 break;
1353 }
1354 case Instruction::PHI: {
1355 const PHINode* phi = cast<PHINode>(I);
1356
1357 Out << "PHINode* " << iName << " = PHINode::Create("
Nicolas Geoffrayc6cf1972011-04-10 17:39:40 +00001358 << getCppName(phi->getType()) << ", "
Jay Foad3ecfc862011-03-30 11:28:46 +00001359 << phi->getNumIncomingValues() << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001360 printEscapedString(phi->getName());
1361 Out << "\", " << bbname << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001362 nl(Out);
Jay Foadc1371202011-06-20 14:18:48 +00001363 for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001364 Out << iName << "->addIncoming("
Jay Foadc1371202011-06-20 14:18:48 +00001365 << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
Jay Foad95c3e482011-06-23 09:09:15 +00001366 << getOpName(phi->getIncomingBlock(i)) << ");";
Chris Lattner627b4702009-10-27 21:24:48 +00001367 nl(Out);
Chris Lattner627b4702009-10-27 21:24:48 +00001368 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001369 break;
1370 }
1371 case Instruction::Trunc:
1372 case Instruction::ZExt:
1373 case Instruction::SExt:
1374 case Instruction::FPTrunc:
1375 case Instruction::FPExt:
1376 case Instruction::FPToUI:
1377 case Instruction::FPToSI:
1378 case Instruction::UIToFP:
1379 case Instruction::SIToFP:
1380 case Instruction::PtrToInt:
1381 case Instruction::IntToPtr:
1382 case Instruction::BitCast: {
1383 const CastInst* cst = cast<CastInst>(I);
1384 Out << "CastInst* " << iName << " = new ";
1385 switch (I->getOpcode()) {
1386 case Instruction::Trunc: Out << "TruncInst"; break;
1387 case Instruction::ZExt: Out << "ZExtInst"; break;
1388 case Instruction::SExt: Out << "SExtInst"; break;
1389 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1390 case Instruction::FPExt: Out << "FPExtInst"; break;
1391 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1392 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1393 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1394 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1395 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1396 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1397 case Instruction::BitCast: Out << "BitCastInst"; break;
Craig Topperbc219812012-02-07 02:50:20 +00001398 default: llvm_unreachable("Unreachable");
Chris Lattner7e6d7452010-06-21 23:12:56 +00001399 }
1400 Out << "(" << opNames[0] << ", "
1401 << getCppName(cst->getType()) << ", \"";
1402 printEscapedString(cst->getName());
1403 Out << "\", " << bbname << ");";
1404 break;
1405 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001406 case Instruction::Call: {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001407 const CallInst* call = cast<CallInst>(I);
1408 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1409 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1410 << getCppName(ila->getFunctionType()) << ", \""
1411 << ila->getAsmString() << "\", \""
1412 << ila->getConstraintString() << "\","
1413 << (ila->hasSideEffects() ? "true" : "false") << ");";
1414 nl(Out);
1415 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001416 if (call->getNumArgOperands() > 1) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001417 Out << "std::vector<Value*> " << iName << "_params;";
1418 nl(Out);
Gabor Greif53ba5502010-07-02 19:08:46 +00001419 for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
Gabor Greif63d024f2010-07-13 15:31:36 +00001420 Out << iName << "_params.push_back(" << opNames[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001421 nl(Out);
1422 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001423 Out << "CallInst* " << iName << " = CallInst::Create("
Gabor Greifa3997812010-07-22 10:37:47 +00001424 << opNames[call->getNumArgOperands()] << ", "
Nicolas Geoffraya056d202011-07-21 20:59:21 +00001425 << iName << "_params, \"";
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001426 } else if (call->getNumArgOperands() == 1) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001427 Out << "CallInst* " << iName << " = CallInst::Create("
Gabor Greif63d024f2010-07-13 15:31:36 +00001428 << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001429 } else {
Gabor Greif63d024f2010-07-13 15:31:36 +00001430 Out << "CallInst* " << iName << " = CallInst::Create("
1431 << opNames[call->getNumArgOperands()] << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001432 }
1433 printEscapedString(call->getName());
1434 Out << "\", " << bbname << ");";
1435 nl(Out) << iName << "->setCallingConv(";
1436 printCallingConv(call->getCallingConv());
1437 Out << ");";
1438 nl(Out) << iName << "->setTailCall("
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001439 << (call->isTailCall() ? "true" : "false");
Chris Lattner7e6d7452010-06-21 23:12:56 +00001440 Out << ");";
Gabor Greif135d7fe2010-07-02 19:26:28 +00001441 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001442 printAttributes(call->getAttributes(), iName);
1443 Out << iName << "->setAttributes(" << iName << "_PAL);";
1444 nl(Out);
1445 break;
1446 }
1447 case Instruction::Select: {
1448 const SelectInst* sel = cast<SelectInst>(I);
1449 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1450 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1451 printEscapedString(sel->getName());
1452 Out << "\", " << bbname << ");";
1453 break;
1454 }
1455 case Instruction::UserOp1:
1456 /// FALL THROUGH
1457 case Instruction::UserOp2: {
1458 /// FIXME: What should be done here?
1459 break;
1460 }
1461 case Instruction::VAArg: {
1462 const VAArgInst* va = cast<VAArgInst>(I);
1463 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1464 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1465 printEscapedString(va->getName());
1466 Out << "\", " << bbname << ");";
1467 break;
1468 }
1469 case Instruction::ExtractElement: {
1470 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1471 Out << "ExtractElementInst* " << getCppName(eei)
1472 << " = new ExtractElementInst(" << opNames[0]
1473 << ", " << opNames[1] << ", \"";
1474 printEscapedString(eei->getName());
1475 Out << "\", " << bbname << ");";
1476 break;
1477 }
1478 case Instruction::InsertElement: {
1479 const InsertElementInst* iei = cast<InsertElementInst>(I);
1480 Out << "InsertElementInst* " << getCppName(iei)
1481 << " = InsertElementInst::Create(" << opNames[0]
1482 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1483 printEscapedString(iei->getName());
1484 Out << "\", " << bbname << ");";
1485 break;
1486 }
1487 case Instruction::ShuffleVector: {
1488 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1489 Out << "ShuffleVectorInst* " << getCppName(svi)
1490 << " = new ShuffleVectorInst(" << opNames[0]
1491 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1492 printEscapedString(svi->getName());
1493 Out << "\", " << bbname << ");";
1494 break;
1495 }
1496 case Instruction::ExtractValue: {
1497 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1498 Out << "std::vector<unsigned> " << iName << "_indices;";
1499 nl(Out);
1500 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1501 Out << iName << "_indices.push_back("
1502 << evi->idx_begin()[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001503 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001504 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001505 Out << "ExtractValueInst* " << getCppName(evi)
1506 << " = ExtractValueInst::Create(" << opNames[0]
1507 << ", "
Nick Lewycky3bca1012011-09-05 18:50:59 +00001508 << iName << "_indices, \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001509 printEscapedString(evi->getName());
1510 Out << "\", " << bbname << ");";
1511 break;
1512 }
1513 case Instruction::InsertValue: {
1514 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1515 Out << "std::vector<unsigned> " << iName << "_indices;";
1516 nl(Out);
1517 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1518 Out << iName << "_indices.push_back("
1519 << ivi->idx_begin()[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001520 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001521 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001522 Out << "InsertValueInst* " << getCppName(ivi)
1523 << " = InsertValueInst::Create(" << opNames[0]
1524 << ", " << opNames[1] << ", "
Nick Lewycky3bca1012011-09-05 18:50:59 +00001525 << iName << "_indices, \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001526 printEscapedString(ivi->getName());
1527 Out << "\", " << bbname << ");";
1528 break;
1529 }
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001530 case Instruction::Fence: {
1531 const FenceInst *fi = cast<FenceInst>(I);
1532 StringRef Ordering = ConvertAtomicOrdering(fi->getOrdering());
1533 StringRef CrossThread = ConvertAtomicSynchScope(fi->getSynchScope());
1534 Out << "FenceInst* " << iName
1535 << " = new FenceInst(mod->getContext(), "
Eli Friedman5b7cc332011-11-04 17:29:35 +00001536 << Ordering << ", " << CrossThread << ", " << bbname
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001537 << ");";
1538 break;
1539 }
1540 case Instruction::AtomicCmpXchg: {
1541 const AtomicCmpXchgInst *cxi = cast<AtomicCmpXchgInst>(I);
1542 StringRef Ordering = ConvertAtomicOrdering(cxi->getOrdering());
1543 StringRef CrossThread = ConvertAtomicSynchScope(cxi->getSynchScope());
1544 Out << "AtomicCmpXchgInst* " << iName
1545 << " = new AtomicCmpXchgInst("
1546 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", "
Eli Friedman5b7cc332011-11-04 17:29:35 +00001547 << Ordering << ", " << CrossThread << ", " << bbname
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001548 << ");";
1549 nl(Out) << iName << "->setName(\"";
1550 printEscapedString(cxi->getName());
1551 Out << "\");";
1552 break;
1553 }
1554 case Instruction::AtomicRMW: {
1555 const AtomicRMWInst *rmwi = cast<AtomicRMWInst>(I);
1556 StringRef Ordering = ConvertAtomicOrdering(rmwi->getOrdering());
1557 StringRef CrossThread = ConvertAtomicSynchScope(rmwi->getSynchScope());
1558 StringRef Operation;
1559 switch (rmwi->getOperation()) {
1560 case AtomicRMWInst::Xchg: Operation = "AtomicRMWInst::Xchg"; break;
1561 case AtomicRMWInst::Add: Operation = "AtomicRMWInst::Add"; break;
1562 case AtomicRMWInst::Sub: Operation = "AtomicRMWInst::Sub"; break;
1563 case AtomicRMWInst::And: Operation = "AtomicRMWInst::And"; break;
1564 case AtomicRMWInst::Nand: Operation = "AtomicRMWInst::Nand"; break;
1565 case AtomicRMWInst::Or: Operation = "AtomicRMWInst::Or"; break;
1566 case AtomicRMWInst::Xor: Operation = "AtomicRMWInst::Xor"; break;
1567 case AtomicRMWInst::Max: Operation = "AtomicRMWInst::Max"; break;
1568 case AtomicRMWInst::Min: Operation = "AtomicRMWInst::Min"; break;
1569 case AtomicRMWInst::UMax: Operation = "AtomicRMWInst::UMax"; break;
1570 case AtomicRMWInst::UMin: Operation = "AtomicRMWInst::UMin"; break;
1571 case AtomicRMWInst::BAD_BINOP: llvm_unreachable("Bad atomic operation");
1572 }
1573 Out << "AtomicRMWInst* " << iName
1574 << " = new AtomicRMWInst("
1575 << Operation << ", "
1576 << opNames[0] << ", " << opNames[1] << ", "
Eli Friedman5b7cc332011-11-04 17:29:35 +00001577 << Ordering << ", " << CrossThread << ", " << bbname
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001578 << ");";
1579 nl(Out) << iName << "->setName(\"";
1580 printEscapedString(rmwi->getName());
1581 Out << "\");";
1582 break;
1583 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001584 }
1585 DefinedValues.insert(I);
1586 nl(Out);
1587 delete [] opNames;
1588}
1589
Chris Lattner7e6d7452010-06-21 23:12:56 +00001590// Print out the types, constants and declarations needed by one function
1591void CppWriter::printFunctionUses(const Function* F) {
1592 nl(Out) << "// Type Definitions"; nl(Out);
1593 if (!is_inline) {
1594 // Print the function's return type
1595 printType(F->getReturnType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001596
Chris Lattner7e6d7452010-06-21 23:12:56 +00001597 // Print the function's function type
1598 printType(F->getFunctionType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001599
Chris Lattner7e6d7452010-06-21 23:12:56 +00001600 // Print the types of each of the function's arguments
Anton Korobeynikov50276522008-04-23 22:29:24 +00001601 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1602 AI != AE; ++AI) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001603 printType(AI->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001604 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001605 }
1606
Chris Lattner7e6d7452010-06-21 23:12:56 +00001607 // Print type definitions for every type referenced by an instruction and
1608 // make a note of any global values or constants that are referenced
1609 SmallPtrSet<GlobalValue*,64> gvs;
1610 SmallPtrSet<Constant*,64> consts;
1611 for (Function::const_iterator BB = F->begin(), BE = F->end();
1612 BB != BE; ++BB){
1613 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
Anton Korobeynikov50276522008-04-23 22:29:24 +00001614 I != E; ++I) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001615 // Print the type of the instruction itself
1616 printType(I->getType());
1617
1618 // Print the type of each of the instruction's operands
1619 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1620 Value* operand = I->getOperand(i);
1621 printType(operand->getType());
1622
1623 // If the operand references a GVal or Constant, make a note of it
1624 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1625 gvs.insert(GV);
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001626 if (GenerationType != GenFunction)
1627 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1628 if (GVar->hasInitializer())
1629 consts.insert(GVar->getInitializer());
1630 } else if (Constant* C = dyn_cast<Constant>(operand)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001631 consts.insert(C);
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001632 for (unsigned j = 0; j < C->getNumOperands(); ++j) {
1633 // If the operand references a GVal or Constant, make a note of it
1634 Value* operand = C->getOperand(j);
1635 printType(operand->getType());
1636 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1637 gvs.insert(GV);
1638 if (GenerationType != GenFunction)
1639 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1640 if (GVar->hasInitializer())
1641 consts.insert(GVar->getInitializer());
1642 }
1643 }
1644 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001645 }
1646 }
1647 }
1648
1649 // Print the function declarations for any functions encountered
1650 nl(Out) << "// Function Declarations"; nl(Out);
1651 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1652 I != E; ++I) {
1653 if (Function* Fun = dyn_cast<Function>(*I)) {
1654 if (!is_inline || Fun != F)
1655 printFunctionHead(Fun);
1656 }
1657 }
1658
1659 // Print the global variable declarations for any variables encountered
1660 nl(Out) << "// Global Variable Declarations"; nl(Out);
1661 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1662 I != E; ++I) {
1663 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1664 printVariableHead(F);
1665 }
1666
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001667 // Print the constants found
Chris Lattner7e6d7452010-06-21 23:12:56 +00001668 nl(Out) << "// Constant Definitions"; nl(Out);
1669 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1670 E = consts.end(); I != E; ++I) {
1671 printConstant(*I);
1672 }
1673
1674 // Process the global variables definitions now that all the constants have
1675 // been emitted. These definitions just couple the gvars with their constant
1676 // initializers.
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001677 if (GenerationType != GenFunction) {
1678 nl(Out) << "// Global Variable Definitions"; nl(Out);
1679 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1680 I != E; ++I) {
1681 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1682 printVariableBody(GV);
1683 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001684 }
1685}
1686
1687void CppWriter::printFunctionHead(const Function* F) {
1688 nl(Out) << "Function* " << getCppName(F);
Nicolas Geoffrayf8557952011-10-08 11:56:36 +00001689 Out << " = mod->getFunction(\"";
1690 printEscapedString(F->getName());
1691 Out << "\");";
1692 nl(Out) << "if (!" << getCppName(F) << ") {";
1693 nl(Out) << getCppName(F);
1694
Chris Lattner7e6d7452010-06-21 23:12:56 +00001695 Out<< " = Function::Create(";
1696 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1697 nl(Out) << "/*Linkage=*/";
1698 printLinkageType(F->getLinkage());
1699 Out << ",";
1700 nl(Out) << "/*Name=*/\"";
1701 printEscapedString(F->getName());
1702 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1703 nl(Out,-1);
1704 printCppName(F);
1705 Out << "->setCallingConv(";
1706 printCallingConv(F->getCallingConv());
1707 Out << ");";
1708 nl(Out);
1709 if (F->hasSection()) {
1710 printCppName(F);
1711 Out << "->setSection(\"" << F->getSection() << "\");";
1712 nl(Out);
1713 }
1714 if (F->getAlignment()) {
1715 printCppName(F);
1716 Out << "->setAlignment(" << F->getAlignment() << ");";
1717 nl(Out);
1718 }
1719 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1720 printCppName(F);
1721 Out << "->setVisibility(";
1722 printVisibilityType(F->getVisibility());
1723 Out << ");";
1724 nl(Out);
1725 }
1726 if (F->hasGC()) {
1727 printCppName(F);
1728 Out << "->setGC(\"" << F->getGC() << "\");";
1729 nl(Out);
1730 }
Nicolas Geoffrayf8557952011-10-08 11:56:36 +00001731 Out << "}";
1732 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001733 printAttributes(F->getAttributes(), getCppName(F));
1734 printCppName(F);
1735 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1736 nl(Out);
1737}
1738
1739void CppWriter::printFunctionBody(const Function *F) {
1740 if (F->isDeclaration())
1741 return; // external functions have no bodies.
1742
1743 // Clear the DefinedValues and ForwardRefs maps because we can't have
1744 // cross-function forward refs
1745 ForwardRefs.clear();
1746 DefinedValues.clear();
1747
1748 // Create all the argument values
1749 if (!is_inline) {
1750 if (!F->arg_empty()) {
1751 Out << "Function::arg_iterator args = " << getCppName(F)
1752 << "->arg_begin();";
1753 nl(Out);
1754 }
1755 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1756 AI != AE; ++AI) {
1757 Out << "Value* " << getCppName(AI) << " = args++;";
1758 nl(Out);
1759 if (AI->hasName()) {
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001760 Out << getCppName(AI) << "->setName(\"";
1761 printEscapedString(AI->getName());
1762 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001763 nl(Out);
1764 }
1765 }
1766 }
1767
Chris Lattner7e6d7452010-06-21 23:12:56 +00001768 // Create all the basic blocks
1769 nl(Out);
1770 for (Function::const_iterator BI = F->begin(), BE = F->end();
1771 BI != BE; ++BI) {
1772 std::string bbname(getCppName(BI));
1773 Out << "BasicBlock* " << bbname <<
1774 " = BasicBlock::Create(mod->getContext(), \"";
1775 if (BI->hasName())
1776 printEscapedString(BI->getName());
1777 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1778 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001779 }
1780
Chris Lattner7e6d7452010-06-21 23:12:56 +00001781 // Output all of its basic blocks... for the function
1782 for (Function::const_iterator BI = F->begin(), BE = F->end();
1783 BI != BE; ++BI) {
1784 std::string bbname(getCppName(BI));
1785 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001786 nl(Out);
1787
Chris Lattner7e6d7452010-06-21 23:12:56 +00001788 // Output all of the instructions in the basic block...
1789 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1790 I != E; ++I) {
1791 printInstruction(I,bbname);
1792 }
1793 }
1794
1795 // Loop over the ForwardRefs and resolve them now that all instructions
1796 // are generated.
1797 if (!ForwardRefs.empty()) {
1798 nl(Out) << "// Resolve Forward References";
1799 nl(Out);
1800 }
1801
1802 while (!ForwardRefs.empty()) {
1803 ForwardRefMap::iterator I = ForwardRefs.begin();
1804 Out << I->second << "->replaceAllUsesWith("
1805 << getCppName(I->first) << "); delete " << I->second << ";";
1806 nl(Out);
1807 ForwardRefs.erase(I);
1808 }
1809}
1810
1811void CppWriter::printInline(const std::string& fname,
1812 const std::string& func) {
1813 const Function* F = TheModule->getFunction(func);
1814 if (!F) {
1815 error(std::string("Function '") + func + "' not found in input module");
1816 return;
1817 }
1818 if (F->isDeclaration()) {
1819 error(std::string("Function '") + func + "' is external!");
1820 return;
1821 }
1822 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1823 << getCppName(F);
1824 unsigned arg_count = 1;
1825 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1826 AI != AE; ++AI) {
1827 Out << ", Value* arg_" << arg_count;
1828 }
1829 Out << ") {";
1830 nl(Out);
1831 is_inline = true;
1832 printFunctionUses(F);
1833 printFunctionBody(F);
1834 is_inline = false;
1835 Out << "return " << getCppName(F->begin()) << ";";
1836 nl(Out) << "}";
1837 nl(Out);
1838}
1839
1840void CppWriter::printModuleBody() {
1841 // Print out all the type definitions
1842 nl(Out) << "// Type Definitions"; nl(Out);
1843 printTypes(TheModule);
1844
1845 // Functions can call each other and global variables can reference them so
1846 // define all the functions first before emitting their function bodies.
1847 nl(Out) << "// Function Declarations"; nl(Out);
1848 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1849 I != E; ++I)
1850 printFunctionHead(I);
1851
1852 // Process the global variables declarations. We can't initialze them until
1853 // after the constants are printed so just print a header for each global
1854 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1855 for (Module::const_global_iterator I = TheModule->global_begin(),
1856 E = TheModule->global_end(); I != E; ++I) {
1857 printVariableHead(I);
1858 }
1859
1860 // Print out all the constants definitions. Constants don't recurse except
1861 // through GlobalValues. All GlobalValues have been declared at this point
1862 // so we can proceed to generate the constants.
1863 nl(Out) << "// Constant Definitions"; nl(Out);
1864 printConstants(TheModule);
1865
1866 // Process the global variables definitions now that all the constants have
1867 // been emitted. These definitions just couple the gvars with their constant
1868 // initializers.
1869 nl(Out) << "// Global Variable Definitions"; nl(Out);
1870 for (Module::const_global_iterator I = TheModule->global_begin(),
1871 E = TheModule->global_end(); I != E; ++I) {
1872 printVariableBody(I);
1873 }
1874
1875 // Finally, we can safely put out all of the function bodies.
1876 nl(Out) << "// Function Definitions"; nl(Out);
1877 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1878 I != E; ++I) {
1879 if (!I->isDeclaration()) {
1880 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1881 << ")";
1882 nl(Out) << "{";
1883 nl(Out,1);
1884 printFunctionBody(I);
1885 nl(Out,-1) << "}";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001886 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001887 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001888 }
1889}
1890
1891void CppWriter::printProgram(const std::string& fname,
1892 const std::string& mName) {
1893 Out << "#include <llvm/LLVMContext.h>\n";
1894 Out << "#include <llvm/Module.h>\n";
1895 Out << "#include <llvm/DerivedTypes.h>\n";
1896 Out << "#include <llvm/Constants.h>\n";
1897 Out << "#include <llvm/GlobalVariable.h>\n";
1898 Out << "#include <llvm/Function.h>\n";
1899 Out << "#include <llvm/CallingConv.h>\n";
1900 Out << "#include <llvm/BasicBlock.h>\n";
1901 Out << "#include <llvm/Instructions.h>\n";
1902 Out << "#include <llvm/InlineAsm.h>\n";
1903 Out << "#include <llvm/Support/FormattedStream.h>\n";
1904 Out << "#include <llvm/Support/MathExtras.h>\n";
1905 Out << "#include <llvm/Pass.h>\n";
1906 Out << "#include <llvm/PassManager.h>\n";
1907 Out << "#include <llvm/ADT/SmallVector.h>\n";
1908 Out << "#include <llvm/Analysis/Verifier.h>\n";
1909 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1910 Out << "#include <algorithm>\n";
1911 Out << "using namespace llvm;\n\n";
1912 Out << "Module* " << fname << "();\n\n";
1913 Out << "int main(int argc, char**argv) {\n";
1914 Out << " Module* Mod = " << fname << "();\n";
1915 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1916 Out << " PassManager PM;\n";
1917 Out << " PM.add(createPrintModulePass(&outs()));\n";
1918 Out << " PM.run(*Mod);\n";
1919 Out << " return 0;\n";
1920 Out << "}\n\n";
1921 printModule(fname,mName);
1922}
1923
1924void CppWriter::printModule(const std::string& fname,
1925 const std::string& mName) {
1926 nl(Out) << "Module* " << fname << "() {";
1927 nl(Out,1) << "// Module Construction";
1928 nl(Out) << "Module* mod = new Module(\"";
1929 printEscapedString(mName);
1930 Out << "\", getGlobalContext());";
1931 if (!TheModule->getTargetTriple().empty()) {
1932 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1933 }
1934 if (!TheModule->getTargetTriple().empty()) {
1935 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1936 << "\");";
1937 }
1938
1939 if (!TheModule->getModuleInlineAsm().empty()) {
1940 nl(Out) << "mod->setModuleInlineAsm(\"";
1941 printEscapedString(TheModule->getModuleInlineAsm());
1942 Out << "\");";
1943 }
1944 nl(Out);
1945
1946 // Loop over the dependent libraries and emit them.
1947 Module::lib_iterator LI = TheModule->lib_begin();
1948 Module::lib_iterator LE = TheModule->lib_end();
1949 while (LI != LE) {
1950 Out << "mod->addLibrary(\"" << *LI << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001951 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001952 ++LI;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001953 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001954 printModuleBody();
1955 nl(Out) << "return mod;";
1956 nl(Out,-1) << "}";
1957 nl(Out);
1958}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001959
Chris Lattner7e6d7452010-06-21 23:12:56 +00001960void CppWriter::printContents(const std::string& fname,
1961 const std::string& mName) {
1962 Out << "\nModule* " << fname << "(Module *mod) {\n";
1963 Out << "\nmod->setModuleIdentifier(\"";
1964 printEscapedString(mName);
1965 Out << "\");\n";
1966 printModuleBody();
1967 Out << "\nreturn mod;\n";
1968 Out << "\n}\n";
1969}
1970
1971void CppWriter::printFunction(const std::string& fname,
1972 const std::string& funcName) {
1973 const Function* F = TheModule->getFunction(funcName);
1974 if (!F) {
1975 error(std::string("Function '") + funcName + "' not found in input module");
1976 return;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001977 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001978 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1979 printFunctionUses(F);
1980 printFunctionHead(F);
1981 printFunctionBody(F);
1982 Out << "return " << getCppName(F) << ";\n";
1983 Out << "}\n";
1984}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001985
Chris Lattner7e6d7452010-06-21 23:12:56 +00001986void CppWriter::printFunctions() {
1987 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1988 Module::const_iterator I = funcs.begin();
1989 Module::const_iterator IE = funcs.end();
Anton Korobeynikov50276522008-04-23 22:29:24 +00001990
Chris Lattner7e6d7452010-06-21 23:12:56 +00001991 for (; I != IE; ++I) {
1992 const Function &func = *I;
1993 if (!func.isDeclaration()) {
1994 std::string name("define_");
1995 name += func.getName();
1996 printFunction(name, func.getName());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001997 }
1998 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001999}
Anton Korobeynikov50276522008-04-23 22:29:24 +00002000
Chris Lattner7e6d7452010-06-21 23:12:56 +00002001void CppWriter::printVariable(const std::string& fname,
2002 const std::string& varName) {
2003 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
Anton Korobeynikov50276522008-04-23 22:29:24 +00002004
Chris Lattner7e6d7452010-06-21 23:12:56 +00002005 if (!GV) {
2006 error(std::string("Variable '") + varName + "' not found in input module");
2007 return;
2008 }
2009 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
2010 printVariableUses(GV);
2011 printVariableHead(GV);
2012 printVariableBody(GV);
2013 Out << "return " << getCppName(GV) << ";\n";
2014 Out << "}\n";
2015}
2016
Chris Lattner1afcace2011-07-09 17:41:24 +00002017void CppWriter::printType(const std::string &fname,
2018 const std::string &typeName) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002019 Type* Ty = TheModule->getTypeByName(typeName);
Chris Lattner7e6d7452010-06-21 23:12:56 +00002020 if (!Ty) {
2021 error(std::string("Type '") + typeName + "' not found in input module");
2022 return;
2023 }
2024 Out << "\nType* " << fname << "(Module *mod) {\n";
2025 printType(Ty);
2026 Out << "return " << getCppName(Ty) << ";\n";
2027 Out << "}\n";
2028}
2029
2030bool CppWriter::runOnModule(Module &M) {
2031 TheModule = &M;
2032
2033 // Emit a header
2034 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
2035
2036 // Get the name of the function we're supposed to generate
2037 std::string fname = FuncName.getValue();
2038
2039 // Get the name of the thing we are to generate
2040 std::string tgtname = NameToGenerate.getValue();
2041 if (GenerationType == GenModule ||
2042 GenerationType == GenContents ||
2043 GenerationType == GenProgram ||
2044 GenerationType == GenFunctions) {
2045 if (tgtname == "!bad!") {
2046 if (M.getModuleIdentifier() == "-")
2047 tgtname = "<stdin>";
2048 else
2049 tgtname = M.getModuleIdentifier();
Anton Korobeynikov50276522008-04-23 22:29:24 +00002050 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00002051 } else if (tgtname == "!bad!")
2052 error("You must use the -for option with -gen-{function,variable,type}");
2053
2054 switch (WhatToGenerate(GenerationType)) {
2055 case GenProgram:
2056 if (fname.empty())
2057 fname = "makeLLVMModule";
2058 printProgram(fname,tgtname);
2059 break;
2060 case GenModule:
2061 if (fname.empty())
2062 fname = "makeLLVMModule";
2063 printModule(fname,tgtname);
2064 break;
2065 case GenContents:
2066 if (fname.empty())
2067 fname = "makeLLVMModuleContents";
2068 printContents(fname,tgtname);
2069 break;
2070 case GenFunction:
2071 if (fname.empty())
2072 fname = "makeLLVMFunction";
2073 printFunction(fname,tgtname);
2074 break;
2075 case GenFunctions:
2076 printFunctions();
2077 break;
2078 case GenInline:
2079 if (fname.empty())
2080 fname = "makeLLVMInline";
2081 printInline(fname,tgtname);
2082 break;
2083 case GenVariable:
2084 if (fname.empty())
2085 fname = "makeLLVMVariable";
2086 printVariable(fname,tgtname);
2087 break;
2088 case GenType:
2089 if (fname.empty())
2090 fname = "makeLLVMType";
2091 printType(fname,tgtname);
2092 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002093 }
2094
Chris Lattner7e6d7452010-06-21 23:12:56 +00002095 return false;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002096}
2097
2098char CppWriter::ID = 0;
2099
2100//===----------------------------------------------------------------------===//
2101// External Interface declaration
2102//===----------------------------------------------------------------------===//
2103
Dan Gohman99dca4f2010-05-11 19:57:55 +00002104bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
2105 formatted_raw_ostream &o,
2106 CodeGenFileType FileType,
Bob Wilson30a507a2012-07-02 19:48:45 +00002107 bool DisableVerify,
2108 AnalysisID StartAfter,
2109 AnalysisID StopAfter) {
Chris Lattner211edae2010-02-02 21:06:45 +00002110 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002111 PM.add(new CppWriter(o));
2112 return false;
2113}