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