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