blob: f4ed2a460a5fa80ef50deca1956d7e837d8b9841 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- CppWriter.cpp - Printing LLVM IR as a C++ Source File -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5f5a5732007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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 "llvm/CallingConv.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/InlineAsm.h"
19#include "llvm/Instruction.h"
20#include "llvm/Instructions.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000021#include "llvm/Module.h"
22#include "llvm/TypeSymbolTable.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/CFG.h"
28#include "llvm/Support/ManagedStatic.h"
29#include "llvm/Support/MathExtras.h"
30#include "llvm/Config/config.h"
31#include <algorithm>
32#include <iostream>
33#include <set>
34
35using namespace llvm;
36
37static cl::opt<std::string>
38FuncName("funcname", cl::desc("Specify the name of the generated function"),
39 cl::value_desc("function name"));
40
41enum WhatToGenerate {
42 GenProgram,
43 GenModule,
44 GenContents,
45 GenFunction,
Chris Lattner0366a6d2007-11-13 18:22:33 +000046 GenFunctions,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047 GenInline,
48 GenVariable,
49 GenType
50};
51
52static cl::opt<WhatToGenerate> GenerationType(cl::Optional,
53 cl::desc("Choose what kind of output to generate"),
54 cl::init(GenProgram),
55 cl::values(
Chris Lattner0366a6d2007-11-13 18:22:33 +000056 clEnumValN(GenProgram, "gen-program", "Generate a complete program"),
57 clEnumValN(GenModule, "gen-module", "Generate a module definition"),
58 clEnumValN(GenContents, "gen-contents", "Generate contents of a module"),
59 clEnumValN(GenFunction, "gen-function", "Generate a function definition"),
60 clEnumValN(GenFunctions,"gen-functions", "Generate all function definitions"),
61 clEnumValN(GenInline, "gen-inline", "Generate an inline function"),
62 clEnumValN(GenVariable, "gen-variable", "Generate a variable definition"),
63 clEnumValN(GenType, "gen-type", "Generate a type definition"),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000064 clEnumValEnd
65 )
66);
67
68static cl::opt<std::string> NameToGenerate("for", cl::Optional,
69 cl::desc("Specify the name of the thing to generate"),
70 cl::init("!bad!"));
71
72namespace {
73typedef std::vector<const Type*> TypeList;
74typedef std::map<const Type*,std::string> TypeMap;
75typedef std::map<const Value*,std::string> ValueMap;
76typedef std::set<std::string> NameSet;
77typedef std::set<const Type*> TypeSet;
78typedef std::set<const Value*> ValueSet;
79typedef std::map<const Value*,std::string> ForwardRefMap;
80
81class CppWriter {
82 const char* progname;
83 std::ostream &Out;
84 const Module *TheModule;
85 uint64_t uniqueNum;
86 TypeMap TypeNames;
87 ValueMap ValueNames;
88 TypeMap UnresolvedTypes;
89 TypeList TypeStack;
90 NameSet UsedNames;
91 TypeSet DefinedTypes;
92 ValueSet DefinedValues;
93 ForwardRefMap ForwardRefs;
94 bool is_inline;
95
96public:
97 inline CppWriter(std::ostream &o, const Module *M, const char* pn="llvm2cpp")
98 : progname(pn), Out(o), TheModule(M), uniqueNum(0), TypeNames(),
99 ValueNames(), UnresolvedTypes(), TypeStack(), is_inline(false) { }
100
101 const Module* getModule() { return TheModule; }
102
103 void printProgram(const std::string& fname, const std::string& modName );
104 void printModule(const std::string& fname, const std::string& modName );
105 void printContents(const std::string& fname, const std::string& modName );
106 void printFunction(const std::string& fname, const std::string& funcName );
Chris Lattner0366a6d2007-11-13 18:22:33 +0000107 void printFunctions();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108 void printInline(const std::string& fname, const std::string& funcName );
109 void printVariable(const std::string& fname, const std::string& varName );
110 void printType(const std::string& fname, const std::string& typeName );
111
112 void error(const std::string& msg);
113
114private:
115 void printLinkageType(GlobalValue::LinkageTypes LT);
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000116 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000117 void printCallingConv(unsigned cc);
118 void printEscapedString(const std::string& str);
119 void printCFP(const ConstantFP* CFP);
120
121 std::string getCppName(const Type* val);
122 inline void printCppName(const Type* val);
123
124 std::string getCppName(const Value* val);
125 inline void printCppName(const Value* val);
126
Chris Lattner1c8733e2008-03-12 17:45:29 +0000127 void printParamAttrs(const PAListPtr &PAL, const std::string &name);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000128 bool printTypeInternal(const Type* Ty);
129 inline void printType(const Type* Ty);
130 void printTypes(const Module* M);
131
132 void printConstant(const Constant *CPV);
133 void printConstants(const Module* M);
134
135 void printVariableUses(const GlobalVariable *GV);
136 void printVariableHead(const GlobalVariable *GV);
137 void printVariableBody(const GlobalVariable *GV);
138
139 void printFunctionUses(const Function *F);
140 void printFunctionHead(const Function *F);
141 void printFunctionBody(const Function *F);
142 void printInstruction(const Instruction *I, const std::string& bbname);
143 std::string getOpName(Value*);
144
145 void printModuleBody();
146
147};
148
149static unsigned indent_level = 0;
150inline std::ostream& nl(std::ostream& Out, int delta = 0) {
151 Out << "\n";
152 if (delta >= 0 || indent_level >= unsigned(-delta))
153 indent_level += delta;
154 for (unsigned i = 0; i < indent_level; ++i)
155 Out << " ";
156 return Out;
157}
158
159inline void in() { indent_level++; }
160inline void out() { if (indent_level >0) indent_level--; }
161
162inline void
163sanitize(std::string& str) {
164 for (size_t i = 0; i < str.length(); ++i)
165 if (!isalnum(str[i]) && str[i] != '_')
166 str[i] = '_';
167}
168
169inline std::string
170getTypePrefix(const Type* Ty ) {
171 switch (Ty->getTypeID()) {
172 case Type::VoidTyID: return "void_";
173 case Type::IntegerTyID:
174 return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
175 "_";
176 case Type::FloatTyID: return "float_";
177 case Type::DoubleTyID: return "double_";
178 case Type::LabelTyID: return "label_";
179 case Type::FunctionTyID: return "func_";
180 case Type::StructTyID: return "struct_";
181 case Type::ArrayTyID: return "array_";
182 case Type::PointerTyID: return "ptr_";
183 case Type::VectorTyID: return "packed_";
184 case Type::OpaqueTyID: return "opaque_";
185 default: return "other_";
186 }
187 return "unknown_";
188}
189
190// Looks up the type in the symbol table and returns a pointer to its name or
191// a null pointer if it wasn't found. Note that this isn't the same as the
192// Mode::getTypeName function which will return an empty string, not a null
193// pointer if the name is not found.
194inline const std::string*
195findTypeName(const TypeSymbolTable& ST, const Type* Ty)
196{
197 TypeSymbolTable::const_iterator TI = ST.begin();
198 TypeSymbolTable::const_iterator TE = ST.end();
199 for (;TI != TE; ++TI)
200 if (TI->second == Ty)
201 return &(TI->first);
202 return 0;
203}
204
205void
206CppWriter::error(const std::string& msg) {
207 std::cerr << progname << ": " << msg << "\n";
208 exit(2);
209}
210
211// printCFP - Print a floating point constant .. very carefully :)
212// This makes sure that conversion to/from floating yields the same binary
213// result so that we don't lose precision.
214void
215CppWriter::printCFP(const ConstantFP *CFP) {
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000216 APFloat APF = APFloat(CFP->getValueAPF()); // copy
217 if (CFP->getType() == Type::FloatTy)
218 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 Out << "ConstantFP::get(";
220 if (CFP->getType() == Type::DoubleTy)
221 Out << "Type::DoubleTy, ";
222 else
223 Out << "Type::FloatTy, ";
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000224 Out << "APFloat(";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225#if HAVE_PRINTF_A
226 char Buffer[100];
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000227 sprintf(Buffer, "%A", APF.convertToDouble());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 if ((!strncmp(Buffer, "0x", 2) ||
229 !strncmp(Buffer, "-0x", 3) ||
230 !strncmp(Buffer, "+0x", 3)) &&
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000231 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232 if (CFP->getType() == Type::DoubleTy)
233 Out << "BitsToDouble(" << Buffer << ")";
234 else
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000235 Out << "BitsToFloat((float)" << Buffer << ")";
236 Out << ")";
237 } else {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238#endif
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000239 std::string StrVal = ftostr(CFP->getValueAPF());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000240
241 while (StrVal[0] == ' ')
242 StrVal.erase(StrVal.begin());
243
244 // Check to make sure that the stringized number is not some string like
245 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
246 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
247 ((StrVal[0] == '-' || StrVal[0] == '+') &&
248 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000249 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000250 if (CFP->getType() == Type::DoubleTy)
251 Out << StrVal;
252 else
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000253 Out << StrVal << "f";
254 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255 else if (CFP->getType() == Type::DoubleTy)
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000256 Out << "BitsToDouble(0x" << std::hex
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000257 << CFP->getValueAPF().convertToAPInt().getZExtValue()
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000258 << std::dec << "ULL) /* " << StrVal << " */";
259 else
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000260 Out << "BitsToFloat(0x" << std::hex
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000261 << (uint32_t)CFP->getValueAPF().convertToAPInt().getZExtValue()
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262 << std::dec << "U) /* " << StrVal << " */";
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000263 Out << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264#if HAVE_PRINTF_A
265 }
266#endif
267 Out << ")";
268}
269
270void
271CppWriter::printCallingConv(unsigned cc){
272 // 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
282void
283CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
284 switch (LT) {
285 case GlobalValue::InternalLinkage:
286 Out << "GlobalValue::InternalLinkage"; break;
287 case GlobalValue::LinkOnceLinkage:
288 Out << "GlobalValue::LinkOnceLinkage "; break;
289 case GlobalValue::WeakLinkage:
290 Out << "GlobalValue::WeakLinkage"; break;
291 case GlobalValue::AppendingLinkage:
292 Out << "GlobalValue::AppendingLinkage"; break;
293 case GlobalValue::ExternalLinkage:
294 Out << "GlobalValue::ExternalLinkage"; break;
295 case GlobalValue::DLLImportLinkage:
296 Out << "GlobalValue::DLLImportLinkage"; break;
297 case GlobalValue::DLLExportLinkage:
298 Out << "GlobalValue::DLLExportLinkage"; break;
299 case GlobalValue::ExternalWeakLinkage:
300 Out << "GlobalValue::ExternalWeakLinkage"; break;
301 case GlobalValue::GhostLinkage:
302 Out << "GlobalValue::GhostLinkage"; break;
303 }
304}
305
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000306void
307CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
308 switch (VisType) {
309 default: assert(0 && "Unknown GVar visibility");
310 case GlobalValue::DefaultVisibility:
311 Out << "GlobalValue::DefaultVisibility";
312 break;
313 case GlobalValue::HiddenVisibility:
314 Out << "GlobalValue::HiddenVisibility";
315 break;
316 case GlobalValue::ProtectedVisibility:
317 Out << "GlobalValue::ProtectedVisibility";
318 break;
319 }
320}
321
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000322// printEscapedString - Print each character of the specified string, escaping
323// it if it is not printable or if it is an escape char.
324void
325CppWriter::printEscapedString(const std::string &Str) {
326 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
327 unsigned char C = Str[i];
328 if (isprint(C) && C != '"' && C != '\\') {
329 Out << C;
330 } else {
331 Out << "\\x"
332 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
333 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
334 }
335 }
336}
337
338std::string
339CppWriter::getCppName(const Type* Ty)
340{
341 // First, handle the primitive types .. easy
342 if (Ty->isPrimitiveType() || Ty->isInteger()) {
343 switch (Ty->getTypeID()) {
344 case Type::VoidTyID: return "Type::VoidTy";
345 case Type::IntegerTyID: {
346 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
347 return "IntegerType::get(" + utostr(BitWidth) + ")";
348 }
349 case Type::FloatTyID: return "Type::FloatTy";
350 case Type::DoubleTyID: return "Type::DoubleTy";
351 case Type::LabelTyID: return "Type::LabelTy";
352 default:
353 error("Invalid primitive type");
354 break;
355 }
356 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
357 }
358
359 // Now, see if we've seen the type before and return that
360 TypeMap::iterator I = TypeNames.find(Ty);
361 if (I != TypeNames.end())
362 return I->second;
363
364 // Okay, let's build a new name for this type. Start with a prefix
365 const char* prefix = 0;
366 switch (Ty->getTypeID()) {
367 case Type::FunctionTyID: prefix = "FuncTy_"; break;
368 case Type::StructTyID: prefix = "StructTy_"; break;
369 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
370 case Type::PointerTyID: prefix = "PointerTy_"; break;
371 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
372 case Type::VectorTyID: prefix = "VectorTy_"; break;
373 default: prefix = "OtherTy_"; break; // prevent breakage
374 }
375
376 // See if the type has a name in the symboltable and build accordingly
377 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
378 std::string name;
379 if (tName)
380 name = std::string(prefix) + *tName;
381 else
382 name = std::string(prefix) + utostr(uniqueNum++);
383 sanitize(name);
384
385 // Save the name
386 return TypeNames[Ty] = name;
387}
388
389void
390CppWriter::printCppName(const Type* Ty)
391{
392 printEscapedString(getCppName(Ty));
393}
394
395std::string
396CppWriter::getCppName(const Value* val) {
397 std::string name;
398 ValueMap::iterator I = ValueNames.find(val);
399 if (I != ValueNames.end() && I->first == val)
400 return I->second;
401
402 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
403 name = std::string("gvar_") +
404 getTypePrefix(GV->getType()->getElementType());
405 } else if (isa<Function>(val)) {
406 name = std::string("func_");
407 } else if (const Constant* C = dyn_cast<Constant>(val)) {
408 name = std::string("const_") + getTypePrefix(C->getType());
409 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
410 if (is_inline) {
411 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
412 Function::const_arg_iterator(Arg)) + 1;
413 name = std::string("arg_") + utostr(argNum);
414 NameSet::iterator NI = UsedNames.find(name);
415 if (NI != UsedNames.end())
416 name += std::string("_") + utostr(uniqueNum++);
417 UsedNames.insert(name);
418 return ValueNames[val] = name;
419 } else {
420 name = getTypePrefix(val->getType());
421 }
422 } else {
423 name = getTypePrefix(val->getType());
424 }
425 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
426 sanitize(name);
427 NameSet::iterator NI = UsedNames.find(name);
428 if (NI != UsedNames.end())
429 name += std::string("_") + utostr(uniqueNum++);
430 UsedNames.insert(name);
431 return ValueNames[val] = name;
432}
433
434void
435CppWriter::printCppName(const Value* val) {
436 printEscapedString(getCppName(val));
437}
438
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000439void
Chris Lattner1c8733e2008-03-12 17:45:29 +0000440CppWriter::printParamAttrs(const PAListPtr &PAL, const std::string &name) {
441 Out << "PAListPtr " << name << "_PAL = 0;";
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000442 nl(Out);
Chris Lattner1c8733e2008-03-12 17:45:29 +0000443 if (!PAL.isEmpty()) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000444 Out << '{'; in(); nl(Out);
Chris Lattner1c8733e2008-03-12 17:45:29 +0000445 Out << "SmallVector<ParamAttrsWithIndex, 4> Attrs;"; nl(Out);
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000446 Out << "ParamAttrsWithIndex PAWI;"; nl(Out);
Chris Lattner1c8733e2008-03-12 17:45:29 +0000447 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
448 uint16_t index = PAL.getSlot(i).Index;
449 ParameterAttributes attrs = PAL.getSlot(i).Attrs;
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000450 Out << "PAWI.index = " << index << "; PAWI.attrs = 0 ";
451 if (attrs & ParamAttr::SExt)
452 Out << " | ParamAttr::SExt";
453 if (attrs & ParamAttr::ZExt)
454 Out << " | ParamAttr::ZExt";
455 if (attrs & ParamAttr::StructRet)
456 Out << " | ParamAttr::StructRet";
457 if (attrs & ParamAttr::InReg)
458 Out << " | ParamAttr::InReg";
459 if (attrs & ParamAttr::NoReturn)
460 Out << " | ParamAttr::NoReturn";
461 if (attrs & ParamAttr::NoUnwind)
462 Out << " | ParamAttr::NoUnwind";
Anton Korobeynikov7e726522008-03-29 11:15:01 +0000463 if (attrs & ParamAttr::ByVal)
464 Out << " | ParamAttr::ByVal";
Anton Korobeynikov1e2f0b42008-03-29 11:25:49 +0000465 if (attrs & ParamAttr::NoAlias)
466 Out << " | ParamAttr::NoAlias";
467 if (attrs & ParamAttr::Nest)
468 Out << " | ParamAttr::Nest";
469 if (attrs & ParamAttr::ReadNone)
470 Out << " | ParamAttr::ReadNone";
471 if (attrs & ParamAttr::ReadOnly)
472 Out << " | ParamAttr::ReadOnly";
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000473 Out << ";";
474 nl(Out);
475 Out << "Attrs.push_back(PAWI);";
476 nl(Out);
477 }
Chris Lattner1c8733e2008-03-12 17:45:29 +0000478 Out << name << "_PAL = PAListPtr::get(Attrs.begin(), Attrs.end());";
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000479 nl(Out);
480 out(); nl(Out);
481 Out << '}'; nl(Out);
482 }
483}
484
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000485bool
486CppWriter::printTypeInternal(const Type* Ty) {
487 // We don't print definitions for primitive types
488 if (Ty->isPrimitiveType() || Ty->isInteger())
489 return false;
490
491 // If we already defined this type, we don't need to define it again.
492 if (DefinedTypes.find(Ty) != DefinedTypes.end())
493 return false;
494
495 // Everything below needs the name for the type so get it now.
496 std::string typeName(getCppName(Ty));
497
498 // Search the type stack for recursion. If we find it, then generate this
499 // as an OpaqueType, but make sure not to do this multiple times because
500 // the type could appear in multiple places on the stack. Once the opaque
501 // definition is issued, it must not be re-issued. Consequently we have to
502 // check the UnresolvedTypes list as well.
503 TypeList::const_iterator TI = std::find(TypeStack.begin(),TypeStack.end(),Ty);
504 if (TI != TypeStack.end()) {
505 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
506 if (I == UnresolvedTypes.end()) {
507 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
508 nl(Out);
509 UnresolvedTypes[Ty] = typeName;
510 }
511 return true;
512 }
513
514 // We're going to print a derived type which, by definition, contains other
515 // types. So, push this one we're printing onto the type stack to assist with
516 // recursive definitions.
517 TypeStack.push_back(Ty);
518
519 // Print the type definition
520 switch (Ty->getTypeID()) {
521 case Type::FunctionTyID: {
522 const FunctionType* FT = cast<FunctionType>(Ty);
523 Out << "std::vector<const Type*>" << typeName << "_args;";
524 nl(Out);
525 FunctionType::param_iterator PI = FT->param_begin();
526 FunctionType::param_iterator PE = FT->param_end();
527 for (; PI != PE; ++PI) {
528 const Type* argTy = static_cast<const Type*>(*PI);
529 bool isForward = printTypeInternal(argTy);
530 std::string argName(getCppName(argTy));
531 Out << typeName << "_args.push_back(" << argName;
532 if (isForward)
533 Out << "_fwd";
534 Out << ");";
535 nl(Out);
536 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000537 bool isForward = printTypeInternal(FT->getReturnType());
538 std::string retTypeName(getCppName(FT->getReturnType()));
539 Out << "FunctionType* " << typeName << " = FunctionType::get(";
540 in(); nl(Out) << "/*Result=*/" << retTypeName;
541 if (isForward)
542 Out << "_fwd";
543 Out << ",";
544 nl(Out) << "/*Params=*/" << typeName << "_args,";
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000545 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000546 out();
547 nl(Out);
548 break;
549 }
550 case Type::StructTyID: {
551 const StructType* ST = cast<StructType>(Ty);
552 Out << "std::vector<const Type*>" << typeName << "_fields;";
553 nl(Out);
554 StructType::element_iterator EI = ST->element_begin();
555 StructType::element_iterator EE = ST->element_end();
556 for (; EI != EE; ++EI) {
557 const Type* fieldTy = static_cast<const Type*>(*EI);
558 bool isForward = printTypeInternal(fieldTy);
559 std::string fieldName(getCppName(fieldTy));
560 Out << typeName << "_fields.push_back(" << fieldName;
561 if (isForward)
562 Out << "_fwd";
563 Out << ");";
564 nl(Out);
565 }
566 Out << "StructType* " << typeName << " = StructType::get("
567 << typeName << "_fields, /*isPacked=*/"
568 << (ST->isPacked() ? "true" : "false") << ");";
569 nl(Out);
570 break;
571 }
572 case Type::ArrayTyID: {
573 const ArrayType* AT = cast<ArrayType>(Ty);
574 const Type* ET = AT->getElementType();
575 bool isForward = printTypeInternal(ET);
576 std::string elemName(getCppName(ET));
577 Out << "ArrayType* " << typeName << " = ArrayType::get("
578 << elemName << (isForward ? "_fwd" : "")
579 << ", " << utostr(AT->getNumElements()) << ");";
580 nl(Out);
581 break;
582 }
583 case Type::PointerTyID: {
584 const PointerType* PT = cast<PointerType>(Ty);
585 const Type* ET = PT->getElementType();
586 bool isForward = printTypeInternal(ET);
587 std::string elemName(getCppName(ET));
588 Out << "PointerType* " << typeName << " = PointerType::get("
Christopher Lambbb2f2222007-12-17 01:12:55 +0000589 << elemName << (isForward ? "_fwd" : "")
590 << ", " << utostr(PT->getAddressSpace()) << ");";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000591 nl(Out);
592 break;
593 }
594 case Type::VectorTyID: {
595 const VectorType* PT = cast<VectorType>(Ty);
596 const Type* ET = PT->getElementType();
597 bool isForward = printTypeInternal(ET);
598 std::string elemName(getCppName(ET));
599 Out << "VectorType* " << typeName << " = VectorType::get("
600 << elemName << (isForward ? "_fwd" : "")
601 << ", " << utostr(PT->getNumElements()) << ");";
602 nl(Out);
603 break;
604 }
605 case Type::OpaqueTyID: {
606 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
607 nl(Out);
608 break;
609 }
610 default:
611 error("Invalid TypeID");
612 }
613
614 // If the type had a name, make sure we recreate it.
615 const std::string* progTypeName =
616 findTypeName(TheModule->getTypeSymbolTable(),Ty);
617 if (progTypeName) {
618 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
619 << typeName << ");";
620 nl(Out);
621 }
622
623 // Pop us off the type stack
624 TypeStack.pop_back();
625
626 // Indicate that this type is now defined.
627 DefinedTypes.insert(Ty);
628
629 // Early resolve as many unresolved types as possible. Search the unresolved
630 // types map for the type we just printed. Now that its definition is complete
631 // we can resolve any previous references to it. This prevents a cascade of
632 // unresolved types.
633 TypeMap::iterator I = UnresolvedTypes.find(Ty);
634 if (I != UnresolvedTypes.end()) {
635 Out << "cast<OpaqueType>(" << I->second
636 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
637 nl(Out);
638 Out << I->second << " = cast<";
639 switch (Ty->getTypeID()) {
640 case Type::FunctionTyID: Out << "FunctionType"; break;
641 case Type::ArrayTyID: Out << "ArrayType"; break;
642 case Type::StructTyID: Out << "StructType"; break;
643 case Type::VectorTyID: Out << "VectorType"; break;
644 case Type::PointerTyID: Out << "PointerType"; break;
645 case Type::OpaqueTyID: Out << "OpaqueType"; break;
646 default: Out << "NoSuchDerivedType"; break;
647 }
648 Out << ">(" << I->second << "_fwd.get());";
649 nl(Out); nl(Out);
650 UnresolvedTypes.erase(I);
651 }
652
653 // Finally, separate the type definition from other with a newline.
654 nl(Out);
655
656 // We weren't a recursive type
657 return false;
658}
659
660// Prints a type definition. Returns true if it could not resolve all the types
661// in the definition but had to use a forward reference.
662void
663CppWriter::printType(const Type* Ty) {
664 assert(TypeStack.empty());
665 TypeStack.clear();
666 printTypeInternal(Ty);
667 assert(TypeStack.empty());
668}
669
670void
671CppWriter::printTypes(const Module* M) {
672
673 // Walk the symbol table and print out all its types
674 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
675 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
676 TI != TE; ++TI) {
677
678 // For primitive types and types already defined, just add a name
679 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
680 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
681 TNI != TypeNames.end()) {
682 Out << "mod->addTypeName(\"";
683 printEscapedString(TI->first);
684 Out << "\", " << getCppName(TI->second) << ");";
685 nl(Out);
686 // For everything else, define the type
687 } else {
688 printType(TI->second);
689 }
690 }
691
692 // Add all of the global variables to the value table...
693 for (Module::const_global_iterator I = TheModule->global_begin(),
694 E = TheModule->global_end(); I != E; ++I) {
695 if (I->hasInitializer())
696 printType(I->getInitializer()->getType());
697 printType(I->getType());
698 }
699
700 // Add all the functions to the table
701 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
702 FI != FE; ++FI) {
703 printType(FI->getReturnType());
704 printType(FI->getFunctionType());
705 // Add all the function arguments
706 for(Function::const_arg_iterator AI = FI->arg_begin(),
707 AE = FI->arg_end(); AI != AE; ++AI) {
708 printType(AI->getType());
709 }
710
711 // Add all of the basic blocks and instructions
712 for (Function::const_iterator BB = FI->begin(),
713 E = FI->end(); BB != E; ++BB) {
714 printType(BB->getType());
715 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
716 ++I) {
717 printType(I->getType());
718 for (unsigned i = 0; i < I->getNumOperands(); ++i)
719 printType(I->getOperand(i)->getType());
720 }
721 }
722 }
723}
724
725
726// printConstant - Print out a constant pool entry...
727void CppWriter::printConstant(const Constant *CV) {
728 // First, if the constant is actually a GlobalValue (variable or function) or
729 // its already in the constant list then we've printed it already and we can
730 // just return.
731 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
732 return;
733
734 std::string constName(getCppName(CV));
735 std::string typeName(getCppName(CV->getType()));
736 if (CV->isNullValue()) {
737 Out << "Constant* " << constName << " = Constant::getNullValue("
738 << typeName << ");";
739 nl(Out);
740 return;
741 }
742 if (isa<GlobalValue>(CV)) {
743 // Skip variables and functions, we emit them elsewhere
744 return;
745 }
746 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
747 Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
748 << cast<IntegerType>(CI->getType())->getBitWidth() << ", "
749 << " \"" << CI->getValue().toStringSigned(10) << "\", 10));";
750 } else if (isa<ConstantAggregateZero>(CV)) {
751 Out << "ConstantAggregateZero* " << constName
752 << " = ConstantAggregateZero::get(" << typeName << ");";
753 } else if (isa<ConstantPointerNull>(CV)) {
754 Out << "ConstantPointerNull* " << constName
755 << " = ConstanPointerNull::get(" << typeName << ");";
756 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
757 Out << "ConstantFP* " << constName << " = ";
758 printCFP(CFP);
759 Out << ";";
760 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
761 if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
762 Out << "Constant* " << constName << " = ConstantArray::get(\"";
763 std::string tmp = CA->getAsString();
764 bool nullTerminate = false;
765 if (tmp[tmp.length()-1] == 0) {
766 tmp.erase(tmp.length()-1);
767 nullTerminate = true;
768 }
769 printEscapedString(tmp);
770 // Determine if we want null termination or not.
771 if (nullTerminate)
772 Out << "\", true"; // Indicate that the null terminator should be added.
773 else
774 Out << "\", false";// No null terminator
775 Out << ");";
776 } else {
777 Out << "std::vector<Constant*> " << constName << "_elems;";
778 nl(Out);
779 unsigned N = CA->getNumOperands();
780 for (unsigned i = 0; i < N; ++i) {
781 printConstant(CA->getOperand(i)); // recurse to print operands
782 Out << constName << "_elems.push_back("
783 << getCppName(CA->getOperand(i)) << ");";
784 nl(Out);
785 }
786 Out << "Constant* " << constName << " = ConstantArray::get("
787 << typeName << ", " << constName << "_elems);";
788 }
789 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
790 Out << "std::vector<Constant*> " << constName << "_fields;";
791 nl(Out);
792 unsigned N = CS->getNumOperands();
793 for (unsigned i = 0; i < N; i++) {
794 printConstant(CS->getOperand(i));
795 Out << constName << "_fields.push_back("
796 << getCppName(CS->getOperand(i)) << ");";
797 nl(Out);
798 }
799 Out << "Constant* " << constName << " = ConstantStruct::get("
800 << typeName << ", " << constName << "_fields);";
801 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
802 Out << "std::vector<Constant*> " << constName << "_elems;";
803 nl(Out);
804 unsigned N = CP->getNumOperands();
805 for (unsigned i = 0; i < N; ++i) {
806 printConstant(CP->getOperand(i));
807 Out << constName << "_elems.push_back("
808 << getCppName(CP->getOperand(i)) << ");";
809 nl(Out);
810 }
811 Out << "Constant* " << constName << " = ConstantVector::get("
812 << typeName << ", " << constName << "_elems);";
813 } else if (isa<UndefValue>(CV)) {
814 Out << "UndefValue* " << constName << " = UndefValue::get("
815 << typeName << ");";
816 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
817 if (CE->getOpcode() == Instruction::GetElementPtr) {
818 Out << "std::vector<Constant*> " << constName << "_indices;";
819 nl(Out);
820 printConstant(CE->getOperand(0));
821 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
822 printConstant(CE->getOperand(i));
823 Out << constName << "_indices.push_back("
824 << getCppName(CE->getOperand(i)) << ");";
825 nl(Out);
826 }
827 Out << "Constant* " << constName
828 << " = ConstantExpr::getGetElementPtr("
829 << getCppName(CE->getOperand(0)) << ", "
David Greene69fc0d52007-09-04 17:15:07 +0000830 << "&" << constName << "_indices[0], "
831 << constName << "_indices.size()"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000832 << " );";
833 } else if (CE->isCast()) {
834 printConstant(CE->getOperand(0));
835 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
836 switch (CE->getOpcode()) {
837 default: assert(0 && "Invalid cast opcode");
838 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
839 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
840 case Instruction::SExt: Out << "Instruction::SExt"; break;
841 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
842 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
843 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
844 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
845 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
846 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
847 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
848 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
849 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
850 }
851 Out << ", " << getCppName(CE->getOperand(0)) << ", "
852 << getCppName(CE->getType()) << ");";
853 } else {
854 unsigned N = CE->getNumOperands();
855 for (unsigned i = 0; i < N; ++i ) {
856 printConstant(CE->getOperand(i));
857 }
858 Out << "Constant* " << constName << " = ConstantExpr::";
859 switch (CE->getOpcode()) {
860 case Instruction::Add: Out << "getAdd("; break;
861 case Instruction::Sub: Out << "getSub("; break;
862 case Instruction::Mul: Out << "getMul("; break;
863 case Instruction::UDiv: Out << "getUDiv("; break;
864 case Instruction::SDiv: Out << "getSDiv("; break;
865 case Instruction::FDiv: Out << "getFDiv("; break;
866 case Instruction::URem: Out << "getURem("; break;
867 case Instruction::SRem: Out << "getSRem("; break;
868 case Instruction::FRem: Out << "getFRem("; break;
869 case Instruction::And: Out << "getAnd("; break;
870 case Instruction::Or: Out << "getOr("; break;
871 case Instruction::Xor: Out << "getXor("; break;
872 case Instruction::ICmp:
873 Out << "getICmp(ICmpInst::ICMP_";
874 switch (CE->getPredicate()) {
875 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
876 case ICmpInst::ICMP_NE: Out << "NE"; break;
877 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
878 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
879 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
880 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
881 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
882 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
883 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
884 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
885 default: error("Invalid ICmp Predicate");
886 }
887 break;
888 case Instruction::FCmp:
889 Out << "getFCmp(FCmpInst::FCMP_";
890 switch (CE->getPredicate()) {
891 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
892 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
893 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
894 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
895 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
896 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
897 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
898 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
899 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
900 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
901 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
902 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
903 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
904 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
905 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
906 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
907 default: error("Invalid FCmp Predicate");
908 }
909 break;
910 case Instruction::Shl: Out << "getShl("; break;
911 case Instruction::LShr: Out << "getLShr("; break;
912 case Instruction::AShr: Out << "getAShr("; break;
913 case Instruction::Select: Out << "getSelect("; break;
914 case Instruction::ExtractElement: Out << "getExtractElement("; break;
915 case Instruction::InsertElement: Out << "getInsertElement("; break;
916 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
917 default:
918 error("Invalid constant expression");
919 break;
920 }
921 Out << getCppName(CE->getOperand(0));
922 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
923 Out << ", " << getCppName(CE->getOperand(i));
924 Out << ");";
925 }
926 } else {
927 error("Bad Constant");
928 Out << "Constant* " << constName << " = 0; ";
929 }
930 nl(Out);
931}
932
933void
934CppWriter::printConstants(const Module* M) {
935 // Traverse all the global variables looking for constant initializers
936 for (Module::const_global_iterator I = TheModule->global_begin(),
937 E = TheModule->global_end(); I != E; ++I)
938 if (I->hasInitializer())
939 printConstant(I->getInitializer());
940
941 // Traverse the LLVM functions looking for constants
942 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
943 FI != FE; ++FI) {
944 // Add all of the basic blocks and instructions
945 for (Function::const_iterator BB = FI->begin(),
946 E = FI->end(); BB != E; ++BB) {
947 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
948 ++I) {
949 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
950 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
951 printConstant(C);
952 }
953 }
954 }
955 }
956 }
957}
958
959void CppWriter::printVariableUses(const GlobalVariable *GV) {
960 nl(Out) << "// Type Definitions";
961 nl(Out);
962 printType(GV->getType());
963 if (GV->hasInitializer()) {
964 Constant* Init = GV->getInitializer();
965 printType(Init->getType());
966 if (Function* F = dyn_cast<Function>(Init)) {
967 nl(Out)<< "/ Function Declarations"; nl(Out);
968 printFunctionHead(F);
969 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
970 nl(Out) << "// Global Variable Declarations"; nl(Out);
971 printVariableHead(gv);
972 } else {
973 nl(Out) << "// Constant Definitions"; nl(Out);
974 printConstant(gv);
975 }
976 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
977 nl(Out) << "// Global Variable Definitions"; nl(Out);
978 printVariableBody(gv);
979 }
980 }
981}
982
983void CppWriter::printVariableHead(const GlobalVariable *GV) {
984 nl(Out) << "GlobalVariable* " << getCppName(GV);
985 if (is_inline) {
986 Out << " = mod->getGlobalVariable(";
987 printEscapedString(GV->getName());
988 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
989 nl(Out) << "if (!" << getCppName(GV) << ") {";
990 in(); nl(Out) << getCppName(GV);
991 }
992 Out << " = new GlobalVariable(";
993 nl(Out) << "/*Type=*/";
994 printCppName(GV->getType()->getElementType());
995 Out << ",";
996 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
997 Out << ",";
998 nl(Out) << "/*Linkage=*/";
999 printLinkageType(GV->getLinkage());
1000 Out << ",";
1001 nl(Out) << "/*Initializer=*/0, ";
1002 if (GV->hasInitializer()) {
1003 Out << "// has initializer, specified below";
1004 }
1005 nl(Out) << "/*Name=*/\"";
1006 printEscapedString(GV->getName());
1007 Out << "\",";
1008 nl(Out) << "mod);";
1009 nl(Out);
1010
1011 if (GV->hasSection()) {
1012 printCppName(GV);
1013 Out << "->setSection(\"";
1014 printEscapedString(GV->getSection());
1015 Out << "\");";
1016 nl(Out);
1017 }
1018 if (GV->getAlignment()) {
1019 printCppName(GV);
1020 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1021 nl(Out);
1022 };
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001023 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1024 printCppName(GV);
1025 Out << "->setVisibility(";
1026 printVisibilityType(GV->getVisibility());
1027 Out << ");";
1028 nl(Out);
1029 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001030 if (is_inline) {
1031 out(); Out << "}"; nl(Out);
1032 }
1033}
1034
1035void
1036CppWriter::printVariableBody(const GlobalVariable *GV) {
1037 if (GV->hasInitializer()) {
1038 printCppName(GV);
1039 Out << "->setInitializer(";
1040 //if (!isa<GlobalValue(GV->getInitializer()))
1041 //else
1042 Out << getCppName(GV->getInitializer()) << ");";
1043 nl(Out);
1044 }
1045}
1046
1047std::string
1048CppWriter::getOpName(Value* V) {
1049 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1050 return getCppName(V);
1051
1052 // See if its alread in the map of forward references, if so just return the
1053 // name we already set up for it
1054 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1055 if (I != ForwardRefs.end())
1056 return I->second;
1057
1058 // This is a new forward reference. Generate a unique name for it
1059 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1060
1061 // Yes, this is a hack. An Argument is the smallest instantiable value that
1062 // we can make as a placeholder for the real value. We'll replace these
1063 // Argument instances later.
1064 Out << "Argument* " << result << " = new Argument("
1065 << getCppName(V->getType()) << ");";
1066 nl(Out);
1067 ForwardRefs[V] = result;
1068 return result;
1069}
1070
1071// printInstruction - This member is called for each Instruction in a function.
1072void
1073CppWriter::printInstruction(const Instruction *I, 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 std::string* opNames = new std::string[I->getNumOperands()];
1079 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1080 opNames[i] = getOpName(I->getOperand(i));
1081 }
1082
1083 switch (I->getOpcode()) {
1084 case Instruction::Ret: {
1085 const ReturnInst* ret = cast<ReturnInst>(I);
1086 Out << "new ReturnInst("
1087 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1088 break;
1089 }
1090 case Instruction::Br: {
1091 const BranchInst* br = cast<BranchInst>(I);
1092 Out << "new BranchInst(" ;
1093 if (br->getNumOperands() == 3 ) {
1094 Out << opNames[0] << ", "
1095 << opNames[1] << ", "
1096 << opNames[2] << ", ";
1097
1098 } else if (br->getNumOperands() == 1) {
1099 Out << opNames[0] << ", ";
1100 } else {
1101 error("Branch with 2 operands?");
1102 }
1103 Out << bbname << ");";
1104 break;
1105 }
1106 case Instruction::Switch: {
1107 const SwitchInst* sw = cast<SwitchInst>(I);
1108 Out << "SwitchInst* " << iName << " = new SwitchInst("
1109 << opNames[0] << ", "
1110 << opNames[1] << ", "
1111 << sw->getNumCases() << ", " << bbname << ");";
1112 nl(Out);
1113 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1114 Out << iName << "->addCase("
1115 << opNames[i] << ", "
1116 << opNames[i+1] << ");";
1117 nl(Out);
1118 }
1119 break;
1120 }
1121 case Instruction::Invoke: {
1122 const InvokeInst* inv = cast<InvokeInst>(I);
1123 Out << "std::vector<Value*> " << iName << "_params;";
1124 nl(Out);
1125 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1126 Out << iName << "_params.push_back("
1127 << opNames[i] << ");";
1128 nl(Out);
1129 }
1130 Out << "InvokeInst *" << iName << " = new InvokeInst("
1131 << opNames[0] << ", "
1132 << opNames[1] << ", "
1133 << opNames[2] << ", "
David Greene8278ef52007-08-27 19:04:21 +00001134 << iName << "_params.begin(), " << iName << "_params.end(), \"";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001135 printEscapedString(inv->getName());
1136 Out << "\", " << bbname << ");";
1137 nl(Out) << iName << "->setCallingConv(";
1138 printCallingConv(inv->getCallingConv());
1139 Out << ");";
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001140 printParamAttrs(inv->getParamAttrs(), iName);
1141 Out << iName << "->setParamAttrs(" << iName << "_PAL);";
1142 nl(Out);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001143 break;
1144 }
1145 case Instruction::Unwind: {
1146 Out << "new UnwindInst("
1147 << bbname << ");";
1148 break;
1149 }
1150 case Instruction::Unreachable:{
1151 Out << "new UnreachableInst("
1152 << bbname << ");";
1153 break;
1154 }
1155 case Instruction::Add:
1156 case Instruction::Sub:
1157 case Instruction::Mul:
1158 case Instruction::UDiv:
1159 case Instruction::SDiv:
1160 case Instruction::FDiv:
1161 case Instruction::URem:
1162 case Instruction::SRem:
1163 case Instruction::FRem:
1164 case Instruction::And:
1165 case Instruction::Or:
1166 case Instruction::Xor:
1167 case Instruction::Shl:
1168 case Instruction::LShr:
1169 case Instruction::AShr:{
1170 Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
1171 switch (I->getOpcode()) {
1172 case Instruction::Add: Out << "Instruction::Add"; break;
1173 case Instruction::Sub: Out << "Instruction::Sub"; break;
1174 case Instruction::Mul: Out << "Instruction::Mul"; break;
1175 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1176 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1177 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1178 case Instruction::URem:Out << "Instruction::URem"; break;
1179 case Instruction::SRem:Out << "Instruction::SRem"; break;
1180 case Instruction::FRem:Out << "Instruction::FRem"; break;
1181 case Instruction::And: Out << "Instruction::And"; break;
1182 case Instruction::Or: Out << "Instruction::Or"; break;
1183 case Instruction::Xor: Out << "Instruction::Xor"; break;
1184 case Instruction::Shl: Out << "Instruction::Shl"; break;
1185 case Instruction::LShr:Out << "Instruction::LShr"; break;
1186 case Instruction::AShr:Out << "Instruction::AShr"; break;
1187 default: Out << "Instruction::BadOpCode"; break;
1188 }
1189 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1190 printEscapedString(I->getName());
1191 Out << "\", " << bbname << ");";
1192 break;
1193 }
1194 case Instruction::FCmp: {
1195 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1196 switch (cast<FCmpInst>(I)->getPredicate()) {
1197 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1198 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1199 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1200 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1201 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1202 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1203 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1204 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1205 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1206 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1207 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1208 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1209 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1210 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1211 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1212 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1213 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1214 }
1215 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1216 printEscapedString(I->getName());
1217 Out << "\", " << bbname << ");";
1218 break;
1219 }
1220 case Instruction::ICmp: {
1221 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1222 switch (cast<ICmpInst>(I)->getPredicate()) {
1223 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1224 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1225 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1226 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1227 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1228 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1229 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1230 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1231 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1232 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1233 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1234 }
1235 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1236 printEscapedString(I->getName());
1237 Out << "\", " << bbname << ");";
1238 break;
1239 }
1240 case Instruction::Malloc: {
1241 const MallocInst* mallocI = cast<MallocInst>(I);
1242 Out << "MallocInst* " << iName << " = new MallocInst("
1243 << getCppName(mallocI->getAllocatedType()) << ", ";
1244 if (mallocI->isArrayAllocation())
1245 Out << opNames[0] << ", " ;
1246 Out << "\"";
1247 printEscapedString(mallocI->getName());
1248 Out << "\", " << bbname << ");";
1249 if (mallocI->getAlignment())
1250 nl(Out) << iName << "->setAlignment("
1251 << mallocI->getAlignment() << ");";
1252 break;
1253 }
1254 case Instruction::Free: {
1255 Out << "FreeInst* " << iName << " = new FreeInst("
1256 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1257 break;
1258 }
1259 case Instruction::Alloca: {
1260 const AllocaInst* allocaI = cast<AllocaInst>(I);
1261 Out << "AllocaInst* " << iName << " = new AllocaInst("
1262 << getCppName(allocaI->getAllocatedType()) << ", ";
1263 if (allocaI->isArrayAllocation())
1264 Out << opNames[0] << ", ";
1265 Out << "\"";
1266 printEscapedString(allocaI->getName());
1267 Out << "\", " << bbname << ");";
1268 if (allocaI->getAlignment())
1269 nl(Out) << iName << "->setAlignment("
1270 << allocaI->getAlignment() << ");";
1271 break;
1272 }
1273 case Instruction::Load:{
1274 const LoadInst* load = cast<LoadInst>(I);
1275 Out << "LoadInst* " << iName << " = new LoadInst("
1276 << opNames[0] << ", \"";
1277 printEscapedString(load->getName());
1278 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1279 << ", " << bbname << ");";
1280 break;
1281 }
1282 case Instruction::Store: {
1283 const StoreInst* store = cast<StoreInst>(I);
1284 Out << "StoreInst* " << iName << " = new StoreInst("
1285 << opNames[0] << ", "
1286 << opNames[1] << ", "
1287 << (store->isVolatile() ? "true" : "false")
1288 << ", " << bbname << ");";
1289 break;
1290 }
1291 case Instruction::GetElementPtr: {
1292 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1293 if (gep->getNumOperands() <= 2) {
1294 Out << "GetElementPtrInst* " << iName << " = new GetElementPtrInst("
1295 << opNames[0];
1296 if (gep->getNumOperands() == 2)
1297 Out << ", " << opNames[1];
1298 } else {
1299 Out << "std::vector<Value*> " << iName << "_indices;";
1300 nl(Out);
1301 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1302 Out << iName << "_indices.push_back("
1303 << opNames[i] << ");";
1304 nl(Out);
1305 }
1306 Out << "Instruction* " << iName << " = new GetElementPtrInst("
David Greene393be882007-09-04 15:46:09 +00001307 << opNames[0] << ", " << iName << "_indices.begin(), "
1308 << iName << "_indices.end()";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001309 }
1310 Out << ", \"";
1311 printEscapedString(gep->getName());
1312 Out << "\", " << bbname << ");";
1313 break;
1314 }
1315 case Instruction::PHI: {
1316 const PHINode* phi = cast<PHINode>(I);
1317
1318 Out << "PHINode* " << iName << " = new PHINode("
1319 << getCppName(phi->getType()) << ", \"";
1320 printEscapedString(phi->getName());
1321 Out << "\", " << bbname << ");";
1322 nl(Out) << iName << "->reserveOperandSpace("
1323 << phi->getNumIncomingValues()
1324 << ");";
1325 nl(Out);
1326 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1327 Out << iName << "->addIncoming("
1328 << opNames[i] << ", " << opNames[i+1] << ");";
1329 nl(Out);
1330 }
1331 break;
1332 }
1333 case Instruction::Trunc:
1334 case Instruction::ZExt:
1335 case Instruction::SExt:
1336 case Instruction::FPTrunc:
1337 case Instruction::FPExt:
1338 case Instruction::FPToUI:
1339 case Instruction::FPToSI:
1340 case Instruction::UIToFP:
1341 case Instruction::SIToFP:
1342 case Instruction::PtrToInt:
1343 case Instruction::IntToPtr:
1344 case Instruction::BitCast: {
1345 const CastInst* cst = cast<CastInst>(I);
1346 Out << "CastInst* " << iName << " = new ";
1347 switch (I->getOpcode()) {
1348 case Instruction::Trunc: Out << "TruncInst"; break;
1349 case Instruction::ZExt: Out << "ZExtInst"; break;
1350 case Instruction::SExt: Out << "SExtInst"; break;
1351 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1352 case Instruction::FPExt: Out << "FPExtInst"; break;
1353 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1354 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1355 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1356 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1357 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1358 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1359 case Instruction::BitCast: Out << "BitCastInst"; break;
1360 default: assert(!"Unreachable"); break;
1361 }
1362 Out << "(" << opNames[0] << ", "
1363 << getCppName(cst->getType()) << ", \"";
1364 printEscapedString(cst->getName());
1365 Out << "\", " << bbname << ");";
1366 break;
1367 }
1368 case Instruction::Call:{
1369 const CallInst* call = cast<CallInst>(I);
1370 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1371 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1372 << getCppName(ila->getFunctionType()) << ", \""
1373 << ila->getAsmString() << "\", \""
1374 << ila->getConstraintString() << "\","
1375 << (ila->hasSideEffects() ? "true" : "false") << ");";
1376 nl(Out);
1377 }
Reid Spencerefbe90e2007-08-02 03:30:26 +00001378 if (call->getNumOperands() > 2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001379 Out << "std::vector<Value*> " << iName << "_params;";
1380 nl(Out);
1381 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1382 Out << iName << "_params.push_back(" << opNames[i] << ");";
1383 nl(Out);
1384 }
1385 Out << "CallInst* " << iName << " = new CallInst("
Reid Spencerefbe90e2007-08-02 03:30:26 +00001386 << opNames[0] << ", " << iName << "_params.begin(), "
1387 << iName << "_params.end(), \"";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001388 } else if (call->getNumOperands() == 2) {
1389 Out << "CallInst* " << iName << " = new CallInst("
1390 << opNames[0] << ", " << opNames[1] << ", \"";
1391 } else {
1392 Out << "CallInst* " << iName << " = new CallInst(" << opNames[0]
1393 << ", \"";
1394 }
1395 printEscapedString(call->getName());
1396 Out << "\", " << bbname << ");";
1397 nl(Out) << iName << "->setCallingConv(";
1398 printCallingConv(call->getCallingConv());
1399 Out << ");";
1400 nl(Out) << iName << "->setTailCall("
1401 << (call->isTailCall() ? "true":"false");
1402 Out << ");";
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001403 printParamAttrs(call->getParamAttrs(), iName);
1404 Out << iName << "->setParamAttrs(" << iName << "_PAL);";
1405 nl(Out);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001406 break;
1407 }
1408 case Instruction::Select: {
1409 const SelectInst* sel = cast<SelectInst>(I);
1410 Out << "SelectInst* " << getCppName(sel) << " = new SelectInst(";
1411 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1412 printEscapedString(sel->getName());
1413 Out << "\", " << bbname << ");";
1414 break;
1415 }
1416 case Instruction::UserOp1:
1417 /// FALL THROUGH
1418 case Instruction::UserOp2: {
1419 /// FIXME: What should be done here?
1420 break;
1421 }
1422 case Instruction::VAArg: {
1423 const VAArgInst* va = cast<VAArgInst>(I);
1424 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1425 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1426 printEscapedString(va->getName());
1427 Out << "\", " << bbname << ");";
1428 break;
1429 }
1430 case Instruction::ExtractElement: {
1431 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1432 Out << "ExtractElementInst* " << getCppName(eei)
1433 << " = new ExtractElementInst(" << opNames[0]
1434 << ", " << opNames[1] << ", \"";
1435 printEscapedString(eei->getName());
1436 Out << "\", " << bbname << ");";
1437 break;
1438 }
1439 case Instruction::InsertElement: {
1440 const InsertElementInst* iei = cast<InsertElementInst>(I);
1441 Out << "InsertElementInst* " << getCppName(iei)
1442 << " = new InsertElementInst(" << opNames[0]
1443 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1444 printEscapedString(iei->getName());
1445 Out << "\", " << bbname << ");";
1446 break;
1447 }
1448 case Instruction::ShuffleVector: {
1449 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1450 Out << "ShuffleVectorInst* " << getCppName(svi)
1451 << " = new ShuffleVectorInst(" << opNames[0]
1452 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1453 printEscapedString(svi->getName());
1454 Out << "\", " << bbname << ");";
1455 break;
1456 }
1457 }
1458 DefinedValues.insert(I);
1459 nl(Out);
1460 delete [] opNames;
1461}
1462
1463// Print out the types, constants and declarations needed by one function
1464void CppWriter::printFunctionUses(const Function* F) {
1465
1466 nl(Out) << "// Type Definitions"; nl(Out);
1467 if (!is_inline) {
1468 // Print the function's return type
1469 printType(F->getReturnType());
1470
1471 // Print the function's function type
1472 printType(F->getFunctionType());
1473
1474 // Print the types of each of the function's arguments
1475 for(Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1476 AI != AE; ++AI) {
1477 printType(AI->getType());
1478 }
1479 }
1480
1481 // Print type definitions for every type referenced by an instruction and
1482 // make a note of any global values or constants that are referenced
1483 SmallPtrSet<GlobalValue*,64> gvs;
1484 SmallPtrSet<Constant*,64> consts;
1485 for (Function::const_iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB){
1486 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1487 I != E; ++I) {
1488 // Print the type of the instruction itself
1489 printType(I->getType());
1490
1491 // Print the type of each of the instruction's operands
1492 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1493 Value* operand = I->getOperand(i);
1494 printType(operand->getType());
1495
1496 // If the operand references a GVal or Constant, make a note of it
1497 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1498 gvs.insert(GV);
1499 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1500 if (GVar->hasInitializer())
1501 consts.insert(GVar->getInitializer());
1502 } else if (Constant* C = dyn_cast<Constant>(operand))
1503 consts.insert(C);
1504 }
1505 }
1506 }
1507
1508 // Print the function declarations for any functions encountered
1509 nl(Out) << "// Function Declarations"; nl(Out);
1510 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1511 I != E; ++I) {
1512 if (Function* Fun = dyn_cast<Function>(*I)) {
1513 if (!is_inline || Fun != F)
1514 printFunctionHead(Fun);
1515 }
1516 }
1517
1518 // Print the global variable declarations for any variables encountered
1519 nl(Out) << "// Global Variable Declarations"; nl(Out);
1520 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1521 I != E; ++I) {
1522 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1523 printVariableHead(F);
1524 }
1525
1526 // Print the constants found
1527 nl(Out) << "// Constant Definitions"; nl(Out);
1528 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(), E = consts.end();
1529 I != E; ++I) {
1530 printConstant(*I);
1531 }
1532
1533 // Process the global variables definitions now that all the constants have
1534 // been emitted. These definitions just couple the gvars with their constant
1535 // initializers.
1536 nl(Out) << "// Global Variable Definitions"; nl(Out);
1537 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1538 I != E; ++I) {
1539 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1540 printVariableBody(GV);
1541 }
1542}
1543
1544void CppWriter::printFunctionHead(const Function* F) {
1545 nl(Out) << "Function* " << getCppName(F);
1546 if (is_inline) {
1547 Out << " = mod->getFunction(\"";
1548 printEscapedString(F->getName());
1549 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1550 nl(Out) << "if (!" << getCppName(F) << ") {";
1551 nl(Out) << getCppName(F);
1552 }
1553 Out<< " = new Function(";
1554 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1555 nl(Out) << "/*Linkage=*/";
1556 printLinkageType(F->getLinkage());
1557 Out << ",";
1558 nl(Out) << "/*Name=*/\"";
1559 printEscapedString(F->getName());
1560 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1561 nl(Out,-1);
1562 printCppName(F);
1563 Out << "->setCallingConv(";
1564 printCallingConv(F->getCallingConv());
1565 Out << ");";
1566 nl(Out);
1567 if (F->hasSection()) {
1568 printCppName(F);
1569 Out << "->setSection(\"" << F->getSection() << "\");";
1570 nl(Out);
1571 }
1572 if (F->getAlignment()) {
1573 printCppName(F);
1574 Out << "->setAlignment(" << F->getAlignment() << ");";
1575 nl(Out);
1576 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001577 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1578 printCppName(F);
1579 Out << "->setVisibility(";
1580 printVisibilityType(F->getVisibility());
1581 Out << ");";
1582 nl(Out);
1583 }
Gordon Henriksen3e7ea1e2007-12-25 22:16:06 +00001584 if (F->hasCollector()) {
1585 printCppName(F);
1586 Out << "->setCollector(\"" << F->getCollector() << "\");";
1587 nl(Out);
1588 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001589 if (is_inline) {
1590 Out << "}";
1591 nl(Out);
1592 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001593 printParamAttrs(F->getParamAttrs(), getCppName(F));
1594 printCppName(F);
1595 Out << "->setParamAttrs(" << getCppName(F) << "_PAL);";
1596 nl(Out);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001597}
1598
1599void CppWriter::printFunctionBody(const Function *F) {
1600 if (F->isDeclaration())
1601 return; // external functions have no bodies.
1602
1603 // Clear the DefinedValues and ForwardRefs maps because we can't have
1604 // cross-function forward refs
1605 ForwardRefs.clear();
1606 DefinedValues.clear();
1607
1608 // Create all the argument values
1609 if (!is_inline) {
1610 if (!F->arg_empty()) {
1611 Out << "Function::arg_iterator args = " << getCppName(F)
1612 << "->arg_begin();";
1613 nl(Out);
1614 }
1615 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1616 AI != AE; ++AI) {
1617 Out << "Value* " << getCppName(AI) << " = args++;";
1618 nl(Out);
1619 if (AI->hasName()) {
1620 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1621 nl(Out);
1622 }
1623 }
1624 }
1625
1626 // Create all the basic blocks
1627 nl(Out);
1628 for (Function::const_iterator BI = F->begin(), BE = F->end();
1629 BI != BE; ++BI) {
1630 std::string bbname(getCppName(BI));
1631 Out << "BasicBlock* " << bbname << " = new BasicBlock(\"";
1632 if (BI->hasName())
1633 printEscapedString(BI->getName());
1634 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1635 nl(Out);
1636 }
1637
1638 // Output all of its basic blocks... for the function
1639 for (Function::const_iterator BI = F->begin(), BE = F->end();
1640 BI != BE; ++BI) {
1641 std::string bbname(getCppName(BI));
1642 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1643 nl(Out);
1644
1645 // Output all of the instructions in the basic block...
1646 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1647 I != E; ++I) {
1648 printInstruction(I,bbname);
1649 }
1650 }
1651
1652 // Loop over the ForwardRefs and resolve them now that all instructions
1653 // are generated.
1654 if (!ForwardRefs.empty()) {
1655 nl(Out) << "// Resolve Forward References";
1656 nl(Out);
1657 }
1658
1659 while (!ForwardRefs.empty()) {
1660 ForwardRefMap::iterator I = ForwardRefs.begin();
1661 Out << I->second << "->replaceAllUsesWith("
1662 << getCppName(I->first) << "); delete " << I->second << ";";
1663 nl(Out);
1664 ForwardRefs.erase(I);
1665 }
1666}
1667
1668void CppWriter::printInline(const std::string& fname, const std::string& func) {
1669 const Function* F = TheModule->getFunction(func);
1670 if (!F) {
1671 error(std::string("Function '") + func + "' not found in input module");
1672 return;
1673 }
1674 if (F->isDeclaration()) {
1675 error(std::string("Function '") + func + "' is external!");
1676 return;
1677 }
1678 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1679 << getCppName(F);
1680 unsigned arg_count = 1;
1681 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1682 AI != AE; ++AI) {
1683 Out << ", Value* arg_" << arg_count;
1684 }
1685 Out << ") {";
1686 nl(Out);
1687 is_inline = true;
1688 printFunctionUses(F);
1689 printFunctionBody(F);
1690 is_inline = false;
1691 Out << "return " << getCppName(F->begin()) << ";";
1692 nl(Out) << "}";
1693 nl(Out);
1694}
1695
1696void CppWriter::printModuleBody() {
1697 // Print out all the type definitions
1698 nl(Out) << "// Type Definitions"; nl(Out);
1699 printTypes(TheModule);
1700
1701 // Functions can call each other and global variables can reference them so
1702 // define all the functions first before emitting their function bodies.
1703 nl(Out) << "// Function Declarations"; nl(Out);
1704 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1705 I != E; ++I)
1706 printFunctionHead(I);
1707
1708 // Process the global variables declarations. We can't initialze them until
1709 // after the constants are printed so just print a header for each global
1710 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1711 for (Module::const_global_iterator I = TheModule->global_begin(),
1712 E = TheModule->global_end(); I != E; ++I) {
1713 printVariableHead(I);
1714 }
1715
1716 // Print out all the constants definitions. Constants don't recurse except
1717 // through GlobalValues. All GlobalValues have been declared at this point
1718 // so we can proceed to generate the constants.
1719 nl(Out) << "// Constant Definitions"; nl(Out);
1720 printConstants(TheModule);
1721
1722 // Process the global variables definitions now that all the constants have
1723 // been emitted. These definitions just couple the gvars with their constant
1724 // initializers.
1725 nl(Out) << "// Global Variable Definitions"; nl(Out);
1726 for (Module::const_global_iterator I = TheModule->global_begin(),
1727 E = TheModule->global_end(); I != E; ++I) {
1728 printVariableBody(I);
1729 }
1730
1731 // Finally, we can safely put out all of the function bodies.
1732 nl(Out) << "// Function Definitions"; nl(Out);
1733 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1734 I != E; ++I) {
1735 if (!I->isDeclaration()) {
1736 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1737 << ")";
1738 nl(Out) << "{";
1739 nl(Out,1);
1740 printFunctionBody(I);
1741 nl(Out,-1) << "}";
1742 nl(Out);
1743 }
1744 }
1745}
1746
1747void CppWriter::printProgram(
1748 const std::string& fname,
1749 const std::string& mName
1750) {
1751 Out << "#include <llvm/Module.h>\n";
1752 Out << "#include <llvm/DerivedTypes.h>\n";
1753 Out << "#include <llvm/Constants.h>\n";
1754 Out << "#include <llvm/GlobalVariable.h>\n";
1755 Out << "#include <llvm/Function.h>\n";
1756 Out << "#include <llvm/CallingConv.h>\n";
1757 Out << "#include <llvm/BasicBlock.h>\n";
1758 Out << "#include <llvm/Instructions.h>\n";
1759 Out << "#include <llvm/InlineAsm.h>\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001760 Out << "#include <llvm/Support/MathExtras.h>\n";
1761 Out << "#include <llvm/Pass.h>\n";
1762 Out << "#include <llvm/PassManager.h>\n";
1763 Out << "#include <llvm/Analysis/Verifier.h>\n";
1764 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1765 Out << "#include <algorithm>\n";
1766 Out << "#include <iostream>\n\n";
1767 Out << "using namespace llvm;\n\n";
1768 Out << "Module* " << fname << "();\n\n";
1769 Out << "int main(int argc, char**argv) {\n";
1770 Out << " Module* Mod = " << fname << "();\n";
1771 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1772 Out << " std::cerr.flush();\n";
1773 Out << " std::cout.flush();\n";
1774 Out << " PassManager PM;\n";
1775 Out << " PM.add(new PrintModulePass(&llvm::cout));\n";
1776 Out << " PM.run(*Mod);\n";
1777 Out << " return 0;\n";
1778 Out << "}\n\n";
1779 printModule(fname,mName);
1780}
1781
1782void CppWriter::printModule(
1783 const std::string& fname,
1784 const std::string& mName
1785) {
1786 nl(Out) << "Module* " << fname << "() {";
1787 nl(Out,1) << "// Module Construction";
1788 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1789 if (!TheModule->getTargetTriple().empty()) {
1790 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1791 }
1792 if (!TheModule->getTargetTriple().empty()) {
1793 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1794 << "\");";
1795 }
1796
1797 if (!TheModule->getModuleInlineAsm().empty()) {
1798 nl(Out) << "mod->setModuleInlineAsm(\"";
1799 printEscapedString(TheModule->getModuleInlineAsm());
1800 Out << "\");";
1801 }
1802 nl(Out);
1803
1804 // Loop over the dependent libraries and emit them.
1805 Module::lib_iterator LI = TheModule->lib_begin();
1806 Module::lib_iterator LE = TheModule->lib_end();
1807 while (LI != LE) {
1808 Out << "mod->addLibrary(\"" << *LI << "\");";
1809 nl(Out);
1810 ++LI;
1811 }
1812 printModuleBody();
1813 nl(Out) << "return mod;";
1814 nl(Out,-1) << "}";
1815 nl(Out);
1816}
1817
1818void CppWriter::printContents(
1819 const std::string& fname, // Name of generated function
1820 const std::string& mName // Name of module generated module
1821) {
1822 Out << "\nModule* " << fname << "(Module *mod) {\n";
1823 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1824 printModuleBody();
1825 Out << "\nreturn mod;\n";
1826 Out << "\n}\n";
1827}
1828
1829void CppWriter::printFunction(
1830 const std::string& fname, // Name of generated function
1831 const std::string& funcName // Name of function to generate
1832) {
1833 const Function* F = TheModule->getFunction(funcName);
1834 if (!F) {
1835 error(std::string("Function '") + funcName + "' not found in input module");
1836 return;
1837 }
1838 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1839 printFunctionUses(F);
1840 printFunctionHead(F);
1841 printFunctionBody(F);
1842 Out << "return " << getCppName(F) << ";\n";
1843 Out << "}\n";
1844}
1845
Chris Lattner0366a6d2007-11-13 18:22:33 +00001846void CppWriter::printFunctions() {
1847 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1848 Module::const_iterator I = funcs.begin();
1849 Module::const_iterator IE = funcs.end();
1850
1851 for (; I != IE; ++I) {
1852 const Function &func = *I;
1853 if (!func.isDeclaration()) {
1854 std::string name("define_");
1855 name += func.getName();
1856 printFunction(name, func.getName());
1857 }
1858 }
1859}
1860
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001861void CppWriter::printVariable(
1862 const std::string& fname, /// Name of generated function
1863 const std::string& varName // Name of variable to generate
1864) {
1865 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1866
1867 if (!GV) {
1868 error(std::string("Variable '") + varName + "' not found in input module");
1869 return;
1870 }
1871 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1872 printVariableUses(GV);
1873 printVariableHead(GV);
1874 printVariableBody(GV);
1875 Out << "return " << getCppName(GV) << ";\n";
1876 Out << "}\n";
1877}
1878
1879void CppWriter::printType(
1880 const std::string& fname, /// Name of generated function
1881 const std::string& typeName // Name of type to generate
1882) {
1883 const Type* Ty = TheModule->getTypeByName(typeName);
1884 if (!Ty) {
1885 error(std::string("Type '") + typeName + "' not found in input module");
1886 return;
1887 }
1888 Out << "\nType* " << fname << "(Module *mod) {\n";
1889 printType(Ty);
1890 Out << "return " << getCppName(Ty) << ";\n";
1891 Out << "}\n";
1892}
1893
1894} // end anonymous llvm
1895
1896namespace llvm {
1897
1898void WriteModuleToCppFile(Module* mod, std::ostream& o) {
1899 // Initialize a CppWriter for us to use
1900 CppWriter W(o, mod);
1901
1902 // Emit a header
1903 o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1904
1905 // Get the name of the function we're supposed to generate
1906 std::string fname = FuncName.getValue();
1907
1908 // Get the name of the thing we are to generate
1909 std::string tgtname = NameToGenerate.getValue();
1910 if (GenerationType == GenModule ||
1911 GenerationType == GenContents ||
Chris Lattner0366a6d2007-11-13 18:22:33 +00001912 GenerationType == GenProgram ||
1913 GenerationType == GenFunctions) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001914 if (tgtname == "!bad!") {
1915 if (mod->getModuleIdentifier() == "-")
1916 tgtname = "<stdin>";
1917 else
1918 tgtname = mod->getModuleIdentifier();
1919 }
1920 } else if (tgtname == "!bad!") {
1921 W.error("You must use the -for option with -gen-{function,variable,type}");
1922 }
1923
1924 switch (WhatToGenerate(GenerationType)) {
1925 case GenProgram:
1926 if (fname.empty())
1927 fname = "makeLLVMModule";
1928 W.printProgram(fname,tgtname);
1929 break;
1930 case GenModule:
1931 if (fname.empty())
1932 fname = "makeLLVMModule";
1933 W.printModule(fname,tgtname);
1934 break;
1935 case GenContents:
1936 if (fname.empty())
1937 fname = "makeLLVMModuleContents";
1938 W.printContents(fname,tgtname);
1939 break;
1940 case GenFunction:
1941 if (fname.empty())
1942 fname = "makeLLVMFunction";
1943 W.printFunction(fname,tgtname);
1944 break;
Chris Lattner0366a6d2007-11-13 18:22:33 +00001945 case GenFunctions:
1946 W.printFunctions();
1947 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001948 case GenInline:
1949 if (fname.empty())
1950 fname = "makeLLVMInline";
1951 W.printInline(fname,tgtname);
1952 break;
1953 case GenVariable:
1954 if (fname.empty())
1955 fname = "makeLLVMVariable";
1956 W.printVariable(fname,tgtname);
1957 break;
1958 case GenType:
1959 if (fname.empty())
1960 fname = "makeLLVMType";
1961 W.printType(fname,tgtname);
1962 break;
1963 default:
1964 W.error("Invalid generation option");
1965 }
1966}
1967
1968}