blob: de73a72ac4911a9cb066215670f2cc2697ab8c3a [file] [log] [blame]
Anton Korobeynikov50276522008-04-23 22:29:24 +00001//===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the writing of the LLVM IR as a set of C++ calls to the
11// LLVM IR interface. The input module is assumed to be verified.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CPPTargetMachine.h"
16#include "llvm/CallingConv.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/InlineAsm.h"
20#include "llvm/Instruction.h"
21#include "llvm/Instructions.h"
22#include "llvm/Module.h"
23#include "llvm/Pass.h"
24#include "llvm/PassManager.h"
Evan Cheng1abf2cb2011-07-14 23:50:31 +000025#include "llvm/MC/MCAsmInfo.h"
Evan Cheng59ee62d2011-07-11 03:57:24 +000026#include "llvm/MC/MCInstrInfo.h"
Evan Chengffc0e732011-07-09 05:47:46 +000027#include "llvm/MC/MCSubtargetInfo.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000028#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/Support/CommandLine.h"
Torok Edwin30464702009-07-08 20:55:50 +000030#include "llvm/Support/ErrorHandling.h"
David Greene71847812009-07-14 20:18:05 +000031#include "llvm/Support/FormattedStream.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000032#include "llvm/Support/TargetRegistry.h"
Chris Lattner23132b12009-08-24 03:52:50 +000033#include "llvm/ADT/StringExtras.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000034#include "llvm/Config/config.h"
35#include <algorithm>
Anton Korobeynikov50276522008-04-23 22:29:24 +000036#include <set>
Chris Lattner1afcace2011-07-09 17:41:24 +000037#include <map>
Anton Korobeynikov50276522008-04-23 22:29:24 +000038using namespace llvm;
39
40static cl::opt<std::string>
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000041FuncName("cppfname", cl::desc("Specify the name of the generated function"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000042 cl::value_desc("function name"));
43
44enum WhatToGenerate {
45 GenProgram,
46 GenModule,
47 GenContents,
48 GenFunction,
49 GenFunctions,
50 GenInline,
51 GenVariable,
52 GenType
53};
54
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000055static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000056 cl::desc("Choose what kind of output to generate"),
57 cl::init(GenProgram),
58 cl::values(
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000059 clEnumValN(GenProgram, "program", "Generate a complete program"),
60 clEnumValN(GenModule, "module", "Generate a module definition"),
61 clEnumValN(GenContents, "contents", "Generate contents of a module"),
62 clEnumValN(GenFunction, "function", "Generate a function definition"),
63 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
64 clEnumValN(GenInline, "inline", "Generate an inline function"),
65 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
66 clEnumValN(GenType, "type", "Generate a type definition"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000067 clEnumValEnd
68 )
69);
70
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000071static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000072 cl::desc("Specify the name of the thing to generate"),
73 cl::init("!bad!"));
74
Daniel Dunbar0c795d62009-07-25 06:49:55 +000075extern "C" void LLVMInitializeCppBackendTarget() {
76 // Register the target.
Daniel Dunbar214e2232009-08-04 04:02:45 +000077 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
Daniel Dunbar0c795d62009-07-25 06:49:55 +000078}
Douglas Gregor1555a232009-06-16 20:12:29 +000079
Dan Gohman844731a2008-05-13 00:00:25 +000080namespace {
Chris Lattnerdb125cf2011-07-18 04:54:35 +000081 typedef std::vector<Type*> TypeList;
82 typedef std::map<Type*,std::string> TypeMap;
Anton Korobeynikov50276522008-04-23 22:29:24 +000083 typedef std::map<const Value*,std::string> ValueMap;
84 typedef std::set<std::string> NameSet;
Chris Lattnerdb125cf2011-07-18 04:54:35 +000085 typedef std::set<Type*> TypeSet;
Anton Korobeynikov50276522008-04-23 22:29:24 +000086 typedef std::set<const Value*> ValueSet;
87 typedef std::map<const Value*,std::string> ForwardRefMap;
88
89 /// CppWriter - This class is the main chunk of code that converts an LLVM
90 /// module to a C++ translation unit.
91 class CppWriter : public ModulePass {
David Greene71847812009-07-14 20:18:05 +000092 formatted_raw_ostream &Out;
Anton Korobeynikov50276522008-04-23 22:29:24 +000093 const Module *TheModule;
94 uint64_t uniqueNum;
95 TypeMap TypeNames;
96 ValueMap ValueNames;
Anton Korobeynikov50276522008-04-23 22:29:24 +000097 NameSet UsedNames;
98 TypeSet DefinedTypes;
99 ValueSet DefinedValues;
100 ForwardRefMap ForwardRefs;
101 bool is_inline;
Chris Lattner1018c242010-06-21 23:14:47 +0000102 unsigned indent_level;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000103
104 public:
105 static char ID;
David Greene71847812009-07-14 20:18:05 +0000106 explicit CppWriter(formatted_raw_ostream &o) :
Owen Anderson90c579d2010-08-06 18:33:48 +0000107 ModulePass(ID), Out(o), uniqueNum(0), is_inline(false), indent_level(0){}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000108
109 virtual const char *getPassName() const { return "C++ backend"; }
110
111 bool runOnModule(Module &M);
112
Anton Korobeynikov50276522008-04-23 22:29:24 +0000113 void printProgram(const std::string& fname, const std::string& modName );
114 void printModule(const std::string& fname, const std::string& modName );
115 void printContents(const std::string& fname, const std::string& modName );
116 void printFunction(const std::string& fname, const std::string& funcName );
117 void printFunctions();
118 void printInline(const std::string& fname, const std::string& funcName );
119 void printVariable(const std::string& fname, const std::string& varName );
120 void printType(const std::string& fname, const std::string& typeName );
121
122 void error(const std::string& msg);
123
Chris Lattner1018c242010-06-21 23:14:47 +0000124
125 formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0);
126 inline void in() { indent_level++; }
127 inline void out() { if (indent_level >0) indent_level--; }
128
Anton Korobeynikov50276522008-04-23 22:29:24 +0000129 private:
130 void printLinkageType(GlobalValue::LinkageTypes LT);
131 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +0000132 void printCallingConv(CallingConv::ID cc);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000133 void printEscapedString(const std::string& str);
134 void printCFP(const ConstantFP* CFP);
135
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000136 std::string getCppName(Type* val);
137 inline void printCppName(Type* val);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000138
139 std::string getCppName(const Value* val);
140 inline void printCppName(const Value* val);
141
Devang Patel05988662008-09-25 21:00:45 +0000142 void printAttributes(const AttrListPtr &PAL, const std::string &name);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000143 void printType(Type* Ty);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000144 void printTypes(const Module* M);
145
146 void printConstant(const Constant *CPV);
147 void printConstants(const Module* M);
148
149 void printVariableUses(const GlobalVariable *GV);
150 void printVariableHead(const GlobalVariable *GV);
151 void printVariableBody(const GlobalVariable *GV);
152
153 void printFunctionUses(const Function *F);
154 void printFunctionHead(const Function *F);
155 void printFunctionBody(const Function *F);
156 void printInstruction(const Instruction *I, const std::string& bbname);
Eli Friedmanbb5a7442011-09-29 20:21:17 +0000157 std::string getOpName(const Value*);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000158
159 void printModuleBody();
160 };
Chris Lattner7e6d7452010-06-21 23:12:56 +0000161} // end anonymous namespace.
Anton Korobeynikov50276522008-04-23 22:29:24 +0000162
Chris Lattner1018c242010-06-21 23:14:47 +0000163formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
164 Out << '\n';
Chris Lattner7e6d7452010-06-21 23:12:56 +0000165 if (delta >= 0 || indent_level >= unsigned(-delta))
166 indent_level += delta;
Chris Lattner1018c242010-06-21 23:14:47 +0000167 Out.indent(indent_level);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000168 return Out;
169}
170
Chris Lattner7e6d7452010-06-21 23:12:56 +0000171static inline void sanitize(std::string &str) {
172 for (size_t i = 0; i < str.length(); ++i)
173 if (!isalnum(str[i]) && str[i] != '_')
174 str[i] = '_';
175}
176
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000177static std::string getTypePrefix(Type *Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000178 switch (Ty->getTypeID()) {
179 case Type::VoidTyID: return "void_";
180 case Type::IntegerTyID:
181 return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
182 case Type::FloatTyID: return "float_";
183 case Type::DoubleTyID: return "double_";
184 case Type::LabelTyID: return "label_";
185 case Type::FunctionTyID: return "func_";
186 case Type::StructTyID: return "struct_";
187 case Type::ArrayTyID: return "array_";
188 case Type::PointerTyID: return "ptr_";
189 case Type::VectorTyID: return "packed_";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000190 default: return "other_";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000191 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000192}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000193
Chris Lattner7e6d7452010-06-21 23:12:56 +0000194void CppWriter::error(const std::string& msg) {
195 report_fatal_error(msg);
196}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000197
Chris Lattner7e6d7452010-06-21 23:12:56 +0000198// printCFP - Print a floating point constant .. very carefully :)
199// This makes sure that conversion to/from floating yields the same binary
200// result so that we don't lose precision.
201void CppWriter::printCFP(const ConstantFP *CFP) {
202 bool ignored;
203 APFloat APF = APFloat(CFP->getValueAPF()); // copy
204 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
205 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
206 Out << "ConstantFP::get(mod->getContext(), ";
207 Out << "APFloat(";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000208#if HAVE_PRINTF_A
Chris Lattner7e6d7452010-06-21 23:12:56 +0000209 char Buffer[100];
210 sprintf(Buffer, "%A", APF.convertToDouble());
211 if ((!strncmp(Buffer, "0x", 2) ||
212 !strncmp(Buffer, "-0x", 3) ||
213 !strncmp(Buffer, "+0x", 3)) &&
214 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
215 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
216 Out << "BitsToDouble(" << Buffer << ")";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000217 else
Chris Lattner7e6d7452010-06-21 23:12:56 +0000218 Out << "BitsToFloat((float)" << Buffer << ")";
219 Out << ")";
220 } else {
221#endif
222 std::string StrVal = ftostr(CFP->getValueAPF());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000223
Chris Lattner7e6d7452010-06-21 23:12:56 +0000224 while (StrVal[0] == ' ')
225 StrVal.erase(StrVal.begin());
226
227 // Check to make sure that the stringized number is not some string like
228 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
229 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
230 ((StrVal[0] == '-' || StrVal[0] == '+') &&
231 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
232 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
233 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
234 Out << StrVal;
235 else
236 Out << StrVal << "f";
237 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
238 Out << "BitsToDouble(0x"
239 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
240 << "ULL) /* " << StrVal << " */";
241 else
242 Out << "BitsToFloat(0x"
243 << utohexstr((uint32_t)CFP->getValueAPF().
244 bitcastToAPInt().getZExtValue())
245 << "U) /* " << StrVal << " */";
246 Out << ")";
247#if HAVE_PRINTF_A
248 }
249#endif
250 Out << ")";
251}
252
253void CppWriter::printCallingConv(CallingConv::ID cc){
254 // Print the calling convention.
255 switch (cc) {
256 case CallingConv::C: Out << "CallingConv::C"; break;
257 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
258 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
259 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
260 default: Out << cc; break;
261 }
262}
263
264void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
265 switch (LT) {
266 case GlobalValue::InternalLinkage:
267 Out << "GlobalValue::InternalLinkage"; break;
268 case GlobalValue::PrivateLinkage:
269 Out << "GlobalValue::PrivateLinkage"; break;
270 case GlobalValue::LinkerPrivateLinkage:
271 Out << "GlobalValue::LinkerPrivateLinkage"; break;
Bill Wendling5e721d72010-07-01 21:55:59 +0000272 case GlobalValue::LinkerPrivateWeakLinkage:
273 Out << "GlobalValue::LinkerPrivateWeakLinkage"; break;
Bill Wendling55ae5152010-08-20 22:05:50 +0000274 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
275 Out << "GlobalValue::LinkerPrivateWeakDefAutoLinkage"; break;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000276 case GlobalValue::AvailableExternallyLinkage:
277 Out << "GlobalValue::AvailableExternallyLinkage "; break;
278 case GlobalValue::LinkOnceAnyLinkage:
279 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
280 case GlobalValue::LinkOnceODRLinkage:
281 Out << "GlobalValue::LinkOnceODRLinkage "; break;
282 case GlobalValue::WeakAnyLinkage:
283 Out << "GlobalValue::WeakAnyLinkage"; break;
284 case GlobalValue::WeakODRLinkage:
285 Out << "GlobalValue::WeakODRLinkage"; break;
286 case GlobalValue::AppendingLinkage:
287 Out << "GlobalValue::AppendingLinkage"; break;
288 case GlobalValue::ExternalLinkage:
289 Out << "GlobalValue::ExternalLinkage"; break;
290 case GlobalValue::DLLImportLinkage:
291 Out << "GlobalValue::DLLImportLinkage"; break;
292 case GlobalValue::DLLExportLinkage:
293 Out << "GlobalValue::DLLExportLinkage"; break;
294 case GlobalValue::ExternalWeakLinkage:
295 Out << "GlobalValue::ExternalWeakLinkage"; break;
296 case GlobalValue::CommonLinkage:
297 Out << "GlobalValue::CommonLinkage"; break;
298 }
299}
300
301void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
302 switch (VisType) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000303 case GlobalValue::DefaultVisibility:
304 Out << "GlobalValue::DefaultVisibility";
305 break;
306 case GlobalValue::HiddenVisibility:
307 Out << "GlobalValue::HiddenVisibility";
308 break;
309 case GlobalValue::ProtectedVisibility:
310 Out << "GlobalValue::ProtectedVisibility";
311 break;
312 }
313}
314
315// printEscapedString - Print each character of the specified string, escaping
316// it if it is not printable or if it is an escape char.
317void CppWriter::printEscapedString(const std::string &Str) {
318 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
319 unsigned char C = Str[i];
320 if (isprint(C) && C != '"' && C != '\\') {
321 Out << C;
322 } else {
323 Out << "\\x"
324 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
325 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
326 }
327 }
328}
329
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000330std::string CppWriter::getCppName(Type* Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000331 // First, handle the primitive types .. easy
332 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
333 switch (Ty->getTypeID()) {
334 case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())";
335 case Type::IntegerTyID: {
336 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
337 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
338 }
339 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
340 case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())";
341 case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())";
342 case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())";
Dale Johannesenbb811a22010-09-10 20:55:01 +0000343 case Type::X86_MMXTyID: return "Type::getX86_MMXTy(mod->getContext())";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000344 default:
345 error("Invalid primitive type");
346 break;
347 }
348 // shouldn't be returned, but make it sensible
349 return "Type::getVoidTy(mod->getContext())";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000350 }
351
Chris Lattner7e6d7452010-06-21 23:12:56 +0000352 // Now, see if we've seen the type before and return that
353 TypeMap::iterator I = TypeNames.find(Ty);
354 if (I != TypeNames.end())
355 return I->second;
356
357 // Okay, let's build a new name for this type. Start with a prefix
358 const char* prefix = 0;
359 switch (Ty->getTypeID()) {
360 case Type::FunctionTyID: prefix = "FuncTy_"; break;
361 case Type::StructTyID: prefix = "StructTy_"; break;
362 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
363 case Type::PointerTyID: prefix = "PointerTy_"; break;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000364 case Type::VectorTyID: prefix = "VectorTy_"; break;
365 default: prefix = "OtherTy_"; break; // prevent breakage
Anton Korobeynikov50276522008-04-23 22:29:24 +0000366 }
367
Chris Lattner7e6d7452010-06-21 23:12:56 +0000368 // See if the type has a name in the symboltable and build accordingly
Chris Lattner7e6d7452010-06-21 23:12:56 +0000369 std::string name;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000370 if (StructType *STy = dyn_cast<StructType>(Ty))
Chris Lattner1afcace2011-07-09 17:41:24 +0000371 if (STy->hasName())
372 name = STy->getName();
373
374 if (name.empty())
375 name = utostr(uniqueNum++);
376
377 name = std::string(prefix) + name;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000378 sanitize(name);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000379
Chris Lattner7e6d7452010-06-21 23:12:56 +0000380 // Save the name
381 return TypeNames[Ty] = name;
382}
383
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000384void CppWriter::printCppName(Type* Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000385 printEscapedString(getCppName(Ty));
386}
387
388std::string CppWriter::getCppName(const Value* val) {
389 std::string name;
390 ValueMap::iterator I = ValueNames.find(val);
391 if (I != ValueNames.end() && I->first == val)
392 return I->second;
393
394 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
395 name = std::string("gvar_") +
396 getTypePrefix(GV->getType()->getElementType());
397 } else if (isa<Function>(val)) {
398 name = std::string("func_");
399 } else if (const Constant* C = dyn_cast<Constant>(val)) {
400 name = std::string("const_") + getTypePrefix(C->getType());
401 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
402 if (is_inline) {
403 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
404 Function::const_arg_iterator(Arg)) + 1;
405 name = std::string("arg_") + utostr(argNum);
406 NameSet::iterator NI = UsedNames.find(name);
407 if (NI != UsedNames.end())
408 name += std::string("_") + utostr(uniqueNum++);
409 UsedNames.insert(name);
410 return ValueNames[val] = name;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000411 } else {
412 name = getTypePrefix(val->getType());
413 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000414 } else {
415 name = getTypePrefix(val->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000416 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000417 if (val->hasName())
418 name += val->getName();
419 else
420 name += utostr(uniqueNum++);
421 sanitize(name);
422 NameSet::iterator NI = UsedNames.find(name);
423 if (NI != UsedNames.end())
424 name += std::string("_") + utostr(uniqueNum++);
425 UsedNames.insert(name);
426 return ValueNames[val] = name;
427}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000428
Chris Lattner7e6d7452010-06-21 23:12:56 +0000429void CppWriter::printCppName(const Value* val) {
430 printEscapedString(getCppName(val));
431}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000432
Chris Lattner7e6d7452010-06-21 23:12:56 +0000433void CppWriter::printAttributes(const AttrListPtr &PAL,
434 const std::string &name) {
435 Out << "AttrListPtr " << name << "_PAL;";
436 nl(Out);
437 if (!PAL.isEmpty()) {
438 Out << '{'; in(); nl(Out);
439 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
440 Out << "AttributeWithIndex PAWI;"; nl(Out);
441 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
442 unsigned index = PAL.getSlot(i).Index;
443 Attributes attrs = PAL.getSlot(i).Attrs;
Nicolas Geoffray81946832012-01-22 20:05:26 +0000444 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = Attribute::None ";
Chris Lattneracca9552009-01-13 07:22:22 +0000445#define HANDLE_ATTR(X) \
Chris Lattner7e6d7452010-06-21 23:12:56 +0000446 if (attrs & Attribute::X) \
447 Out << " | Attribute::" #X; \
448 attrs &= ~Attribute::X;
449
450 HANDLE_ATTR(SExt);
451 HANDLE_ATTR(ZExt);
452 HANDLE_ATTR(NoReturn);
453 HANDLE_ATTR(InReg);
454 HANDLE_ATTR(StructRet);
455 HANDLE_ATTR(NoUnwind);
456 HANDLE_ATTR(NoAlias);
457 HANDLE_ATTR(ByVal);
458 HANDLE_ATTR(Nest);
459 HANDLE_ATTR(ReadNone);
460 HANDLE_ATTR(ReadOnly);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000461 HANDLE_ATTR(NoInline);
462 HANDLE_ATTR(AlwaysInline);
463 HANDLE_ATTR(OptimizeForSize);
464 HANDLE_ATTR(StackProtect);
465 HANDLE_ATTR(StackProtectReq);
466 HANDLE_ATTR(NoCapture);
Eli Friedman32bb4df2010-07-16 18:47:20 +0000467 HANDLE_ATTR(NoRedZone);
468 HANDLE_ATTR(NoImplicitFloat);
469 HANDLE_ATTR(Naked);
470 HANDLE_ATTR(InlineHint);
Rafael Espindola25456ef2011-10-03 14:45:37 +0000471 HANDLE_ATTR(ReturnsTwice);
Bill Wendling54f15362011-08-09 00:47:30 +0000472 HANDLE_ATTR(UWTable);
473 HANDLE_ATTR(NonLazyBind);
Chris Lattneracca9552009-01-13 07:22:22 +0000474#undef HANDLE_ATTR
Eli Friedman32bb4df2010-07-16 18:47:20 +0000475 if (attrs & Attribute::StackAlignment)
476 Out << " | Attribute::constructStackAlignmentFromInt("
477 << Attribute::getStackAlignmentFromAttrs(attrs)
478 << ")";
479 attrs &= ~Attribute::StackAlignment;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000480 assert(attrs == 0 && "Unhandled attribute!");
481 Out << ";";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000482 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000483 Out << "Attrs.push_back(PAWI);";
484 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000485 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000486 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
487 nl(Out);
488 out(); nl(Out);
489 Out << '}'; nl(Out);
490 }
491}
492
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000493void CppWriter::printType(Type* Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000494 // We don't print definitions for primitive types
495 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000496 return;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000497
498 // If we already defined this type, we don't need to define it again.
499 if (DefinedTypes.find(Ty) != DefinedTypes.end())
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000500 return;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000501
502 // Everything below needs the name for the type so get it now.
503 std::string typeName(getCppName(Ty));
504
Chris Lattner7e6d7452010-06-21 23:12:56 +0000505 // Print the type definition
506 switch (Ty->getTypeID()) {
507 case Type::FunctionTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000508 FunctionType* FT = cast<FunctionType>(Ty);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000509 Out << "std::vector<Type*>" << typeName << "_args;";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000510 nl(Out);
511 FunctionType::param_iterator PI = FT->param_begin();
512 FunctionType::param_iterator PE = FT->param_end();
513 for (; PI != PE; ++PI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000514 Type* argTy = static_cast<Type*>(*PI);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000515 printType(argTy);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000516 std::string argName(getCppName(argTy));
517 Out << typeName << "_args.push_back(" << argName;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000518 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000519 nl(Out);
520 }
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000521 printType(FT->getReturnType());
Chris Lattner7e6d7452010-06-21 23:12:56 +0000522 std::string retTypeName(getCppName(FT->getReturnType()));
523 Out << "FunctionType* " << typeName << " = FunctionType::get(";
524 in(); nl(Out) << "/*Result=*/" << retTypeName;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000525 Out << ",";
526 nl(Out) << "/*Params=*/" << typeName << "_args,";
527 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
528 out();
Anton Korobeynikov50276522008-04-23 22:29:24 +0000529 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000530 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000531 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000532 case Type::StructTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000533 StructType* ST = cast<StructType>(Ty);
Chris Lattnerc4d0e9f2011-08-12 18:07:07 +0000534 if (!ST->isLiteral()) {
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000535 Out << "StructType *" << typeName << " = mod->getTypeByName(\"";
536 printEscapedString(ST->getName());
537 Out << "\");";
538 nl(Out);
539 Out << "if (!" << typeName << ") {";
540 nl(Out);
541 Out << typeName << " = ";
Chris Lattnerc4d0e9f2011-08-12 18:07:07 +0000542 Out << "StructType::create(mod->getContext(), \"";
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000543 printEscapedString(ST->getName());
544 Out << "\");";
545 nl(Out);
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000546 Out << "}";
547 nl(Out);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000548 // Indicate that this type is now defined.
549 DefinedTypes.insert(Ty);
550 }
551
552 Out << "std::vector<Type*>" << typeName << "_fields;";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000553 nl(Out);
554 StructType::element_iterator EI = ST->element_begin();
555 StructType::element_iterator EE = ST->element_end();
556 for (; EI != EE; ++EI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000557 Type* fieldTy = static_cast<Type*>(*EI);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000558 printType(fieldTy);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000559 std::string fieldName(getCppName(fieldTy));
560 Out << typeName << "_fields.push_back(" << fieldName;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000561 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000562 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000563 }
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000564
Chris Lattnerc4d0e9f2011-08-12 18:07:07 +0000565 if (ST->isLiteral()) {
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000566 Out << "StructType *" << typeName << " = ";
Chris Lattner1afcace2011-07-09 17:41:24 +0000567 Out << "StructType::get(" << "mod->getContext(), ";
568 } else {
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000569 Out << "if (" << typeName << "->isOpaque()) {";
570 nl(Out);
Chris Lattner1afcace2011-07-09 17:41:24 +0000571 Out << typeName << "->setBody(";
572 }
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000573
Chris Lattner1afcace2011-07-09 17:41:24 +0000574 Out << typeName << "_fields, /*isPacked=*/"
Chris Lattner7e6d7452010-06-21 23:12:56 +0000575 << (ST->isPacked() ? "true" : "false") << ");";
576 nl(Out);
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000577 if (!ST->isLiteral()) {
578 Out << "}";
579 nl(Out);
580 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000581 break;
582 }
583 case Type::ArrayTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000584 ArrayType* AT = cast<ArrayType>(Ty);
585 Type* ET = AT->getElementType();
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000586 printType(ET);
587 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
588 std::string elemName(getCppName(ET));
589 Out << "ArrayType* " << typeName << " = ArrayType::get("
590 << elemName
591 << ", " << utostr(AT->getNumElements()) << ");";
592 nl(Out);
593 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000594 break;
595 }
596 case Type::PointerTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000597 PointerType* PT = cast<PointerType>(Ty);
598 Type* ET = PT->getElementType();
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000599 printType(ET);
600 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
601 std::string elemName(getCppName(ET));
602 Out << "PointerType* " << typeName << " = PointerType::get("
603 << elemName
604 << ", " << utostr(PT->getAddressSpace()) << ");";
605 nl(Out);
606 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000607 break;
608 }
609 case Type::VectorTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000610 VectorType* PT = cast<VectorType>(Ty);
611 Type* ET = PT->getElementType();
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000612 printType(ET);
613 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
614 std::string elemName(getCppName(ET));
615 Out << "VectorType* " << typeName << " = VectorType::get("
616 << elemName
617 << ", " << utostr(PT->getNumElements()) << ");";
618 nl(Out);
619 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000620 break;
621 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000622 default:
623 error("Invalid TypeID");
624 }
625
Chris Lattner7e6d7452010-06-21 23:12:56 +0000626 // Indicate that this type is now defined.
627 DefinedTypes.insert(Ty);
628
Chris Lattner7e6d7452010-06-21 23:12:56 +0000629 // Finally, separate the type definition from other with a newline.
630 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000631}
632
633void CppWriter::printTypes(const Module* M) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000634 // Add all of the global variables to the value table.
Chris Lattner7e6d7452010-06-21 23:12:56 +0000635 for (Module::const_global_iterator I = TheModule->global_begin(),
636 E = TheModule->global_end(); I != E; ++I) {
637 if (I->hasInitializer())
638 printType(I->getInitializer()->getType());
639 printType(I->getType());
640 }
641
642 // Add all the functions to the table
643 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
644 FI != FE; ++FI) {
645 printType(FI->getReturnType());
646 printType(FI->getFunctionType());
647 // Add all the function arguments
648 for (Function::const_arg_iterator AI = FI->arg_begin(),
649 AE = FI->arg_end(); AI != AE; ++AI) {
650 printType(AI->getType());
651 }
652
653 // Add all of the basic blocks and instructions
654 for (Function::const_iterator BB = FI->begin(),
655 E = FI->end(); BB != E; ++BB) {
656 printType(BB->getType());
657 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
658 ++I) {
659 printType(I->getType());
660 for (unsigned i = 0; i < I->getNumOperands(); ++i)
661 printType(I->getOperand(i)->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000662 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000663 }
664 }
665}
666
667
668// printConstant - Print out a constant pool entry...
669void CppWriter::printConstant(const Constant *CV) {
670 // First, if the constant is actually a GlobalValue (variable or function)
671 // or its already in the constant list then we've printed it already and we
672 // can just return.
673 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
674 return;
675
676 std::string constName(getCppName(CV));
677 std::string typeName(getCppName(CV->getType()));
678
679 if (isa<GlobalValue>(CV)) {
680 // Skip variables and functions, we emit them elsewhere
681 return;
682 }
683
684 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
685 std::string constValue = CI->getValue().toString(10, true);
686 Out << "ConstantInt* " << constName
687 << " = ConstantInt::get(mod->getContext(), APInt("
688 << cast<IntegerType>(CI->getType())->getBitWidth()
689 << ", StringRef(\"" << constValue << "\"), 10));";
690 } else if (isa<ConstantAggregateZero>(CV)) {
691 Out << "ConstantAggregateZero* " << constName
692 << " = ConstantAggregateZero::get(" << typeName << ");";
693 } else if (isa<ConstantPointerNull>(CV)) {
694 Out << "ConstantPointerNull* " << constName
695 << " = ConstantPointerNull::get(" << typeName << ");";
696 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
697 Out << "ConstantFP* " << constName << " = ";
698 printCFP(CFP);
699 Out << ";";
700 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000701 if (CA->isString()) {
702 Out << "Constant* " << constName <<
703 " = ConstantArray::get(mod->getContext(), \"";
704 std::string tmp = CA->getAsString();
705 bool nullTerminate = false;
706 if (tmp[tmp.length()-1] == 0) {
707 tmp.erase(tmp.length()-1);
708 nullTerminate = true;
709 }
710 printEscapedString(tmp);
711 // Determine if we want null termination or not.
712 if (nullTerminate)
713 Out << "\", true"; // Indicate that the null terminator should be
714 // added.
715 else
716 Out << "\", false";// No null terminator
717 Out << ");";
718 } else {
719 Out << "std::vector<Constant*> " << constName << "_elems;";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000720 nl(Out);
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000721 unsigned N = CA->getNumOperands();
722 for (unsigned i = 0; i < N; ++i) {
723 printConstant(CA->getOperand(i)); // recurse to print operands
724 Out << constName << "_elems.push_back("
725 << getCppName(CA->getOperand(i)) << ");";
726 nl(Out);
727 }
728 Out << "Constant* " << constName << " = ConstantArray::get("
729 << typeName << ", " << constName << "_elems);";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000730 }
731 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
732 Out << "std::vector<Constant*> " << constName << "_fields;";
733 nl(Out);
734 unsigned N = CS->getNumOperands();
735 for (unsigned i = 0; i < N; i++) {
736 printConstant(CS->getOperand(i));
737 Out << constName << "_fields.push_back("
738 << getCppName(CS->getOperand(i)) << ");";
739 nl(Out);
740 }
741 Out << "Constant* " << constName << " = ConstantStruct::get("
742 << typeName << ", " << constName << "_fields);";
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000743 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000744 Out << "std::vector<Constant*> " << constName << "_elems;";
745 nl(Out);
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000746 unsigned N = CP->getNumOperands();
Chris Lattner7e6d7452010-06-21 23:12:56 +0000747 for (unsigned i = 0; i < N; ++i) {
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000748 printConstant(CP->getOperand(i));
Chris Lattner7e6d7452010-06-21 23:12:56 +0000749 Out << constName << "_elems.push_back("
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000750 << getCppName(CP->getOperand(i)) << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000751 nl(Out);
752 }
753 Out << "Constant* " << constName << " = ConstantVector::get("
754 << typeName << ", " << constName << "_elems);";
755 } else if (isa<UndefValue>(CV)) {
756 Out << "UndefValue* " << constName << " = UndefValue::get("
757 << typeName << ");";
Chris Lattner29cc6cb2012-01-24 14:17:05 +0000758 } else if (const ConstantDataSequential *CDS =
759 dyn_cast<ConstantDataSequential>(CV)) {
760 if (CDS->isString()) {
761 Out << "Constant *" << constName <<
762 " = ConstantDataArray::getString(mod->getContext(), \"";
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000763 StringRef Str = CA->getAsString();
Chris Lattner29cc6cb2012-01-24 14:17:05 +0000764 bool nullTerminate = false;
765 if (Str.back() == 0) {
766 Str = Str.drop_back();
767 nullTerminate = true;
768 }
769 printEscapedString(Str);
770 // Determine if we want null termination or not.
771 if (nullTerminate)
772 Out << "\", true);";
773 else
774 Out << "\", false);";// No null terminator
775 } else {
776 // TODO: Could generate more efficient code generating CDS calls instead.
777 Out << "std::vector<Constant*> " << constName << "_elems;";
778 nl(Out);
779 for (unsigned i = 0; i != CDS->getNumElements(); ++i) {
780 Constant *Elt = CDS->getElementAsConstant(i);
781 printConstant(Elt);
782 Out << constName << "_elems.push_back(" << getCppName(Elt) << ");";
783 nl(Out);
784 }
785 Out << "Constant* " << constName;
786
787 if (isa<ArrayType>(CDS->getType()))
788 Out << " = ConstantArray::get(";
789 else
790 Out << " = ConstantVector::get(";
791 Out << typeName << ", " << constName << "_elems);";
792 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000793 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
794 if (CE->getOpcode() == Instruction::GetElementPtr) {
795 Out << "std::vector<Constant*> " << constName << "_indices;";
796 nl(Out);
797 printConstant(CE->getOperand(0));
798 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
799 printConstant(CE->getOperand(i));
800 Out << constName << "_indices.push_back("
801 << getCppName(CE->getOperand(i)) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000802 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000803 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000804 Out << "Constant* " << constName
805 << " = ConstantExpr::getGetElementPtr("
806 << getCppName(CE->getOperand(0)) << ", "
Nicolas Geoffraya056d202011-07-21 20:59:21 +0000807 << constName << "_indices);";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000808 } else if (CE->isCast()) {
809 printConstant(CE->getOperand(0));
810 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
811 switch (CE->getOpcode()) {
812 default: llvm_unreachable("Invalid cast opcode");
813 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
814 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
815 case Instruction::SExt: Out << "Instruction::SExt"; break;
816 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
817 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
818 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
819 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
820 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
821 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
822 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
823 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
824 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
825 }
826 Out << ", " << getCppName(CE->getOperand(0)) << ", "
827 << getCppName(CE->getType()) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000828 } else {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000829 unsigned N = CE->getNumOperands();
830 for (unsigned i = 0; i < N; ++i ) {
831 printConstant(CE->getOperand(i));
832 }
833 Out << "Constant* " << constName << " = ConstantExpr::";
834 switch (CE->getOpcode()) {
835 case Instruction::Add: Out << "getAdd("; break;
836 case Instruction::FAdd: Out << "getFAdd("; break;
837 case Instruction::Sub: Out << "getSub("; break;
838 case Instruction::FSub: Out << "getFSub("; break;
839 case Instruction::Mul: Out << "getMul("; break;
840 case Instruction::FMul: Out << "getFMul("; break;
841 case Instruction::UDiv: Out << "getUDiv("; break;
842 case Instruction::SDiv: Out << "getSDiv("; break;
843 case Instruction::FDiv: Out << "getFDiv("; break;
844 case Instruction::URem: Out << "getURem("; break;
845 case Instruction::SRem: Out << "getSRem("; break;
846 case Instruction::FRem: Out << "getFRem("; break;
847 case Instruction::And: Out << "getAnd("; break;
848 case Instruction::Or: Out << "getOr("; break;
849 case Instruction::Xor: Out << "getXor("; break;
850 case Instruction::ICmp:
851 Out << "getICmp(ICmpInst::ICMP_";
852 switch (CE->getPredicate()) {
853 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
854 case ICmpInst::ICMP_NE: Out << "NE"; break;
855 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
856 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
857 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
858 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
859 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
860 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
861 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
862 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
863 default: error("Invalid ICmp Predicate");
864 }
865 break;
866 case Instruction::FCmp:
867 Out << "getFCmp(FCmpInst::FCMP_";
868 switch (CE->getPredicate()) {
869 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
870 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
871 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
872 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
873 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
874 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
875 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
876 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
877 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
878 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
879 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
880 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
881 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
882 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
883 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
884 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
885 default: error("Invalid FCmp Predicate");
886 }
887 break;
888 case Instruction::Shl: Out << "getShl("; break;
889 case Instruction::LShr: Out << "getLShr("; break;
890 case Instruction::AShr: Out << "getAShr("; break;
891 case Instruction::Select: Out << "getSelect("; break;
892 case Instruction::ExtractElement: Out << "getExtractElement("; break;
893 case Instruction::InsertElement: Out << "getInsertElement("; break;
894 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
895 default:
896 error("Invalid constant expression");
897 break;
898 }
899 Out << getCppName(CE->getOperand(0));
900 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
901 Out << ", " << getCppName(CE->getOperand(i));
902 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000903 }
Chris Lattner32848772010-06-21 23:19:36 +0000904 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
905 Out << "Constant* " << constName << " = ";
906 Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000907 } else {
908 error("Bad Constant");
909 Out << "Constant* " << constName << " = 0; ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000910 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000911 nl(Out);
912}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000913
Chris Lattner7e6d7452010-06-21 23:12:56 +0000914void CppWriter::printConstants(const Module* M) {
915 // Traverse all the global variables looking for constant initializers
916 for (Module::const_global_iterator I = TheModule->global_begin(),
917 E = TheModule->global_end(); I != E; ++I)
918 if (I->hasInitializer())
919 printConstant(I->getInitializer());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000920
Chris Lattner7e6d7452010-06-21 23:12:56 +0000921 // Traverse the LLVM functions looking for constants
922 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
923 FI != FE; ++FI) {
924 // Add all of the basic blocks and instructions
925 for (Function::const_iterator BB = FI->begin(),
926 E = FI->end(); BB != E; ++BB) {
927 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
928 ++I) {
929 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
930 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
931 printConstant(C);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000932 }
933 }
934 }
935 }
936 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000937}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000938
Chris Lattner7e6d7452010-06-21 23:12:56 +0000939void CppWriter::printVariableUses(const GlobalVariable *GV) {
940 nl(Out) << "// Type Definitions";
941 nl(Out);
942 printType(GV->getType());
943 if (GV->hasInitializer()) {
Jay Foad7d715df2011-06-19 18:37:11 +0000944 const Constant *Init = GV->getInitializer();
Chris Lattner7e6d7452010-06-21 23:12:56 +0000945 printType(Init->getType());
Jay Foad7d715df2011-06-19 18:37:11 +0000946 if (const Function *F = dyn_cast<Function>(Init)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000947 nl(Out)<< "/ Function Declarations"; nl(Out);
948 printFunctionHead(F);
Jay Foad7d715df2011-06-19 18:37:11 +0000949 } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000950 nl(Out) << "// Global Variable Declarations"; nl(Out);
951 printVariableHead(gv);
952
953 nl(Out) << "// Global Variable Definitions"; nl(Out);
954 printVariableBody(gv);
955 } else {
956 nl(Out) << "// Constant Definitions"; nl(Out);
957 printConstant(Init);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000958 }
959 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000960}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000961
Chris Lattner7e6d7452010-06-21 23:12:56 +0000962void CppWriter::printVariableHead(const GlobalVariable *GV) {
963 nl(Out) << "GlobalVariable* " << getCppName(GV);
964 if (is_inline) {
965 Out << " = mod->getGlobalVariable(mod->getContext(), ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000966 printEscapedString(GV->getName());
Chris Lattner7e6d7452010-06-21 23:12:56 +0000967 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
968 nl(Out) << "if (!" << getCppName(GV) << ") {";
969 in(); nl(Out) << getCppName(GV);
970 }
971 Out << " = new GlobalVariable(/*Module=*/*mod, ";
972 nl(Out) << "/*Type=*/";
973 printCppName(GV->getType()->getElementType());
974 Out << ",";
975 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
976 Out << ",";
977 nl(Out) << "/*Linkage=*/";
978 printLinkageType(GV->getLinkage());
979 Out << ",";
980 nl(Out) << "/*Initializer=*/0, ";
981 if (GV->hasInitializer()) {
982 Out << "// has initializer, specified below";
983 }
984 nl(Out) << "/*Name=*/\"";
985 printEscapedString(GV->getName());
986 Out << "\");";
987 nl(Out);
988
989 if (GV->hasSection()) {
990 printCppName(GV);
991 Out << "->setSection(\"";
992 printEscapedString(GV->getSection());
Owen Anderson16a412e2009-07-10 16:42:19 +0000993 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000994 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000995 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000996 if (GV->getAlignment()) {
997 printCppName(GV);
998 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000999 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001000 }
1001 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1002 printCppName(GV);
1003 Out << "->setVisibility(";
1004 printVisibilityType(GV->getVisibility());
1005 Out << ");";
1006 nl(Out);
1007 }
1008 if (GV->isThreadLocal()) {
1009 printCppName(GV);
1010 Out << "->setThreadLocal(true);";
1011 nl(Out);
1012 }
1013 if (is_inline) {
1014 out(); Out << "}"; nl(Out);
1015 }
1016}
1017
1018void CppWriter::printVariableBody(const GlobalVariable *GV) {
1019 if (GV->hasInitializer()) {
1020 printCppName(GV);
1021 Out << "->setInitializer(";
1022 Out << getCppName(GV->getInitializer()) << ");";
1023 nl(Out);
1024 }
1025}
1026
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001027std::string CppWriter::getOpName(const Value* V) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001028 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1029 return getCppName(V);
1030
1031 // See if its alread in the map of forward references, if so just return the
1032 // name we already set up for it
1033 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1034 if (I != ForwardRefs.end())
1035 return I->second;
1036
1037 // This is a new forward reference. Generate a unique name for it
1038 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1039
1040 // Yes, this is a hack. An Argument is the smallest instantiable value that
1041 // we can make as a placeholder for the real value. We'll replace these
1042 // Argument instances later.
1043 Out << "Argument* " << result << " = new Argument("
1044 << getCppName(V->getType()) << ");";
1045 nl(Out);
1046 ForwardRefs[V] = result;
1047 return result;
1048}
1049
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001050static StringRef ConvertAtomicOrdering(AtomicOrdering Ordering) {
1051 switch (Ordering) {
1052 case NotAtomic: return "NotAtomic";
1053 case Unordered: return "Unordered";
1054 case Monotonic: return "Monotonic";
1055 case Acquire: return "Acquire";
1056 case Release: return "Release";
1057 case AcquireRelease: return "AcquireRelease";
1058 case SequentiallyConsistent: return "SequentiallyConsistent";
1059 }
1060 llvm_unreachable("Unknown ordering");
1061}
1062
1063static StringRef ConvertAtomicSynchScope(SynchronizationScope SynchScope) {
1064 switch (SynchScope) {
1065 case SingleThread: return "SingleThread";
1066 case CrossThread: return "CrossThread";
1067 }
1068 llvm_unreachable("Unknown synch scope");
1069}
1070
Chris Lattner7e6d7452010-06-21 23:12:56 +00001071// printInstruction - This member is called for each Instruction in a function.
1072void CppWriter::printInstruction(const Instruction *I,
1073 const std::string& bbname) {
1074 std::string iName(getCppName(I));
1075
1076 // Before we emit this instruction, we need to take care of generating any
1077 // forward references. So, we get the names of all the operands in advance
1078 const unsigned Ops(I->getNumOperands());
1079 std::string* opNames = new std::string[Ops];
Chris Lattner32848772010-06-21 23:19:36 +00001080 for (unsigned i = 0; i < Ops; i++)
Chris Lattner7e6d7452010-06-21 23:12:56 +00001081 opNames[i] = getOpName(I->getOperand(i));
Anton Korobeynikov50276522008-04-23 22:29:24 +00001082
Chris Lattner7e6d7452010-06-21 23:12:56 +00001083 switch (I->getOpcode()) {
1084 default:
1085 error("Invalid instruction");
1086 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001087
Chris Lattner7e6d7452010-06-21 23:12:56 +00001088 case Instruction::Ret: {
1089 const ReturnInst* ret = cast<ReturnInst>(I);
1090 Out << "ReturnInst::Create(mod->getContext(), "
1091 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1092 break;
1093 }
1094 case Instruction::Br: {
1095 const BranchInst* br = cast<BranchInst>(I);
1096 Out << "BranchInst::Create(" ;
Chris Lattner32848772010-06-21 23:19:36 +00001097 if (br->getNumOperands() == 3) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001098 Out << opNames[2] << ", "
Anton Korobeynikov50276522008-04-23 22:29:24 +00001099 << opNames[1] << ", "
Chris Lattner7e6d7452010-06-21 23:12:56 +00001100 << opNames[0] << ", ";
1101
1102 } else if (br->getNumOperands() == 1) {
1103 Out << opNames[0] << ", ";
1104 } else {
1105 error("Branch with 2 operands?");
1106 }
1107 Out << bbname << ");";
1108 break;
1109 }
1110 case Instruction::Switch: {
1111 const SwitchInst *SI = cast<SwitchInst>(I);
1112 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001113 << getOpName(SI->getCondition()) << ", "
1114 << getOpName(SI->getDefaultDest()) << ", "
Chris Lattner7e6d7452010-06-21 23:12:56 +00001115 << SI->getNumCases() << ", " << bbname << ");";
1116 nl(Out);
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001117 unsigned NumCases = SI->getNumCases();
1118 for (unsigned i = 1; i < NumCases; ++i) {
1119 const ConstantInt* CaseVal = SI->getCaseValue(i);
1120 const BasicBlock* BB = SI->getSuccessor(i);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001121 Out << iName << "->addCase("
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001122 << getOpName(CaseVal) << ", "
1123 << getOpName(BB) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001124 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001125 }
1126 break;
1127 }
1128 case Instruction::IndirectBr: {
1129 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1130 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1131 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1132 nl(Out);
1133 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1134 Out << iName << "->addDestination(" << opNames[i] << ");";
1135 nl(Out);
1136 }
1137 break;
1138 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00001139 case Instruction::Resume: {
1140 Out << "ResumeInst::Create(mod->getContext(), " << opNames[0]
1141 << ", " << bbname << ");";
1142 break;
1143 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001144 case Instruction::Invoke: {
1145 const InvokeInst* inv = cast<InvokeInst>(I);
1146 Out << "std::vector<Value*> " << iName << "_params;";
1147 nl(Out);
1148 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1149 Out << iName << "_params.push_back("
1150 << getOpName(inv->getArgOperand(i)) << ");";
1151 nl(Out);
1152 }
1153 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1154 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1155 << getOpName(inv->getCalledFunction()) << ", "
1156 << getOpName(inv->getNormalDest()) << ", "
1157 << getOpName(inv->getUnwindDest()) << ", "
Nick Lewycky3bca1012011-09-05 18:50:59 +00001158 << iName << "_params, \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001159 printEscapedString(inv->getName());
1160 Out << "\", " << bbname << ");";
1161 nl(Out) << iName << "->setCallingConv(";
1162 printCallingConv(inv->getCallingConv());
1163 Out << ");";
1164 printAttributes(inv->getAttributes(), iName);
1165 Out << iName << "->setAttributes(" << iName << "_PAL);";
1166 nl(Out);
1167 break;
1168 }
1169 case Instruction::Unwind: {
1170 Out << "new UnwindInst("
1171 << bbname << ");";
1172 break;
1173 }
1174 case Instruction::Unreachable: {
1175 Out << "new UnreachableInst("
1176 << "mod->getContext(), "
1177 << bbname << ");";
1178 break;
1179 }
1180 case Instruction::Add:
1181 case Instruction::FAdd:
1182 case Instruction::Sub:
1183 case Instruction::FSub:
1184 case Instruction::Mul:
1185 case Instruction::FMul:
1186 case Instruction::UDiv:
1187 case Instruction::SDiv:
1188 case Instruction::FDiv:
1189 case Instruction::URem:
1190 case Instruction::SRem:
1191 case Instruction::FRem:
1192 case Instruction::And:
1193 case Instruction::Or:
1194 case Instruction::Xor:
1195 case Instruction::Shl:
1196 case Instruction::LShr:
1197 case Instruction::AShr:{
1198 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1199 switch (I->getOpcode()) {
1200 case Instruction::Add: Out << "Instruction::Add"; break;
1201 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1202 case Instruction::Sub: Out << "Instruction::Sub"; break;
1203 case Instruction::FSub: Out << "Instruction::FSub"; break;
1204 case Instruction::Mul: Out << "Instruction::Mul"; break;
1205 case Instruction::FMul: Out << "Instruction::FMul"; break;
1206 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1207 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1208 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1209 case Instruction::URem:Out << "Instruction::URem"; break;
1210 case Instruction::SRem:Out << "Instruction::SRem"; break;
1211 case Instruction::FRem:Out << "Instruction::FRem"; break;
1212 case Instruction::And: Out << "Instruction::And"; break;
1213 case Instruction::Or: Out << "Instruction::Or"; break;
1214 case Instruction::Xor: Out << "Instruction::Xor"; break;
1215 case Instruction::Shl: Out << "Instruction::Shl"; break;
1216 case Instruction::LShr:Out << "Instruction::LShr"; break;
1217 case Instruction::AShr:Out << "Instruction::AShr"; break;
1218 default: Out << "Instruction::BadOpCode"; break;
1219 }
1220 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1221 printEscapedString(I->getName());
1222 Out << "\", " << bbname << ");";
1223 break;
1224 }
1225 case Instruction::FCmp: {
1226 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1227 switch (cast<FCmpInst>(I)->getPredicate()) {
1228 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1229 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1230 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1231 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1232 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1233 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1234 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1235 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1236 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1237 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1238 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1239 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1240 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1241 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1242 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1243 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1244 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1245 }
1246 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1247 printEscapedString(I->getName());
1248 Out << "\");";
1249 break;
1250 }
1251 case Instruction::ICmp: {
1252 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1253 switch (cast<ICmpInst>(I)->getPredicate()) {
1254 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1255 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1256 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1257 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1258 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1259 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1260 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1261 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1262 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1263 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1264 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1265 }
1266 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1267 printEscapedString(I->getName());
1268 Out << "\");";
1269 break;
1270 }
1271 case Instruction::Alloca: {
1272 const AllocaInst* allocaI = cast<AllocaInst>(I);
1273 Out << "AllocaInst* " << iName << " = new AllocaInst("
1274 << getCppName(allocaI->getAllocatedType()) << ", ";
1275 if (allocaI->isArrayAllocation())
1276 Out << opNames[0] << ", ";
1277 Out << "\"";
1278 printEscapedString(allocaI->getName());
1279 Out << "\", " << bbname << ");";
1280 if (allocaI->getAlignment())
1281 nl(Out) << iName << "->setAlignment("
1282 << allocaI->getAlignment() << ");";
1283 break;
1284 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001285 case Instruction::Load: {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001286 const LoadInst* load = cast<LoadInst>(I);
1287 Out << "LoadInst* " << iName << " = new LoadInst("
1288 << opNames[0] << ", \"";
1289 printEscapedString(load->getName());
1290 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1291 << ", " << bbname << ");";
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001292 if (load->getAlignment())
1293 nl(Out) << iName << "->setAlignment("
1294 << load->getAlignment() << ");";
1295 if (load->isAtomic()) {
1296 StringRef Ordering = ConvertAtomicOrdering(load->getOrdering());
1297 StringRef CrossThread = ConvertAtomicSynchScope(load->getSynchScope());
1298 nl(Out) << iName << "->setAtomic("
1299 << Ordering << ", " << CrossThread << ");";
1300 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001301 break;
1302 }
1303 case Instruction::Store: {
1304 const StoreInst* store = cast<StoreInst>(I);
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001305 Out << "StoreInst* " << iName << " = new StoreInst("
Chris Lattner7e6d7452010-06-21 23:12:56 +00001306 << opNames[0] << ", "
1307 << opNames[1] << ", "
1308 << (store->isVolatile() ? "true" : "false")
1309 << ", " << bbname << ");";
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001310 if (store->getAlignment())
1311 nl(Out) << iName << "->setAlignment("
1312 << store->getAlignment() << ");";
1313 if (store->isAtomic()) {
1314 StringRef Ordering = ConvertAtomicOrdering(store->getOrdering());
1315 StringRef CrossThread = ConvertAtomicSynchScope(store->getSynchScope());
1316 nl(Out) << iName << "->setAtomic("
1317 << Ordering << ", " << CrossThread << ");";
1318 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001319 break;
1320 }
1321 case Instruction::GetElementPtr: {
1322 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1323 if (gep->getNumOperands() <= 2) {
1324 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1325 << opNames[0];
1326 if (gep->getNumOperands() == 2)
1327 Out << ", " << opNames[1];
1328 } else {
1329 Out << "std::vector<Value*> " << iName << "_indices;";
1330 nl(Out);
1331 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1332 Out << iName << "_indices.push_back("
1333 << opNames[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001334 nl(Out);
1335 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001336 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
Nicolas Geoffray45c8d2b2011-07-26 20:52:25 +00001337 << opNames[0] << ", " << iName << "_indices";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001338 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001339 Out << ", \"";
1340 printEscapedString(gep->getName());
1341 Out << "\", " << bbname << ");";
1342 break;
1343 }
1344 case Instruction::PHI: {
1345 const PHINode* phi = cast<PHINode>(I);
1346
1347 Out << "PHINode* " << iName << " = PHINode::Create("
Nicolas Geoffrayc6cf1972011-04-10 17:39:40 +00001348 << getCppName(phi->getType()) << ", "
Jay Foad3ecfc862011-03-30 11:28:46 +00001349 << phi->getNumIncomingValues() << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001350 printEscapedString(phi->getName());
1351 Out << "\", " << bbname << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001352 nl(Out);
Jay Foadc1371202011-06-20 14:18:48 +00001353 for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001354 Out << iName << "->addIncoming("
Jay Foadc1371202011-06-20 14:18:48 +00001355 << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
Jay Foad95c3e482011-06-23 09:09:15 +00001356 << getOpName(phi->getIncomingBlock(i)) << ");";
Chris Lattner627b4702009-10-27 21:24:48 +00001357 nl(Out);
Chris Lattner627b4702009-10-27 21:24:48 +00001358 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001359 break;
1360 }
1361 case Instruction::Trunc:
1362 case Instruction::ZExt:
1363 case Instruction::SExt:
1364 case Instruction::FPTrunc:
1365 case Instruction::FPExt:
1366 case Instruction::FPToUI:
1367 case Instruction::FPToSI:
1368 case Instruction::UIToFP:
1369 case Instruction::SIToFP:
1370 case Instruction::PtrToInt:
1371 case Instruction::IntToPtr:
1372 case Instruction::BitCast: {
1373 const CastInst* cst = cast<CastInst>(I);
1374 Out << "CastInst* " << iName << " = new ";
1375 switch (I->getOpcode()) {
1376 case Instruction::Trunc: Out << "TruncInst"; break;
1377 case Instruction::ZExt: Out << "ZExtInst"; break;
1378 case Instruction::SExt: Out << "SExtInst"; break;
1379 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1380 case Instruction::FPExt: Out << "FPExtInst"; break;
1381 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1382 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1383 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1384 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1385 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1386 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1387 case Instruction::BitCast: Out << "BitCastInst"; break;
Richard Trieu23946fc2011-09-21 03:09:09 +00001388 default: assert(0 && "Unreachable"); break;
Chris Lattner7e6d7452010-06-21 23:12:56 +00001389 }
1390 Out << "(" << opNames[0] << ", "
1391 << getCppName(cst->getType()) << ", \"";
1392 printEscapedString(cst->getName());
1393 Out << "\", " << bbname << ");";
1394 break;
1395 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001396 case Instruction::Call: {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001397 const CallInst* call = cast<CallInst>(I);
1398 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1399 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1400 << getCppName(ila->getFunctionType()) << ", \""
1401 << ila->getAsmString() << "\", \""
1402 << ila->getConstraintString() << "\","
1403 << (ila->hasSideEffects() ? "true" : "false") << ");";
1404 nl(Out);
1405 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001406 if (call->getNumArgOperands() > 1) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001407 Out << "std::vector<Value*> " << iName << "_params;";
1408 nl(Out);
Gabor Greif53ba5502010-07-02 19:08:46 +00001409 for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
Gabor Greif63d024f2010-07-13 15:31:36 +00001410 Out << iName << "_params.push_back(" << opNames[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001411 nl(Out);
1412 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001413 Out << "CallInst* " << iName << " = CallInst::Create("
Gabor Greifa3997812010-07-22 10:37:47 +00001414 << opNames[call->getNumArgOperands()] << ", "
Nicolas Geoffraya056d202011-07-21 20:59:21 +00001415 << iName << "_params, \"";
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001416 } else if (call->getNumArgOperands() == 1) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001417 Out << "CallInst* " << iName << " = CallInst::Create("
Gabor Greif63d024f2010-07-13 15:31:36 +00001418 << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001419 } else {
Gabor Greif63d024f2010-07-13 15:31:36 +00001420 Out << "CallInst* " << iName << " = CallInst::Create("
1421 << opNames[call->getNumArgOperands()] << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001422 }
1423 printEscapedString(call->getName());
1424 Out << "\", " << bbname << ");";
1425 nl(Out) << iName << "->setCallingConv(";
1426 printCallingConv(call->getCallingConv());
1427 Out << ");";
1428 nl(Out) << iName << "->setTailCall("
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001429 << (call->isTailCall() ? "true" : "false");
Chris Lattner7e6d7452010-06-21 23:12:56 +00001430 Out << ");";
Gabor Greif135d7fe2010-07-02 19:26:28 +00001431 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001432 printAttributes(call->getAttributes(), iName);
1433 Out << iName << "->setAttributes(" << iName << "_PAL);";
1434 nl(Out);
1435 break;
1436 }
1437 case Instruction::Select: {
1438 const SelectInst* sel = cast<SelectInst>(I);
1439 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1440 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1441 printEscapedString(sel->getName());
1442 Out << "\", " << bbname << ");";
1443 break;
1444 }
1445 case Instruction::UserOp1:
1446 /// FALL THROUGH
1447 case Instruction::UserOp2: {
1448 /// FIXME: What should be done here?
1449 break;
1450 }
1451 case Instruction::VAArg: {
1452 const VAArgInst* va = cast<VAArgInst>(I);
1453 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1454 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1455 printEscapedString(va->getName());
1456 Out << "\", " << bbname << ");";
1457 break;
1458 }
1459 case Instruction::ExtractElement: {
1460 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1461 Out << "ExtractElementInst* " << getCppName(eei)
1462 << " = new ExtractElementInst(" << opNames[0]
1463 << ", " << opNames[1] << ", \"";
1464 printEscapedString(eei->getName());
1465 Out << "\", " << bbname << ");";
1466 break;
1467 }
1468 case Instruction::InsertElement: {
1469 const InsertElementInst* iei = cast<InsertElementInst>(I);
1470 Out << "InsertElementInst* " << getCppName(iei)
1471 << " = InsertElementInst::Create(" << opNames[0]
1472 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1473 printEscapedString(iei->getName());
1474 Out << "\", " << bbname << ");";
1475 break;
1476 }
1477 case Instruction::ShuffleVector: {
1478 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1479 Out << "ShuffleVectorInst* " << getCppName(svi)
1480 << " = new ShuffleVectorInst(" << opNames[0]
1481 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1482 printEscapedString(svi->getName());
1483 Out << "\", " << bbname << ");";
1484 break;
1485 }
1486 case Instruction::ExtractValue: {
1487 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1488 Out << "std::vector<unsigned> " << iName << "_indices;";
1489 nl(Out);
1490 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1491 Out << iName << "_indices.push_back("
1492 << evi->idx_begin()[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001493 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001494 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001495 Out << "ExtractValueInst* " << getCppName(evi)
1496 << " = ExtractValueInst::Create(" << opNames[0]
1497 << ", "
Nick Lewycky3bca1012011-09-05 18:50:59 +00001498 << iName << "_indices, \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001499 printEscapedString(evi->getName());
1500 Out << "\", " << bbname << ");";
1501 break;
1502 }
1503 case Instruction::InsertValue: {
1504 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1505 Out << "std::vector<unsigned> " << iName << "_indices;";
1506 nl(Out);
1507 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1508 Out << iName << "_indices.push_back("
1509 << ivi->idx_begin()[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001510 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001511 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001512 Out << "InsertValueInst* " << getCppName(ivi)
1513 << " = InsertValueInst::Create(" << opNames[0]
1514 << ", " << opNames[1] << ", "
Nick Lewycky3bca1012011-09-05 18:50:59 +00001515 << iName << "_indices, \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001516 printEscapedString(ivi->getName());
1517 Out << "\", " << bbname << ");";
1518 break;
1519 }
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001520 case Instruction::Fence: {
1521 const FenceInst *fi = cast<FenceInst>(I);
1522 StringRef Ordering = ConvertAtomicOrdering(fi->getOrdering());
1523 StringRef CrossThread = ConvertAtomicSynchScope(fi->getSynchScope());
1524 Out << "FenceInst* " << iName
1525 << " = new FenceInst(mod->getContext(), "
Eli Friedman5b7cc332011-11-04 17:29:35 +00001526 << Ordering << ", " << CrossThread << ", " << bbname
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001527 << ");";
1528 break;
1529 }
1530 case Instruction::AtomicCmpXchg: {
1531 const AtomicCmpXchgInst *cxi = cast<AtomicCmpXchgInst>(I);
1532 StringRef Ordering = ConvertAtomicOrdering(cxi->getOrdering());
1533 StringRef CrossThread = ConvertAtomicSynchScope(cxi->getSynchScope());
1534 Out << "AtomicCmpXchgInst* " << iName
1535 << " = new AtomicCmpXchgInst("
1536 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", "
Eli Friedman5b7cc332011-11-04 17:29:35 +00001537 << Ordering << ", " << CrossThread << ", " << bbname
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001538 << ");";
1539 nl(Out) << iName << "->setName(\"";
1540 printEscapedString(cxi->getName());
1541 Out << "\");";
1542 break;
1543 }
1544 case Instruction::AtomicRMW: {
1545 const AtomicRMWInst *rmwi = cast<AtomicRMWInst>(I);
1546 StringRef Ordering = ConvertAtomicOrdering(rmwi->getOrdering());
1547 StringRef CrossThread = ConvertAtomicSynchScope(rmwi->getSynchScope());
1548 StringRef Operation;
1549 switch (rmwi->getOperation()) {
1550 case AtomicRMWInst::Xchg: Operation = "AtomicRMWInst::Xchg"; break;
1551 case AtomicRMWInst::Add: Operation = "AtomicRMWInst::Add"; break;
1552 case AtomicRMWInst::Sub: Operation = "AtomicRMWInst::Sub"; break;
1553 case AtomicRMWInst::And: Operation = "AtomicRMWInst::And"; break;
1554 case AtomicRMWInst::Nand: Operation = "AtomicRMWInst::Nand"; break;
1555 case AtomicRMWInst::Or: Operation = "AtomicRMWInst::Or"; break;
1556 case AtomicRMWInst::Xor: Operation = "AtomicRMWInst::Xor"; break;
1557 case AtomicRMWInst::Max: Operation = "AtomicRMWInst::Max"; break;
1558 case AtomicRMWInst::Min: Operation = "AtomicRMWInst::Min"; break;
1559 case AtomicRMWInst::UMax: Operation = "AtomicRMWInst::UMax"; break;
1560 case AtomicRMWInst::UMin: Operation = "AtomicRMWInst::UMin"; break;
1561 case AtomicRMWInst::BAD_BINOP: llvm_unreachable("Bad atomic operation");
1562 }
1563 Out << "AtomicRMWInst* " << iName
1564 << " = new AtomicRMWInst("
1565 << Operation << ", "
1566 << opNames[0] << ", " << opNames[1] << ", "
Eli Friedman5b7cc332011-11-04 17:29:35 +00001567 << Ordering << ", " << CrossThread << ", " << bbname
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001568 << ");";
1569 nl(Out) << iName << "->setName(\"";
1570 printEscapedString(rmwi->getName());
1571 Out << "\");";
1572 break;
1573 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001574 }
1575 DefinedValues.insert(I);
1576 nl(Out);
1577 delete [] opNames;
1578}
1579
Chris Lattner7e6d7452010-06-21 23:12:56 +00001580// Print out the types, constants and declarations needed by one function
1581void CppWriter::printFunctionUses(const Function* F) {
1582 nl(Out) << "// Type Definitions"; nl(Out);
1583 if (!is_inline) {
1584 // Print the function's return type
1585 printType(F->getReturnType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001586
Chris Lattner7e6d7452010-06-21 23:12:56 +00001587 // Print the function's function type
1588 printType(F->getFunctionType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001589
Chris Lattner7e6d7452010-06-21 23:12:56 +00001590 // Print the types of each of the function's arguments
Anton Korobeynikov50276522008-04-23 22:29:24 +00001591 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1592 AI != AE; ++AI) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001593 printType(AI->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001594 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001595 }
1596
Chris Lattner7e6d7452010-06-21 23:12:56 +00001597 // Print type definitions for every type referenced by an instruction and
1598 // make a note of any global values or constants that are referenced
1599 SmallPtrSet<GlobalValue*,64> gvs;
1600 SmallPtrSet<Constant*,64> consts;
1601 for (Function::const_iterator BB = F->begin(), BE = F->end();
1602 BB != BE; ++BB){
1603 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
Anton Korobeynikov50276522008-04-23 22:29:24 +00001604 I != E; ++I) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001605 // Print the type of the instruction itself
1606 printType(I->getType());
1607
1608 // Print the type of each of the instruction's operands
1609 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1610 Value* operand = I->getOperand(i);
1611 printType(operand->getType());
1612
1613 // If the operand references a GVal or Constant, make a note of it
1614 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1615 gvs.insert(GV);
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001616 if (GenerationType != GenFunction)
1617 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1618 if (GVar->hasInitializer())
1619 consts.insert(GVar->getInitializer());
1620 } else if (Constant* C = dyn_cast<Constant>(operand)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001621 consts.insert(C);
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001622 for (unsigned j = 0; j < C->getNumOperands(); ++j) {
1623 // If the operand references a GVal or Constant, make a note of it
1624 Value* operand = C->getOperand(j);
1625 printType(operand->getType());
1626 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1627 gvs.insert(GV);
1628 if (GenerationType != GenFunction)
1629 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1630 if (GVar->hasInitializer())
1631 consts.insert(GVar->getInitializer());
1632 }
1633 }
1634 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001635 }
1636 }
1637 }
1638
1639 // Print the function declarations for any functions encountered
1640 nl(Out) << "// Function Declarations"; nl(Out);
1641 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1642 I != E; ++I) {
1643 if (Function* Fun = dyn_cast<Function>(*I)) {
1644 if (!is_inline || Fun != F)
1645 printFunctionHead(Fun);
1646 }
1647 }
1648
1649 // Print the global variable declarations for any variables encountered
1650 nl(Out) << "// Global Variable Declarations"; nl(Out);
1651 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1652 I != E; ++I) {
1653 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1654 printVariableHead(F);
1655 }
1656
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001657 // Print the constants found
Chris Lattner7e6d7452010-06-21 23:12:56 +00001658 nl(Out) << "// Constant Definitions"; nl(Out);
1659 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1660 E = consts.end(); I != E; ++I) {
1661 printConstant(*I);
1662 }
1663
1664 // Process the global variables definitions now that all the constants have
1665 // been emitted. These definitions just couple the gvars with their constant
1666 // initializers.
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001667 if (GenerationType != GenFunction) {
1668 nl(Out) << "// Global Variable Definitions"; nl(Out);
1669 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1670 I != E; ++I) {
1671 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1672 printVariableBody(GV);
1673 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001674 }
1675}
1676
1677void CppWriter::printFunctionHead(const Function* F) {
1678 nl(Out) << "Function* " << getCppName(F);
Nicolas Geoffrayf8557952011-10-08 11:56:36 +00001679 Out << " = mod->getFunction(\"";
1680 printEscapedString(F->getName());
1681 Out << "\");";
1682 nl(Out) << "if (!" << getCppName(F) << ") {";
1683 nl(Out) << getCppName(F);
1684
Chris Lattner7e6d7452010-06-21 23:12:56 +00001685 Out<< " = Function::Create(";
1686 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1687 nl(Out) << "/*Linkage=*/";
1688 printLinkageType(F->getLinkage());
1689 Out << ",";
1690 nl(Out) << "/*Name=*/\"";
1691 printEscapedString(F->getName());
1692 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1693 nl(Out,-1);
1694 printCppName(F);
1695 Out << "->setCallingConv(";
1696 printCallingConv(F->getCallingConv());
1697 Out << ");";
1698 nl(Out);
1699 if (F->hasSection()) {
1700 printCppName(F);
1701 Out << "->setSection(\"" << F->getSection() << "\");";
1702 nl(Out);
1703 }
1704 if (F->getAlignment()) {
1705 printCppName(F);
1706 Out << "->setAlignment(" << F->getAlignment() << ");";
1707 nl(Out);
1708 }
1709 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1710 printCppName(F);
1711 Out << "->setVisibility(";
1712 printVisibilityType(F->getVisibility());
1713 Out << ");";
1714 nl(Out);
1715 }
1716 if (F->hasGC()) {
1717 printCppName(F);
1718 Out << "->setGC(\"" << F->getGC() << "\");";
1719 nl(Out);
1720 }
Nicolas Geoffrayf8557952011-10-08 11:56:36 +00001721 Out << "}";
1722 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001723 printAttributes(F->getAttributes(), getCppName(F));
1724 printCppName(F);
1725 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1726 nl(Out);
1727}
1728
1729void CppWriter::printFunctionBody(const Function *F) {
1730 if (F->isDeclaration())
1731 return; // external functions have no bodies.
1732
1733 // Clear the DefinedValues and ForwardRefs maps because we can't have
1734 // cross-function forward refs
1735 ForwardRefs.clear();
1736 DefinedValues.clear();
1737
1738 // Create all the argument values
1739 if (!is_inline) {
1740 if (!F->arg_empty()) {
1741 Out << "Function::arg_iterator args = " << getCppName(F)
1742 << "->arg_begin();";
1743 nl(Out);
1744 }
1745 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1746 AI != AE; ++AI) {
1747 Out << "Value* " << getCppName(AI) << " = args++;";
1748 nl(Out);
1749 if (AI->hasName()) {
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001750 Out << getCppName(AI) << "->setName(\"";
1751 printEscapedString(AI->getName());
1752 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001753 nl(Out);
1754 }
1755 }
1756 }
1757
Chris Lattner7e6d7452010-06-21 23:12:56 +00001758 // Create all the basic blocks
1759 nl(Out);
1760 for (Function::const_iterator BI = F->begin(), BE = F->end();
1761 BI != BE; ++BI) {
1762 std::string bbname(getCppName(BI));
1763 Out << "BasicBlock* " << bbname <<
1764 " = BasicBlock::Create(mod->getContext(), \"";
1765 if (BI->hasName())
1766 printEscapedString(BI->getName());
1767 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1768 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001769 }
1770
Chris Lattner7e6d7452010-06-21 23:12:56 +00001771 // Output all of its basic blocks... for the function
1772 for (Function::const_iterator BI = F->begin(), BE = F->end();
1773 BI != BE; ++BI) {
1774 std::string bbname(getCppName(BI));
1775 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001776 nl(Out);
1777
Chris Lattner7e6d7452010-06-21 23:12:56 +00001778 // Output all of the instructions in the basic block...
1779 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1780 I != E; ++I) {
1781 printInstruction(I,bbname);
1782 }
1783 }
1784
1785 // Loop over the ForwardRefs and resolve them now that all instructions
1786 // are generated.
1787 if (!ForwardRefs.empty()) {
1788 nl(Out) << "// Resolve Forward References";
1789 nl(Out);
1790 }
1791
1792 while (!ForwardRefs.empty()) {
1793 ForwardRefMap::iterator I = ForwardRefs.begin();
1794 Out << I->second << "->replaceAllUsesWith("
1795 << getCppName(I->first) << "); delete " << I->second << ";";
1796 nl(Out);
1797 ForwardRefs.erase(I);
1798 }
1799}
1800
1801void CppWriter::printInline(const std::string& fname,
1802 const std::string& func) {
1803 const Function* F = TheModule->getFunction(func);
1804 if (!F) {
1805 error(std::string("Function '") + func + "' not found in input module");
1806 return;
1807 }
1808 if (F->isDeclaration()) {
1809 error(std::string("Function '") + func + "' is external!");
1810 return;
1811 }
1812 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1813 << getCppName(F);
1814 unsigned arg_count = 1;
1815 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1816 AI != AE; ++AI) {
1817 Out << ", Value* arg_" << arg_count;
1818 }
1819 Out << ") {";
1820 nl(Out);
1821 is_inline = true;
1822 printFunctionUses(F);
1823 printFunctionBody(F);
1824 is_inline = false;
1825 Out << "return " << getCppName(F->begin()) << ";";
1826 nl(Out) << "}";
1827 nl(Out);
1828}
1829
1830void CppWriter::printModuleBody() {
1831 // Print out all the type definitions
1832 nl(Out) << "// Type Definitions"; nl(Out);
1833 printTypes(TheModule);
1834
1835 // Functions can call each other and global variables can reference them so
1836 // define all the functions first before emitting their function bodies.
1837 nl(Out) << "// Function Declarations"; nl(Out);
1838 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1839 I != E; ++I)
1840 printFunctionHead(I);
1841
1842 // Process the global variables declarations. We can't initialze them until
1843 // after the constants are printed so just print a header for each global
1844 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1845 for (Module::const_global_iterator I = TheModule->global_begin(),
1846 E = TheModule->global_end(); I != E; ++I) {
1847 printVariableHead(I);
1848 }
1849
1850 // Print out all the constants definitions. Constants don't recurse except
1851 // through GlobalValues. All GlobalValues have been declared at this point
1852 // so we can proceed to generate the constants.
1853 nl(Out) << "// Constant Definitions"; nl(Out);
1854 printConstants(TheModule);
1855
1856 // Process the global variables definitions now that all the constants have
1857 // been emitted. These definitions just couple the gvars with their constant
1858 // initializers.
1859 nl(Out) << "// Global Variable Definitions"; nl(Out);
1860 for (Module::const_global_iterator I = TheModule->global_begin(),
1861 E = TheModule->global_end(); I != E; ++I) {
1862 printVariableBody(I);
1863 }
1864
1865 // Finally, we can safely put out all of the function bodies.
1866 nl(Out) << "// Function Definitions"; nl(Out);
1867 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1868 I != E; ++I) {
1869 if (!I->isDeclaration()) {
1870 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1871 << ")";
1872 nl(Out) << "{";
1873 nl(Out,1);
1874 printFunctionBody(I);
1875 nl(Out,-1) << "}";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001876 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001877 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001878 }
1879}
1880
1881void CppWriter::printProgram(const std::string& fname,
1882 const std::string& mName) {
1883 Out << "#include <llvm/LLVMContext.h>\n";
1884 Out << "#include <llvm/Module.h>\n";
1885 Out << "#include <llvm/DerivedTypes.h>\n";
1886 Out << "#include <llvm/Constants.h>\n";
1887 Out << "#include <llvm/GlobalVariable.h>\n";
1888 Out << "#include <llvm/Function.h>\n";
1889 Out << "#include <llvm/CallingConv.h>\n";
1890 Out << "#include <llvm/BasicBlock.h>\n";
1891 Out << "#include <llvm/Instructions.h>\n";
1892 Out << "#include <llvm/InlineAsm.h>\n";
1893 Out << "#include <llvm/Support/FormattedStream.h>\n";
1894 Out << "#include <llvm/Support/MathExtras.h>\n";
1895 Out << "#include <llvm/Pass.h>\n";
1896 Out << "#include <llvm/PassManager.h>\n";
1897 Out << "#include <llvm/ADT/SmallVector.h>\n";
1898 Out << "#include <llvm/Analysis/Verifier.h>\n";
1899 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1900 Out << "#include <algorithm>\n";
1901 Out << "using namespace llvm;\n\n";
1902 Out << "Module* " << fname << "();\n\n";
1903 Out << "int main(int argc, char**argv) {\n";
1904 Out << " Module* Mod = " << fname << "();\n";
1905 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1906 Out << " PassManager PM;\n";
1907 Out << " PM.add(createPrintModulePass(&outs()));\n";
1908 Out << " PM.run(*Mod);\n";
1909 Out << " return 0;\n";
1910 Out << "}\n\n";
1911 printModule(fname,mName);
1912}
1913
1914void CppWriter::printModule(const std::string& fname,
1915 const std::string& mName) {
1916 nl(Out) << "Module* " << fname << "() {";
1917 nl(Out,1) << "// Module Construction";
1918 nl(Out) << "Module* mod = new Module(\"";
1919 printEscapedString(mName);
1920 Out << "\", getGlobalContext());";
1921 if (!TheModule->getTargetTriple().empty()) {
1922 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1923 }
1924 if (!TheModule->getTargetTriple().empty()) {
1925 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1926 << "\");";
1927 }
1928
1929 if (!TheModule->getModuleInlineAsm().empty()) {
1930 nl(Out) << "mod->setModuleInlineAsm(\"";
1931 printEscapedString(TheModule->getModuleInlineAsm());
1932 Out << "\");";
1933 }
1934 nl(Out);
1935
1936 // Loop over the dependent libraries and emit them.
1937 Module::lib_iterator LI = TheModule->lib_begin();
1938 Module::lib_iterator LE = TheModule->lib_end();
1939 while (LI != LE) {
1940 Out << "mod->addLibrary(\"" << *LI << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001941 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001942 ++LI;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001943 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001944 printModuleBody();
1945 nl(Out) << "return mod;";
1946 nl(Out,-1) << "}";
1947 nl(Out);
1948}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001949
Chris Lattner7e6d7452010-06-21 23:12:56 +00001950void CppWriter::printContents(const std::string& fname,
1951 const std::string& mName) {
1952 Out << "\nModule* " << fname << "(Module *mod) {\n";
1953 Out << "\nmod->setModuleIdentifier(\"";
1954 printEscapedString(mName);
1955 Out << "\");\n";
1956 printModuleBody();
1957 Out << "\nreturn mod;\n";
1958 Out << "\n}\n";
1959}
1960
1961void CppWriter::printFunction(const std::string& fname,
1962 const std::string& funcName) {
1963 const Function* F = TheModule->getFunction(funcName);
1964 if (!F) {
1965 error(std::string("Function '") + funcName + "' not found in input module");
1966 return;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001967 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001968 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1969 printFunctionUses(F);
1970 printFunctionHead(F);
1971 printFunctionBody(F);
1972 Out << "return " << getCppName(F) << ";\n";
1973 Out << "}\n";
1974}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001975
Chris Lattner7e6d7452010-06-21 23:12:56 +00001976void CppWriter::printFunctions() {
1977 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1978 Module::const_iterator I = funcs.begin();
1979 Module::const_iterator IE = funcs.end();
Anton Korobeynikov50276522008-04-23 22:29:24 +00001980
Chris Lattner7e6d7452010-06-21 23:12:56 +00001981 for (; I != IE; ++I) {
1982 const Function &func = *I;
1983 if (!func.isDeclaration()) {
1984 std::string name("define_");
1985 name += func.getName();
1986 printFunction(name, func.getName());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001987 }
1988 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001989}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001990
Chris Lattner7e6d7452010-06-21 23:12:56 +00001991void CppWriter::printVariable(const std::string& fname,
1992 const std::string& varName) {
1993 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001994
Chris Lattner7e6d7452010-06-21 23:12:56 +00001995 if (!GV) {
1996 error(std::string("Variable '") + varName + "' not found in input module");
1997 return;
1998 }
1999 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
2000 printVariableUses(GV);
2001 printVariableHead(GV);
2002 printVariableBody(GV);
2003 Out << "return " << getCppName(GV) << ";\n";
2004 Out << "}\n";
2005}
2006
Chris Lattner1afcace2011-07-09 17:41:24 +00002007void CppWriter::printType(const std::string &fname,
2008 const std::string &typeName) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002009 Type* Ty = TheModule->getTypeByName(typeName);
Chris Lattner7e6d7452010-06-21 23:12:56 +00002010 if (!Ty) {
2011 error(std::string("Type '") + typeName + "' not found in input module");
2012 return;
2013 }
2014 Out << "\nType* " << fname << "(Module *mod) {\n";
2015 printType(Ty);
2016 Out << "return " << getCppName(Ty) << ";\n";
2017 Out << "}\n";
2018}
2019
2020bool CppWriter::runOnModule(Module &M) {
2021 TheModule = &M;
2022
2023 // Emit a header
2024 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
2025
2026 // Get the name of the function we're supposed to generate
2027 std::string fname = FuncName.getValue();
2028
2029 // Get the name of the thing we are to generate
2030 std::string tgtname = NameToGenerate.getValue();
2031 if (GenerationType == GenModule ||
2032 GenerationType == GenContents ||
2033 GenerationType == GenProgram ||
2034 GenerationType == GenFunctions) {
2035 if (tgtname == "!bad!") {
2036 if (M.getModuleIdentifier() == "-")
2037 tgtname = "<stdin>";
2038 else
2039 tgtname = M.getModuleIdentifier();
Anton Korobeynikov50276522008-04-23 22:29:24 +00002040 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00002041 } else if (tgtname == "!bad!")
2042 error("You must use the -for option with -gen-{function,variable,type}");
2043
2044 switch (WhatToGenerate(GenerationType)) {
2045 case GenProgram:
2046 if (fname.empty())
2047 fname = "makeLLVMModule";
2048 printProgram(fname,tgtname);
2049 break;
2050 case GenModule:
2051 if (fname.empty())
2052 fname = "makeLLVMModule";
2053 printModule(fname,tgtname);
2054 break;
2055 case GenContents:
2056 if (fname.empty())
2057 fname = "makeLLVMModuleContents";
2058 printContents(fname,tgtname);
2059 break;
2060 case GenFunction:
2061 if (fname.empty())
2062 fname = "makeLLVMFunction";
2063 printFunction(fname,tgtname);
2064 break;
2065 case GenFunctions:
2066 printFunctions();
2067 break;
2068 case GenInline:
2069 if (fname.empty())
2070 fname = "makeLLVMInline";
2071 printInline(fname,tgtname);
2072 break;
2073 case GenVariable:
2074 if (fname.empty())
2075 fname = "makeLLVMVariable";
2076 printVariable(fname,tgtname);
2077 break;
2078 case GenType:
2079 if (fname.empty())
2080 fname = "makeLLVMType";
2081 printType(fname,tgtname);
2082 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002083 }
2084
Chris Lattner7e6d7452010-06-21 23:12:56 +00002085 return false;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002086}
2087
2088char CppWriter::ID = 0;
2089
2090//===----------------------------------------------------------------------===//
2091// External Interface declaration
2092//===----------------------------------------------------------------------===//
2093
Dan Gohman99dca4f2010-05-11 19:57:55 +00002094bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
2095 formatted_raw_ostream &o,
2096 CodeGenFileType FileType,
Dan Gohman99dca4f2010-05-11 19:57:55 +00002097 bool DisableVerify) {
Chris Lattner211edae2010-02-02 21:06:45 +00002098 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002099 PM.add(new CppWriter(o));
2100 return false;
2101}