blob: a872fbd614e1c70104ddcad4cee800f3ac346627 [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"
25#include "llvm/TypeSymbolTable.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000026#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/Support/CommandLine.h"
Torok Edwin30464702009-07-08 20:55:50 +000028#include "llvm/Support/ErrorHandling.h"
David Greene71847812009-07-14 20:18:05 +000029#include "llvm/Support/FormattedStream.h"
Daniel Dunbar0c795d62009-07-25 06:49:55 +000030#include "llvm/Target/TargetRegistry.h"
Chris Lattner23132b12009-08-24 03:52:50 +000031#include "llvm/ADT/StringExtras.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000032#include "llvm/Config/config.h"
33#include <algorithm>
Anton Korobeynikov50276522008-04-23 22:29:24 +000034#include <set>
35
36using namespace llvm;
37
38static cl::opt<std::string>
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000039FuncName("cppfname", cl::desc("Specify the name of the generated function"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000040 cl::value_desc("function name"));
41
42enum WhatToGenerate {
43 GenProgram,
44 GenModule,
45 GenContents,
46 GenFunction,
47 GenFunctions,
48 GenInline,
49 GenVariable,
50 GenType
51};
52
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000053static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000054 cl::desc("Choose what kind of output to generate"),
55 cl::init(GenProgram),
56 cl::values(
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000057 clEnumValN(GenProgram, "program", "Generate a complete program"),
58 clEnumValN(GenModule, "module", "Generate a module definition"),
59 clEnumValN(GenContents, "contents", "Generate contents of a module"),
60 clEnumValN(GenFunction, "function", "Generate a function definition"),
61 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
62 clEnumValN(GenInline, "inline", "Generate an inline function"),
63 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
64 clEnumValN(GenType, "type", "Generate a type definition"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000065 clEnumValEnd
66 )
67);
68
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000069static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000070 cl::desc("Specify the name of the thing to generate"),
71 cl::init("!bad!"));
72
Daniel Dunbar0c795d62009-07-25 06:49:55 +000073extern "C" void LLVMInitializeCppBackendTarget() {
74 // Register the target.
Daniel Dunbar214e2232009-08-04 04:02:45 +000075 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
Daniel Dunbar0c795d62009-07-25 06:49:55 +000076}
Douglas Gregor1555a232009-06-16 20:12:29 +000077
Dan Gohman844731a2008-05-13 00:00:25 +000078namespace {
Anton Korobeynikov50276522008-04-23 22:29:24 +000079 typedef std::vector<const Type*> TypeList;
80 typedef std::map<const Type*,std::string> TypeMap;
81 typedef std::map<const Value*,std::string> ValueMap;
82 typedef std::set<std::string> NameSet;
83 typedef std::set<const Type*> TypeSet;
84 typedef std::set<const Value*> ValueSet;
85 typedef std::map<const Value*,std::string> ForwardRefMap;
86
87 /// CppWriter - This class is the main chunk of code that converts an LLVM
88 /// module to a C++ translation unit.
89 class CppWriter : public ModulePass {
David Greene71847812009-07-14 20:18:05 +000090 formatted_raw_ostream &Out;
Anton Korobeynikov50276522008-04-23 22:29:24 +000091 const Module *TheModule;
92 uint64_t uniqueNum;
93 TypeMap TypeNames;
94 ValueMap ValueNames;
95 TypeMap UnresolvedTypes;
96 TypeList TypeStack;
97 NameSet UsedNames;
98 TypeSet DefinedTypes;
99 ValueSet DefinedValues;
100 ForwardRefMap ForwardRefs;
101 bool is_inline;
102
103 public:
104 static char ID;
David Greene71847812009-07-14 20:18:05 +0000105 explicit CppWriter(formatted_raw_ostream &o) :
Dan Gohmanae73dc12008-09-04 17:05:41 +0000106 ModulePass(&ID), Out(o), uniqueNum(0), is_inline(false) {}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000107
108 virtual const char *getPassName() const { return "C++ backend"; }
109
110 bool runOnModule(Module &M);
111
Anton Korobeynikov50276522008-04-23 22:29:24 +0000112 void printProgram(const std::string& fname, const std::string& modName );
113 void printModule(const std::string& fname, const std::string& modName );
114 void printContents(const std::string& fname, const std::string& modName );
115 void printFunction(const std::string& fname, const std::string& funcName );
116 void printFunctions();
117 void printInline(const std::string& fname, const std::string& funcName );
118 void printVariable(const std::string& fname, const std::string& varName );
119 void printType(const std::string& fname, const std::string& typeName );
120
121 void error(const std::string& msg);
122
123 private:
124 void printLinkageType(GlobalValue::LinkageTypes LT);
125 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +0000126 void printCallingConv(CallingConv::ID cc);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000127 void printEscapedString(const std::string& str);
128 void printCFP(const ConstantFP* CFP);
129
130 std::string getCppName(const Type* val);
131 inline void printCppName(const Type* val);
132
133 std::string getCppName(const Value* val);
134 inline void printCppName(const Value* val);
135
Devang Patel05988662008-09-25 21:00:45 +0000136 void printAttributes(const AttrListPtr &PAL, const std::string &name);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000137 bool printTypeInternal(const Type* Ty);
138 inline void printType(const Type* Ty);
139 void printTypes(const Module* M);
140
141 void printConstant(const Constant *CPV);
142 void printConstants(const Module* M);
143
144 void printVariableUses(const GlobalVariable *GV);
145 void printVariableHead(const GlobalVariable *GV);
146 void printVariableBody(const GlobalVariable *GV);
147
148 void printFunctionUses(const Function *F);
149 void printFunctionHead(const Function *F);
150 void printFunctionBody(const Function *F);
151 void printInstruction(const Instruction *I, const std::string& bbname);
152 std::string getOpName(Value*);
153
154 void printModuleBody();
155 };
156
157 static unsigned indent_level = 0;
David Greene71847812009-07-14 20:18:05 +0000158 inline formatted_raw_ostream& nl(formatted_raw_ostream& Out, int delta = 0) {
Anton Korobeynikov50276522008-04-23 22:29:24 +0000159 Out << "\n";
160 if (delta >= 0 || indent_level >= unsigned(-delta))
161 indent_level += delta;
162 for (unsigned i = 0; i < indent_level; ++i)
163 Out << " ";
164 return Out;
165 }
166
167 inline void in() { indent_level++; }
168 inline void out() { if (indent_level >0) indent_level--; }
169
170 inline void
171 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
177 inline std::string
178 getTypePrefix(const Type* Ty ) {
179 switch (Ty->getTypeID()) {
180 case Type::VoidTyID: return "void_";
181 case Type::IntegerTyID:
182 return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
183 "_";
184 case Type::FloatTyID: return "float_";
185 case Type::DoubleTyID: return "double_";
186 case Type::LabelTyID: return "label_";
187 case Type::FunctionTyID: return "func_";
188 case Type::StructTyID: return "struct_";
189 case Type::ArrayTyID: return "array_";
190 case Type::PointerTyID: return "ptr_";
191 case Type::VectorTyID: return "packed_";
192 case Type::OpaqueTyID: return "opaque_";
193 default: return "other_";
194 }
195 return "unknown_";
196 }
197
198 // Looks up the type in the symbol table and returns a pointer to its name or
199 // a null pointer if it wasn't found. Note that this isn't the same as the
200 // Mode::getTypeName function which will return an empty string, not a null
201 // pointer if the name is not found.
202 inline const std::string*
203 findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
204 TypeSymbolTable::const_iterator TI = ST.begin();
205 TypeSymbolTable::const_iterator TE = ST.end();
206 for (;TI != TE; ++TI)
207 if (TI->second == Ty)
208 return &(TI->first);
209 return 0;
210 }
211
212 void CppWriter::error(const std::string& msg) {
Torok Edwin30464702009-07-08 20:55:50 +0000213 llvm_report_error(msg);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000214 }
215
216 // printCFP - Print a floating point constant .. very carefully :)
217 // This makes sure that conversion to/from floating yields the same binary
218 // result so that we don't lose precision.
219 void CppWriter::printCFP(const ConstantFP *CFP) {
Dale Johannesen23a98552008-10-09 23:00:39 +0000220 bool ignored;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000221 APFloat APF = APFloat(CFP->getValueAPF()); // copy
Owen Anderson1d0be152009-08-13 21:58:54 +0000222 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
Dale Johannesen23a98552008-10-09 23:00:39 +0000223 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Anton Korobeynikovd083dfb2009-08-21 12:50:54 +0000224 Out << "ConstantFP::get(getGlobalContext(), ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000225 Out << "APFloat(";
226#if HAVE_PRINTF_A
227 char Buffer[100];
228 sprintf(Buffer, "%A", APF.convertToDouble());
229 if ((!strncmp(Buffer, "0x", 2) ||
230 !strncmp(Buffer, "-0x", 3) ||
231 !strncmp(Buffer, "+0x", 3)) &&
232 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000233 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
Anton Korobeynikov50276522008-04-23 22:29:24 +0000234 Out << "BitsToDouble(" << Buffer << ")";
235 else
236 Out << "BitsToFloat((float)" << Buffer << ")";
237 Out << ")";
238 } else {
239#endif
240 std::string StrVal = ftostr(CFP->getValueAPF());
241
242 while (StrVal[0] == ' ')
243 StrVal.erase(StrVal.begin());
244
245 // Check to make sure that the stringized number is not some string like
246 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
247 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
248 ((StrVal[0] == '-' || StrVal[0] == '+') &&
249 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
250 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000251 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
Anton Korobeynikov50276522008-04-23 22:29:24 +0000252 Out << StrVal;
253 else
254 Out << StrVal << "f";
Owen Anderson1d0be152009-08-13 21:58:54 +0000255 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
Owen Andersoncb371882008-08-21 00:14:44 +0000256 Out << "BitsToDouble(0x"
Dale Johannesen7111b022008-10-09 18:53:47 +0000257 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
Owen Andersoncb371882008-08-21 00:14:44 +0000258 << "ULL) /* " << StrVal << " */";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000259 else
Owen Andersoncb371882008-08-21 00:14:44 +0000260 Out << "BitsToFloat(0x"
Dale Johannesen7111b022008-10-09 18:53:47 +0000261 << utohexstr((uint32_t)CFP->getValueAPF().
262 bitcastToAPInt().getZExtValue())
Owen Andersoncb371882008-08-21 00:14:44 +0000263 << "U) /* " << StrVal << " */";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000264 Out << ")";
265#if HAVE_PRINTF_A
266 }
267#endif
268 Out << ")";
269 }
270
Sandeep Patel65c3c8f2009-09-02 08:44:58 +0000271 void CppWriter::printCallingConv(CallingConv::ID cc){
Anton Korobeynikov50276522008-04-23 22:29:24 +0000272 // Print the calling convention.
273 switch (cc) {
274 case CallingConv::C: Out << "CallingConv::C"; break;
275 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
276 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
277 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
278 default: Out << cc; break;
279 }
280 }
281
282 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
283 switch (LT) {
284 case GlobalValue::InternalLinkage:
285 Out << "GlobalValue::InternalLinkage"; break;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000286 case GlobalValue::PrivateLinkage:
287 Out << "GlobalValue::PrivateLinkage"; break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000288 case GlobalValue::LinkerPrivateLinkage:
289 Out << "GlobalValue::LinkerPrivateLinkage"; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000290 case GlobalValue::AvailableExternallyLinkage:
291 Out << "GlobalValue::AvailableExternallyLinkage "; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000292 case GlobalValue::LinkOnceAnyLinkage:
293 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
294 case GlobalValue::LinkOnceODRLinkage:
295 Out << "GlobalValue::LinkOnceODRLinkage "; break;
296 case GlobalValue::WeakAnyLinkage:
297 Out << "GlobalValue::WeakAnyLinkage"; break;
298 case GlobalValue::WeakODRLinkage:
299 Out << "GlobalValue::WeakODRLinkage"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000300 case GlobalValue::AppendingLinkage:
301 Out << "GlobalValue::AppendingLinkage"; break;
302 case GlobalValue::ExternalLinkage:
303 Out << "GlobalValue::ExternalLinkage"; break;
304 case GlobalValue::DLLImportLinkage:
305 Out << "GlobalValue::DLLImportLinkage"; break;
306 case GlobalValue::DLLExportLinkage:
307 Out << "GlobalValue::DLLExportLinkage"; break;
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000308 case GlobalValue::ExternalWeakLinkage:
309 Out << "GlobalValue::ExternalWeakLinkage"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000310 case GlobalValue::GhostLinkage:
311 Out << "GlobalValue::GhostLinkage"; break;
Duncan Sands4dc2b392009-03-11 20:14:15 +0000312 case GlobalValue::CommonLinkage:
313 Out << "GlobalValue::CommonLinkage"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000314 }
315 }
316
317 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
318 switch (VisType) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000319 default: llvm_unreachable("Unknown GVar visibility");
Anton Korobeynikov50276522008-04-23 22:29:24 +0000320 case GlobalValue::DefaultVisibility:
321 Out << "GlobalValue::DefaultVisibility";
322 break;
323 case GlobalValue::HiddenVisibility:
324 Out << "GlobalValue::HiddenVisibility";
325 break;
326 case GlobalValue::ProtectedVisibility:
327 Out << "GlobalValue::ProtectedVisibility";
328 break;
329 }
330 }
331
332 // printEscapedString - Print each character of the specified string, escaping
333 // it if it is not printable or if it is an escape char.
334 void CppWriter::printEscapedString(const std::string &Str) {
335 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
336 unsigned char C = Str[i];
337 if (isprint(C) && C != '"' && C != '\\') {
338 Out << C;
339 } else {
340 Out << "\\x"
341 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
342 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
343 }
344 }
345 }
346
347 std::string CppWriter::getCppName(const Type* Ty) {
348 // First, handle the primitive types .. easy
349 if (Ty->isPrimitiveType() || Ty->isInteger()) {
350 switch (Ty->getTypeID()) {
Nicolas Geoffrayab2a6632009-08-15 14:47:42 +0000351 case Type::VoidTyID: return "Type::getVoidTy(getGlobalContext())";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000352 case Type::IntegerTyID: {
353 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
Owen Anderson267a0ff2009-08-14 17:41:33 +0000354 return "IntegerType::get(getGlobalContext(), " + utostr(BitWidth) + ")";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000355 }
Nicolas Geoffrayab2a6632009-08-15 14:47:42 +0000356 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(getGlobalContext())";
357 case Type::FloatTyID: return "Type::getFloatTy(getGlobalContext())";
358 case Type::DoubleTyID: return "Type::getDoubleTy(getGlobalContext())";
359 case Type::LabelTyID: return "Type::getLabelTy(getGlobalContext())";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000360 default:
361 error("Invalid primitive type");
362 break;
363 }
Nicolas Geoffrayab2a6632009-08-15 14:47:42 +0000364 // shouldn't be returned, but make it sensible
365 return "Type::getVoidTy(getGlobalContext())";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000366 }
367
368 // Now, see if we've seen the type before and return that
369 TypeMap::iterator I = TypeNames.find(Ty);
370 if (I != TypeNames.end())
371 return I->second;
372
373 // Okay, let's build a new name for this type. Start with a prefix
374 const char* prefix = 0;
375 switch (Ty->getTypeID()) {
376 case Type::FunctionTyID: prefix = "FuncTy_"; break;
377 case Type::StructTyID: prefix = "StructTy_"; break;
378 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
379 case Type::PointerTyID: prefix = "PointerTy_"; break;
380 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
381 case Type::VectorTyID: prefix = "VectorTy_"; break;
382 default: prefix = "OtherTy_"; break; // prevent breakage
383 }
384
385 // See if the type has a name in the symboltable and build accordingly
386 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
387 std::string name;
388 if (tName)
389 name = std::string(prefix) + *tName;
390 else
391 name = std::string(prefix) + utostr(uniqueNum++);
392 sanitize(name);
393
394 // Save the name
395 return TypeNames[Ty] = name;
396 }
397
398 void CppWriter::printCppName(const Type* Ty) {
399 printEscapedString(getCppName(Ty));
400 }
401
402 std::string CppWriter::getCppName(const Value* val) {
403 std::string name;
404 ValueMap::iterator I = ValueNames.find(val);
405 if (I != ValueNames.end() && I->first == val)
406 return I->second;
407
408 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
409 name = std::string("gvar_") +
410 getTypePrefix(GV->getType()->getElementType());
411 } else if (isa<Function>(val)) {
412 name = std::string("func_");
413 } else if (const Constant* C = dyn_cast<Constant>(val)) {
414 name = std::string("const_") + getTypePrefix(C->getType());
415 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
416 if (is_inline) {
417 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
418 Function::const_arg_iterator(Arg)) + 1;
419 name = std::string("arg_") + utostr(argNum);
420 NameSet::iterator NI = UsedNames.find(name);
421 if (NI != UsedNames.end())
422 name += std::string("_") + utostr(uniqueNum++);
423 UsedNames.insert(name);
424 return ValueNames[val] = name;
425 } else {
426 name = getTypePrefix(val->getType());
427 }
428 } else {
429 name = getTypePrefix(val->getType());
430 }
Daniel Dunbar8f603022009-07-22 21:10:12 +0000431 if (val->hasName())
432 name += val->getName();
433 else
434 name += utostr(uniqueNum++);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000435 sanitize(name);
436 NameSet::iterator NI = UsedNames.find(name);
437 if (NI != UsedNames.end())
438 name += std::string("_") + utostr(uniqueNum++);
439 UsedNames.insert(name);
440 return ValueNames[val] = name;
441 }
442
443 void CppWriter::printCppName(const Value* val) {
444 printEscapedString(getCppName(val));
445 }
446
Devang Patel05988662008-09-25 21:00:45 +0000447 void CppWriter::printAttributes(const AttrListPtr &PAL,
Anton Korobeynikov50276522008-04-23 22:29:24 +0000448 const std::string &name) {
Devang Patel05988662008-09-25 21:00:45 +0000449 Out << "AttrListPtr " << name << "_PAL;";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000450 nl(Out);
451 if (!PAL.isEmpty()) {
452 Out << '{'; in(); nl(Out);
Devang Patel05988662008-09-25 21:00:45 +0000453 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
454 Out << "AttributeWithIndex PAWI;"; nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000455 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
Nicolas Geoffrayd9afb4d2008-11-08 15:36:01 +0000456 unsigned index = PAL.getSlot(i).Index;
Devang Pateleaf42ab2008-09-23 23:03:40 +0000457 Attributes attrs = PAL.getSlot(i).Attrs;
Nicolas Geoffrayd9afb4d2008-11-08 15:36:01 +0000458 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
Chris Lattneracca9552009-01-13 07:22:22 +0000459#define HANDLE_ATTR(X) \
460 if (attrs & Attribute::X) \
461 Out << " | Attribute::" #X; \
462 attrs &= ~Attribute::X;
463
464 HANDLE_ATTR(SExt);
465 HANDLE_ATTR(ZExt);
Chris Lattneracca9552009-01-13 07:22:22 +0000466 HANDLE_ATTR(NoReturn);
Jeffrey Yasskin2d92c712009-05-28 03:16:17 +0000467 HANDLE_ATTR(InReg);
468 HANDLE_ATTR(StructRet);
Chris Lattneracca9552009-01-13 07:22:22 +0000469 HANDLE_ATTR(NoUnwind);
Chris Lattneracca9552009-01-13 07:22:22 +0000470 HANDLE_ATTR(NoAlias);
Jeffrey Yasskin2d92c712009-05-28 03:16:17 +0000471 HANDLE_ATTR(ByVal);
Chris Lattneracca9552009-01-13 07:22:22 +0000472 HANDLE_ATTR(Nest);
473 HANDLE_ATTR(ReadNone);
474 HANDLE_ATTR(ReadOnly);
Dale Johannesende86d472009-08-26 01:08:21 +0000475 HANDLE_ATTR(InlineHint);
Jeffrey Yasskin2d92c712009-05-28 03:16:17 +0000476 HANDLE_ATTR(NoInline);
477 HANDLE_ATTR(AlwaysInline);
478 HANDLE_ATTR(OptimizeForSize);
479 HANDLE_ATTR(StackProtect);
480 HANDLE_ATTR(StackProtectReq);
Chris Lattneracca9552009-01-13 07:22:22 +0000481 HANDLE_ATTR(NoCapture);
482#undef HANDLE_ATTR
483 assert(attrs == 0 && "Unhandled attribute!");
Anton Korobeynikov50276522008-04-23 22:29:24 +0000484 Out << ";";
485 nl(Out);
486 Out << "Attrs.push_back(PAWI);";
487 nl(Out);
488 }
Devang Patel05988662008-09-25 21:00:45 +0000489 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000490 nl(Out);
491 out(); nl(Out);
492 Out << '}'; nl(Out);
493 }
494 }
495
496 bool CppWriter::printTypeInternal(const Type* Ty) {
497 // We don't print definitions for primitive types
498 if (Ty->isPrimitiveType() || Ty->isInteger())
499 return false;
500
501 // If we already defined this type, we don't need to define it again.
502 if (DefinedTypes.find(Ty) != DefinedTypes.end())
503 return false;
504
505 // Everything below needs the name for the type so get it now.
506 std::string typeName(getCppName(Ty));
507
508 // Search the type stack for recursion. If we find it, then generate this
509 // as an OpaqueType, but make sure not to do this multiple times because
510 // the type could appear in multiple places on the stack. Once the opaque
511 // definition is issued, it must not be re-issued. Consequently we have to
512 // check the UnresolvedTypes list as well.
513 TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
514 Ty);
515 if (TI != TypeStack.end()) {
516 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
517 if (I == UnresolvedTypes.end()) {
Nicolas Geoffraybad9def2009-08-15 15:41:32 +0000518 Out << "PATypeHolder " << typeName;
519 Out << "_fwd = OpaqueType::get(getGlobalContext());";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000520 nl(Out);
521 UnresolvedTypes[Ty] = typeName;
522 }
523 return true;
524 }
525
526 // We're going to print a derived type which, by definition, contains other
527 // types. So, push this one we're printing onto the type stack to assist with
528 // recursive definitions.
529 TypeStack.push_back(Ty);
530
531 // Print the type definition
532 switch (Ty->getTypeID()) {
533 case Type::FunctionTyID: {
534 const FunctionType* FT = cast<FunctionType>(Ty);
535 Out << "std::vector<const Type*>" << typeName << "_args;";
536 nl(Out);
537 FunctionType::param_iterator PI = FT->param_begin();
538 FunctionType::param_iterator PE = FT->param_end();
539 for (; PI != PE; ++PI) {
540 const Type* argTy = static_cast<const Type*>(*PI);
541 bool isForward = printTypeInternal(argTy);
542 std::string argName(getCppName(argTy));
543 Out << typeName << "_args.push_back(" << argName;
544 if (isForward)
545 Out << "_fwd";
546 Out << ");";
547 nl(Out);
548 }
549 bool isForward = printTypeInternal(FT->getReturnType());
550 std::string retTypeName(getCppName(FT->getReturnType()));
551 Out << "FunctionType* " << typeName << " = FunctionType::get(";
552 in(); nl(Out) << "/*Result=*/" << retTypeName;
553 if (isForward)
554 Out << "_fwd";
555 Out << ",";
556 nl(Out) << "/*Params=*/" << typeName << "_args,";
557 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
558 out();
559 nl(Out);
560 break;
561 }
562 case Type::StructTyID: {
563 const StructType* ST = cast<StructType>(Ty);
564 Out << "std::vector<const Type*>" << typeName << "_fields;";
565 nl(Out);
566 StructType::element_iterator EI = ST->element_begin();
567 StructType::element_iterator EE = ST->element_end();
568 for (; EI != EE; ++EI) {
569 const Type* fieldTy = static_cast<const Type*>(*EI);
570 bool isForward = printTypeInternal(fieldTy);
571 std::string fieldName(getCppName(fieldTy));
572 Out << typeName << "_fields.push_back(" << fieldName;
573 if (isForward)
574 Out << "_fwd";
575 Out << ");";
576 nl(Out);
577 }
578 Out << "StructType* " << typeName << " = StructType::get("
Nicolas Geoffray6f62cff2009-08-06 21:31:35 +0000579 << "mod->getContext(), "
Anton Korobeynikov50276522008-04-23 22:29:24 +0000580 << typeName << "_fields, /*isPacked=*/"
581 << (ST->isPacked() ? "true" : "false") << ");";
582 nl(Out);
583 break;
584 }
585 case Type::ArrayTyID: {
586 const ArrayType* AT = cast<ArrayType>(Ty);
587 const Type* ET = AT->getElementType();
588 bool isForward = printTypeInternal(ET);
589 std::string elemName(getCppName(ET));
590 Out << "ArrayType* " << typeName << " = ArrayType::get("
591 << elemName << (isForward ? "_fwd" : "")
592 << ", " << utostr(AT->getNumElements()) << ");";
593 nl(Out);
594 break;
595 }
596 case Type::PointerTyID: {
597 const PointerType* PT = cast<PointerType>(Ty);
598 const Type* ET = PT->getElementType();
599 bool isForward = printTypeInternal(ET);
600 std::string elemName(getCppName(ET));
601 Out << "PointerType* " << typeName << " = PointerType::get("
602 << elemName << (isForward ? "_fwd" : "")
603 << ", " << utostr(PT->getAddressSpace()) << ");";
604 nl(Out);
605 break;
606 }
607 case Type::VectorTyID: {
608 const VectorType* PT = cast<VectorType>(Ty);
609 const Type* ET = PT->getElementType();
610 bool isForward = printTypeInternal(ET);
611 std::string elemName(getCppName(ET));
612 Out << "VectorType* " << typeName << " = VectorType::get("
613 << elemName << (isForward ? "_fwd" : "")
614 << ", " << utostr(PT->getNumElements()) << ");";
615 nl(Out);
616 break;
617 }
618 case Type::OpaqueTyID: {
Nicolas Geoffraybad9def2009-08-15 15:41:32 +0000619 Out << "OpaqueType* " << typeName;
620 Out << " = OpaqueType::get(getGlobalContext());";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000621 nl(Out);
622 break;
623 }
624 default:
625 error("Invalid TypeID");
626 }
627
628 // If the type had a name, make sure we recreate it.
629 const std::string* progTypeName =
630 findTypeName(TheModule->getTypeSymbolTable(),Ty);
631 if (progTypeName) {
632 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
633 << typeName << ");";
634 nl(Out);
635 }
636
637 // Pop us off the type stack
638 TypeStack.pop_back();
639
640 // Indicate that this type is now defined.
641 DefinedTypes.insert(Ty);
642
643 // Early resolve as many unresolved types as possible. Search the unresolved
644 // types map for the type we just printed. Now that its definition is complete
645 // we can resolve any previous references to it. This prevents a cascade of
646 // unresolved types.
647 TypeMap::iterator I = UnresolvedTypes.find(Ty);
648 if (I != UnresolvedTypes.end()) {
649 Out << "cast<OpaqueType>(" << I->second
650 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
651 nl(Out);
652 Out << I->second << " = cast<";
653 switch (Ty->getTypeID()) {
654 case Type::FunctionTyID: Out << "FunctionType"; break;
655 case Type::ArrayTyID: Out << "ArrayType"; break;
656 case Type::StructTyID: Out << "StructType"; break;
657 case Type::VectorTyID: Out << "VectorType"; break;
658 case Type::PointerTyID: Out << "PointerType"; break;
659 case Type::OpaqueTyID: Out << "OpaqueType"; break;
660 default: Out << "NoSuchDerivedType"; break;
661 }
662 Out << ">(" << I->second << "_fwd.get());";
663 nl(Out); nl(Out);
664 UnresolvedTypes.erase(I);
665 }
666
667 // Finally, separate the type definition from other with a newline.
668 nl(Out);
669
670 // We weren't a recursive type
671 return false;
672 }
673
674 // Prints a type definition. Returns true if it could not resolve all the
675 // types in the definition but had to use a forward reference.
676 void CppWriter::printType(const Type* Ty) {
677 assert(TypeStack.empty());
678 TypeStack.clear();
679 printTypeInternal(Ty);
680 assert(TypeStack.empty());
681 }
682
683 void CppWriter::printTypes(const Module* M) {
684 // Walk the symbol table and print out all its types
685 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
686 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
687 TI != TE; ++TI) {
688
689 // For primitive types and types already defined, just add a name
690 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
691 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
692 TNI != TypeNames.end()) {
693 Out << "mod->addTypeName(\"";
694 printEscapedString(TI->first);
695 Out << "\", " << getCppName(TI->second) << ");";
696 nl(Out);
697 // For everything else, define the type
698 } else {
699 printType(TI->second);
700 }
701 }
702
703 // Add all of the global variables to the value table...
704 for (Module::const_global_iterator I = TheModule->global_begin(),
705 E = TheModule->global_end(); I != E; ++I) {
706 if (I->hasInitializer())
707 printType(I->getInitializer()->getType());
708 printType(I->getType());
709 }
710
711 // Add all the functions to the table
712 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
713 FI != FE; ++FI) {
714 printType(FI->getReturnType());
715 printType(FI->getFunctionType());
716 // Add all the function arguments
717 for (Function::const_arg_iterator AI = FI->arg_begin(),
718 AE = FI->arg_end(); AI != AE; ++AI) {
719 printType(AI->getType());
720 }
721
722 // Add all of the basic blocks and instructions
723 for (Function::const_iterator BB = FI->begin(),
724 E = FI->end(); BB != E; ++BB) {
725 printType(BB->getType());
726 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
727 ++I) {
728 printType(I->getType());
729 for (unsigned i = 0; i < I->getNumOperands(); ++i)
730 printType(I->getOperand(i)->getType());
731 }
732 }
733 }
734 }
735
736
737 // printConstant - Print out a constant pool entry...
738 void CppWriter::printConstant(const Constant *CV) {
739 // First, if the constant is actually a GlobalValue (variable or function)
740 // or its already in the constant list then we've printed it already and we
741 // can just return.
742 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
743 return;
744
745 std::string constName(getCppName(CV));
746 std::string typeName(getCppName(CV->getType()));
Anton Korobeynikovff4ca2e2008-10-05 15:07:06 +0000747
Anton Korobeynikov50276522008-04-23 22:29:24 +0000748 if (isa<GlobalValue>(CV)) {
749 // Skip variables and functions, we emit them elsewhere
750 return;
751 }
Anton Korobeynikovff4ca2e2008-10-05 15:07:06 +0000752
Anton Korobeynikov50276522008-04-23 22:29:24 +0000753 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
Anton Korobeynikov70053c32008-08-18 20:03:45 +0000754 std::string constValue = CI->getValue().toString(10, true);
Owen Anderson267a0ff2009-08-14 17:41:33 +0000755 Out << "ConstantInt* " << constName
756 << " = ConstantInt::get(getGlobalContext(), APInt("
757 << cast<IntegerType>(CI->getType())->getBitWidth()
Benjamin Kramer6d5f0f02009-09-03 14:58:24 +0000758 << ", StringRef(\"" << constValue << "\"), 10));";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000759 } else if (isa<ConstantAggregateZero>(CV)) {
760 Out << "ConstantAggregateZero* " << constName
761 << " = ConstantAggregateZero::get(" << typeName << ");";
762 } else if (isa<ConstantPointerNull>(CV)) {
763 Out << "ConstantPointerNull* " << constName
Anton Korobeynikovff4ca2e2008-10-05 15:07:06 +0000764 << " = ConstantPointerNull::get(" << typeName << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000765 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
766 Out << "ConstantFP* " << constName << " = ";
767 printCFP(CFP);
768 Out << ";";
769 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000770 if (CA->isString() &&
771 CA->getType()->getElementType() ==
772 Type::getInt8Ty(CA->getContext())) {
Owen Anderson267a0ff2009-08-14 17:41:33 +0000773 Out << "Constant* " << constName <<
774 " = ConstantArray::get(getGlobalContext(), \"";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000775 std::string tmp = CA->getAsString();
776 bool nullTerminate = false;
777 if (tmp[tmp.length()-1] == 0) {
778 tmp.erase(tmp.length()-1);
779 nullTerminate = true;
780 }
781 printEscapedString(tmp);
782 // Determine if we want null termination or not.
783 if (nullTerminate)
784 Out << "\", true"; // Indicate that the null terminator should be
785 // added.
786 else
787 Out << "\", false";// No null terminator
788 Out << ");";
789 } else {
790 Out << "std::vector<Constant*> " << constName << "_elems;";
791 nl(Out);
792 unsigned N = CA->getNumOperands();
793 for (unsigned i = 0; i < N; ++i) {
794 printConstant(CA->getOperand(i)); // recurse to print operands
795 Out << constName << "_elems.push_back("
796 << getCppName(CA->getOperand(i)) << ");";
797 nl(Out);
798 }
799 Out << "Constant* " << constName << " = ConstantArray::get("
800 << typeName << ", " << constName << "_elems);";
801 }
802 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
803 Out << "std::vector<Constant*> " << constName << "_fields;";
804 nl(Out);
805 unsigned N = CS->getNumOperands();
806 for (unsigned i = 0; i < N; i++) {
807 printConstant(CS->getOperand(i));
808 Out << constName << "_fields.push_back("
809 << getCppName(CS->getOperand(i)) << ");";
810 nl(Out);
811 }
812 Out << "Constant* " << constName << " = ConstantStruct::get("
813 << typeName << ", " << constName << "_fields);";
814 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
815 Out << "std::vector<Constant*> " << constName << "_elems;";
816 nl(Out);
817 unsigned N = CP->getNumOperands();
818 for (unsigned i = 0; i < N; ++i) {
819 printConstant(CP->getOperand(i));
820 Out << constName << "_elems.push_back("
821 << getCppName(CP->getOperand(i)) << ");";
822 nl(Out);
823 }
824 Out << "Constant* " << constName << " = ConstantVector::get("
825 << typeName << ", " << constName << "_elems);";
826 } else if (isa<UndefValue>(CV)) {
827 Out << "UndefValue* " << constName << " = UndefValue::get("
828 << typeName << ");";
829 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
830 if (CE->getOpcode() == Instruction::GetElementPtr) {
831 Out << "std::vector<Constant*> " << constName << "_indices;";
832 nl(Out);
833 printConstant(CE->getOperand(0));
834 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
835 printConstant(CE->getOperand(i));
836 Out << constName << "_indices.push_back("
837 << getCppName(CE->getOperand(i)) << ");";
838 nl(Out);
839 }
840 Out << "Constant* " << constName
841 << " = ConstantExpr::getGetElementPtr("
842 << getCppName(CE->getOperand(0)) << ", "
843 << "&" << constName << "_indices[0], "
844 << constName << "_indices.size()"
Benjamin Kramer6d5f0f02009-09-03 14:58:24 +0000845 << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000846 } else if (CE->isCast()) {
847 printConstant(CE->getOperand(0));
848 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
849 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000850 default: llvm_unreachable("Invalid cast opcode");
Anton Korobeynikov50276522008-04-23 22:29:24 +0000851 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
852 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
853 case Instruction::SExt: Out << "Instruction::SExt"; break;
854 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
855 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
856 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
857 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
858 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
859 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
860 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
861 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
862 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
863 }
864 Out << ", " << getCppName(CE->getOperand(0)) << ", "
865 << getCppName(CE->getType()) << ");";
866 } else {
867 unsigned N = CE->getNumOperands();
868 for (unsigned i = 0; i < N; ++i ) {
869 printConstant(CE->getOperand(i));
870 }
871 Out << "Constant* " << constName << " = ConstantExpr::";
872 switch (CE->getOpcode()) {
873 case Instruction::Add: Out << "getAdd("; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000874 case Instruction::FAdd: Out << "getFAdd("; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000875 case Instruction::Sub: Out << "getSub("; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000876 case Instruction::FSub: Out << "getFSub("; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000877 case Instruction::Mul: Out << "getMul("; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000878 case Instruction::FMul: Out << "getFMul("; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000879 case Instruction::UDiv: Out << "getUDiv("; break;
880 case Instruction::SDiv: Out << "getSDiv("; break;
881 case Instruction::FDiv: Out << "getFDiv("; break;
882 case Instruction::URem: Out << "getURem("; break;
883 case Instruction::SRem: Out << "getSRem("; break;
884 case Instruction::FRem: Out << "getFRem("; break;
885 case Instruction::And: Out << "getAnd("; break;
886 case Instruction::Or: Out << "getOr("; break;
887 case Instruction::Xor: Out << "getXor("; break;
888 case Instruction::ICmp:
889 Out << "getICmp(ICmpInst::ICMP_";
890 switch (CE->getPredicate()) {
891 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
892 case ICmpInst::ICMP_NE: Out << "NE"; break;
893 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
894 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
895 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
896 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
897 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
898 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
899 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
900 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
901 default: error("Invalid ICmp Predicate");
902 }
903 break;
904 case Instruction::FCmp:
905 Out << "getFCmp(FCmpInst::FCMP_";
906 switch (CE->getPredicate()) {
907 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
908 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
909 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
910 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
911 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
912 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
913 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
914 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
915 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
916 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
917 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
918 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
919 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
920 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
921 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
922 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
923 default: error("Invalid FCmp Predicate");
924 }
925 break;
926 case Instruction::Shl: Out << "getShl("; break;
927 case Instruction::LShr: Out << "getLShr("; break;
928 case Instruction::AShr: Out << "getAShr("; break;
929 case Instruction::Select: Out << "getSelect("; break;
930 case Instruction::ExtractElement: Out << "getExtractElement("; break;
931 case Instruction::InsertElement: Out << "getInsertElement("; break;
932 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
933 default:
934 error("Invalid constant expression");
935 break;
936 }
937 Out << getCppName(CE->getOperand(0));
938 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
939 Out << ", " << getCppName(CE->getOperand(i));
940 Out << ");";
941 }
942 } else {
943 error("Bad Constant");
944 Out << "Constant* " << constName << " = 0; ";
945 }
946 nl(Out);
947 }
948
949 void CppWriter::printConstants(const Module* M) {
950 // Traverse all the global variables looking for constant initializers
951 for (Module::const_global_iterator I = TheModule->global_begin(),
952 E = TheModule->global_end(); I != E; ++I)
953 if (I->hasInitializer())
954 printConstant(I->getInitializer());
955
956 // Traverse the LLVM functions looking for constants
957 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
958 FI != FE; ++FI) {
959 // Add all of the basic blocks and instructions
960 for (Function::const_iterator BB = FI->begin(),
961 E = FI->end(); BB != E; ++BB) {
962 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
963 ++I) {
964 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
965 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
966 printConstant(C);
967 }
968 }
969 }
970 }
971 }
972 }
973
974 void CppWriter::printVariableUses(const GlobalVariable *GV) {
975 nl(Out) << "// Type Definitions";
976 nl(Out);
977 printType(GV->getType());
978 if (GV->hasInitializer()) {
Chris Lattnercdfb3022009-12-14 19:34:32 +0000979 Constant *Init = GV->getInitializer();
Anton Korobeynikov50276522008-04-23 22:29:24 +0000980 printType(Init->getType());
Chris Lattnercdfb3022009-12-14 19:34:32 +0000981 if (Function *F = dyn_cast<Function>(Init)) {
Anton Korobeynikov50276522008-04-23 22:29:24 +0000982 nl(Out)<< "/ Function Declarations"; nl(Out);
983 printFunctionHead(F);
984 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
985 nl(Out) << "// Global Variable Declarations"; nl(Out);
986 printVariableHead(gv);
Chris Lattnercdfb3022009-12-14 19:34:32 +0000987
Anton Korobeynikov50276522008-04-23 22:29:24 +0000988 nl(Out) << "// Global Variable Definitions"; nl(Out);
989 printVariableBody(gv);
Chris Lattnercdfb3022009-12-14 19:34:32 +0000990 } else {
991 nl(Out) << "// Constant Definitions"; nl(Out);
992 printConstant(Init);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000993 }
994 }
995 }
996
997 void CppWriter::printVariableHead(const GlobalVariable *GV) {
998 nl(Out) << "GlobalVariable* " << getCppName(GV);
999 if (is_inline) {
Owen Anderson267a0ff2009-08-14 17:41:33 +00001000 Out << " = mod->getGlobalVariable(getGlobalContext(), ";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001001 printEscapedString(GV->getName());
1002 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
1003 nl(Out) << "if (!" << getCppName(GV) << ") {";
1004 in(); nl(Out) << getCppName(GV);
1005 }
Owen Anderson267a0ff2009-08-14 17:41:33 +00001006 Out << " = new GlobalVariable(/*Module=*/*mod, ";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001007 nl(Out) << "/*Type=*/";
1008 printCppName(GV->getType()->getElementType());
1009 Out << ",";
1010 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
1011 Out << ",";
1012 nl(Out) << "/*Linkage=*/";
1013 printLinkageType(GV->getLinkage());
1014 Out << ",";
1015 nl(Out) << "/*Initializer=*/0, ";
1016 if (GV->hasInitializer()) {
1017 Out << "// has initializer, specified below";
1018 }
1019 nl(Out) << "/*Name=*/\"";
1020 printEscapedString(GV->getName());
Owen Anderson16a412e2009-07-10 16:42:19 +00001021 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001022 nl(Out);
1023
1024 if (GV->hasSection()) {
1025 printCppName(GV);
1026 Out << "->setSection(\"";
1027 printEscapedString(GV->getSection());
1028 Out << "\");";
1029 nl(Out);
1030 }
1031 if (GV->getAlignment()) {
1032 printCppName(GV);
1033 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1034 nl(Out);
1035 }
1036 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1037 printCppName(GV);
1038 Out << "->setVisibility(";
1039 printVisibilityType(GV->getVisibility());
1040 Out << ");";
1041 nl(Out);
1042 }
1043 if (is_inline) {
1044 out(); Out << "}"; nl(Out);
1045 }
1046 }
1047
1048 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1049 if (GV->hasInitializer()) {
1050 printCppName(GV);
1051 Out << "->setInitializer(";
1052 Out << getCppName(GV->getInitializer()) << ");";
1053 nl(Out);
1054 }
1055 }
1056
1057 std::string CppWriter::getOpName(Value* V) {
1058 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1059 return getCppName(V);
1060
1061 // See if its alread in the map of forward references, if so just return the
1062 // name we already set up for it
1063 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1064 if (I != ForwardRefs.end())
1065 return I->second;
1066
1067 // This is a new forward reference. Generate a unique name for it
1068 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1069
1070 // Yes, this is a hack. An Argument is the smallest instantiable value that
1071 // we can make as a placeholder for the real value. We'll replace these
1072 // Argument instances later.
1073 Out << "Argument* " << result << " = new Argument("
1074 << getCppName(V->getType()) << ");";
1075 nl(Out);
1076 ForwardRefs[V] = result;
1077 return result;
1078 }
1079
1080 // printInstruction - This member is called for each Instruction in a function.
1081 void CppWriter::printInstruction(const Instruction *I,
1082 const std::string& bbname) {
1083 std::string iName(getCppName(I));
1084
1085 // Before we emit this instruction, we need to take care of generating any
1086 // forward references. So, we get the names of all the operands in advance
1087 std::string* opNames = new std::string[I->getNumOperands()];
1088 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1089 opNames[i] = getOpName(I->getOperand(i));
1090 }
1091
1092 switch (I->getOpcode()) {
Dan Gohman26825a82008-06-09 14:09:13 +00001093 default:
1094 error("Invalid instruction");
1095 break;
1096
Anton Korobeynikov50276522008-04-23 22:29:24 +00001097 case Instruction::Ret: {
1098 const ReturnInst* ret = cast<ReturnInst>(I);
Owen Anderson267a0ff2009-08-14 17:41:33 +00001099 Out << "ReturnInst::Create(getGlobalContext(), "
Anton Korobeynikov50276522008-04-23 22:29:24 +00001100 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1101 break;
1102 }
1103 case Instruction::Br: {
1104 const BranchInst* br = cast<BranchInst>(I);
1105 Out << "BranchInst::Create(" ;
1106 if (br->getNumOperands() == 3 ) {
Anton Korobeynikovcffb5282009-05-04 19:10:38 +00001107 Out << opNames[2] << ", "
Anton Korobeynikov50276522008-04-23 22:29:24 +00001108 << opNames[1] << ", "
Anton Korobeynikovcffb5282009-05-04 19:10:38 +00001109 << opNames[0] << ", ";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001110
1111 } else if (br->getNumOperands() == 1) {
1112 Out << opNames[0] << ", ";
1113 } else {
1114 error("Branch with 2 operands?");
1115 }
1116 Out << bbname << ");";
1117 break;
1118 }
1119 case Instruction::Switch: {
Chris Lattner627b4702009-10-27 21:24:48 +00001120 const SwitchInst *SI = cast<SwitchInst>(I);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001121 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1122 << opNames[0] << ", "
1123 << opNames[1] << ", "
Chris Lattner627b4702009-10-27 21:24:48 +00001124 << SI->getNumCases() << ", " << bbname << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001125 nl(Out);
Chris Lattner627b4702009-10-27 21:24:48 +00001126 for (unsigned i = 2; i != SI->getNumOperands(); i += 2) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001127 Out << iName << "->addCase("
1128 << opNames[i] << ", "
1129 << opNames[i+1] << ");";
1130 nl(Out);
1131 }
1132 break;
1133 }
Chris Lattnerab21db72009-10-28 00:19:10 +00001134 case Instruction::IndirectBr: {
1135 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1136 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
Chris Lattner627b4702009-10-27 21:24:48 +00001137 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1138 nl(Out);
1139 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1140 Out << iName << "->addDestination(" << opNames[i] << ");";
1141 nl(Out);
1142 }
1143 break;
1144 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001145 case Instruction::Invoke: {
1146 const InvokeInst* inv = cast<InvokeInst>(I);
1147 Out << "std::vector<Value*> " << iName << "_params;";
1148 nl(Out);
1149 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1150 Out << iName << "_params.push_back("
1151 << opNames[i] << ");";
1152 nl(Out);
1153 }
1154 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1155 << opNames[0] << ", "
1156 << opNames[1] << ", "
1157 << opNames[2] << ", "
1158 << iName << "_params.begin(), " << iName << "_params.end(), \"";
1159 printEscapedString(inv->getName());
1160 Out << "\", " << bbname << ");";
1161 nl(Out) << iName << "->setCallingConv(";
1162 printCallingConv(inv->getCallingConv());
1163 Out << ");";
Devang Patel05988662008-09-25 21:00:45 +00001164 printAttributes(inv->getAttributes(), iName);
1165 Out << iName << "->setAttributes(" << iName << "_PAL);";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001166 nl(Out);
1167 break;
1168 }
1169 case Instruction::Unwind: {
1170 Out << "new UnwindInst("
1171 << bbname << ");";
1172 break;
1173 }
Reid Kleckner781c2b82009-08-19 22:38:37 +00001174 case Instruction::Unreachable: {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001175 Out << "new UnreachableInst("
Reid Kleckner781c2b82009-08-19 22:38:37 +00001176 << "getGlobalContext(), "
Anton Korobeynikov50276522008-04-23 22:29:24 +00001177 << bbname << ");";
1178 break;
1179 }
1180 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001181 case Instruction::FAdd:
Anton Korobeynikov50276522008-04-23 22:29:24 +00001182 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001183 case Instruction::FSub:
Anton Korobeynikov50276522008-04-23 22:29:24 +00001184 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001185 case Instruction::FMul:
Anton Korobeynikov50276522008-04-23 22:29:24 +00001186 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:{
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001198 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001199 switch (I->getOpcode()) {
1200 case Instruction::Add: Out << "Instruction::Add"; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001201 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001202 case Instruction::Sub: Out << "Instruction::Sub"; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001203 case Instruction::FSub: Out << "Instruction::FSub"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001204 case Instruction::Mul: Out << "Instruction::Mul"; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001205 case Instruction::FMul: Out << "Instruction::FMul"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001206 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: {
Anton Korobeynikovd083dfb2009-08-21 12:50:54 +00001226 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001227 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());
Anton Korobeynikovd083dfb2009-08-21 12:50:54 +00001248 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001249 break;
1250 }
1251 case Instruction::ICmp: {
Reid Kleckner781c2b82009-08-19 22:38:37 +00001252 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001253 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());
Reid Kleckner781c2b82009-08-19 22:38:37 +00001268 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001269 break;
1270 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001271 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 }
1285 case Instruction::Load:{
1286 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 << ");";
1292 break;
1293 }
1294 case Instruction::Store: {
1295 const StoreInst* store = cast<StoreInst>(I);
Anton Korobeynikovb0714db2008-11-09 02:54:13 +00001296 Out << " new StoreInst("
Anton Korobeynikov50276522008-04-23 22:29:24 +00001297 << opNames[0] << ", "
1298 << opNames[1] << ", "
1299 << (store->isVolatile() ? "true" : "false")
1300 << ", " << bbname << ");";
1301 break;
1302 }
1303 case Instruction::GetElementPtr: {
1304 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1305 if (gep->getNumOperands() <= 2) {
1306 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1307 << opNames[0];
1308 if (gep->getNumOperands() == 2)
1309 Out << ", " << opNames[1];
1310 } else {
1311 Out << "std::vector<Value*> " << iName << "_indices;";
1312 nl(Out);
1313 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1314 Out << iName << "_indices.push_back("
1315 << opNames[i] << ");";
1316 nl(Out);
1317 }
1318 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1319 << opNames[0] << ", " << iName << "_indices.begin(), "
1320 << iName << "_indices.end()";
1321 }
1322 Out << ", \"";
1323 printEscapedString(gep->getName());
1324 Out << "\", " << bbname << ");";
1325 break;
1326 }
1327 case Instruction::PHI: {
1328 const PHINode* phi = cast<PHINode>(I);
1329
1330 Out << "PHINode* " << iName << " = PHINode::Create("
1331 << getCppName(phi->getType()) << ", \"";
1332 printEscapedString(phi->getName());
1333 Out << "\", " << bbname << ");";
1334 nl(Out) << iName << "->reserveOperandSpace("
1335 << phi->getNumIncomingValues()
1336 << ");";
1337 nl(Out);
1338 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1339 Out << iName << "->addIncoming("
1340 << opNames[i] << ", " << opNames[i+1] << ");";
1341 nl(Out);
1342 }
1343 break;
1344 }
1345 case Instruction::Trunc:
1346 case Instruction::ZExt:
1347 case Instruction::SExt:
1348 case Instruction::FPTrunc:
1349 case Instruction::FPExt:
1350 case Instruction::FPToUI:
1351 case Instruction::FPToSI:
1352 case Instruction::UIToFP:
1353 case Instruction::SIToFP:
1354 case Instruction::PtrToInt:
1355 case Instruction::IntToPtr:
1356 case Instruction::BitCast: {
1357 const CastInst* cst = cast<CastInst>(I);
1358 Out << "CastInst* " << iName << " = new ";
1359 switch (I->getOpcode()) {
1360 case Instruction::Trunc: Out << "TruncInst"; break;
1361 case Instruction::ZExt: Out << "ZExtInst"; break;
1362 case Instruction::SExt: Out << "SExtInst"; break;
1363 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1364 case Instruction::FPExt: Out << "FPExtInst"; break;
1365 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1366 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1367 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1368 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1369 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1370 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1371 case Instruction::BitCast: Out << "BitCastInst"; break;
1372 default: assert(!"Unreachable"); break;
1373 }
1374 Out << "(" << opNames[0] << ", "
1375 << getCppName(cst->getType()) << ", \"";
1376 printEscapedString(cst->getName());
1377 Out << "\", " << bbname << ");";
1378 break;
1379 }
1380 case Instruction::Call:{
1381 const CallInst* call = cast<CallInst>(I);
Gabor Greif0c8f7dc2009-03-25 06:32:59 +00001382 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001383 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1384 << getCppName(ila->getFunctionType()) << ", \""
1385 << ila->getAsmString() << "\", \""
1386 << ila->getConstraintString() << "\","
1387 << (ila->hasSideEffects() ? "true" : "false") << ");";
1388 nl(Out);
1389 }
1390 if (call->getNumOperands() > 2) {
1391 Out << "std::vector<Value*> " << iName << "_params;";
1392 nl(Out);
1393 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1394 Out << iName << "_params.push_back(" << opNames[i] << ");";
1395 nl(Out);
1396 }
1397 Out << "CallInst* " << iName << " = CallInst::Create("
1398 << opNames[0] << ", " << iName << "_params.begin(), "
1399 << iName << "_params.end(), \"";
1400 } else if (call->getNumOperands() == 2) {
1401 Out << "CallInst* " << iName << " = CallInst::Create("
1402 << opNames[0] << ", " << opNames[1] << ", \"";
1403 } else {
1404 Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
1405 << ", \"";
1406 }
1407 printEscapedString(call->getName());
1408 Out << "\", " << bbname << ");";
1409 nl(Out) << iName << "->setCallingConv(";
1410 printCallingConv(call->getCallingConv());
1411 Out << ");";
1412 nl(Out) << iName << "->setTailCall("
1413 << (call->isTailCall() ? "true":"false");
1414 Out << ");";
Devang Patel05988662008-09-25 21:00:45 +00001415 printAttributes(call->getAttributes(), iName);
1416 Out << iName << "->setAttributes(" << iName << "_PAL);";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001417 nl(Out);
1418 break;
1419 }
1420 case Instruction::Select: {
1421 const SelectInst* sel = cast<SelectInst>(I);
1422 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1423 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1424 printEscapedString(sel->getName());
1425 Out << "\", " << bbname << ");";
1426 break;
1427 }
1428 case Instruction::UserOp1:
1429 /// FALL THROUGH
1430 case Instruction::UserOp2: {
1431 /// FIXME: What should be done here?
1432 break;
1433 }
1434 case Instruction::VAArg: {
1435 const VAArgInst* va = cast<VAArgInst>(I);
1436 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1437 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1438 printEscapedString(va->getName());
1439 Out << "\", " << bbname << ");";
1440 break;
1441 }
1442 case Instruction::ExtractElement: {
1443 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1444 Out << "ExtractElementInst* " << getCppName(eei)
1445 << " = new ExtractElementInst(" << opNames[0]
1446 << ", " << opNames[1] << ", \"";
1447 printEscapedString(eei->getName());
1448 Out << "\", " << bbname << ");";
1449 break;
1450 }
1451 case Instruction::InsertElement: {
1452 const InsertElementInst* iei = cast<InsertElementInst>(I);
1453 Out << "InsertElementInst* " << getCppName(iei)
1454 << " = InsertElementInst::Create(" << opNames[0]
1455 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1456 printEscapedString(iei->getName());
1457 Out << "\", " << bbname << ");";
1458 break;
1459 }
1460 case Instruction::ShuffleVector: {
1461 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1462 Out << "ShuffleVectorInst* " << getCppName(svi)
1463 << " = new ShuffleVectorInst(" << opNames[0]
1464 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1465 printEscapedString(svi->getName());
1466 Out << "\", " << bbname << ");";
1467 break;
1468 }
Dan Gohman75146a62008-06-09 14:12:10 +00001469 case Instruction::ExtractValue: {
1470 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1471 Out << "std::vector<unsigned> " << iName << "_indices;";
1472 nl(Out);
1473 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1474 Out << iName << "_indices.push_back("
1475 << evi->idx_begin()[i] << ");";
1476 nl(Out);
1477 }
1478 Out << "ExtractValueInst* " << getCppName(evi)
1479 << " = ExtractValueInst::Create(" << opNames[0]
1480 << ", "
1481 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1482 printEscapedString(evi->getName());
1483 Out << "\", " << bbname << ");";
1484 break;
1485 }
1486 case Instruction::InsertValue: {
1487 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1488 Out << "std::vector<unsigned> " << iName << "_indices;";
1489 nl(Out);
1490 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1491 Out << iName << "_indices.push_back("
1492 << ivi->idx_begin()[i] << ");";
1493 nl(Out);
1494 }
1495 Out << "InsertValueInst* " << getCppName(ivi)
1496 << " = InsertValueInst::Create(" << opNames[0]
1497 << ", " << opNames[1] << ", "
1498 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1499 printEscapedString(ivi->getName());
1500 Out << "\", " << bbname << ");";
1501 break;
1502 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001503 }
1504 DefinedValues.insert(I);
1505 nl(Out);
1506 delete [] opNames;
1507}
1508
1509 // Print out the types, constants and declarations needed by one function
1510 void CppWriter::printFunctionUses(const Function* F) {
1511 nl(Out) << "// Type Definitions"; nl(Out);
1512 if (!is_inline) {
1513 // Print the function's return type
1514 printType(F->getReturnType());
1515
1516 // Print the function's function type
1517 printType(F->getFunctionType());
1518
1519 // Print the types of each of the function's arguments
1520 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1521 AI != AE; ++AI) {
1522 printType(AI->getType());
1523 }
1524 }
1525
1526 // Print type definitions for every type referenced by an instruction and
1527 // make a note of any global values or constants that are referenced
1528 SmallPtrSet<GlobalValue*,64> gvs;
1529 SmallPtrSet<Constant*,64> consts;
1530 for (Function::const_iterator BB = F->begin(), BE = F->end();
1531 BB != BE; ++BB){
1532 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1533 I != E; ++I) {
1534 // Print the type of the instruction itself
1535 printType(I->getType());
1536
1537 // Print the type of each of the instruction's operands
1538 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1539 Value* operand = I->getOperand(i);
1540 printType(operand->getType());
1541
1542 // If the operand references a GVal or Constant, make a note of it
1543 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1544 gvs.insert(GV);
1545 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1546 if (GVar->hasInitializer())
1547 consts.insert(GVar->getInitializer());
1548 } else if (Constant* C = dyn_cast<Constant>(operand))
1549 consts.insert(C);
1550 }
1551 }
1552 }
1553
1554 // Print the function declarations for any functions encountered
1555 nl(Out) << "// Function Declarations"; nl(Out);
1556 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1557 I != E; ++I) {
1558 if (Function* Fun = dyn_cast<Function>(*I)) {
1559 if (!is_inline || Fun != F)
1560 printFunctionHead(Fun);
1561 }
1562 }
1563
1564 // Print the global variable declarations for any variables encountered
1565 nl(Out) << "// Global Variable Declarations"; nl(Out);
1566 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1567 I != E; ++I) {
1568 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1569 printVariableHead(F);
1570 }
1571
1572 // Print the constants found
1573 nl(Out) << "// Constant Definitions"; nl(Out);
1574 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1575 E = consts.end(); I != E; ++I) {
1576 printConstant(*I);
1577 }
1578
1579 // Process the global variables definitions now that all the constants have
1580 // been emitted. These definitions just couple the gvars with their constant
1581 // initializers.
1582 nl(Out) << "// Global Variable Definitions"; nl(Out);
1583 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1584 I != E; ++I) {
1585 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1586 printVariableBody(GV);
1587 }
1588 }
1589
1590 void CppWriter::printFunctionHead(const Function* F) {
1591 nl(Out) << "Function* " << getCppName(F);
1592 if (is_inline) {
1593 Out << " = mod->getFunction(\"";
1594 printEscapedString(F->getName());
1595 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1596 nl(Out) << "if (!" << getCppName(F) << ") {";
1597 nl(Out) << getCppName(F);
1598 }
1599 Out<< " = Function::Create(";
1600 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1601 nl(Out) << "/*Linkage=*/";
1602 printLinkageType(F->getLinkage());
1603 Out << ",";
1604 nl(Out) << "/*Name=*/\"";
1605 printEscapedString(F->getName());
1606 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1607 nl(Out,-1);
1608 printCppName(F);
1609 Out << "->setCallingConv(";
1610 printCallingConv(F->getCallingConv());
1611 Out << ");";
1612 nl(Out);
1613 if (F->hasSection()) {
1614 printCppName(F);
1615 Out << "->setSection(\"" << F->getSection() << "\");";
1616 nl(Out);
1617 }
1618 if (F->getAlignment()) {
1619 printCppName(F);
1620 Out << "->setAlignment(" << F->getAlignment() << ");";
1621 nl(Out);
1622 }
1623 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1624 printCppName(F);
1625 Out << "->setVisibility(";
1626 printVisibilityType(F->getVisibility());
1627 Out << ");";
1628 nl(Out);
1629 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001630 if (F->hasGC()) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001631 printCppName(F);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001632 Out << "->setGC(\"" << F->getGC() << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001633 nl(Out);
1634 }
1635 if (is_inline) {
1636 Out << "}";
1637 nl(Out);
1638 }
Devang Patel05988662008-09-25 21:00:45 +00001639 printAttributes(F->getAttributes(), getCppName(F));
Anton Korobeynikov50276522008-04-23 22:29:24 +00001640 printCppName(F);
Devang Patel05988662008-09-25 21:00:45 +00001641 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001642 nl(Out);
1643 }
1644
1645 void CppWriter::printFunctionBody(const Function *F) {
1646 if (F->isDeclaration())
1647 return; // external functions have no bodies.
1648
1649 // Clear the DefinedValues and ForwardRefs maps because we can't have
1650 // cross-function forward refs
1651 ForwardRefs.clear();
1652 DefinedValues.clear();
1653
1654 // Create all the argument values
1655 if (!is_inline) {
1656 if (!F->arg_empty()) {
1657 Out << "Function::arg_iterator args = " << getCppName(F)
1658 << "->arg_begin();";
1659 nl(Out);
1660 }
1661 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1662 AI != AE; ++AI) {
1663 Out << "Value* " << getCppName(AI) << " = args++;";
1664 nl(Out);
1665 if (AI->hasName()) {
1666 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1667 nl(Out);
1668 }
1669 }
1670 }
1671
1672 // Create all the basic blocks
1673 nl(Out);
1674 for (Function::const_iterator BI = F->begin(), BE = F->end();
1675 BI != BE; ++BI) {
1676 std::string bbname(getCppName(BI));
Owen Anderson267a0ff2009-08-14 17:41:33 +00001677 Out << "BasicBlock* " << bbname <<
1678 " = BasicBlock::Create(getGlobalContext(), \"";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001679 if (BI->hasName())
1680 printEscapedString(BI->getName());
1681 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1682 nl(Out);
1683 }
1684
1685 // Output all of its basic blocks... for the function
1686 for (Function::const_iterator BI = F->begin(), BE = F->end();
1687 BI != BE; ++BI) {
1688 std::string bbname(getCppName(BI));
1689 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1690 nl(Out);
1691
1692 // Output all of the instructions in the basic block...
1693 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1694 I != E; ++I) {
1695 printInstruction(I,bbname);
1696 }
1697 }
1698
1699 // Loop over the ForwardRefs and resolve them now that all instructions
1700 // are generated.
1701 if (!ForwardRefs.empty()) {
1702 nl(Out) << "// Resolve Forward References";
1703 nl(Out);
1704 }
1705
1706 while (!ForwardRefs.empty()) {
1707 ForwardRefMap::iterator I = ForwardRefs.begin();
1708 Out << I->second << "->replaceAllUsesWith("
1709 << getCppName(I->first) << "); delete " << I->second << ";";
1710 nl(Out);
1711 ForwardRefs.erase(I);
1712 }
1713 }
1714
1715 void CppWriter::printInline(const std::string& fname,
1716 const std::string& func) {
1717 const Function* F = TheModule->getFunction(func);
1718 if (!F) {
1719 error(std::string("Function '") + func + "' not found in input module");
1720 return;
1721 }
1722 if (F->isDeclaration()) {
1723 error(std::string("Function '") + func + "' is external!");
1724 return;
1725 }
1726 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1727 << getCppName(F);
1728 unsigned arg_count = 1;
1729 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1730 AI != AE; ++AI) {
1731 Out << ", Value* arg_" << arg_count;
1732 }
1733 Out << ") {";
1734 nl(Out);
1735 is_inline = true;
1736 printFunctionUses(F);
1737 printFunctionBody(F);
1738 is_inline = false;
1739 Out << "return " << getCppName(F->begin()) << ";";
1740 nl(Out) << "}";
1741 nl(Out);
1742 }
1743
1744 void CppWriter::printModuleBody() {
1745 // Print out all the type definitions
1746 nl(Out) << "// Type Definitions"; nl(Out);
1747 printTypes(TheModule);
1748
1749 // Functions can call each other and global variables can reference them so
1750 // define all the functions first before emitting their function bodies.
1751 nl(Out) << "// Function Declarations"; nl(Out);
1752 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1753 I != E; ++I)
1754 printFunctionHead(I);
1755
1756 // Process the global variables declarations. We can't initialze them until
1757 // after the constants are printed so just print a header for each global
1758 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1759 for (Module::const_global_iterator I = TheModule->global_begin(),
1760 E = TheModule->global_end(); I != E; ++I) {
1761 printVariableHead(I);
1762 }
1763
1764 // Print out all the constants definitions. Constants don't recurse except
1765 // through GlobalValues. All GlobalValues have been declared at this point
1766 // so we can proceed to generate the constants.
1767 nl(Out) << "// Constant Definitions"; nl(Out);
1768 printConstants(TheModule);
1769
1770 // Process the global variables definitions now that all the constants have
1771 // been emitted. These definitions just couple the gvars with their constant
1772 // initializers.
1773 nl(Out) << "// Global Variable Definitions"; nl(Out);
1774 for (Module::const_global_iterator I = TheModule->global_begin(),
1775 E = TheModule->global_end(); I != E; ++I) {
1776 printVariableBody(I);
1777 }
1778
1779 // Finally, we can safely put out all of the function bodies.
1780 nl(Out) << "// Function Definitions"; nl(Out);
1781 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1782 I != E; ++I) {
1783 if (!I->isDeclaration()) {
1784 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1785 << ")";
1786 nl(Out) << "{";
1787 nl(Out,1);
1788 printFunctionBody(I);
1789 nl(Out,-1) << "}";
1790 nl(Out);
1791 }
1792 }
1793 }
1794
1795 void CppWriter::printProgram(const std::string& fname,
1796 const std::string& mName) {
Owen Anderson267a0ff2009-08-14 17:41:33 +00001797 Out << "#include <llvm/LLVMContext.h>\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001798 Out << "#include <llvm/Module.h>\n";
1799 Out << "#include <llvm/DerivedTypes.h>\n";
1800 Out << "#include <llvm/Constants.h>\n";
1801 Out << "#include <llvm/GlobalVariable.h>\n";
1802 Out << "#include <llvm/Function.h>\n";
1803 Out << "#include <llvm/CallingConv.h>\n";
1804 Out << "#include <llvm/BasicBlock.h>\n";
1805 Out << "#include <llvm/Instructions.h>\n";
1806 Out << "#include <llvm/InlineAsm.h>\n";
David Greene71847812009-07-14 20:18:05 +00001807 Out << "#include <llvm/Support/FormattedStream.h>\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001808 Out << "#include <llvm/Support/MathExtras.h>\n";
1809 Out << "#include <llvm/Pass.h>\n";
1810 Out << "#include <llvm/PassManager.h>\n";
Nicolas Geoffray9474ede2008-05-14 07:52:03 +00001811 Out << "#include <llvm/ADT/SmallVector.h>\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001812 Out << "#include <llvm/Analysis/Verifier.h>\n";
1813 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1814 Out << "#include <algorithm>\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001815 Out << "using namespace llvm;\n\n";
1816 Out << "Module* " << fname << "();\n\n";
1817 Out << "int main(int argc, char**argv) {\n";
1818 Out << " Module* Mod = " << fname << "();\n";
1819 Out << " verifyModule(*Mod, PrintMessageAction);\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001820 Out << " PassManager PM;\n";
Dan Gohmanf9231292008-12-08 07:07:24 +00001821 Out << " PM.add(createPrintModulePass(&outs()));\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001822 Out << " PM.run(*Mod);\n";
1823 Out << " return 0;\n";
1824 Out << "}\n\n";
1825 printModule(fname,mName);
1826 }
1827
1828 void CppWriter::printModule(const std::string& fname,
1829 const std::string& mName) {
1830 nl(Out) << "Module* " << fname << "() {";
1831 nl(Out,1) << "// Module Construction";
Nick Lewyckyb8b73472009-06-26 04:33:37 +00001832 nl(Out) << "Module* mod = new Module(\"";
1833 printEscapedString(mName);
Owen Anderson267a0ff2009-08-14 17:41:33 +00001834 Out << "\", getGlobalContext());";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001835 if (!TheModule->getTargetTriple().empty()) {
1836 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1837 }
1838 if (!TheModule->getTargetTriple().empty()) {
1839 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1840 << "\");";
1841 }
1842
1843 if (!TheModule->getModuleInlineAsm().empty()) {
1844 nl(Out) << "mod->setModuleInlineAsm(\"";
1845 printEscapedString(TheModule->getModuleInlineAsm());
1846 Out << "\");";
1847 }
1848 nl(Out);
1849
1850 // Loop over the dependent libraries and emit them.
1851 Module::lib_iterator LI = TheModule->lib_begin();
1852 Module::lib_iterator LE = TheModule->lib_end();
1853 while (LI != LE) {
1854 Out << "mod->addLibrary(\"" << *LI << "\");";
1855 nl(Out);
1856 ++LI;
1857 }
1858 printModuleBody();
1859 nl(Out) << "return mod;";
1860 nl(Out,-1) << "}";
1861 nl(Out);
1862 }
1863
1864 void CppWriter::printContents(const std::string& fname,
1865 const std::string& mName) {
1866 Out << "\nModule* " << fname << "(Module *mod) {\n";
Nick Lewyckyb8b73472009-06-26 04:33:37 +00001867 Out << "\nmod->setModuleIdentifier(\"";
1868 printEscapedString(mName);
1869 Out << "\");\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001870 printModuleBody();
1871 Out << "\nreturn mod;\n";
1872 Out << "\n}\n";
1873 }
1874
1875 void CppWriter::printFunction(const std::string& fname,
1876 const std::string& funcName) {
1877 const Function* F = TheModule->getFunction(funcName);
1878 if (!F) {
1879 error(std::string("Function '") + funcName + "' not found in input module");
1880 return;
1881 }
1882 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1883 printFunctionUses(F);
1884 printFunctionHead(F);
1885 printFunctionBody(F);
1886 Out << "return " << getCppName(F) << ";\n";
1887 Out << "}\n";
1888 }
1889
1890 void CppWriter::printFunctions() {
1891 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1892 Module::const_iterator I = funcs.begin();
1893 Module::const_iterator IE = funcs.end();
1894
1895 for (; I != IE; ++I) {
1896 const Function &func = *I;
1897 if (!func.isDeclaration()) {
1898 std::string name("define_");
1899 name += func.getName();
1900 printFunction(name, func.getName());
1901 }
1902 }
1903 }
1904
1905 void CppWriter::printVariable(const std::string& fname,
1906 const std::string& varName) {
1907 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1908
1909 if (!GV) {
1910 error(std::string("Variable '") + varName + "' not found in input module");
1911 return;
1912 }
1913 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1914 printVariableUses(GV);
1915 printVariableHead(GV);
1916 printVariableBody(GV);
1917 Out << "return " << getCppName(GV) << ";\n";
1918 Out << "}\n";
1919 }
1920
1921 void CppWriter::printType(const std::string& fname,
1922 const std::string& typeName) {
1923 const Type* Ty = TheModule->getTypeByName(typeName);
1924 if (!Ty) {
1925 error(std::string("Type '") + typeName + "' not found in input module");
1926 return;
1927 }
1928 Out << "\nType* " << fname << "(Module *mod) {\n";
1929 printType(Ty);
1930 Out << "return " << getCppName(Ty) << ";\n";
1931 Out << "}\n";
1932 }
1933
1934 bool CppWriter::runOnModule(Module &M) {
1935 TheModule = &M;
1936
1937 // Emit a header
1938 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1939
1940 // Get the name of the function we're supposed to generate
1941 std::string fname = FuncName.getValue();
1942
1943 // Get the name of the thing we are to generate
1944 std::string tgtname = NameToGenerate.getValue();
1945 if (GenerationType == GenModule ||
1946 GenerationType == GenContents ||
1947 GenerationType == GenProgram ||
1948 GenerationType == GenFunctions) {
1949 if (tgtname == "!bad!") {
1950 if (M.getModuleIdentifier() == "-")
1951 tgtname = "<stdin>";
1952 else
1953 tgtname = M.getModuleIdentifier();
1954 }
1955 } else if (tgtname == "!bad!")
1956 error("You must use the -for option with -gen-{function,variable,type}");
1957
1958 switch (WhatToGenerate(GenerationType)) {
1959 case GenProgram:
1960 if (fname.empty())
1961 fname = "makeLLVMModule";
1962 printProgram(fname,tgtname);
1963 break;
1964 case GenModule:
1965 if (fname.empty())
1966 fname = "makeLLVMModule";
1967 printModule(fname,tgtname);
1968 break;
1969 case GenContents:
1970 if (fname.empty())
1971 fname = "makeLLVMModuleContents";
1972 printContents(fname,tgtname);
1973 break;
1974 case GenFunction:
1975 if (fname.empty())
1976 fname = "makeLLVMFunction";
1977 printFunction(fname,tgtname);
1978 break;
1979 case GenFunctions:
1980 printFunctions();
1981 break;
1982 case GenInline:
1983 if (fname.empty())
1984 fname = "makeLLVMInline";
1985 printInline(fname,tgtname);
1986 break;
1987 case GenVariable:
1988 if (fname.empty())
1989 fname = "makeLLVMVariable";
1990 printVariable(fname,tgtname);
1991 break;
1992 case GenType:
1993 if (fname.empty())
1994 fname = "makeLLVMType";
1995 printType(fname,tgtname);
1996 break;
1997 default:
1998 error("Invalid generation option");
1999 }
2000
2001 return false;
2002 }
2003}
2004
2005char CppWriter::ID = 0;
2006
2007//===----------------------------------------------------------------------===//
2008// External Interface declaration
2009//===----------------------------------------------------------------------===//
2010
2011bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
David Greene71847812009-07-14 20:18:05 +00002012 formatted_raw_ostream &o,
Anton Korobeynikov50276522008-04-23 22:29:24 +00002013 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +00002014 CodeGenOpt::Level OptLevel) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00002015 if (FileType != TargetMachine::AssemblyFile) return true;
2016 PM.add(new CppWriter(o));
2017 return false;
2018}