blob: c18a22cbbb549cadd996b6baedea3d319eec37eb [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";
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000465 Out << ";";
466 nl(Out);
467 Out << "Attrs.push_back(PAWI);";
468 nl(Out);
469 }
Chris Lattner1c8733e2008-03-12 17:45:29 +0000470 Out << name << "_PAL = PAListPtr::get(Attrs.begin(), Attrs.end());";
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000471 nl(Out);
472 out(); nl(Out);
473 Out << '}'; nl(Out);
474 }
475}
476
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000477bool
478CppWriter::printTypeInternal(const Type* Ty) {
479 // We don't print definitions for primitive types
480 if (Ty->isPrimitiveType() || Ty->isInteger())
481 return false;
482
483 // If we already defined this type, we don't need to define it again.
484 if (DefinedTypes.find(Ty) != DefinedTypes.end())
485 return false;
486
487 // Everything below needs the name for the type so get it now.
488 std::string typeName(getCppName(Ty));
489
490 // Search the type stack for recursion. If we find it, then generate this
491 // as an OpaqueType, but make sure not to do this multiple times because
492 // the type could appear in multiple places on the stack. Once the opaque
493 // definition is issued, it must not be re-issued. Consequently we have to
494 // check the UnresolvedTypes list as well.
495 TypeList::const_iterator TI = std::find(TypeStack.begin(),TypeStack.end(),Ty);
496 if (TI != TypeStack.end()) {
497 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
498 if (I == UnresolvedTypes.end()) {
499 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
500 nl(Out);
501 UnresolvedTypes[Ty] = typeName;
502 }
503 return true;
504 }
505
506 // We're going to print a derived type which, by definition, contains other
507 // types. So, push this one we're printing onto the type stack to assist with
508 // recursive definitions.
509 TypeStack.push_back(Ty);
510
511 // Print the type definition
512 switch (Ty->getTypeID()) {
513 case Type::FunctionTyID: {
514 const FunctionType* FT = cast<FunctionType>(Ty);
515 Out << "std::vector<const Type*>" << typeName << "_args;";
516 nl(Out);
517 FunctionType::param_iterator PI = FT->param_begin();
518 FunctionType::param_iterator PE = FT->param_end();
519 for (; PI != PE; ++PI) {
520 const Type* argTy = static_cast<const Type*>(*PI);
521 bool isForward = printTypeInternal(argTy);
522 std::string argName(getCppName(argTy));
523 Out << typeName << "_args.push_back(" << argName;
524 if (isForward)
525 Out << "_fwd";
526 Out << ");";
527 nl(Out);
528 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000529 bool isForward = printTypeInternal(FT->getReturnType());
530 std::string retTypeName(getCppName(FT->getReturnType()));
531 Out << "FunctionType* " << typeName << " = FunctionType::get(";
532 in(); nl(Out) << "/*Result=*/" << retTypeName;
533 if (isForward)
534 Out << "_fwd";
535 Out << ",";
536 nl(Out) << "/*Params=*/" << typeName << "_args,";
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000537 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000538 out();
539 nl(Out);
540 break;
541 }
542 case Type::StructTyID: {
543 const StructType* ST = cast<StructType>(Ty);
544 Out << "std::vector<const Type*>" << typeName << "_fields;";
545 nl(Out);
546 StructType::element_iterator EI = ST->element_begin();
547 StructType::element_iterator EE = ST->element_end();
548 for (; EI != EE; ++EI) {
549 const Type* fieldTy = static_cast<const Type*>(*EI);
550 bool isForward = printTypeInternal(fieldTy);
551 std::string fieldName(getCppName(fieldTy));
552 Out << typeName << "_fields.push_back(" << fieldName;
553 if (isForward)
554 Out << "_fwd";
555 Out << ");";
556 nl(Out);
557 }
558 Out << "StructType* " << typeName << " = StructType::get("
559 << typeName << "_fields, /*isPacked=*/"
560 << (ST->isPacked() ? "true" : "false") << ");";
561 nl(Out);
562 break;
563 }
564 case Type::ArrayTyID: {
565 const ArrayType* AT = cast<ArrayType>(Ty);
566 const Type* ET = AT->getElementType();
567 bool isForward = printTypeInternal(ET);
568 std::string elemName(getCppName(ET));
569 Out << "ArrayType* " << typeName << " = ArrayType::get("
570 << elemName << (isForward ? "_fwd" : "")
571 << ", " << utostr(AT->getNumElements()) << ");";
572 nl(Out);
573 break;
574 }
575 case Type::PointerTyID: {
576 const PointerType* PT = cast<PointerType>(Ty);
577 const Type* ET = PT->getElementType();
578 bool isForward = printTypeInternal(ET);
579 std::string elemName(getCppName(ET));
580 Out << "PointerType* " << typeName << " = PointerType::get("
Christopher Lambbb2f2222007-12-17 01:12:55 +0000581 << elemName << (isForward ? "_fwd" : "")
582 << ", " << utostr(PT->getAddressSpace()) << ");";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583 nl(Out);
584 break;
585 }
586 case Type::VectorTyID: {
587 const VectorType* PT = cast<VectorType>(Ty);
588 const Type* ET = PT->getElementType();
589 bool isForward = printTypeInternal(ET);
590 std::string elemName(getCppName(ET));
591 Out << "VectorType* " << typeName << " = VectorType::get("
592 << elemName << (isForward ? "_fwd" : "")
593 << ", " << utostr(PT->getNumElements()) << ");";
594 nl(Out);
595 break;
596 }
597 case Type::OpaqueTyID: {
598 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
599 nl(Out);
600 break;
601 }
602 default:
603 error("Invalid TypeID");
604 }
605
606 // If the type had a name, make sure we recreate it.
607 const std::string* progTypeName =
608 findTypeName(TheModule->getTypeSymbolTable(),Ty);
609 if (progTypeName) {
610 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
611 << typeName << ");";
612 nl(Out);
613 }
614
615 // Pop us off the type stack
616 TypeStack.pop_back();
617
618 // Indicate that this type is now defined.
619 DefinedTypes.insert(Ty);
620
621 // Early resolve as many unresolved types as possible. Search the unresolved
622 // types map for the type we just printed. Now that its definition is complete
623 // we can resolve any previous references to it. This prevents a cascade of
624 // unresolved types.
625 TypeMap::iterator I = UnresolvedTypes.find(Ty);
626 if (I != UnresolvedTypes.end()) {
627 Out << "cast<OpaqueType>(" << I->second
628 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
629 nl(Out);
630 Out << I->second << " = cast<";
631 switch (Ty->getTypeID()) {
632 case Type::FunctionTyID: Out << "FunctionType"; break;
633 case Type::ArrayTyID: Out << "ArrayType"; break;
634 case Type::StructTyID: Out << "StructType"; break;
635 case Type::VectorTyID: Out << "VectorType"; break;
636 case Type::PointerTyID: Out << "PointerType"; break;
637 case Type::OpaqueTyID: Out << "OpaqueType"; break;
638 default: Out << "NoSuchDerivedType"; break;
639 }
640 Out << ">(" << I->second << "_fwd.get());";
641 nl(Out); nl(Out);
642 UnresolvedTypes.erase(I);
643 }
644
645 // Finally, separate the type definition from other with a newline.
646 nl(Out);
647
648 // We weren't a recursive type
649 return false;
650}
651
652// Prints a type definition. Returns true if it could not resolve all the types
653// in the definition but had to use a forward reference.
654void
655CppWriter::printType(const Type* Ty) {
656 assert(TypeStack.empty());
657 TypeStack.clear();
658 printTypeInternal(Ty);
659 assert(TypeStack.empty());
660}
661
662void
663CppWriter::printTypes(const Module* M) {
664
665 // Walk the symbol table and print out all its types
666 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
667 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
668 TI != TE; ++TI) {
669
670 // For primitive types and types already defined, just add a name
671 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
672 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
673 TNI != TypeNames.end()) {
674 Out << "mod->addTypeName(\"";
675 printEscapedString(TI->first);
676 Out << "\", " << getCppName(TI->second) << ");";
677 nl(Out);
678 // For everything else, define the type
679 } else {
680 printType(TI->second);
681 }
682 }
683
684 // Add all of the global variables to the value table...
685 for (Module::const_global_iterator I = TheModule->global_begin(),
686 E = TheModule->global_end(); I != E; ++I) {
687 if (I->hasInitializer())
688 printType(I->getInitializer()->getType());
689 printType(I->getType());
690 }
691
692 // Add all the functions to the table
693 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
694 FI != FE; ++FI) {
695 printType(FI->getReturnType());
696 printType(FI->getFunctionType());
697 // Add all the function arguments
698 for(Function::const_arg_iterator AI = FI->arg_begin(),
699 AE = FI->arg_end(); AI != AE; ++AI) {
700 printType(AI->getType());
701 }
702
703 // Add all of the basic blocks and instructions
704 for (Function::const_iterator BB = FI->begin(),
705 E = FI->end(); BB != E; ++BB) {
706 printType(BB->getType());
707 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
708 ++I) {
709 printType(I->getType());
710 for (unsigned i = 0; i < I->getNumOperands(); ++i)
711 printType(I->getOperand(i)->getType());
712 }
713 }
714 }
715}
716
717
718// printConstant - Print out a constant pool entry...
719void CppWriter::printConstant(const Constant *CV) {
720 // First, if the constant is actually a GlobalValue (variable or function) or
721 // its already in the constant list then we've printed it already and we can
722 // just return.
723 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
724 return;
725
726 std::string constName(getCppName(CV));
727 std::string typeName(getCppName(CV->getType()));
728 if (CV->isNullValue()) {
729 Out << "Constant* " << constName << " = Constant::getNullValue("
730 << typeName << ");";
731 nl(Out);
732 return;
733 }
734 if (isa<GlobalValue>(CV)) {
735 // Skip variables and functions, we emit them elsewhere
736 return;
737 }
738 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
739 Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
740 << cast<IntegerType>(CI->getType())->getBitWidth() << ", "
741 << " \"" << CI->getValue().toStringSigned(10) << "\", 10));";
742 } else if (isa<ConstantAggregateZero>(CV)) {
743 Out << "ConstantAggregateZero* " << constName
744 << " = ConstantAggregateZero::get(" << typeName << ");";
745 } else if (isa<ConstantPointerNull>(CV)) {
746 Out << "ConstantPointerNull* " << constName
747 << " = ConstanPointerNull::get(" << typeName << ");";
748 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
749 Out << "ConstantFP* " << constName << " = ";
750 printCFP(CFP);
751 Out << ";";
752 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
753 if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
754 Out << "Constant* " << constName << " = ConstantArray::get(\"";
755 std::string tmp = CA->getAsString();
756 bool nullTerminate = false;
757 if (tmp[tmp.length()-1] == 0) {
758 tmp.erase(tmp.length()-1);
759 nullTerminate = true;
760 }
761 printEscapedString(tmp);
762 // Determine if we want null termination or not.
763 if (nullTerminate)
764 Out << "\", true"; // Indicate that the null terminator should be added.
765 else
766 Out << "\", false";// No null terminator
767 Out << ");";
768 } else {
769 Out << "std::vector<Constant*> " << constName << "_elems;";
770 nl(Out);
771 unsigned N = CA->getNumOperands();
772 for (unsigned i = 0; i < N; ++i) {
773 printConstant(CA->getOperand(i)); // recurse to print operands
774 Out << constName << "_elems.push_back("
775 << getCppName(CA->getOperand(i)) << ");";
776 nl(Out);
777 }
778 Out << "Constant* " << constName << " = ConstantArray::get("
779 << typeName << ", " << constName << "_elems);";
780 }
781 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
782 Out << "std::vector<Constant*> " << constName << "_fields;";
783 nl(Out);
784 unsigned N = CS->getNumOperands();
785 for (unsigned i = 0; i < N; i++) {
786 printConstant(CS->getOperand(i));
787 Out << constName << "_fields.push_back("
788 << getCppName(CS->getOperand(i)) << ");";
789 nl(Out);
790 }
791 Out << "Constant* " << constName << " = ConstantStruct::get("
792 << typeName << ", " << constName << "_fields);";
793 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
794 Out << "std::vector<Constant*> " << constName << "_elems;";
795 nl(Out);
796 unsigned N = CP->getNumOperands();
797 for (unsigned i = 0; i < N; ++i) {
798 printConstant(CP->getOperand(i));
799 Out << constName << "_elems.push_back("
800 << getCppName(CP->getOperand(i)) << ");";
801 nl(Out);
802 }
803 Out << "Constant* " << constName << " = ConstantVector::get("
804 << typeName << ", " << constName << "_elems);";
805 } else if (isa<UndefValue>(CV)) {
806 Out << "UndefValue* " << constName << " = UndefValue::get("
807 << typeName << ");";
808 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
809 if (CE->getOpcode() == Instruction::GetElementPtr) {
810 Out << "std::vector<Constant*> " << constName << "_indices;";
811 nl(Out);
812 printConstant(CE->getOperand(0));
813 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
814 printConstant(CE->getOperand(i));
815 Out << constName << "_indices.push_back("
816 << getCppName(CE->getOperand(i)) << ");";
817 nl(Out);
818 }
819 Out << "Constant* " << constName
820 << " = ConstantExpr::getGetElementPtr("
821 << getCppName(CE->getOperand(0)) << ", "
David Greene69fc0d52007-09-04 17:15:07 +0000822 << "&" << constName << "_indices[0], "
823 << constName << "_indices.size()"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000824 << " );";
825 } else if (CE->isCast()) {
826 printConstant(CE->getOperand(0));
827 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
828 switch (CE->getOpcode()) {
829 default: assert(0 && "Invalid cast opcode");
830 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
831 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
832 case Instruction::SExt: Out << "Instruction::SExt"; break;
833 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
834 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
835 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
836 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
837 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
838 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
839 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
840 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
841 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
842 }
843 Out << ", " << getCppName(CE->getOperand(0)) << ", "
844 << getCppName(CE->getType()) << ");";
845 } else {
846 unsigned N = CE->getNumOperands();
847 for (unsigned i = 0; i < N; ++i ) {
848 printConstant(CE->getOperand(i));
849 }
850 Out << "Constant* " << constName << " = ConstantExpr::";
851 switch (CE->getOpcode()) {
852 case Instruction::Add: Out << "getAdd("; break;
853 case Instruction::Sub: Out << "getSub("; break;
854 case Instruction::Mul: Out << "getMul("; break;
855 case Instruction::UDiv: Out << "getUDiv("; break;
856 case Instruction::SDiv: Out << "getSDiv("; break;
857 case Instruction::FDiv: Out << "getFDiv("; break;
858 case Instruction::URem: Out << "getURem("; break;
859 case Instruction::SRem: Out << "getSRem("; break;
860 case Instruction::FRem: Out << "getFRem("; break;
861 case Instruction::And: Out << "getAnd("; break;
862 case Instruction::Or: Out << "getOr("; break;
863 case Instruction::Xor: Out << "getXor("; break;
864 case Instruction::ICmp:
865 Out << "getICmp(ICmpInst::ICMP_";
866 switch (CE->getPredicate()) {
867 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
868 case ICmpInst::ICMP_NE: Out << "NE"; break;
869 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
870 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
871 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
872 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
873 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
874 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
875 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
876 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
877 default: error("Invalid ICmp Predicate");
878 }
879 break;
880 case Instruction::FCmp:
881 Out << "getFCmp(FCmpInst::FCMP_";
882 switch (CE->getPredicate()) {
883 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
884 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
885 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
886 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
887 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
888 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
889 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
890 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
891 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
892 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
893 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
894 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
895 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
896 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
897 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
898 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
899 default: error("Invalid FCmp Predicate");
900 }
901 break;
902 case Instruction::Shl: Out << "getShl("; break;
903 case Instruction::LShr: Out << "getLShr("; break;
904 case Instruction::AShr: Out << "getAShr("; break;
905 case Instruction::Select: Out << "getSelect("; break;
906 case Instruction::ExtractElement: Out << "getExtractElement("; break;
907 case Instruction::InsertElement: Out << "getInsertElement("; break;
908 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
909 default:
910 error("Invalid constant expression");
911 break;
912 }
913 Out << getCppName(CE->getOperand(0));
914 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
915 Out << ", " << getCppName(CE->getOperand(i));
916 Out << ");";
917 }
918 } else {
919 error("Bad Constant");
920 Out << "Constant* " << constName << " = 0; ";
921 }
922 nl(Out);
923}
924
925void
926CppWriter::printConstants(const Module* M) {
927 // Traverse all the global variables looking for constant initializers
928 for (Module::const_global_iterator I = TheModule->global_begin(),
929 E = TheModule->global_end(); I != E; ++I)
930 if (I->hasInitializer())
931 printConstant(I->getInitializer());
932
933 // Traverse the LLVM functions looking for constants
934 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
935 FI != FE; ++FI) {
936 // Add all of the basic blocks and instructions
937 for (Function::const_iterator BB = FI->begin(),
938 E = FI->end(); BB != E; ++BB) {
939 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
940 ++I) {
941 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
942 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
943 printConstant(C);
944 }
945 }
946 }
947 }
948 }
949}
950
951void CppWriter::printVariableUses(const GlobalVariable *GV) {
952 nl(Out) << "// Type Definitions";
953 nl(Out);
954 printType(GV->getType());
955 if (GV->hasInitializer()) {
956 Constant* Init = GV->getInitializer();
957 printType(Init->getType());
958 if (Function* F = dyn_cast<Function>(Init)) {
959 nl(Out)<< "/ Function Declarations"; nl(Out);
960 printFunctionHead(F);
961 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
962 nl(Out) << "// Global Variable Declarations"; nl(Out);
963 printVariableHead(gv);
964 } else {
965 nl(Out) << "// Constant Definitions"; nl(Out);
966 printConstant(gv);
967 }
968 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
969 nl(Out) << "// Global Variable Definitions"; nl(Out);
970 printVariableBody(gv);
971 }
972 }
973}
974
975void CppWriter::printVariableHead(const GlobalVariable *GV) {
976 nl(Out) << "GlobalVariable* " << getCppName(GV);
977 if (is_inline) {
978 Out << " = mod->getGlobalVariable(";
979 printEscapedString(GV->getName());
980 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
981 nl(Out) << "if (!" << getCppName(GV) << ") {";
982 in(); nl(Out) << getCppName(GV);
983 }
984 Out << " = new GlobalVariable(";
985 nl(Out) << "/*Type=*/";
986 printCppName(GV->getType()->getElementType());
987 Out << ",";
988 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
989 Out << ",";
990 nl(Out) << "/*Linkage=*/";
991 printLinkageType(GV->getLinkage());
992 Out << ",";
993 nl(Out) << "/*Initializer=*/0, ";
994 if (GV->hasInitializer()) {
995 Out << "// has initializer, specified below";
996 }
997 nl(Out) << "/*Name=*/\"";
998 printEscapedString(GV->getName());
999 Out << "\",";
1000 nl(Out) << "mod);";
1001 nl(Out);
1002
1003 if (GV->hasSection()) {
1004 printCppName(GV);
1005 Out << "->setSection(\"";
1006 printEscapedString(GV->getSection());
1007 Out << "\");";
1008 nl(Out);
1009 }
1010 if (GV->getAlignment()) {
1011 printCppName(GV);
1012 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1013 nl(Out);
1014 };
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001015 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1016 printCppName(GV);
1017 Out << "->setVisibility(";
1018 printVisibilityType(GV->getVisibility());
1019 Out << ");";
1020 nl(Out);
1021 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001022 if (is_inline) {
1023 out(); Out << "}"; nl(Out);
1024 }
1025}
1026
1027void
1028CppWriter::printVariableBody(const GlobalVariable *GV) {
1029 if (GV->hasInitializer()) {
1030 printCppName(GV);
1031 Out << "->setInitializer(";
1032 //if (!isa<GlobalValue(GV->getInitializer()))
1033 //else
1034 Out << getCppName(GV->getInitializer()) << ");";
1035 nl(Out);
1036 }
1037}
1038
1039std::string
1040CppWriter::getOpName(Value* V) {
1041 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1042 return getCppName(V);
1043
1044 // See if its alread in the map of forward references, if so just return the
1045 // name we already set up for it
1046 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1047 if (I != ForwardRefs.end())
1048 return I->second;
1049
1050 // This is a new forward reference. Generate a unique name for it
1051 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1052
1053 // Yes, this is a hack. An Argument is the smallest instantiable value that
1054 // we can make as a placeholder for the real value. We'll replace these
1055 // Argument instances later.
1056 Out << "Argument* " << result << " = new Argument("
1057 << getCppName(V->getType()) << ");";
1058 nl(Out);
1059 ForwardRefs[V] = result;
1060 return result;
1061}
1062
1063// printInstruction - This member is called for each Instruction in a function.
1064void
1065CppWriter::printInstruction(const Instruction *I, const std::string& bbname) {
1066 std::string iName(getCppName(I));
1067
1068 // Before we emit this instruction, we need to take care of generating any
1069 // forward references. So, we get the names of all the operands in advance
1070 std::string* opNames = new std::string[I->getNumOperands()];
1071 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1072 opNames[i] = getOpName(I->getOperand(i));
1073 }
1074
1075 switch (I->getOpcode()) {
1076 case Instruction::Ret: {
1077 const ReturnInst* ret = cast<ReturnInst>(I);
1078 Out << "new ReturnInst("
1079 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1080 break;
1081 }
1082 case Instruction::Br: {
1083 const BranchInst* br = cast<BranchInst>(I);
1084 Out << "new BranchInst(" ;
1085 if (br->getNumOperands() == 3 ) {
1086 Out << opNames[0] << ", "
1087 << opNames[1] << ", "
1088 << opNames[2] << ", ";
1089
1090 } else if (br->getNumOperands() == 1) {
1091 Out << opNames[0] << ", ";
1092 } else {
1093 error("Branch with 2 operands?");
1094 }
1095 Out << bbname << ");";
1096 break;
1097 }
1098 case Instruction::Switch: {
1099 const SwitchInst* sw = cast<SwitchInst>(I);
1100 Out << "SwitchInst* " << iName << " = new SwitchInst("
1101 << opNames[0] << ", "
1102 << opNames[1] << ", "
1103 << sw->getNumCases() << ", " << bbname << ");";
1104 nl(Out);
1105 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1106 Out << iName << "->addCase("
1107 << opNames[i] << ", "
1108 << opNames[i+1] << ");";
1109 nl(Out);
1110 }
1111 break;
1112 }
1113 case Instruction::Invoke: {
1114 const InvokeInst* inv = cast<InvokeInst>(I);
1115 Out << "std::vector<Value*> " << iName << "_params;";
1116 nl(Out);
1117 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1118 Out << iName << "_params.push_back("
1119 << opNames[i] << ");";
1120 nl(Out);
1121 }
1122 Out << "InvokeInst *" << iName << " = new InvokeInst("
1123 << opNames[0] << ", "
1124 << opNames[1] << ", "
1125 << opNames[2] << ", "
David Greene8278ef52007-08-27 19:04:21 +00001126 << iName << "_params.begin(), " << iName << "_params.end(), \"";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001127 printEscapedString(inv->getName());
1128 Out << "\", " << bbname << ");";
1129 nl(Out) << iName << "->setCallingConv(";
1130 printCallingConv(inv->getCallingConv());
1131 Out << ");";
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001132 printParamAttrs(inv->getParamAttrs(), iName);
1133 Out << iName << "->setParamAttrs(" << iName << "_PAL);";
1134 nl(Out);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001135 break;
1136 }
1137 case Instruction::Unwind: {
1138 Out << "new UnwindInst("
1139 << bbname << ");";
1140 break;
1141 }
1142 case Instruction::Unreachable:{
1143 Out << "new UnreachableInst("
1144 << bbname << ");";
1145 break;
1146 }
1147 case Instruction::Add:
1148 case Instruction::Sub:
1149 case Instruction::Mul:
1150 case Instruction::UDiv:
1151 case Instruction::SDiv:
1152 case Instruction::FDiv:
1153 case Instruction::URem:
1154 case Instruction::SRem:
1155 case Instruction::FRem:
1156 case Instruction::And:
1157 case Instruction::Or:
1158 case Instruction::Xor:
1159 case Instruction::Shl:
1160 case Instruction::LShr:
1161 case Instruction::AShr:{
1162 Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
1163 switch (I->getOpcode()) {
1164 case Instruction::Add: Out << "Instruction::Add"; break;
1165 case Instruction::Sub: Out << "Instruction::Sub"; break;
1166 case Instruction::Mul: Out << "Instruction::Mul"; break;
1167 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1168 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1169 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1170 case Instruction::URem:Out << "Instruction::URem"; break;
1171 case Instruction::SRem:Out << "Instruction::SRem"; break;
1172 case Instruction::FRem:Out << "Instruction::FRem"; break;
1173 case Instruction::And: Out << "Instruction::And"; break;
1174 case Instruction::Or: Out << "Instruction::Or"; break;
1175 case Instruction::Xor: Out << "Instruction::Xor"; break;
1176 case Instruction::Shl: Out << "Instruction::Shl"; break;
1177 case Instruction::LShr:Out << "Instruction::LShr"; break;
1178 case Instruction::AShr:Out << "Instruction::AShr"; break;
1179 default: Out << "Instruction::BadOpCode"; break;
1180 }
1181 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1182 printEscapedString(I->getName());
1183 Out << "\", " << bbname << ");";
1184 break;
1185 }
1186 case Instruction::FCmp: {
1187 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1188 switch (cast<FCmpInst>(I)->getPredicate()) {
1189 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1190 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1191 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1192 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1193 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1194 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1195 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1196 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1197 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1198 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1199 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1200 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1201 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1202 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1203 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1204 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1205 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1206 }
1207 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1208 printEscapedString(I->getName());
1209 Out << "\", " << bbname << ");";
1210 break;
1211 }
1212 case Instruction::ICmp: {
1213 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1214 switch (cast<ICmpInst>(I)->getPredicate()) {
1215 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1216 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1217 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1218 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1219 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1220 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1221 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1222 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1223 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1224 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1225 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1226 }
1227 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1228 printEscapedString(I->getName());
1229 Out << "\", " << bbname << ");";
1230 break;
1231 }
1232 case Instruction::Malloc: {
1233 const MallocInst* mallocI = cast<MallocInst>(I);
1234 Out << "MallocInst* " << iName << " = new MallocInst("
1235 << getCppName(mallocI->getAllocatedType()) << ", ";
1236 if (mallocI->isArrayAllocation())
1237 Out << opNames[0] << ", " ;
1238 Out << "\"";
1239 printEscapedString(mallocI->getName());
1240 Out << "\", " << bbname << ");";
1241 if (mallocI->getAlignment())
1242 nl(Out) << iName << "->setAlignment("
1243 << mallocI->getAlignment() << ");";
1244 break;
1245 }
1246 case Instruction::Free: {
1247 Out << "FreeInst* " << iName << " = new FreeInst("
1248 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1249 break;
1250 }
1251 case Instruction::Alloca: {
1252 const AllocaInst* allocaI = cast<AllocaInst>(I);
1253 Out << "AllocaInst* " << iName << " = new AllocaInst("
1254 << getCppName(allocaI->getAllocatedType()) << ", ";
1255 if (allocaI->isArrayAllocation())
1256 Out << opNames[0] << ", ";
1257 Out << "\"";
1258 printEscapedString(allocaI->getName());
1259 Out << "\", " << bbname << ");";
1260 if (allocaI->getAlignment())
1261 nl(Out) << iName << "->setAlignment("
1262 << allocaI->getAlignment() << ");";
1263 break;
1264 }
1265 case Instruction::Load:{
1266 const LoadInst* load = cast<LoadInst>(I);
1267 Out << "LoadInst* " << iName << " = new LoadInst("
1268 << opNames[0] << ", \"";
1269 printEscapedString(load->getName());
1270 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1271 << ", " << bbname << ");";
1272 break;
1273 }
1274 case Instruction::Store: {
1275 const StoreInst* store = cast<StoreInst>(I);
1276 Out << "StoreInst* " << iName << " = new StoreInst("
1277 << opNames[0] << ", "
1278 << opNames[1] << ", "
1279 << (store->isVolatile() ? "true" : "false")
1280 << ", " << bbname << ");";
1281 break;
1282 }
1283 case Instruction::GetElementPtr: {
1284 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1285 if (gep->getNumOperands() <= 2) {
1286 Out << "GetElementPtrInst* " << iName << " = new GetElementPtrInst("
1287 << opNames[0];
1288 if (gep->getNumOperands() == 2)
1289 Out << ", " << opNames[1];
1290 } else {
1291 Out << "std::vector<Value*> " << iName << "_indices;";
1292 nl(Out);
1293 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1294 Out << iName << "_indices.push_back("
1295 << opNames[i] << ");";
1296 nl(Out);
1297 }
1298 Out << "Instruction* " << iName << " = new GetElementPtrInst("
David Greene393be882007-09-04 15:46:09 +00001299 << opNames[0] << ", " << iName << "_indices.begin(), "
1300 << iName << "_indices.end()";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001301 }
1302 Out << ", \"";
1303 printEscapedString(gep->getName());
1304 Out << "\", " << bbname << ");";
1305 break;
1306 }
1307 case Instruction::PHI: {
1308 const PHINode* phi = cast<PHINode>(I);
1309
1310 Out << "PHINode* " << iName << " = new PHINode("
1311 << getCppName(phi->getType()) << ", \"";
1312 printEscapedString(phi->getName());
1313 Out << "\", " << bbname << ");";
1314 nl(Out) << iName << "->reserveOperandSpace("
1315 << phi->getNumIncomingValues()
1316 << ");";
1317 nl(Out);
1318 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1319 Out << iName << "->addIncoming("
1320 << opNames[i] << ", " << opNames[i+1] << ");";
1321 nl(Out);
1322 }
1323 break;
1324 }
1325 case Instruction::Trunc:
1326 case Instruction::ZExt:
1327 case Instruction::SExt:
1328 case Instruction::FPTrunc:
1329 case Instruction::FPExt:
1330 case Instruction::FPToUI:
1331 case Instruction::FPToSI:
1332 case Instruction::UIToFP:
1333 case Instruction::SIToFP:
1334 case Instruction::PtrToInt:
1335 case Instruction::IntToPtr:
1336 case Instruction::BitCast: {
1337 const CastInst* cst = cast<CastInst>(I);
1338 Out << "CastInst* " << iName << " = new ";
1339 switch (I->getOpcode()) {
1340 case Instruction::Trunc: Out << "TruncInst"; break;
1341 case Instruction::ZExt: Out << "ZExtInst"; break;
1342 case Instruction::SExt: Out << "SExtInst"; break;
1343 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1344 case Instruction::FPExt: Out << "FPExtInst"; break;
1345 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1346 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1347 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1348 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1349 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1350 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1351 case Instruction::BitCast: Out << "BitCastInst"; break;
1352 default: assert(!"Unreachable"); break;
1353 }
1354 Out << "(" << opNames[0] << ", "
1355 << getCppName(cst->getType()) << ", \"";
1356 printEscapedString(cst->getName());
1357 Out << "\", " << bbname << ");";
1358 break;
1359 }
1360 case Instruction::Call:{
1361 const CallInst* call = cast<CallInst>(I);
1362 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1363 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1364 << getCppName(ila->getFunctionType()) << ", \""
1365 << ila->getAsmString() << "\", \""
1366 << ila->getConstraintString() << "\","
1367 << (ila->hasSideEffects() ? "true" : "false") << ");";
1368 nl(Out);
1369 }
Reid Spencerefbe90e2007-08-02 03:30:26 +00001370 if (call->getNumOperands() > 2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001371 Out << "std::vector<Value*> " << iName << "_params;";
1372 nl(Out);
1373 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1374 Out << iName << "_params.push_back(" << opNames[i] << ");";
1375 nl(Out);
1376 }
1377 Out << "CallInst* " << iName << " = new CallInst("
Reid Spencerefbe90e2007-08-02 03:30:26 +00001378 << opNames[0] << ", " << iName << "_params.begin(), "
1379 << iName << "_params.end(), \"";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001380 } else if (call->getNumOperands() == 2) {
1381 Out << "CallInst* " << iName << " = new CallInst("
1382 << opNames[0] << ", " << opNames[1] << ", \"";
1383 } else {
1384 Out << "CallInst* " << iName << " = new CallInst(" << opNames[0]
1385 << ", \"";
1386 }
1387 printEscapedString(call->getName());
1388 Out << "\", " << bbname << ");";
1389 nl(Out) << iName << "->setCallingConv(";
1390 printCallingConv(call->getCallingConv());
1391 Out << ");";
1392 nl(Out) << iName << "->setTailCall("
1393 << (call->isTailCall() ? "true":"false");
1394 Out << ");";
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001395 printParamAttrs(call->getParamAttrs(), iName);
1396 Out << iName << "->setParamAttrs(" << iName << "_PAL);";
1397 nl(Out);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001398 break;
1399 }
1400 case Instruction::Select: {
1401 const SelectInst* sel = cast<SelectInst>(I);
1402 Out << "SelectInst* " << getCppName(sel) << " = new SelectInst(";
1403 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1404 printEscapedString(sel->getName());
1405 Out << "\", " << bbname << ");";
1406 break;
1407 }
1408 case Instruction::UserOp1:
1409 /// FALL THROUGH
1410 case Instruction::UserOp2: {
1411 /// FIXME: What should be done here?
1412 break;
1413 }
1414 case Instruction::VAArg: {
1415 const VAArgInst* va = cast<VAArgInst>(I);
1416 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1417 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1418 printEscapedString(va->getName());
1419 Out << "\", " << bbname << ");";
1420 break;
1421 }
1422 case Instruction::ExtractElement: {
1423 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1424 Out << "ExtractElementInst* " << getCppName(eei)
1425 << " = new ExtractElementInst(" << opNames[0]
1426 << ", " << opNames[1] << ", \"";
1427 printEscapedString(eei->getName());
1428 Out << "\", " << bbname << ");";
1429 break;
1430 }
1431 case Instruction::InsertElement: {
1432 const InsertElementInst* iei = cast<InsertElementInst>(I);
1433 Out << "InsertElementInst* " << getCppName(iei)
1434 << " = new InsertElementInst(" << opNames[0]
1435 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1436 printEscapedString(iei->getName());
1437 Out << "\", " << bbname << ");";
1438 break;
1439 }
1440 case Instruction::ShuffleVector: {
1441 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1442 Out << "ShuffleVectorInst* " << getCppName(svi)
1443 << " = new ShuffleVectorInst(" << opNames[0]
1444 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1445 printEscapedString(svi->getName());
1446 Out << "\", " << bbname << ");";
1447 break;
1448 }
1449 }
1450 DefinedValues.insert(I);
1451 nl(Out);
1452 delete [] opNames;
1453}
1454
1455// Print out the types, constants and declarations needed by one function
1456void CppWriter::printFunctionUses(const Function* F) {
1457
1458 nl(Out) << "// Type Definitions"; nl(Out);
1459 if (!is_inline) {
1460 // Print the function's return type
1461 printType(F->getReturnType());
1462
1463 // Print the function's function type
1464 printType(F->getFunctionType());
1465
1466 // Print the types of each of the function's arguments
1467 for(Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1468 AI != AE; ++AI) {
1469 printType(AI->getType());
1470 }
1471 }
1472
1473 // Print type definitions for every type referenced by an instruction and
1474 // make a note of any global values or constants that are referenced
1475 SmallPtrSet<GlobalValue*,64> gvs;
1476 SmallPtrSet<Constant*,64> consts;
1477 for (Function::const_iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB){
1478 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1479 I != E; ++I) {
1480 // Print the type of the instruction itself
1481 printType(I->getType());
1482
1483 // Print the type of each of the instruction's operands
1484 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1485 Value* operand = I->getOperand(i);
1486 printType(operand->getType());
1487
1488 // If the operand references a GVal or Constant, make a note of it
1489 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1490 gvs.insert(GV);
1491 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1492 if (GVar->hasInitializer())
1493 consts.insert(GVar->getInitializer());
1494 } else if (Constant* C = dyn_cast<Constant>(operand))
1495 consts.insert(C);
1496 }
1497 }
1498 }
1499
1500 // Print the function declarations for any functions encountered
1501 nl(Out) << "// Function Declarations"; nl(Out);
1502 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1503 I != E; ++I) {
1504 if (Function* Fun = dyn_cast<Function>(*I)) {
1505 if (!is_inline || Fun != F)
1506 printFunctionHead(Fun);
1507 }
1508 }
1509
1510 // Print the global variable declarations for any variables encountered
1511 nl(Out) << "// Global Variable Declarations"; nl(Out);
1512 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1513 I != E; ++I) {
1514 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1515 printVariableHead(F);
1516 }
1517
1518 // Print the constants found
1519 nl(Out) << "// Constant Definitions"; nl(Out);
1520 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(), E = consts.end();
1521 I != E; ++I) {
1522 printConstant(*I);
1523 }
1524
1525 // Process the global variables definitions now that all the constants have
1526 // been emitted. These definitions just couple the gvars with their constant
1527 // initializers.
1528 nl(Out) << "// Global Variable Definitions"; nl(Out);
1529 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1530 I != E; ++I) {
1531 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1532 printVariableBody(GV);
1533 }
1534}
1535
1536void CppWriter::printFunctionHead(const Function* F) {
1537 nl(Out) << "Function* " << getCppName(F);
1538 if (is_inline) {
1539 Out << " = mod->getFunction(\"";
1540 printEscapedString(F->getName());
1541 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1542 nl(Out) << "if (!" << getCppName(F) << ") {";
1543 nl(Out) << getCppName(F);
1544 }
1545 Out<< " = new Function(";
1546 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1547 nl(Out) << "/*Linkage=*/";
1548 printLinkageType(F->getLinkage());
1549 Out << ",";
1550 nl(Out) << "/*Name=*/\"";
1551 printEscapedString(F->getName());
1552 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1553 nl(Out,-1);
1554 printCppName(F);
1555 Out << "->setCallingConv(";
1556 printCallingConv(F->getCallingConv());
1557 Out << ");";
1558 nl(Out);
1559 if (F->hasSection()) {
1560 printCppName(F);
1561 Out << "->setSection(\"" << F->getSection() << "\");";
1562 nl(Out);
1563 }
1564 if (F->getAlignment()) {
1565 printCppName(F);
1566 Out << "->setAlignment(" << F->getAlignment() << ");";
1567 nl(Out);
1568 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001569 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1570 printCppName(F);
1571 Out << "->setVisibility(";
1572 printVisibilityType(F->getVisibility());
1573 Out << ");";
1574 nl(Out);
1575 }
Gordon Henriksen3e7ea1e2007-12-25 22:16:06 +00001576 if (F->hasCollector()) {
1577 printCppName(F);
1578 Out << "->setCollector(\"" << F->getCollector() << "\");";
1579 nl(Out);
1580 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001581 if (is_inline) {
1582 Out << "}";
1583 nl(Out);
1584 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001585 printParamAttrs(F->getParamAttrs(), getCppName(F));
1586 printCppName(F);
1587 Out << "->setParamAttrs(" << getCppName(F) << "_PAL);";
1588 nl(Out);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001589}
1590
1591void CppWriter::printFunctionBody(const Function *F) {
1592 if (F->isDeclaration())
1593 return; // external functions have no bodies.
1594
1595 // Clear the DefinedValues and ForwardRefs maps because we can't have
1596 // cross-function forward refs
1597 ForwardRefs.clear();
1598 DefinedValues.clear();
1599
1600 // Create all the argument values
1601 if (!is_inline) {
1602 if (!F->arg_empty()) {
1603 Out << "Function::arg_iterator args = " << getCppName(F)
1604 << "->arg_begin();";
1605 nl(Out);
1606 }
1607 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1608 AI != AE; ++AI) {
1609 Out << "Value* " << getCppName(AI) << " = args++;";
1610 nl(Out);
1611 if (AI->hasName()) {
1612 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1613 nl(Out);
1614 }
1615 }
1616 }
1617
1618 // Create all the basic blocks
1619 nl(Out);
1620 for (Function::const_iterator BI = F->begin(), BE = F->end();
1621 BI != BE; ++BI) {
1622 std::string bbname(getCppName(BI));
1623 Out << "BasicBlock* " << bbname << " = new BasicBlock(\"";
1624 if (BI->hasName())
1625 printEscapedString(BI->getName());
1626 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1627 nl(Out);
1628 }
1629
1630 // Output all of its basic blocks... for the function
1631 for (Function::const_iterator BI = F->begin(), BE = F->end();
1632 BI != BE; ++BI) {
1633 std::string bbname(getCppName(BI));
1634 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1635 nl(Out);
1636
1637 // Output all of the instructions in the basic block...
1638 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1639 I != E; ++I) {
1640 printInstruction(I,bbname);
1641 }
1642 }
1643
1644 // Loop over the ForwardRefs and resolve them now that all instructions
1645 // are generated.
1646 if (!ForwardRefs.empty()) {
1647 nl(Out) << "// Resolve Forward References";
1648 nl(Out);
1649 }
1650
1651 while (!ForwardRefs.empty()) {
1652 ForwardRefMap::iterator I = ForwardRefs.begin();
1653 Out << I->second << "->replaceAllUsesWith("
1654 << getCppName(I->first) << "); delete " << I->second << ";";
1655 nl(Out);
1656 ForwardRefs.erase(I);
1657 }
1658}
1659
1660void CppWriter::printInline(const std::string& fname, const std::string& func) {
1661 const Function* F = TheModule->getFunction(func);
1662 if (!F) {
1663 error(std::string("Function '") + func + "' not found in input module");
1664 return;
1665 }
1666 if (F->isDeclaration()) {
1667 error(std::string("Function '") + func + "' is external!");
1668 return;
1669 }
1670 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1671 << getCppName(F);
1672 unsigned arg_count = 1;
1673 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1674 AI != AE; ++AI) {
1675 Out << ", Value* arg_" << arg_count;
1676 }
1677 Out << ") {";
1678 nl(Out);
1679 is_inline = true;
1680 printFunctionUses(F);
1681 printFunctionBody(F);
1682 is_inline = false;
1683 Out << "return " << getCppName(F->begin()) << ";";
1684 nl(Out) << "}";
1685 nl(Out);
1686}
1687
1688void CppWriter::printModuleBody() {
1689 // Print out all the type definitions
1690 nl(Out) << "// Type Definitions"; nl(Out);
1691 printTypes(TheModule);
1692
1693 // Functions can call each other and global variables can reference them so
1694 // define all the functions first before emitting their function bodies.
1695 nl(Out) << "// Function Declarations"; nl(Out);
1696 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1697 I != E; ++I)
1698 printFunctionHead(I);
1699
1700 // Process the global variables declarations. We can't initialze them until
1701 // after the constants are printed so just print a header for each global
1702 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1703 for (Module::const_global_iterator I = TheModule->global_begin(),
1704 E = TheModule->global_end(); I != E; ++I) {
1705 printVariableHead(I);
1706 }
1707
1708 // Print out all the constants definitions. Constants don't recurse except
1709 // through GlobalValues. All GlobalValues have been declared at this point
1710 // so we can proceed to generate the constants.
1711 nl(Out) << "// Constant Definitions"; nl(Out);
1712 printConstants(TheModule);
1713
1714 // Process the global variables definitions now that all the constants have
1715 // been emitted. These definitions just couple the gvars with their constant
1716 // initializers.
1717 nl(Out) << "// Global Variable Definitions"; nl(Out);
1718 for (Module::const_global_iterator I = TheModule->global_begin(),
1719 E = TheModule->global_end(); I != E; ++I) {
1720 printVariableBody(I);
1721 }
1722
1723 // Finally, we can safely put out all of the function bodies.
1724 nl(Out) << "// Function Definitions"; nl(Out);
1725 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1726 I != E; ++I) {
1727 if (!I->isDeclaration()) {
1728 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1729 << ")";
1730 nl(Out) << "{";
1731 nl(Out,1);
1732 printFunctionBody(I);
1733 nl(Out,-1) << "}";
1734 nl(Out);
1735 }
1736 }
1737}
1738
1739void CppWriter::printProgram(
1740 const std::string& fname,
1741 const std::string& mName
1742) {
1743 Out << "#include <llvm/Module.h>\n";
1744 Out << "#include <llvm/DerivedTypes.h>\n";
1745 Out << "#include <llvm/Constants.h>\n";
1746 Out << "#include <llvm/GlobalVariable.h>\n";
1747 Out << "#include <llvm/Function.h>\n";
1748 Out << "#include <llvm/CallingConv.h>\n";
1749 Out << "#include <llvm/BasicBlock.h>\n";
1750 Out << "#include <llvm/Instructions.h>\n";
1751 Out << "#include <llvm/InlineAsm.h>\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001752 Out << "#include <llvm/Support/MathExtras.h>\n";
1753 Out << "#include <llvm/Pass.h>\n";
1754 Out << "#include <llvm/PassManager.h>\n";
1755 Out << "#include <llvm/Analysis/Verifier.h>\n";
1756 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1757 Out << "#include <algorithm>\n";
1758 Out << "#include <iostream>\n\n";
1759 Out << "using namespace llvm;\n\n";
1760 Out << "Module* " << fname << "();\n\n";
1761 Out << "int main(int argc, char**argv) {\n";
1762 Out << " Module* Mod = " << fname << "();\n";
1763 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1764 Out << " std::cerr.flush();\n";
1765 Out << " std::cout.flush();\n";
1766 Out << " PassManager PM;\n";
1767 Out << " PM.add(new PrintModulePass(&llvm::cout));\n";
1768 Out << " PM.run(*Mod);\n";
1769 Out << " return 0;\n";
1770 Out << "}\n\n";
1771 printModule(fname,mName);
1772}
1773
1774void CppWriter::printModule(
1775 const std::string& fname,
1776 const std::string& mName
1777) {
1778 nl(Out) << "Module* " << fname << "() {";
1779 nl(Out,1) << "// Module Construction";
1780 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1781 if (!TheModule->getTargetTriple().empty()) {
1782 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1783 }
1784 if (!TheModule->getTargetTriple().empty()) {
1785 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1786 << "\");";
1787 }
1788
1789 if (!TheModule->getModuleInlineAsm().empty()) {
1790 nl(Out) << "mod->setModuleInlineAsm(\"";
1791 printEscapedString(TheModule->getModuleInlineAsm());
1792 Out << "\");";
1793 }
1794 nl(Out);
1795
1796 // Loop over the dependent libraries and emit them.
1797 Module::lib_iterator LI = TheModule->lib_begin();
1798 Module::lib_iterator LE = TheModule->lib_end();
1799 while (LI != LE) {
1800 Out << "mod->addLibrary(\"" << *LI << "\");";
1801 nl(Out);
1802 ++LI;
1803 }
1804 printModuleBody();
1805 nl(Out) << "return mod;";
1806 nl(Out,-1) << "}";
1807 nl(Out);
1808}
1809
1810void CppWriter::printContents(
1811 const std::string& fname, // Name of generated function
1812 const std::string& mName // Name of module generated module
1813) {
1814 Out << "\nModule* " << fname << "(Module *mod) {\n";
1815 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1816 printModuleBody();
1817 Out << "\nreturn mod;\n";
1818 Out << "\n}\n";
1819}
1820
1821void CppWriter::printFunction(
1822 const std::string& fname, // Name of generated function
1823 const std::string& funcName // Name of function to generate
1824) {
1825 const Function* F = TheModule->getFunction(funcName);
1826 if (!F) {
1827 error(std::string("Function '") + funcName + "' not found in input module");
1828 return;
1829 }
1830 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1831 printFunctionUses(F);
1832 printFunctionHead(F);
1833 printFunctionBody(F);
1834 Out << "return " << getCppName(F) << ";\n";
1835 Out << "}\n";
1836}
1837
Chris Lattner0366a6d2007-11-13 18:22:33 +00001838void CppWriter::printFunctions() {
1839 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1840 Module::const_iterator I = funcs.begin();
1841 Module::const_iterator IE = funcs.end();
1842
1843 for (; I != IE; ++I) {
1844 const Function &func = *I;
1845 if (!func.isDeclaration()) {
1846 std::string name("define_");
1847 name += func.getName();
1848 printFunction(name, func.getName());
1849 }
1850 }
1851}
1852
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001853void CppWriter::printVariable(
1854 const std::string& fname, /// Name of generated function
1855 const std::string& varName // Name of variable to generate
1856) {
1857 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1858
1859 if (!GV) {
1860 error(std::string("Variable '") + varName + "' not found in input module");
1861 return;
1862 }
1863 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1864 printVariableUses(GV);
1865 printVariableHead(GV);
1866 printVariableBody(GV);
1867 Out << "return " << getCppName(GV) << ";\n";
1868 Out << "}\n";
1869}
1870
1871void CppWriter::printType(
1872 const std::string& fname, /// Name of generated function
1873 const std::string& typeName // Name of type to generate
1874) {
1875 const Type* Ty = TheModule->getTypeByName(typeName);
1876 if (!Ty) {
1877 error(std::string("Type '") + typeName + "' not found in input module");
1878 return;
1879 }
1880 Out << "\nType* " << fname << "(Module *mod) {\n";
1881 printType(Ty);
1882 Out << "return " << getCppName(Ty) << ";\n";
1883 Out << "}\n";
1884}
1885
1886} // end anonymous llvm
1887
1888namespace llvm {
1889
1890void WriteModuleToCppFile(Module* mod, std::ostream& o) {
1891 // Initialize a CppWriter for us to use
1892 CppWriter W(o, mod);
1893
1894 // Emit a header
1895 o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1896
1897 // Get the name of the function we're supposed to generate
1898 std::string fname = FuncName.getValue();
1899
1900 // Get the name of the thing we are to generate
1901 std::string tgtname = NameToGenerate.getValue();
1902 if (GenerationType == GenModule ||
1903 GenerationType == GenContents ||
Chris Lattner0366a6d2007-11-13 18:22:33 +00001904 GenerationType == GenProgram ||
1905 GenerationType == GenFunctions) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001906 if (tgtname == "!bad!") {
1907 if (mod->getModuleIdentifier() == "-")
1908 tgtname = "<stdin>";
1909 else
1910 tgtname = mod->getModuleIdentifier();
1911 }
1912 } else if (tgtname == "!bad!") {
1913 W.error("You must use the -for option with -gen-{function,variable,type}");
1914 }
1915
1916 switch (WhatToGenerate(GenerationType)) {
1917 case GenProgram:
1918 if (fname.empty())
1919 fname = "makeLLVMModule";
1920 W.printProgram(fname,tgtname);
1921 break;
1922 case GenModule:
1923 if (fname.empty())
1924 fname = "makeLLVMModule";
1925 W.printModule(fname,tgtname);
1926 break;
1927 case GenContents:
1928 if (fname.empty())
1929 fname = "makeLLVMModuleContents";
1930 W.printContents(fname,tgtname);
1931 break;
1932 case GenFunction:
1933 if (fname.empty())
1934 fname = "makeLLVMFunction";
1935 W.printFunction(fname,tgtname);
1936 break;
Chris Lattner0366a6d2007-11-13 18:22:33 +00001937 case GenFunctions:
1938 W.printFunctions();
1939 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001940 case GenInline:
1941 if (fname.empty())
1942 fname = "makeLLVMInline";
1943 W.printInline(fname,tgtname);
1944 break;
1945 case GenVariable:
1946 if (fname.empty())
1947 fname = "makeLLVMVariable";
1948 W.printVariable(fname,tgtname);
1949 break;
1950 case GenType:
1951 if (fname.empty())
1952 fname = "makeLLVMType";
1953 W.printType(fname,tgtname);
1954 break;
1955 default:
1956 W.error("Invalid generation option");
1957 }
1958}
1959
1960}