19 #include "llvm/Config/config.h"
59 cl::desc(
"Choose what kind of output to generate"),
75 cl::desc(
"Specify the name of the thing to generate"),
84 typedef std::vector<Type*> TypeList;
85 typedef std::map<Type*,std::string> TypeMap;
86 typedef std::map<const Value*,std::string>
ValueMap;
87 typedef std::set<std::string> NameSet;
88 typedef std::set<Type*> TypeSet;
89 typedef std::set<const Value*> ValueSet;
90 typedef std::map<const Value*,std::string> ForwardRefMap;
95 std::unique_ptr<formatted_raw_ostream> OutOwner;
102 TypeSet DefinedTypes;
103 ValueSet DefinedValues;
104 ForwardRefMap ForwardRefs;
106 unsigned indent_level;
110 explicit CppWriter(std::unique_ptr<formatted_raw_ostream> o)
111 :
ModulePass(
ID), OutOwner(std::move(o)), Out(*OutOwner), uniqueNum(0),
112 is_inline(
false), indent_level(0) {}
114 const char *getPassName()
const override {
return "C++ backend"; }
116 bool runOnModule(
Module &M)
override;
118 void printProgram(
const std::string& fname,
const std::string& modName );
119 void printModule(
const std::string& fname,
const std::string& modName );
120 void printContents(
const std::string& fname,
const std::string& modName );
121 void printFunction(
const std::string& fname,
const std::string& funcName );
122 void printFunctions();
123 void printInline(
const std::string& fname,
const std::string& funcName );
124 void printVariable(
const std::string& fname,
const std::string& varName );
125 void printType(
const std::string& fname,
const std::string& typeName );
127 void error(
const std::string& msg);
131 inline void in() { indent_level++; }
132 inline void out() {
if (indent_level >0) indent_level--; }
140 void printEscapedString(
const std::string& str);
143 std::string getCppName(
Type* val);
144 inline void printCppName(
Type* val);
146 std::string getCppName(
const Value* val);
147 inline void printCppName(
const Value* val);
150 void printType(
Type* Ty);
151 void printTypes(
const Module* M);
153 void printConstant(
const Constant *CPV);
154 void printConstants(
const Module* M);
160 void printFunctionUses(
const Function *
F);
161 void printFunctionHead(
const Function *
F);
162 void printFunctionBody(
const Function *
F);
163 void printInstruction(
const Instruction *
I,
const std::string& bbname);
164 std::string getOpName(
const Value*);
166 void printModuleBody();
172 if (delta >= 0 || indent_level >=
unsigned(-delta))
173 indent_level += delta;
179 for (
size_t i = 0; i < str.length(); ++i)
180 if (!isalnum(str[i]) && str[i] !=
'_')
197 default:
return "other_";
214 return "<unknown format in ftostr>";
220 void CppWriter::printCFP(
const ConstantFP *CFP) {
225 Out <<
"ConstantFP::get(mod->getContext(), ";
230 if ((!strncmp(Buffer,
"0x", 2) ||
231 !strncmp(Buffer,
"-0x", 3) ||
232 !strncmp(Buffer,
"+0x", 3)) &&
235 Out <<
"BitsToDouble(" << Buffer <<
")";
237 Out <<
"BitsToFloat((float)" << Buffer <<
")";
243 while (StrVal[0] ==
' ')
244 StrVal.erase(StrVal.begin());
248 if (((StrVal[0] >=
'0' && StrVal[0] <=
'9') ||
249 ((StrVal[0] ==
'-' || StrVal[0] ==
'+') &&
250 (StrVal[1] >=
'0' && StrVal[1] <=
'9'))) &&
255 Out << StrVal <<
"f";
257 Out <<
"BitsToDouble(0x"
259 <<
"ULL) /* " << StrVal <<
" */";
261 Out <<
"BitsToFloat(0x"
263 bitcastToAPInt().getZExtValue())
264 <<
"U) /* " << StrVal <<
" */";
279 default: Out << cc;
break;
286 Out <<
"GlobalValue::InternalLinkage";
break;
288 Out <<
"GlobalValue::PrivateLinkage";
break;
290 Out <<
"GlobalValue::AvailableExternallyLinkage ";
break;
292 Out <<
"GlobalValue::LinkOnceAnyLinkage ";
break;
294 Out <<
"GlobalValue::LinkOnceODRLinkage ";
break;
296 Out <<
"GlobalValue::WeakAnyLinkage";
break;
298 Out <<
"GlobalValue::WeakODRLinkage";
break;
300 Out <<
"GlobalValue::AppendingLinkage";
break;
302 Out <<
"GlobalValue::ExternalLinkage";
break;
304 Out <<
"GlobalValue::ExternalWeakLinkage";
break;
306 Out <<
"GlobalValue::CommonLinkage";
break;
313 Out <<
"GlobalValue::DefaultVisibility";
316 Out <<
"GlobalValue::HiddenVisibility";
319 Out <<
"GlobalValue::ProtectedVisibility";
324 void CppWriter::printDLLStorageClassType(
328 Out <<
"GlobalValue::DefaultStorageClass";
331 Out <<
"GlobalValue::DLLImportStorageClass";
334 Out <<
"GlobalValue::DLLExportStorageClass";
342 Out <<
"GlobalVariable::NotThreadLocal";
345 Out <<
"GlobalVariable::GeneralDynamicTLSModel";
348 Out <<
"GlobalVariable::LocalDynamicTLSModel";
351 Out <<
"GlobalVariable::InitialExecTLSModel";
354 Out <<
"GlobalVariable::LocalExecTLSModel";
361 void CppWriter::printEscapedString(
const std::string &Str) {
362 for (
unsigned i = 0, e = Str.size(); i != e; ++i) {
363 unsigned char C = Str[i];
364 if (isprint(C) && C !=
'"' && C !=
'\\') {
368 << (char) ((C/16 < 10) ? ( C/16 +
'0') : ( C/16 -10+
'A'))
369 << (
char)(((C&15) < 10) ? ((C&15)+
'0') : ((C&15)-10+
'A'));
374 std::string CppWriter::getCppName(
Type* Ty) {
379 return "Type::getVoidTy(mod->getContext())";
381 unsigned BitWidth = cast<IntegerType>(Ty)->
getBitWidth();
382 return "IntegerType::get(mod->getContext(), " +
utostr(BitWidth) +
")";
385 return "Type::getX86_FP80Ty(mod->getContext())";
387 return "Type::getFloatTy(mod->getContext())";
389 return "Type::getDoubleTy(mod->getContext())";
391 return "Type::getLabelTy(mod->getContext())";
393 return "Type::getX86_MMXTy(mod->getContext())";
397 TypeMap::iterator
I = TypeNames.find(Ty);
398 if (I != TypeNames.end())
402 const char* prefix =
nullptr;
409 default: prefix =
"OtherTy_";
break;
414 if (
StructType *STy = dyn_cast<StructType>(Ty))
416 name = STy->getName();
419 name =
utostr(uniqueNum++);
421 name = std::string(prefix) +
name;
425 return TypeNames[Ty] =
name;
428 void CppWriter::printCppName(
Type* Ty) {
429 printEscapedString(getCppName(Ty));
432 std::string CppWriter::getCppName(
const Value* val) {
435 if (I != ValueNames.end() && I->
first == val)
439 name = std::string(
"gvar_") +
441 }
else if (isa<Function>(val)) {
442 name = std::string(
"func_");
443 }
else if (
const Constant* C = dyn_cast<Constant>(val)) {
445 }
else if (
const Argument* Arg = dyn_cast<Argument>(val)) {
447 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
449 name = std::string(
"arg_") +
utostr(argNum);
450 NameSet::iterator NI = UsedNames.find(name);
451 if (NI != UsedNames.end())
452 name += std::string(
"_") +
utostr(uniqueNum++);
453 UsedNames.insert(name);
454 return ValueNames[val] =
name;
464 name +=
utostr(uniqueNum++);
466 NameSet::iterator NI = UsedNames.find(name);
467 if (NI != UsedNames.end())
468 name += std::string(
"_") +
utostr(uniqueNum++);
469 UsedNames.insert(name);
470 return ValueNames[val] =
name;
473 void CppWriter::printCppName(
const Value* val) {
474 printEscapedString(getCppName(val));
477 void CppWriter::printAttributes(
const AttributeSet &PAL,
478 const std::string &name) {
479 Out <<
"AttributeSet " << name <<
"_PAL;";
482 Out <<
'{'; in(); nl(Out);
483 Out <<
"SmallVector<AttributeSet, 4> Attrs;"; nl(Out);
484 Out <<
"AttributeSet PAS;"; in(); nl(Out);
488 Out <<
"{"; in(); nl(Out);
489 Out <<
"AttrBuilder B;"; nl(Out);
491 #define HANDLE_ATTR(X) \
492 if (attrs.contains(Attribute::X)) { \
493 Out << "B.addAttribute(Attribute::" #X ");"; nl(Out); \
494 attrs.removeAttribute(Attribute::X); \
529 Out <<
"B.addStackAlignmentAttr(" << attrs.getStackAlignment()<<
')';
534 Out <<
"PAS = AttributeSet::get(mod->getContext(), ";
538 Out << index <<
"U,";
539 Out <<
" B);"; out(); nl(Out);
540 Out <<
"}"; out(); nl(Out);
542 Out <<
"Attrs.push_back(PAS);"; nl(Out);
544 Out << name <<
"_PAL = AttributeSet::get(mod->getContext(), Attrs);";
551 void CppWriter::printType(
Type* Ty) {
558 if (DefinedTypes.find(Ty) != DefinedTypes.end())
562 std::string typeName(getCppName(Ty));
568 Out <<
"std::vector<Type*>" << typeName <<
"_args;";
572 for (; PI != PE; ++PI) {
573 Type* argTy =
static_cast<Type*
>(*PI);
575 std::string argName(getCppName(argTy));
576 Out << typeName <<
"_args.push_back(" << argName;
582 Out <<
"FunctionType* " << typeName <<
" = FunctionType::get(";
583 in(); nl(Out) <<
"/*Result=*/" << retTypeName;
585 nl(Out) <<
"/*Params=*/" << typeName <<
"_args,";
586 nl(Out) <<
"/*isVarArg=*/" << (FT->
isVarArg() ?
"true" :
"false") <<
");";
594 Out <<
"StructType *" << typeName <<
" = mod->getTypeByName(\"";
595 printEscapedString(ST->
getName());
598 Out <<
"if (!" << typeName <<
") {";
600 Out << typeName <<
" = ";
601 Out <<
"StructType::create(mod->getContext(), \"";
602 printEscapedString(ST->
getName());
608 DefinedTypes.insert(Ty);
611 Out <<
"std::vector<Type*>" << typeName <<
"_fields;";
615 for (; EI != EE; ++EI) {
616 Type* fieldTy =
static_cast<Type*
>(*EI);
618 std::string fieldName(getCppName(fieldTy));
619 Out << typeName <<
"_fields.push_back(" << fieldName;
625 Out <<
"StructType *" << typeName <<
" = ";
626 Out <<
"StructType::get(" <<
"mod->getContext(), ";
628 Out <<
"if (" << typeName <<
"->isOpaque()) {";
630 Out << typeName <<
"->setBody(";
633 Out << typeName <<
"_fields, /*isPacked=*/"
634 << (ST->
isPacked() ?
"true" :
"false") <<
");";
646 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
647 std::string elemName(getCppName(ET));
648 Out <<
"ArrayType* " << typeName <<
" = ArrayType::get("
658 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
659 std::string elemName(getCppName(ET));
660 Out <<
"PointerType* " << typeName <<
" = PointerType::get("
670 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
671 std::string elemName(getCppName(ET));
672 Out <<
"VectorType* " << typeName <<
" = VectorType::get("
679 error(
"Invalid TypeID");
683 DefinedTypes.insert(Ty);
689 void CppWriter::printTypes(
const Module* M) {
692 E = TheModule->global_end(); I != E; ++
I) {
693 if (I->hasInitializer())
694 printType(I->getInitializer()->getType());
695 printType(I->getType());
701 printType(FI->getReturnType());
702 printType(FI->getFunctionType());
705 AE = FI->arg_end(); AI != AE; ++AI) {
706 printType(AI->getType());
711 E = FI->end(); BB != E; ++BB) {
712 printType(BB->getType());
715 printType(I->getType());
716 for (
unsigned i = 0; i < I->getNumOperands(); ++i)
717 printType(I->getOperand(i)->getType());
725 void CppWriter::printConstant(
const Constant *CV) {
729 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
732 std::string constName(getCppName(CV));
733 std::string typeName(getCppName(CV->
getType()));
735 if (
const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
736 std::string constValue = CI->getValue().toString(10,
true);
737 Out <<
"ConstantInt* " << constName
738 <<
" = ConstantInt::get(mod->getContext(), APInt("
740 <<
", StringRef(\"" << constValue <<
"\"), 10));";
741 }
else if (isa<ConstantAggregateZero>(CV)) {
742 Out <<
"ConstantAggregateZero* " << constName
743 <<
" = ConstantAggregateZero::get(" << typeName <<
");";
744 }
else if (isa<ConstantPointerNull>(CV)) {
745 Out <<
"ConstantPointerNull* " << constName
746 <<
" = ConstantPointerNull::get(" << typeName <<
");";
747 }
else if (
const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
748 Out <<
"ConstantFP* " << constName <<
" = ";
751 }
else if (
const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
752 Out <<
"std::vector<Constant*> " << constName <<
"_elems;";
754 unsigned N = CA->getNumOperands();
755 for (
unsigned i = 0; i <
N; ++i) {
756 printConstant(CA->getOperand(i));
757 Out << constName <<
"_elems.push_back("
758 << getCppName(CA->getOperand(i)) <<
");";
761 Out <<
"Constant* " << constName <<
" = ConstantArray::get("
762 << typeName <<
", " << constName <<
"_elems);";
763 }
else if (
const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
764 Out <<
"std::vector<Constant*> " << constName <<
"_fields;";
766 unsigned N =
CS->getNumOperands();
767 for (
unsigned i = 0; i <
N; i++) {
768 printConstant(
CS->getOperand(i));
769 Out << constName <<
"_fields.push_back("
770 << getCppName(
CS->getOperand(i)) <<
");";
773 Out <<
"Constant* " << constName <<
" = ConstantStruct::get("
774 << typeName <<
", " << constName <<
"_fields);";
775 }
else if (
const ConstantVector *CVec = dyn_cast<ConstantVector>(CV)) {
776 Out <<
"std::vector<Constant*> " << constName <<
"_elems;";
778 unsigned N = CVec->getNumOperands();
779 for (
unsigned i = 0; i <
N; ++i) {
780 printConstant(CVec->getOperand(i));
781 Out << constName <<
"_elems.push_back("
782 << getCppName(CVec->getOperand(i)) <<
");";
785 Out <<
"Constant* " << constName <<
" = ConstantVector::get("
786 << typeName <<
", " << constName <<
"_elems);";
787 }
else if (isa<UndefValue>(CV)) {
788 Out <<
"UndefValue* " << constName <<
" = UndefValue::get("
791 dyn_cast<ConstantDataSequential>(CV)) {
792 if (CDS->isString()) {
793 Out <<
"Constant *" << constName <<
794 " = ConstantDataArray::getString(mod->getContext(), \"";
796 bool nullTerminate =
false;
797 if (Str.
back() == 0) {
799 nullTerminate =
true;
801 printEscapedString(Str);
806 Out <<
"\", false);";
809 Out <<
"std::vector<Constant*> " << constName <<
"_elems;";
811 for (
unsigned i = 0; i != CDS->getNumElements(); ++i) {
812 Constant *Elt = CDS->getElementAsConstant(i);
814 Out << constName <<
"_elems.push_back(" << getCppName(Elt) <<
");";
817 Out <<
"Constant* " << constName;
819 if (isa<ArrayType>(CDS->getType()))
820 Out <<
" = ConstantArray::get(";
822 Out <<
" = ConstantVector::get(";
823 Out << typeName <<
", " << constName <<
"_elems);";
825 }
else if (
const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
826 if (
CE->getOpcode() == Instruction::GetElementPtr) {
827 Out <<
"std::vector<Constant*> " << constName <<
"_indices;";
829 printConstant(
CE->getOperand(0));
830 for (
unsigned i = 1; i <
CE->getNumOperands(); ++i ) {
831 printConstant(
CE->getOperand(i));
832 Out << constName <<
"_indices.push_back("
833 << getCppName(
CE->getOperand(i)) <<
");";
836 Out <<
"Constant* " << constName
837 <<
" = ConstantExpr::getGetElementPtr("
838 << getCppName(
CE->getOperand(0)) <<
", "
839 << constName <<
"_indices);";
840 }
else if (
CE->isCast()) {
841 printConstant(
CE->getOperand(0));
842 Out <<
"Constant* " << constName <<
" = ConstantExpr::getCast(";
843 switch (
CE->getOpcode()) {
845 case Instruction::Trunc: Out <<
"Instruction::Trunc";
break;
846 case Instruction::ZExt: Out <<
"Instruction::ZExt";
break;
847 case Instruction::SExt: Out <<
"Instruction::SExt";
break;
848 case Instruction::FPTrunc: Out <<
"Instruction::FPTrunc";
break;
849 case Instruction::FPExt: Out <<
"Instruction::FPExt";
break;
850 case Instruction::FPToUI: Out <<
"Instruction::FPToUI";
break;
851 case Instruction::FPToSI: Out <<
"Instruction::FPToSI";
break;
852 case Instruction::UIToFP: Out <<
"Instruction::UIToFP";
break;
853 case Instruction::SIToFP: Out <<
"Instruction::SIToFP";
break;
854 case Instruction::PtrToInt: Out <<
"Instruction::PtrToInt";
break;
855 case Instruction::IntToPtr: Out <<
"Instruction::IntToPtr";
break;
856 case Instruction::BitCast: Out <<
"Instruction::BitCast";
break;
858 Out <<
", " << getCppName(
CE->getOperand(0)) <<
", "
859 << getCppName(
CE->getType()) <<
");";
861 unsigned N =
CE->getNumOperands();
862 for (
unsigned i = 0; i <
N; ++i ) {
863 printConstant(
CE->getOperand(i));
865 Out <<
"Constant* " << constName <<
" = ConstantExpr::";
866 switch (
CE->getOpcode()) {
867 case Instruction::Add: Out <<
"getAdd(";
break;
868 case Instruction::FAdd: Out <<
"getFAdd(";
break;
869 case Instruction::Sub: Out <<
"getSub(";
break;
870 case Instruction::FSub: Out <<
"getFSub(";
break;
871 case Instruction::Mul: Out <<
"getMul(";
break;
872 case Instruction::FMul: Out <<
"getFMul(";
break;
873 case Instruction::UDiv: Out <<
"getUDiv(";
break;
874 case Instruction::SDiv: Out <<
"getSDiv(";
break;
875 case Instruction::FDiv: Out <<
"getFDiv(";
break;
876 case Instruction::URem: Out <<
"getURem(";
break;
877 case Instruction::SRem: Out <<
"getSRem(";
break;
878 case Instruction::FRem: Out <<
"getFRem(";
break;
882 case Instruction::ICmp:
883 Out <<
"getICmp(ICmpInst::ICMP_";
884 switch (
CE->getPredicate()) {
895 default:
error(
"Invalid ICmp Predicate");
898 case Instruction::FCmp:
899 Out <<
"getFCmp(FCmpInst::FCMP_";
900 switch (
CE->getPredicate()) {
917 default:
error(
"Invalid FCmp Predicate");
920 case Instruction::Shl: Out <<
"getShl(";
break;
921 case Instruction::LShr: Out <<
"getLShr(";
break;
922 case Instruction::AShr: Out <<
"getAShr(";
break;
925 case Instruction::InsertElement: Out <<
"getInsertElement(";
break;
926 case Instruction::ShuffleVector: Out <<
"getShuffleVector(";
break;
928 error(
"Invalid constant expression");
931 Out << getCppName(
CE->getOperand(0));
932 for (
unsigned i = 1; i <
CE->getNumOperands(); ++i)
933 Out <<
", " << getCppName(
CE->getOperand(i));
936 }
else if (
const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
937 Out <<
"Constant* " << constName <<
" = ";
938 Out <<
"BlockAddress::get(" << getOpName(BA->getBasicBlock()) <<
");";
940 error(
"Bad Constant");
941 Out <<
"Constant* " << constName <<
" = 0; ";
946 void CppWriter::printConstants(
const Module* M) {
949 E = TheModule->global_end(); I != E; ++
I)
950 if (I->hasInitializer())
951 printConstant(I->getInitializer());
958 E = FI->end(); BB != E; ++BB) {
961 for (
unsigned i = 0; i < I->getNumOperands(); ++i) {
962 if (
Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
972 nl(Out) <<
"// Type Definitions";
978 if (
const Function *
F = dyn_cast<Function>(Init)) {
979 nl(Out)<<
"/ Function Declarations"; nl(Out);
980 printFunctionHead(
F);
981 }
else if (
const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
982 nl(Out) <<
"// Global Variable Declarations"; nl(Out);
983 printVariableHead(gv);
985 nl(Out) <<
"// Global Variable Definitions"; nl(Out);
986 printVariableBody(gv);
988 nl(Out) <<
"// Constant Definitions"; nl(Out);
995 nl(Out) <<
"GlobalVariable* " << getCppName(GV);
997 Out <<
" = mod->getGlobalVariable(mod->getContext(), ";
998 printEscapedString(GV->
getName());
1000 nl(Out) <<
"if (!" << getCppName(GV) <<
") {";
1001 in(); nl(Out) << getCppName(GV);
1003 Out <<
" = new GlobalVariable(/*Module=*/*mod, ";
1004 nl(Out) <<
"/*Type=*/";
1007 nl(Out) <<
"/*isConstant=*/" << (GV->
isConstant()?
"true":
"false");
1009 nl(Out) <<
"/*Linkage=*/";
1012 nl(Out) <<
"/*Initializer=*/0, ";
1014 Out <<
"// has initializer, specified below";
1016 nl(Out) <<
"/*Name=*/\"";
1017 printEscapedString(GV->
getName());
1023 Out <<
"->setSection(\"";
1030 Out <<
"->setAlignment(" << GV->
getAlignment() <<
");";
1035 Out <<
"->setVisibility(";
1042 Out <<
"->setDLLStorageClass(";
1049 Out <<
"->setThreadLocalMode(";
1055 out(); Out <<
"}"; nl(Out);
1062 Out <<
"->setInitializer(";
1068 std::string CppWriter::getOpName(
const Value* V) {
1069 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1070 return getCppName(V);
1074 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1075 if (I != ForwardRefs.end())
1079 std::string result(std::string(
"fwdref_") +
utostr(uniqueNum++));
1084 Out <<
"Argument* " << result <<
" = new Argument("
1085 << getCppName(V->
getType()) <<
");";
1087 ForwardRefs[V] = result;
1096 case Acquire:
return "Acquire";
1097 case Release:
return "Release";
1105 switch (SynchScope) {
1113 void CppWriter::printInstruction(
const Instruction *I,
1114 const std::string& bbname) {
1115 std::string iName(getCppName(I));
1120 std::string* opNames =
new std::string[Ops];
1121 for (
unsigned i = 0; i < Ops; i++)
1126 error(
"Invalid instruction");
1131 Out <<
"ReturnInst::Create(mod->getContext(), "
1132 << (ret->
getReturnValue() ? opNames[0] +
", " :
"") << bbname <<
");";
1135 case Instruction::Br: {
1137 Out <<
"BranchInst::Create(" ;
1139 Out << opNames[2] <<
", "
1140 << opNames[1] <<
", "
1141 << opNames[0] <<
", ";
1144 Out << opNames[0] <<
", ";
1146 error(
"Branch with 2 operands?");
1148 Out << bbname <<
");";
1151 case Instruction::Switch: {
1153 Out <<
"SwitchInst* " << iName <<
" = SwitchInst::Create("
1162 Out << iName <<
"->addCase("
1163 << getOpName(CaseVal) <<
", "
1164 << getOpName(BB) <<
");";
1169 case Instruction::IndirectBr: {
1171 Out <<
"IndirectBrInst *" << iName <<
" = IndirectBrInst::Create("
1175 Out << iName <<
"->addDestination(" << opNames[i] <<
");";
1180 case Instruction::Resume: {
1181 Out <<
"ResumeInst::Create(" << opNames[0] <<
", " << bbname <<
");";
1184 case Instruction::Invoke: {
1186 Out <<
"std::vector<Value*> " << iName <<
"_params;";
1189 Out << iName <<
"_params.push_back("
1194 Out <<
"InvokeInst *" << iName <<
" = InvokeInst::Create("
1198 << iName <<
"_params, \"";
1199 printEscapedString(inv->
getName());
1200 Out <<
"\", " << bbname <<
");";
1201 nl(Out) << iName <<
"->setCallingConv(";
1205 Out << iName <<
"->setAttributes(" << iName <<
"_PAL);";
1209 case Instruction::Unreachable: {
1210 Out <<
"new UnreachableInst("
1211 <<
"mod->getContext(), "
1215 case Instruction::Add:
1216 case Instruction::FAdd:
1217 case Instruction::Sub:
1218 case Instruction::FSub:
1219 case Instruction::Mul:
1220 case Instruction::FMul:
1221 case Instruction::UDiv:
1222 case Instruction::SDiv:
1223 case Instruction::FDiv:
1224 case Instruction::URem:
1225 case Instruction::SRem:
1226 case Instruction::FRem:
1230 case Instruction::Shl:
1231 case Instruction::LShr:
1232 case Instruction::AShr:{
1233 Out <<
"BinaryOperator* " << iName <<
" = BinaryOperator::Create(";
1235 case Instruction::Add: Out <<
"Instruction::Add";
break;
1236 case Instruction::FAdd: Out <<
"Instruction::FAdd";
break;
1237 case Instruction::Sub: Out <<
"Instruction::Sub";
break;
1238 case Instruction::FSub: Out <<
"Instruction::FSub";
break;
1239 case Instruction::Mul: Out <<
"Instruction::Mul";
break;
1240 case Instruction::FMul: Out <<
"Instruction::FMul";
break;
1241 case Instruction::UDiv:Out <<
"Instruction::UDiv";
break;
1242 case Instruction::SDiv:Out <<
"Instruction::SDiv";
break;
1243 case Instruction::FDiv:Out <<
"Instruction::FDiv";
break;
1244 case Instruction::URem:Out <<
"Instruction::URem";
break;
1245 case Instruction::SRem:Out <<
"Instruction::SRem";
break;
1246 case Instruction::FRem:Out <<
"Instruction::FRem";
break;
1250 case Instruction::Shl: Out <<
"Instruction::Shl";
break;
1251 case Instruction::LShr:Out <<
"Instruction::LShr";
break;
1252 case Instruction::AShr:Out <<
"Instruction::AShr";
break;
1253 default: Out <<
"Instruction::BadOpCode";
break;
1255 Out <<
", " << opNames[0] <<
", " << opNames[1] <<
", \"";
1256 printEscapedString(I->
getName());
1257 Out <<
"\", " << bbname <<
");";
1260 case Instruction::FCmp: {
1261 Out <<
"FCmpInst* " << iName <<
" = new FCmpInst(*" << bbname <<
", ";
1262 switch (cast<FCmpInst>(I)->getPredicate()) {
1279 default: Out <<
"FCmpInst::BAD_ICMP_PREDICATE";
break;
1281 Out <<
", " << opNames[0] <<
", " << opNames[1] <<
", \"";
1282 printEscapedString(I->
getName());
1286 case Instruction::ICmp: {
1287 Out <<
"ICmpInst* " << iName <<
" = new ICmpInst(*" << bbname <<
", ";
1288 switch (cast<ICmpInst>(I)->getPredicate()) {
1299 default: Out <<
"ICmpInst::BAD_ICMP_PREDICATE";
break;
1301 Out <<
", " << opNames[0] <<
", " << opNames[1] <<
", \"";
1302 printEscapedString(I->
getName());
1306 case Instruction::Alloca: {
1308 Out <<
"AllocaInst* " << iName <<
" = new AllocaInst("
1311 Out << opNames[0] <<
", ";
1313 printEscapedString(allocaI->
getName());
1314 Out <<
"\", " << bbname <<
");";
1316 nl(Out) << iName <<
"->setAlignment("
1321 const LoadInst* load = cast<LoadInst>(
I);
1322 Out <<
"LoadInst* " << iName <<
" = new LoadInst("
1323 << opNames[0] <<
", \"";
1324 printEscapedString(load->
getName());
1325 Out <<
"\", " << (load->
isVolatile() ?
"true" :
"false" )
1326 <<
", " << bbname <<
");";
1328 nl(Out) << iName <<
"->setAlignment("
1333 nl(Out) << iName <<
"->setAtomic("
1334 << Ordering <<
", " << CrossThread <<
");";
1340 Out <<
"StoreInst* " << iName <<
" = new StoreInst("
1341 << opNames[0] <<
", "
1342 << opNames[1] <<
", "
1344 <<
", " << bbname <<
");";
1346 nl(Out) << iName <<
"->setAlignment("
1351 nl(Out) << iName <<
"->setAtomic("
1352 << Ordering <<
", " << CrossThread <<
");";
1356 case Instruction::GetElementPtr: {
1359 Out <<
"GetElementPtrInst* " << iName <<
" = GetElementPtrInst::Create("
1362 Out <<
", " << opNames[1];
1364 Out <<
"std::vector<Value*> " << iName <<
"_indices;";
1367 Out << iName <<
"_indices.push_back("
1368 << opNames[i] <<
");";
1371 Out <<
"Instruction* " << iName <<
" = GetElementPtrInst::Create("
1372 << opNames[0] <<
", " << iName <<
"_indices";
1375 printEscapedString(gep->
getName());
1376 Out <<
"\", " << bbname <<
");";
1380 const PHINode* phi = cast<PHINode>(
I);
1382 Out <<
"PHINode* " << iName <<
" = PHINode::Create("
1383 << getCppName(phi->
getType()) <<
", "
1385 printEscapedString(phi->
getName());
1386 Out <<
"\", " << bbname <<
");";
1389 Out << iName <<
"->addIncoming("
1396 case Instruction::Trunc:
1397 case Instruction::ZExt:
1398 case Instruction::SExt:
1399 case Instruction::FPTrunc:
1400 case Instruction::FPExt:
1401 case Instruction::FPToUI:
1402 case Instruction::FPToSI:
1403 case Instruction::UIToFP:
1404 case Instruction::SIToFP:
1405 case Instruction::PtrToInt:
1406 case Instruction::IntToPtr:
1407 case Instruction::BitCast: {
1408 const CastInst* cst = cast<CastInst>(
I);
1409 Out <<
"CastInst* " << iName <<
" = new ";
1411 case Instruction::Trunc: Out <<
"TruncInst";
break;
1412 case Instruction::ZExt: Out <<
"ZExtInst";
break;
1413 case Instruction::SExt: Out <<
"SExtInst";
break;
1414 case Instruction::FPTrunc: Out <<
"FPTruncInst";
break;
1415 case Instruction::FPExt: Out <<
"FPExtInst";
break;
1416 case Instruction::FPToUI: Out <<
"FPToUIInst";
break;
1417 case Instruction::FPToSI: Out <<
"FPToSIInst";
break;
1418 case Instruction::UIToFP: Out <<
"UIToFPInst";
break;
1419 case Instruction::SIToFP: Out <<
"SIToFPInst";
break;
1420 case Instruction::PtrToInt: Out <<
"PtrToIntInst";
break;
1421 case Instruction::IntToPtr: Out <<
"IntToPtrInst";
break;
1422 case Instruction::BitCast: Out <<
"BitCastInst";
break;
1425 Out <<
"(" << opNames[0] <<
", "
1426 << getCppName(cst->
getType()) <<
", \"";
1427 printEscapedString(cst->
getName());
1428 Out <<
"\", " << bbname <<
");";
1432 const CallInst* call = cast<CallInst>(
I);
1434 Out <<
"InlineAsm* " << getCppName(ila) <<
" = InlineAsm::get("
1435 << getCppName(ila->getFunctionType()) <<
", \""
1436 << ila->getAsmString() <<
"\", \""
1437 << ila->getConstraintString() <<
"\","
1438 << (ila->hasSideEffects() ?
"true" :
"false") <<
");";
1442 Out <<
"std::vector<Value*> " << iName <<
"_params;";
1445 Out << iName <<
"_params.push_back(" << opNames[i] <<
");";
1448 Out <<
"CallInst* " << iName <<
" = CallInst::Create("
1450 << iName <<
"_params, \"";
1452 Out <<
"CallInst* " << iName <<
" = CallInst::Create("
1455 Out <<
"CallInst* " << iName <<
" = CallInst::Create("
1458 printEscapedString(call->
getName());
1459 Out <<
"\", " << bbname <<
");";
1460 nl(Out) << iName <<
"->setCallingConv(";
1463 nl(Out) << iName <<
"->setTailCall("
1468 Out << iName <<
"->setAttributes(" << iName <<
"_PAL);";
1474 Out <<
"SelectInst* " << getCppName(sel) <<
" = SelectInst::Create(";
1475 Out << opNames[0] <<
", " << opNames[1] <<
", " << opNames[2] <<
", \"";
1476 printEscapedString(sel->
getName());
1477 Out <<
"\", " << bbname <<
");";
1480 case Instruction::UserOp1:
1482 case Instruction::UserOp2: {
1486 case Instruction::VAArg: {
1488 Out <<
"VAArgInst* " << getCppName(va) <<
" = new VAArgInst("
1489 << opNames[0] <<
", " << getCppName(va->
getType()) <<
", \"";
1490 printEscapedString(va->
getName());
1491 Out <<
"\", " << bbname <<
");";
1496 Out <<
"ExtractElementInst* " << getCppName(eei)
1497 <<
" = new ExtractElementInst(" << opNames[0]
1498 <<
", " << opNames[1] <<
", \"";
1499 printEscapedString(eei->
getName());
1500 Out <<
"\", " << bbname <<
");";
1503 case Instruction::InsertElement: {
1505 Out <<
"InsertElementInst* " << getCppName(iei)
1506 <<
" = InsertElementInst::Create(" << opNames[0]
1507 <<
", " << opNames[1] <<
", " << opNames[2] <<
", \"";
1508 printEscapedString(iei->
getName());
1509 Out <<
"\", " << bbname <<
");";
1512 case Instruction::ShuffleVector: {
1514 Out <<
"ShuffleVectorInst* " << getCppName(svi)
1515 <<
" = new ShuffleVectorInst(" << opNames[0]
1516 <<
", " << opNames[1] <<
", " << opNames[2] <<
", \"";
1517 printEscapedString(svi->
getName());
1518 Out <<
"\", " << bbname <<
");";
1521 case Instruction::ExtractValue: {
1523 Out <<
"std::vector<unsigned> " << iName <<
"_indices;";
1526 Out << iName <<
"_indices.push_back("
1530 Out <<
"ExtractValueInst* " << getCppName(evi)
1531 <<
" = ExtractValueInst::Create(" << opNames[0]
1533 << iName <<
"_indices, \"";
1534 printEscapedString(evi->
getName());
1535 Out <<
"\", " << bbname <<
");";
1538 case Instruction::InsertValue: {
1540 Out <<
"std::vector<unsigned> " << iName <<
"_indices;";
1543 Out << iName <<
"_indices.push_back("
1547 Out <<
"InsertValueInst* " << getCppName(ivi)
1548 <<
" = InsertValueInst::Create(" << opNames[0]
1549 <<
", " << opNames[1] <<
", "
1550 << iName <<
"_indices, \"";
1551 printEscapedString(ivi->
getName());
1552 Out <<
"\", " << bbname <<
");";
1555 case Instruction::Fence: {
1559 Out <<
"FenceInst* " << iName
1560 <<
" = new FenceInst(mod->getContext(), "
1561 << Ordering <<
", " << CrossThread <<
", " << bbname
1565 case Instruction::AtomicCmpXchg: {
1572 Out <<
"AtomicCmpXchgInst* " << iName
1573 <<
" = new AtomicCmpXchgInst("
1574 << opNames[0] <<
", " << opNames[1] <<
", " << opNames[2] <<
", "
1575 << SuccessOrdering <<
", " << FailureOrdering <<
", "
1576 << CrossThread <<
", " << bbname
1578 nl(Out) << iName <<
"->setName(\"";
1579 printEscapedString(cxi->
getName());
1581 nl(Out) << iName <<
"->setVolatile("
1582 << (cxi->
isVolatile() ?
"true" :
"false") <<
");";
1583 nl(Out) << iName <<
"->setWeak("
1584 << (cxi->
isWeak() ?
"true" :
"false") <<
");";
1587 case Instruction::AtomicRMW: {
1606 Out <<
"AtomicRMWInst* " << iName
1607 <<
" = new AtomicRMWInst("
1608 << Operation <<
", "
1609 << opNames[0] <<
", " << opNames[1] <<
", "
1610 << Ordering <<
", " << CrossThread <<
", " << bbname
1612 nl(Out) << iName <<
"->setName(\"";
1613 printEscapedString(rmwi->
getName());
1615 nl(Out) << iName <<
"->setVolatile("
1616 << (rmwi->
isVolatile() ?
"true" :
"false") <<
");";
1619 case Instruction::LandingPad: {
1621 Out <<
"LandingPadInst* " << iName <<
" = LandingPadInst::Create(";
1623 Out <<
", " << opNames[0] <<
", " << lpi->
getNumClauses() <<
", \"";
1624 printEscapedString(lpi->
getName());
1625 Out <<
"\", " << bbname <<
");";
1626 nl(Out) << iName <<
"->setCleanup("
1627 << (lpi->
isCleanup() ?
"true" :
"false")
1630 nl(Out) << iName <<
"->addClause(" << opNames[i+1] <<
");";
1634 DefinedValues.insert(I);
1640 void CppWriter::printFunctionUses(
const Function*
F) {
1641 nl(Out) <<
"// Type Definitions"; nl(Out);
1652 printType(AI->getType());
1670 printType(operand->
getType());
1673 if (
GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1677 if (GVar->hasInitializer())
1678 consts.
insert(GVar->getInitializer());
1679 }
else if (
Constant* C = dyn_cast<Constant>(operand)) {
1681 for (
Value* operand : C->operands()) {
1683 printType(operand->
getType());
1684 if (
GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1688 if (GVar->hasInitializer())
1689 consts.
insert(GVar->getInitializer());
1698 nl(Out) <<
"// Function Declarations"; nl(Out);
1699 for (
auto *GV : gvs) {
1700 if (
Function *Fun = dyn_cast<Function>(GV)) {
1701 if (!is_inline || Fun != F)
1702 printFunctionHead(Fun);
1707 nl(Out) <<
"// Global Variable Declarations"; nl(Out);
1708 for (
auto *GV : gvs) {
1710 printVariableHead(F);
1714 nl(Out) <<
"// Constant Definitions"; nl(Out);
1715 for (
const auto *C : consts) {
1723 nl(Out) <<
"// Global Variable Definitions"; nl(Out);
1724 for (
auto *GV : gvs) {
1726 printVariableBody(Var);
1731 void CppWriter::printFunctionHead(
const Function* F) {
1732 nl(Out) <<
"Function* " << getCppName(F);
1733 Out <<
" = mod->getFunction(\"";
1734 printEscapedString(F->
getName());
1736 nl(Out) <<
"if (!" << getCppName(F) <<
") {";
1737 nl(Out) << getCppName(F);
1739 Out<<
" = Function::Create(";
1741 nl(Out) <<
"/*Linkage=*/";
1744 nl(Out) <<
"/*Name=*/\"";
1745 printEscapedString(F->
getName());
1746 Out <<
"\", mod); " << (F->
isDeclaration()?
"// (external, no body)" :
"");
1749 Out <<
"->setCallingConv(";
1755 Out <<
"->setSection(\"" << F->
getSection() <<
"\");";
1765 Out <<
"->setVisibility(";
1772 Out <<
"->setDLLStorageClass(";
1779 Out <<
"->setGC(\"" << F->
getGC() <<
"\");";
1786 Out <<
"->setAttributes(" << getCppName(F) <<
"_PAL);";
1790 void CppWriter::printFunctionBody(
const Function *F) {
1796 ForwardRefs.clear();
1797 DefinedValues.clear();
1802 Out <<
"Function::arg_iterator args = " << getCppName(F)
1803 <<
"->arg_begin();";
1808 Out <<
"Value* " << getCppName(AI) <<
" = args++;";
1810 if (AI->hasName()) {
1811 Out << getCppName(AI) <<
"->setName(\"";
1812 printEscapedString(AI->getName());
1823 std::string bbname(getCppName(BI));
1824 Out <<
"BasicBlock* " << bbname <<
1825 " = BasicBlock::Create(mod->getContext(), \"";
1827 printEscapedString(BI->getName());
1828 Out <<
"\"," << getCppName(BI->getParent()) <<
",0);";
1835 std::string bbname(getCppName(BI));
1836 nl(Out) <<
"// Block " << BI->getName() <<
" (" << bbname <<
")";
1842 printInstruction(I,bbname);
1848 if (!ForwardRefs.empty()) {
1849 nl(Out) <<
"// Resolve Forward References";
1853 while (!ForwardRefs.empty()) {
1854 ForwardRefMap::iterator I = ForwardRefs.begin();
1855 Out << I->second <<
"->replaceAllUsesWith("
1856 << getCppName(I->first) <<
"); delete " << I->second <<
";";
1858 ForwardRefs.erase(I);
1862 void CppWriter::printInline(
const std::string& fname,
1863 const std::string& func) {
1864 const Function* F = TheModule->getFunction(func);
1866 error(std::string(
"Function '") + func +
"' not found in input module");
1870 error(std::string(
"Function '") + func +
"' is external!");
1873 nl(Out) <<
"BasicBlock* " << fname <<
"(Module* mod, Function *"
1875 unsigned arg_count = 1;
1878 Out <<
", Value* arg_" << arg_count++;
1883 printFunctionUses(F);
1884 printFunctionBody(F);
1886 Out <<
"return " << getCppName(F->
begin()) <<
";";
1891 void CppWriter::printModuleBody() {
1893 nl(Out) <<
"// Type Definitions"; nl(Out);
1894 printTypes(TheModule);
1898 nl(Out) <<
"// Function Declarations"; nl(Out);
1901 printFunctionHead(I);
1905 nl(Out) <<
"// Global Variable Declarations\n"; nl(Out);
1907 E = TheModule->global_end(); I != E; ++
I) {
1908 printVariableHead(I);
1914 nl(Out) <<
"// Constant Definitions"; nl(Out);
1915 printConstants(TheModule);
1920 nl(Out) <<
"// Global Variable Definitions"; nl(Out);
1922 E = TheModule->global_end(); I != E; ++
I) {
1923 printVariableBody(I);
1927 nl(Out) <<
"// Function Definitions"; nl(Out);
1930 if (!I->isDeclaration()) {
1931 nl(Out) <<
"// Function: " << I->getName() <<
" (" << getCppName(I)
1935 printFunctionBody(I);
1942 void CppWriter::printProgram(
const std::string& fname,
1943 const std::string& mName) {
1944 Out <<
"#include <llvm/Pass.h>\n";
1946 Out <<
"#include <llvm/ADT/SmallVector.h>\n";
1947 Out <<
"#include <llvm/Analysis/Verifier.h>\n";
1948 Out <<
"#include <llvm/IR/BasicBlock.h>\n";
1949 Out <<
"#include <llvm/IR/CallingConv.h>\n";
1950 Out <<
"#include <llvm/IR/Constants.h>\n";
1951 Out <<
"#include <llvm/IR/DerivedTypes.h>\n";
1952 Out <<
"#include <llvm/IR/Function.h>\n";
1953 Out <<
"#include <llvm/IR/GlobalVariable.h>\n";
1954 Out <<
"#include <llvm/IR/IRPrintingPasses.h>\n";
1955 Out <<
"#include <llvm/IR/InlineAsm.h>\n";
1956 Out <<
"#include <llvm/IR/Instructions.h>\n";
1957 Out <<
"#include <llvm/IR/LLVMContext.h>\n";
1958 Out <<
"#include <llvm/IR/LegacyPassManager.h>\n";
1959 Out <<
"#include <llvm/IR/Module.h>\n";
1960 Out <<
"#include <llvm/Support/FormattedStream.h>\n";
1961 Out <<
"#include <llvm/Support/MathExtras.h>\n";
1962 Out <<
"#include <algorithm>\n";
1963 Out <<
"using namespace llvm;\n\n";
1964 Out <<
"Module* " << fname <<
"();\n\n";
1965 Out <<
"int main(int argc, char**argv) {\n";
1966 Out <<
" Module* Mod = " << fname <<
"();\n";
1967 Out <<
" verifyModule(*Mod, PrintMessageAction);\n";
1968 Out <<
" PassManager PM;\n";
1969 Out <<
" PM.add(createPrintModulePass(&outs()));\n";
1970 Out <<
" PM.run(*Mod);\n";
1971 Out <<
" return 0;\n";
1973 printModule(fname,mName);
1976 void CppWriter::printModule(
const std::string& fname,
1977 const std::string& mName) {
1978 nl(Out) <<
"Module* " << fname <<
"() {";
1979 nl(Out,1) <<
"// Module Construction";
1980 nl(Out) <<
"Module* mod = new Module(\"";
1981 printEscapedString(mName);
1982 Out <<
"\", getGlobalContext());";
1983 if (!TheModule->getTargetTriple().empty()) {
1984 nl(Out) <<
"mod->setDataLayout(\"" << TheModule->getDataLayoutStr()
1987 if (!TheModule->getTargetTriple().empty()) {
1988 nl(Out) <<
"mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1992 if (!TheModule->getModuleInlineAsm().empty()) {
1993 nl(Out) <<
"mod->setModuleInlineAsm(\"";
1994 printEscapedString(TheModule->getModuleInlineAsm());
2000 nl(Out) <<
"return mod;";
2005 void CppWriter::printContents(
const std::string& fname,
2006 const std::string& mName) {
2007 Out <<
"\nModule* " << fname <<
"(Module *mod) {\n";
2008 Out <<
"\nmod->setModuleIdentifier(\"";
2009 printEscapedString(mName);
2012 Out <<
"\nreturn mod;\n";
2016 void CppWriter::printFunction(
const std::string& fname,
2017 const std::string& funcName) {
2018 const Function* F = TheModule->getFunction(funcName);
2020 error(std::string(
"Function '") + funcName +
"' not found in input module");
2023 Out <<
"\nFunction* " << fname <<
"(Module *mod) {\n";
2024 printFunctionUses(F);
2025 printFunctionHead(F);
2026 printFunctionBody(F);
2027 Out <<
"return " << getCppName(F) <<
";\n";
2031 void CppWriter::printFunctions() {
2036 for (; I !=
IE; ++
I) {
2039 std::string
name(
"define_");
2041 printFunction(name, func.
getName());
2046 void CppWriter::printVariable(
const std::string& fname,
2047 const std::string& varName) {
2051 error(std::string(
"Variable '") + varName +
"' not found in input module");
2054 Out <<
"\nGlobalVariable* " << fname <<
"(Module *mod) {\n";
2055 printVariableUses(GV);
2056 printVariableHead(GV);
2057 printVariableBody(GV);
2058 Out <<
"return " << getCppName(GV) <<
";\n";
2062 void CppWriter::printType(
const std::string &fname,
2063 const std::string &typeName) {
2064 Type* Ty = TheModule->getTypeByName(typeName);
2066 error(std::string(
"Type '") + typeName +
"' not found in input module");
2069 Out <<
"\nType* " << fname <<
"(Module *mod) {\n";
2071 Out <<
"return " << getCppName(Ty) <<
";\n";
2075 bool CppWriter::runOnModule(
Module &M) {
2079 Out <<
"// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
2082 std::string fname =
FuncName.getValue();
2090 if (tgtname ==
"!bad!") {
2092 tgtname =
"<stdin>";
2096 }
else if (tgtname ==
"!bad!")
2097 error(
"You must use the -for option with -gen-{function,variable,type}");
2102 fname =
"makeLLVMModule";
2103 printProgram(fname,tgtname);
2107 fname =
"makeLLVMModule";
2108 printModule(fname,tgtname);
2112 fname =
"makeLLVMModuleContents";
2113 printContents(fname,tgtname);
2117 fname =
"makeLLVMFunction";
2118 printFunction(fname,tgtname);
2125 fname =
"makeLLVMInline";
2126 printInline(fname,tgtname);
2130 fname =
"makeLLVMVariable";
2131 printVariable(fname,tgtname);
2135 fname =
"makeLLVMType";
2136 printType(fname,tgtname);
2155 auto FOut = llvm::make_unique<formatted_raw_ostream>(o);
2156 PM.add(
new CppWriter(std::move(FOut)));
static StringRef ConvertAtomicOrdering(AtomicOrdering Ordering)
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type (if unknown returns 0).
ReturnInst - Return a value (possibly void), from a function.
const Value * getCalledValue() const
getCalledValue - Get a pointer to the function that is invoked by this instruction.
ValuesClass< DataType > LLVM_END_WITH_NULL values(const char *Arg, DataType Val, const char *Desc,...)
AtomicOrdering getFailureOrdering() const
Returns the ordering constraint on this cmpxchg.
LinkageTypes getLinkage() const
CaseIt case_end()
Returns a read/write iterator that points one past the last in the SwitchInst.
static Type * getDoubleTy(LLVMContext &C)
Special purpose, only applies to global arrays.
VisibilityTypes getVisibility() const
*p = old <signed v ? old : v
LLVM Argument representation.
uint64_t getZExtValue() const
Get zero extended value.
Alignment of stack for function (3 bits) stored as log2 of alignment with +1 bias 0 means unaligned (...
bool isVolatile() const
isVolatile - Return true if this is a store to a volatile memory location.
SynchronizationScope getSynchScope() const
static const fltSemantics IEEEdouble
A Module instance is used to store all the information related to an LLVM module. ...
2: 32-bit floating point type
AtomicOrdering getSuccessOrdering() const
Returns the ordering constraint on this cmpxchg.
FenceInst - an instruction for ordering other memory operations.
Same, but only replaced by something equivalent.
AtomicCmpXchgInst - an instruction that atomically checks whether a specified value is in a memory lo...
unsigned getNumOperands() const
Available for inspection, not emission.
Type::subtype_iterator param_iterator
const char * getGC() const
CallInst - This class represents a function call, abstracting a target machine's calling convention...
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
CaseIt case_begin()
Returns a read/write iterator that points to the first case in SwitchInst.
*p = old <unsigned v ? old : v
0 1 0 0 True if ordered and less than
Like Internal, but omit from symbol table.
void LLVMInitializeCppBackendTarget()
*p = old >unsigned v ? old : v
ShuffleVectorInst - This instruction constructs a fixed permutation of two input vectors.
Externally visible function.
1 1 1 0 True if unordered or not equal
Type * getReturnType() const
unsigned getNumIndices() const
The two locations do not alias at all.
4: 80-bit floating point type (X87)
bool addPassesToEmitFile(PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileType, bool DisableVerify, AnalysisID StartBefore, AnalysisID StartAfter, AnalysisID StopAfter, MachineFunctionInitializer *MFInitializer) override
Add passes to the specified pass manager to get the specified file emitted.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
LoadInst - an instruction for reading from memory.
AtomicRMWInst - an instruction that atomically reads a memory location, combines it with another valu...
static std::string ftostr(const APFloat &V)
StringRef drop_back(size_t N=1) const
Return a StringRef equal to 'this' but with the last N elements dropped.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
*p = old >signed v ? old : v
bool bitwiseIsEqual(const APFloat &) const
Bitwise comparison for equality (QNaNs compare equal, 0!=-0).
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(const char *reason, bool gen_crash_diag=true)
Reports a serious error, calling any installed error handler.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
StringRef getName() const
Return a constant reference to the value's name.
element_iterator element_end() const
bool isArrayAllocation() const
isArrayAllocation - Return true if there is an allocation size parameter to the allocation instructio...
1 0 0 1 True if unordered or equal
BlockAddress - The address of a basic block.
static unsigned getOperandNumForIncomingValue(unsigned i)
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
SelectInst - This class represents the LLVM 'select' instruction.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
Type::subtype_iterator element_iterator
static Type * getFloatTy(LLVMContext &C)
This is the base class for all instructions that perform data casts.
StructType - Class to represent struct types.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
param_iterator param_end() const
unsigned getNumArgOperands() const
getNumArgOperands - Return the number of call arguments.
const Value * getCalledValue() const
getCalledValue - Get a pointer to the function that is invoked by this instruction ...
bool isLiteral() const
isLiteral - Return true if this type is uniqued by structural equivalence, false if it is a struct de...
0 1 0 1 True if ordered and less than or equal
Windows NT (Windows on ARM)
element_iterator element_begin() const
static ConstantInt * ExtractElement(Constant *V, Constant *Idx)
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
SynchronizationScope getSynchScope() const
static cl::opt< WhatToGenerate > GenerationType("cppgen", cl::Optional, cl::desc("Choose what kind of output to generate"), cl::init(GenProgram), cl::values(clEnumValN(GenProgram,"program","Generate a complete program"), clEnumValN(GenModule,"module","Generate a module definition"), clEnumValN(GenContents,"contents","Generate contents of a module"), clEnumValN(GenFunction,"function","Generate a function definition"), clEnumValN(GenFunctions,"functions","Generate all function definitions"), clEnumValN(GenInline,"inline","Generate an inline function"), clEnumValN(GenVariable,"variable","Generate a variable definition"), clEnumValN(GenType,"type","Generate a type definition"), clEnumValEnd))
static void sanitize(std::string &str)
ConstantExpr - a constant value that is initialized with an expression using other constant values...
FunctionType - Class to represent function types.
bool isVolatile() const
isVolatile - Return true if this is a cmpxchg from a volatile memory location.
AtomicOrdering getOrdering() const
Returns the ordering constraint on this RMW.
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
unsigned getAlignment() const
ArrayType - Class to represent array types.
static cl::opt< std::string > FuncName("cppfname", cl::desc("Specify the name of the generated function"), cl::value_desc("function name"))
VisibilityTypes
An enumeration for the kinds of visibility of global values.
static std::string utostr(uint64_t X, bool isNeg=false)
double convertToDouble() const
TypeID getTypeID() const
getTypeID - Return the type id for the type.
bool isFloatingPointTy() const
isFloatingPointTy - Return true if this is one of the six floating point types
unsigned getNumClauses() const
getNumClauses - Get the number of clauses for this landing pad.
static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler, std::error_code EC, const Twine &Message)
StoreInst - an instruction for storing to memory.
unsigned getNumElements() const
Return the number of elements in the Vector type.
Type * getElementType() const
bool isAtomic() const
isAtomic - Return true if this instruction has an AtomicOrdering of unordered or higher.
BasicBlock * getNormalDest() const
PointerType - Class to represent pointers.
unsigned getNumIncomingValues() const
getNumIncomingValues - Return the number of incoming edges
static cl::opt< std::string > NameToGenerate("cppfor", cl::Optional, cl::desc("Specify the name of the thing to generate"), cl::init("!bad!"))
10: Arbitrary bit width integers
ExternalWeak linkage description.
GetElementPtrInst - an instruction for type-safe pointer arithmetic to access elements of arrays and ...
A self-contained host- and target-independent arbitrary-precision floating-point software implementat...
bool isX86_MMXTy() const
isX86_MMXTy - Return true if this is X86 MMX.
Same, but only replaced by something equivalent.
unsigned getNumSlots() const
Return the number of slots used in this attribute list.
initializer< Ty > init(const Ty &Val)
InsertElementInst - This instruction inserts a single (scalar) element into a VectorType value...
LandingPadInst - The landingpad instruction holds all of the information necessary to generate correc...
unsigned getAlignment() const
getAlignment - Return the alignment of the access that is being performed
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
SynchronizationScope getSynchScope() const
Returns whether this RMW is atomic between threads or only within a single thread.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
BranchInst - Conditional or Unconditional Branch instruction.
AttributeSet getSlotAttributes(unsigned Slot) const
Return the attributes at the given slot.
This is an important base class in LLVM.
Target TheCppBackendTarget
This file contains the declarations for the subclasses of Constant, which represent the different fla...
param_iterator param_begin() const
char back() const
back - Get the last character in the string.
IndirectBrInst - Indirect Branch Instruction.
APInt Or(const APInt &LHS, const APInt &RHS)
Bitwise OR function for APInt.
unsigned getAlignment() const
getAlignment - Return the alignment of the memory that is being allocated by the instruction.
ConstantFP - Floating Point Values [float, double].
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
APInt Xor(const APInt &LHS, const APInt &RHS)
Bitwise XOR function for APInt.
BasicBlock * getIncomingBlock(unsigned i) const
getIncomingBlock - Return incoming basic block number i.
uint64_t getNumElements() const
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
opStatus convert(const fltSemantics &, roundingMode, bool *)
APFloat::convert - convert a value of one floating point type to another.
DLLStorageClassTypes
Storage classes of global values for PE targets.
Value * getOperand(unsigned i) const
0 1 1 1 True if ordered (no nans)
ConstantVector - Constant Vector Declarations.
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
1 1 1 1 Always true (always folded)
VAArgInst - This class represents the va_arg llvm instruction, which returns an argument of the speci...
LLVMContext & getContext() const
All values hold a context through their type.
1 1 0 1 True if unordered, less than, or equal
CallingConv::ID getCallingConv() const
getCallingConv/setCallingConv - Get or set the calling convention of this function call...
const char * getSection() const
0 0 1 0 True if ordered and greater than
idx_iterator idx_begin() const
BasicBlock * getUnwindDest() const
AtomicOrdering getOrdering() const
Returns the ordering effect of this store.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
15: SIMD 'packed' format, or other vector type
1 1 0 0 True if unordered or less than
Keep one copy of function when linking (inline)
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
bool isVolatile() const
isVolatile - Return true if this is a load from a volatile memory location.
AtomicOrdering getOrdering() const
Returns the ordering effect of this fence.
BinOp getOperation() const
AttributeSet getAttributes() const
Return the attribute list for this Function.
SynchronizationScope getSynchScope() const
VectorType - Class to represent vector types.
bool hasInitializer() const
Definitions have initializers, declarations don't.
ConstantArray - Constant Array Declarations.
LinkageTypes
An enumeration for the kinds of linkage for global values.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool isIntegerTy() const
isIntegerTy - True if this is an instance of IntegerType.
StringRef getName() const
getName - Return the name for this struct type if it has an identity.
APInt bitcastToAPInt() const
bool hasGC() const
hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm to use during code generatio...
Value * getCondition() const
const AttributeSet & getAttributes() const
getAttributes - Return the parameter attributes for this call.
APInt And(const APInt &LHS, const APInt &RHS)
Bitwise AND function for APInt.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
ThreadLocalMode getThreadLocalMode() const
Function to be accessible from DLL.
PointerType * getType() const
Global values are always pointers.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th invoke argument.
static const fltSemantics IEEEsingle
const AttributeSet & getAttributes() const
getAttributes - Return the parameter attributes for this invoke.
BasicBlock * getDefaultDest() const
AtomicOrdering getOrdering() const
Returns the ordering effect of this fence.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
unsigned getSlotIndex(unsigned Slot) const
Return the index for the given slot.
unsigned greater or equal
unsigned getAlignment() const
getAlignment - Return the alignment of the access that is being performed
FunctionType * getFunctionType() const
Fast - This calling convention attempts to make calls as fast as possible (e.g.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
0 1 1 0 True if ordered and operands are unequal
float convertToFloat() const
cl::opt< std::string > StopAfter("stop-after", cl::desc("Stop compilation after a specific pass"), cl::value_desc("pass-name"), cl::init(""))
cl::opt< std::string > StartAfter("start-after", cl::desc("Resume compilation after a specific pass"), cl::value_desc("pass-name"), cl::init(""))
Keep one copy of named function when linking (weak)
Rename collisions when linking (static functions).
cl::opt< TargetMachine::CodeGenFileType > FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile), cl::desc("Choose a file type (not all types are supported by all targets):"), cl::values(clEnumValN(TargetMachine::CGFT_AssemblyFile,"asm","Emit an assembly ('.s') file"), clEnumValN(TargetMachine::CGFT_ObjectFile,"obj","Emit a native object ('.o') file"), clEnumValN(TargetMachine::CGFT_Null,"null","Emit nothing, for performance testing"), clEnumValEnd))
static std::string getTypePrefix(Type *Ty)
1 0 1 0 True if unordered or greater than
unsigned getNumCases() const
getNumCases - return the number of 'cases' in this switch instruction, except the default case ...
Function to be imported from DLL.
static std::string utohexstr(uint64_t X, bool LowerCase=false)
const APFloat & getValueAPF() const
An abstract base class for streams implementations that also support a pwrite operation.
bool isExactlyValue(const APFloat &V) const
isExactlyValue - We don't rely on operator== working on double values, as it returns true for things ...
3: 64-bit floating point type
SwitchInst - Multiway switch.
separate const offset from gep
bool isWeak() const
Return true if this cmpxchg may spuriously fail.
Type * getReturnType() const
RegisterTargetMachine - Helper template for registering a target machine implementation, for use in the target machine initialization function.
A raw_ostream that writes to an std::string.
bool isLabelTy() const
isLabelTy - Return true if this is 'label'.
0 0 0 1 True if ordered and equal
LLVM Value Representation.
1 0 1 1 True if unordered, greater than, or equal
unsigned getOpcode() const
getOpcode() returns a member of one of the enums like Instruction::Add.
DLLStorageClassTypes getDLLStorageClass() const
InvokeInst - Invoke instruction.
bool isCleanup() const
isCleanup - Return 'true' if this landingpad instruction is a cleanup.
C - The default llvm calling convention, compatible with C.
const HexagonInstrInfo bool ShouldCombineAggressively switch(MI->getOpcode())
StringRef - Represent a constant reference to a string, i.e.
This interface provides a way to initialize machine functions after they are created by the machine f...
CallingConv::ID getCallingConv() const
getCallingConv/setCallingConv - Get or set the calling convention of this function call...
static StringRef ConvertAtomicSynchScope(SynchronizationScope SynchScope)
ArgumentListType::const_iterator const_arg_iterator
9: MMX vectors (64 bits, X86 specific)
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit...
Type * getAllocatedType() const
getAllocatedType - Return the type that is being allocated by the instruction.
0 0 1 1 True if ordered and greater than or equal
SynchronizationScope getSynchScope() const
Returns whether this cmpxchg is atomic between threads or only within a single thread.
unsigned getNumArgOperands() const
getNumArgOperands - Return the number of invoke arguments.
unsigned getNumDestinations() const
getNumDestinations - return the number of possible destinations in this indirectbr instruction...
bool isEmpty() const
Return true if there are no attributes.
const fltSemantics & getSemantics() const
0 0 0 0 Always false (always folded)
bool isVoidTy() const
isVoidTy - Return true if this is 'void'.
AllocaInst - an instruction to allocate memory on the stack.
InsertValueInst - This instruction inserts a struct field of array element value into an aggregate va...
bool isMetadataTy() const
isMetadataTy - Return true if this is 'metadata'.
bool isVolatile() const
isVolatile - Return true if this is a RMW on a volatile memory location.