code stringlengths 1 2.06M | language stringclasses 1 value |
|---|---|
// Copyright 2003 Michael A. Muller
// Copyright 2009 Google Inc.
#ifndef TOKEN_H
#define TOKEN_H
#include "Location.h"
namespace parser {
class Toker;
/** Basic representation of a token. */
class Token {
friend class Toker;
public:
// the token types
typedef enum { ann, bitAnd, bitLSh, bitOr, bitRSh, bitXor, aliasKw,
breakKw, caseKw, catchKw, classKw, constKw, continueKw,
dollar, enumKw, forKw, elseKw, ifKw, importKw, inKw,
isKw, lambdaKw, moduleKw, nullKw, onKw, operKw,
returnKw, switchKw, throwKw, tryKw, typeofKw, whileKw,
assign, assignAnd, assignAsterisk, assignLSh, assignOr,
assignRSh, assignXor, assignMinus, assignPercent,
assignPlus, assignSlash, asterisk, bang, colon, comma,
decr, define, dot, end, eq, ge, gt, ident, incr,
integer, lbracket, lcurly, le, lparen, lt, minus, ne,
percent, plus, quest, rbracket, rcurly, rparen, semi,
slash, string, tilde, istrBegin, istrEnd, logicAnd,
logicOr, floatLit, octalLit, hexLit, binLit,
// these tokens are special - they are used to
// communicate actions that need to be performed in the
// token stream.
popErrCtx, // pop error context
} Type;
private:
// the token's state
Type type;
std::string data;
// source location for the token
Location loc;
public:
Token();
Token(Type type, const std::string &data, const Location &loc);
/** returns the token type */
Type getType() const { return type; }
/** returns the token raw data */
const std::string &getData() const { return data; }
/** Returns the source location for the token */
const Location &getLocation() const { return loc; }
/** dump a representation of the token to a stream */
friend std::ostream &operator <<(std::ostream &out, const Token &tok) {
return out << tok.loc << ":\"" << tok.data;
}
/** Methods to check the token type */
/** @{ */
bool isAlias() const { return type == aliasKw; }
bool isAnn() const { return type == ann; }
bool isBoolAnd() const { return type == bitAnd; }
bool isBoolOr() const { return type == bitOr; }
bool isCase() const { return type == caseKw; }
bool isCatch() const { return type == catchKw; }
bool isConst() const { return type == constKw; }
bool isEnum() const { return type == enumKw; }
bool isFor() const { return type == forKw; }
bool isIf() const { return type == ifKw; }
bool isIn() const { return type == inKw; }
bool isImport() const { return type == importKw; }
bool isLambda() const { return type == lambdaKw; }
bool isModule() const { return type == moduleKw; }
bool isElse() const { return type == elseKw; }
bool isOn() const { return type == onKw; }
bool isOper() const { return type == operKw; }
bool isWhile() const { return type == whileKw; }
bool isReturn() const { return type == returnKw; }
bool isSwitch() const { return type == switchKw; }
bool isThrow() const { return type == throwKw; }
bool isTry() const { return type == tryKw; }
bool isBreak() const { return type == breakKw; }
bool isClass() const { return type == classKw; }
bool isContinue() const { return type == continueKw; }
bool isDollar() const { return type == dollar; }
bool isNull() const { return type == nullKw; }
bool isIdent() const { return type == ident; }
bool isString() const { return type == string; }
bool isIstrBegin() const { return type == istrBegin; }
bool isIstrEnd() const { return type == istrEnd; }
bool isSemi() const { return type == semi; }
bool isComma() const { return type == comma; }
bool isColon() const { return type == colon; }
bool isDecr() const { return type == decr; }
bool isDefine() const { return type == define; }
bool isDot() const { return type == dot; }
bool isIncr() const { return type == incr; }
bool isAssign() const { return type == assign; }
bool isLParen() const { return type == lparen; }
bool isRParen() const { return type == rparen; }
bool isLCurly() const { return type == lcurly; }
bool isRCurly() const { return type == rcurly; }
bool isLBracket() const { return type == lbracket; }
bool isRBracket() const { return type == rbracket; }
bool isInteger() const { return type == integer; }
bool isFloat() const { return type == floatLit; }
bool isOctal() const { return type == octalLit; }
bool isHex() const { return type == hexLit; }
bool isBinary() const { return type == binLit; }
bool isPlus() const { return type == plus; }
bool isQuest() const { return type == quest; }
bool isMinus() const { return type == minus; }
bool isAsterisk() const { return type == asterisk; }
bool isBang() const { return type == bang; }
bool isSlash() const { return type == slash; }
bool isPercent() const { return type == percent; }
bool isNot() const { return type == bang; }
bool isTilde() const { return type == tilde; }
bool isGT() const { return type == gt; }
bool isLT() const { return type == lt; }
bool isEQ() const { return type == eq; }
bool isNE() const { return type == ne; }
bool isGE() const { return type == ge; }
bool isLE() const { return type == le; }
bool isEnd() const { return type == end; }
bool isLogicAnd() const { return type == logicAnd; }
bool isLogicOr() const { return type == logicOr; }
bool isTypeof() const { return type == typeofKw; }
bool isBinOp() const {
switch (type) {
case plus:
case minus:
case asterisk:
case slash:
case percent:
case eq:
case ne:
case lt:
case gt:
case le:
case ge:
case isKw:
case logicAnd:
case logicOr:
case bitAnd:
case bitOr:
case bitXor:
case bitLSh:
case bitRSh:
return true;
default:
return false;
}
}
bool isAugAssign() const {
switch(type) {
case assignAnd:
case assignAsterisk:
case assignLSh:
case assignOr:
case assignRSh:
case assignXor:
case assignMinus:
case assignPercent:
case assignPlus:
case assignSlash:
return true;
default:
return false;
}
}
/** @} */
};
} // namespace parser
#endif
| C++ |
// Copyright 2003 Michael A. Muller
#include <sstream>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
#include <cppunit/extensions/HelperMacros.h>
#include "parser/Toker.h"
using namespace parser;
using namespace std;
class TokerTests : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(TokerTests);
CPPUNIT_TEST(testBasics);
CPPUNIT_TEST(testComments);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {}
void tearDown() {}
void constructTest() {}
void testBasics() {
Token::Type types[] = {
Token::ident, Token::string, Token::semi, Token::comma,
Token::colon, Token::dot, Token::assign, Token::lparen,
Token::rparen, Token::lcurly, Token::rcurly, //Token::oper,
Token::integer, Token::plus, Token::minus,
Token::asterisk, Token::slash, Token::end
};
const char *vals[] = {
"ident", "test", ";", ",", ":", ".", "=", "(", ")", "{",
"}", "100", "+", "-", "*", "/", ""
};
stringstream src("ident'test';,:.=(){}100+-*/\n");
Toker toker(src, "input");
for (int i = 0; i < sizeof(types) / sizeof(Token::Type); ++i) {
Token tok = toker.getToken();
CPPUNIT_ASSERT_EQUAL(tok.getType(), types[i]);
CPPUNIT_ASSERT(!strcmp(tok.getData(), vals[i]));
}
}
void testComments() {
stringstream src("ident1 // comment\nident2");
Toker toker(src, "input");
Token tok = toker.getToken();
CPPUNIT_ASSERT_EQUAL(Token::ident, tok.getType());
CPPUNIT_ASSERT(!strcmp(tok.getData(), (const char *)"ident1"));
tok = toker.getToken();
CPPUNIT_ASSERT_EQUAL(Token::ident, tok.getType());
CPPUNIT_ASSERT(!strcmp(tok.getData(), (const char *)"ident2"));
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(TokerTests);
int main(int argc, char* argv[])
{
// Get the top level suite from the registry
CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
// Adds the test to the list of test to run
CppUnit::TextUi::TestRunner runner;
runner.addTest( suite );
// Change the default outputter to a compiler error format outputter
runner.setOutputter( new CppUnit::CompilerOutputter( &runner.result(),
std::cerr ) );
// Run the tests.
bool wasSucessful = runner.run();
// Return error code 1 if the one of test failed.
return wasSucessful ? 0 : 1;
}
| C++ |
// Copyright 2010 Google Inc.
#include "init.h"
#include "spug/StringFmt.h"
#include "model/FuncDef.h"
#include "parser/Parser.h"
#include "ext/Func.h"
#include "ext/Module.h"
#include "ext/Type.h"
#include "Annotation.h"
#include "CrackContext.h"
#include "Token.h"
#include "Location.h"
using namespace std;
using namespace crack::ext;
namespace compiler {
vector<parser::ParserCallback *> callbacks;
void cleanUpCallbacks(CrackContext *ctx) {
for (int i = 0; i < callbacks.size(); ++i)
ctx->removeCallback(callbacks[i]);
callbacks.clear();
}
void unexpectedElement(CrackContext *ctx) {
ctx->error("Function expected after annotation");
ctx->setNextFuncFlags(model::FuncDef::noFlags);
ctx->setNextClassFlags(model::TypeDef::noFlags);
}
void funcAnnCheck(CrackContext *ctx, const char *name) {
parser::Parser::State parseState =
static_cast<parser::Parser::State>(ctx->getParseState());
if (ctx->getScope() != model::Context::composite ||
(parseState != parser::Parser::st_base &&
parseState != parser::Parser::st_optElse
)
)
ctx->error(SPUG_FSTR(name << " annotation can not be used here (it "
"must precede a function "
"definition in a class body)"
).c_str()
);
callbacks.push_back(ctx->addCallback(parser::Parser::funcDef,
cleanUpCallbacks
)
);
callbacks.push_back(ctx->addCallback(parser::Parser::classDef,
unexpectedElement
)
);
callbacks.push_back(ctx->addCallback(parser::Parser::exprBegin,
unexpectedElement
)
);
callbacks.push_back(ctx->addCallback(parser::Parser::controlStmt,
unexpectedElement
)
);
}
void staticAnn(CrackContext *ctx) {
funcAnnCheck(ctx, "static");
ctx->setNextFuncFlags(model::FuncDef::explicitFlags);
}
void finalAnn(CrackContext *ctx) {
funcAnnCheck(ctx, "final");
ctx->setNextFuncFlags(model::FuncDef::explicitFlags |
model::FuncDef::method
);
}
void cleanUpAfterClass(CrackContext *ctx) {
cleanUpCallbacks(ctx);
ctx->setNextFuncFlags(model::FuncDef::noFlags);
}
void cleanUpAfterFunc(CrackContext *ctx) {
cleanUpCallbacks(ctx);
ctx->setNextClassFlags(model::TypeDef::noFlags);
}
void abstractAnn(CrackContext *ctx) {
// @abstract is not strictly a function annotation, it may precede a class
// definition.
parser::Parser::State parseState =
static_cast<parser::Parser::State>(ctx->getParseState());
if (parseState != parser::Parser::st_base &&
parseState != parser::Parser::st_optElse
)
ctx->error("abstract annotation can not be used here (it must precede "
"a function or class definition)"
);
callbacks.push_back(ctx->addCallback(parser::Parser::funcDef,
cleanUpAfterFunc
)
);
callbacks.push_back(ctx->addCallback(parser::Parser::classDef,
cleanUpAfterClass
)
);
callbacks.push_back(ctx->addCallback(parser::Parser::exprBegin,
unexpectedElement
)
);
callbacks.push_back(ctx->addCallback(parser::Parser::controlStmt,
unexpectedElement
)
);
ctx->setNextFuncFlags(model::FuncDef::explicitFlags |
model::FuncDef::method |
model::FuncDef::virtualized |
model::FuncDef::abstract
);
ctx->setNextClassFlags(model::TypeDef::explicitFlags |
model::TypeDef::abstractClass
);
}
void fileAnn(CrackContext *ctx) {
Location *loc = ctx->getLocation();
Token *newTok = new Token(parser::Token::string, loc->getName(), loc);
ctx->putBack(newTok);
loc->release();
newTok->release();
}
void lineAnn(CrackContext *ctx) {
Location *loc = ctx->getLocation();
Token *newTok = new Token(parser::Token::integer,
SPUG_FSTR(loc->getLineNumber()).c_str(),
loc
);
ctx->putBack(newTok);
loc->release();
newTok->release();
}
void encodingAnn(CrackContext *ctx) {
Token *tok = ctx->getToken();
bool isString = tok->isString();
tok->release();
if (!isString)
ctx->error("String expected after 'encoding' annotation");
}
void export_symbolsAnn(CrackContext *ctx) {
// get the module namespace
model::Context *realCtx = ctx->getContext();
model::ModuleDefPtr mod =
model::ModuleDefPtr::rcast(realCtx->getModuleContext()->ns);
while (true) {
Token *tok = ctx->getToken();
if (!tok->isIdent())
ctx->error("Identifier expected.");
// add the symbol to the module's exports
mod->exports[tok->getText()] = true;
// check for a comma or semicolon
tok = ctx->getToken();
if (tok->isSemi())
break;
else if (!tok->isComma())
ctx->error("Comma or semicolon expected in export_symbols.");
}
}
void init(Module *mod) {
Func *f;
Type *locationType = mod->addType("Location", sizeof(Location));
locationType->addMethod(mod->getByteptrType(), "getName",
(void *)Location::_getName
);
locationType->addMethod(mod->getIntType(), "getLineNumber",
(void *)Location::_getLineNumber
);
locationType->addMethod(mod->getVoidType(), "oper bind",
(void *)Location::_bind
);
locationType->addMethod(mod->getVoidType(), "oper release",
(void *)Location::_release
);
locationType->finish();
Type *tokenType = mod->addType("Token", sizeof(Token));
f = tokenType->addStaticMethod(tokenType, "oper new",
(void *)&Token::create
);
f->addArg(mod->getIntType(), "type");
f->addArg(mod->getByteptrType(), "text");
f->addArg(locationType, "loc");
tokenType->addMethod(mod->getVoidType(), "oper bind",
(void *)Token::_bind
);
tokenType->addMethod(mod->getVoidType(), "oper release",
(void *)Token::_release
);
f = tokenType->addMethod(mod->getBoolType(), "hasText",
(void *)Token::_hasText
);
f->addArg(mod->getByteptrType(), "text");
tokenType->addMethod(mod->getByteptrType(), "getText",
(void *)Token::_getText
);
tokenType->addMethod(mod->getIntType(), "getType",
(void *)Token::_getType
);
tokenType->addMethod(locationType, "getLocation",
(void *)Token::_getLocation
);
tokenType->addMethod(mod->getBoolType(), "isAlias",
(void *)Token::_isAlias
);
tokenType->addMethod(mod->getBoolType(), "isAnn", (void *)Token::_isAnn);
tokenType->addMethod(mod->getBoolType(), "isBoolAnd",
(void *)Token::_isBoolAnd
);
tokenType->addMethod(mod->getBoolType(), "isBoolOr",
(void *)Token::_isBoolOr
);
tokenType->addMethod(mod->getBoolType(), "isCase",
(void *)Token::_isCase
);
tokenType->addMethod(mod->getBoolType(), "isIf", (void *)Token::_isIf);
tokenType->addMethod(mod->getBoolType(), "isIn", (void *)Token::_isIn);
tokenType->addMethod(mod->getBoolType(), "isImport",
(void *)Token::_isImport
);
tokenType->addMethod(mod->getBoolType(), "isElse", (void *)Token::_isElse);
tokenType->addMethod(mod->getBoolType(), "isOper", (void *)Token::_isOper);
tokenType->addMethod(mod->getBoolType(), "isOn", (void *)Token::_isOn);
tokenType->addMethod(mod->getBoolType(), "isWhile",
(void *)Token::_isWhile);
tokenType->addMethod(mod->getBoolType(), "isReturn",
(void *)Token::_isReturn);
tokenType->addMethod(mod->getBoolType(), "isSwitch",
(void *)Token::_isSwitch
);
tokenType->addMethod(mod->getBoolType(), "isBreak",
(void *)Token::_isBreak
);
tokenType->addMethod(mod->getBoolType(), "isClass",
(void *)Token::_isClass
);
tokenType->addMethod(mod->getBoolType(), "isContinue",
(void *)Token::_isContinue
);
tokenType->addMethod(mod->getBoolType(), "isDollar",
(void *)Token::_isDollar
);
tokenType->addMethod(mod->getBoolType(), "isNull", (void *)Token::_isNull);
tokenType->addMethod(mod->getBoolType(), "isIdent", (void *)Token::_isIdent);
tokenType->addMethod(mod->getBoolType(), "isString", (void *)Token::_isString);
tokenType->addMethod(mod->getBoolType(), "isIstrBegin", (void *)Token::_isIstrBegin);
tokenType->addMethod(mod->getBoolType(), "isIstrEnd", (void *)Token::_isIstrEnd);
tokenType->addMethod(mod->getBoolType(), "isSemi", (void *)Token::_isSemi);
tokenType->addMethod(mod->getBoolType(), "isComma", (void *)Token::_isComma);
tokenType->addMethod(mod->getBoolType(), "isColon", (void *)Token::_isColon);
tokenType->addMethod(mod->getBoolType(), "isConst", (void *)Token::_isConst);
tokenType->addMethod(mod->getBoolType(), "isDecr", (void *)Token::_isDecr);
tokenType->addMethod(mod->getBoolType(), "isDefine", (void *)Token::_isDefine);
tokenType->addMethod(mod->getBoolType(), "isDot", (void *)Token::_isDot);
tokenType->addMethod(mod->getBoolType(), "isIncr", (void *)Token::_isIncr);
tokenType->addMethod(mod->getBoolType(), "isAssign", (void *)Token::_isAssign);
tokenType->addMethod(mod->getBoolType(), "isLambda", (void *)Token::_isLambda);
tokenType->addMethod(mod->getBoolType(), "isLParen", (void *)Token::_isLParen);
tokenType->addMethod(mod->getBoolType(), "isModule", (void *)Token::_isModule);
tokenType->addMethod(mod->getBoolType(), "isRParen", (void *)Token::_isRParen);
tokenType->addMethod(mod->getBoolType(), "isLCurly", (void *)Token::_isLCurly);
tokenType->addMethod(mod->getBoolType(), "isRCurly", (void *)Token::_isRCurly);
tokenType->addMethod(mod->getBoolType(), "isLBracket", (void *)Token::_isLBracket);
tokenType->addMethod(mod->getBoolType(), "isRBracket", (void *)Token::_isRBracket);
tokenType->addMethod(mod->getBoolType(), "isInteger", (void *)Token::_isInteger);
tokenType->addMethod(mod->getBoolType(), "isFloat", (void *)Token::_isFloat);
tokenType->addMethod(mod->getBoolType(), "isOctal", (void *)Token::_isOctal);
tokenType->addMethod(mod->getBoolType(), "isHex", (void *)Token::_isHex);
tokenType->addMethod(mod->getBoolType(), "isBinary", (void *)Token::_isBinary);
tokenType->addMethod(mod->getBoolType(), "isPlus", (void *)Token::_isPlus);
tokenType->addMethod(mod->getBoolType(), "isQuest", (void *)Token::_isQuest);
tokenType->addMethod(mod->getBoolType(), "isMinus", (void *)Token::_isMinus);
tokenType->addMethod(mod->getBoolType(), "isAsterisk", (void *)Token::_isAsterisk);
tokenType->addMethod(mod->getBoolType(), "isBang", (void *)Token::_isBang);
tokenType->addMethod(mod->getBoolType(), "isSlash", (void *)Token::_isSlash);
tokenType->addMethod(mod->getBoolType(), "isPercent", (void *)Token::_isPercent);
tokenType->addMethod(mod->getBoolType(), "isNot", (void *)Token::_isNot);
tokenType->addMethod(mod->getBoolType(), "isTilde", (void *)Token::_isTilde);
tokenType->addMethod(mod->getBoolType(), "isGT", (void *)Token::_isGT);
tokenType->addMethod(mod->getBoolType(), "isLT", (void *)Token::_isLT);
tokenType->addMethod(mod->getBoolType(), "isEQ", (void *)Token::_isEQ);
tokenType->addMethod(mod->getBoolType(), "isNE", (void *)Token::_isNE);
tokenType->addMethod(mod->getBoolType(), "isGE", (void *)Token::_isGE);
tokenType->addMethod(mod->getBoolType(), "isLE", (void *)Token::_isLE);
tokenType->addMethod(mod->getBoolType(), "isEnd", (void *)Token::_isEnd);
tokenType->addMethod(mod->getBoolType(), "isLogicAnd", (void *)Token::_isLogicAnd);
tokenType->addMethod(mod->getBoolType(), "isLogicOr", (void *)Token::_isLogicOr);
tokenType->addMethod(mod->getBoolType(), "isBinOp", (void *)Token::_isBinOp);
tokenType->addMethod(mod->getBoolType(), "isAugAssign", (void *)Token::_isAugAssign);
tokenType->finish();
Type *opaqCallbackType = mod->addType("Callback", 0);
opaqCallbackType->finish();
Type *annotationType = mod->addType("Annotation", sizeof(Annotation));
annotationType->addMethod(mod->getVoidptrType(), "getUserData",
(void *)Annotation::_getUserData
);
annotationType->addMethod(mod->getVoidptrType(), "getFunc",
(void *)Annotation::_getName
);
annotationType->addMethod(mod->getVoidptrType(), "getName",
(void *)Annotation::_getName
);
annotationType->finish();
Type *cc = mod->addType("CrackContext", sizeof(CrackContext));
f = cc->addMethod(mod->getVoidType(), "inject",
(void *)CrackContext::_inject
);
f->addArg(mod->getByteptrType(), "sourceName");
f->addArg(mod->getIntType(), "lineNumber");
f->addArg(mod->getByteptrType(), "code");
cc->addMethod(tokenType, "getToken", (void *)CrackContext::_getToken);
f = cc->addMethod(mod->getVoidType(), "putBack",
(void *)CrackContext::_putBack
);
f->addArg(tokenType, "tok");
cc->addMethod(mod->getIntType(), "getScope",
(void *)CrackContext::_getScope
);
cc->addMethod(mod->getVoidptrType(), "getUserData",
(void *)CrackContext::_getUserData
);
typedef void (*G1)(CrackContext *, const char *, void (*)(CrackContext *));
G1 g1 = CrackContext::_storeAnnotation;
f = cc->addMethod(mod->getVoidType(), "storeAnnotation", (void *)g1);
f->addArg(mod->getByteptrType(), "name");
f->addArg(mod->getVoidptrType(), "func");
typedef void (*G2)(CrackContext *, const char *, void (*)(CrackContext *),
void *
);
G2 g2 = CrackContext::_storeAnnotation;
f = cc->addMethod(mod->getVoidType(), "storeAnnotation", (void *)g2);
f->addArg(mod->getByteptrType(), "name");
f->addArg(mod->getVoidptrType(), "func");
f->addArg(mod->getVoidptrType(), "userData");
// error/warning functions
// error(byteptr text)
void (*g3)(CrackContext *, const char *) = CrackContext::_error;
f = cc->addMethod(mod->getVoidType(), "error", (void *)g3);
f->addArg(mod->getByteptrType(), "text");
// error(Token tok, byteptr text)
void (*g4)(CrackContext *, Token *, const char *) = CrackContext::_error;
f = cc->addMethod(mod->getVoidType(), "error", (void *)g4);
f->addArg(tokenType, "tok");
f->addArg(mod->getByteptrType(), "text");
// warn(byteptr text)
g3 = CrackContext::_warn;
f = cc->addMethod(mod->getVoidType(), "warn", (void *)g3);
f->addArg(mod->getByteptrType(), "text");
g4 = CrackContext::_warn;
f = cc->addMethod(mod->getVoidType(), "warn", (void *)g4);
f->addArg(tokenType, "tok");
f->addArg(mod->getByteptrType(), "text");
f = cc->addMethod(mod->getVoidType(), "pushErrorContext",
(void *)CrackContext::_pushErrorContext
);
f->addArg(mod->getByteptrType(), "text");
cc->addMethod(mod->getVoidType(), "popErrorContext",
(void *)CrackContext::_popErrorContext
);
cc->addMethod(mod->getIntType(), "getParseState",
(void *)CrackContext::_getParseState
);
f = cc->addMethod(opaqCallbackType, "addCallback",
(void *)CrackContext::_addCallback
);
f->addArg(mod->getIntType(), "event");
f->addArg(mod->getVoidptrType(), "callback");
f = cc->addMethod(mod->getVoidType(), "removeCallback",
(void *)CrackContext::_removeCallback);
f->addArg(opaqCallbackType, "callback");
f = cc->addMethod(mod->getVoidType(), "setNextFuncFlags",
(void *)CrackContext::_setNextFuncFlags
);
f->addArg(mod->getIntType(), "flags");
typedef Location *(*L1)(CrackContext *);
typedef Location *(*L2)(CrackContext *, const char *, int);
f = cc->addMethod(locationType, "getLocation",
(void *)static_cast<L2>(CrackContext::_getLocation)
);
f->addArg(mod->getByteptrType(), "name");
f->addArg(mod->getIntType(), "lineNumber");
cc->addMethod(locationType, "getLocation",
(void *)static_cast<L1>(CrackContext::_getLocation)
);
f = cc->addMethod(annotationType, "getAnnotation",
(void *)CrackContext::_getAnnotation
);
f->addArg(mod->getByteptrType(), "name");
cc->addMethod(mod->getVoidType(), "continueIString",
(void *)CrackContext::_continueIString
);
cc->finish();
// our annotations
f = mod->addFunc(mod->getVoidType(), "static", (void *)staticAnn);
f->addArg(cc, "ctx");
f = mod->addFunc(mod->getVoidType(), "final", (void *)finalAnn);
f->addArg(cc, "ctx");
f = mod->addFunc(mod->getVoidType(), "abstract", (void *)abstractAnn);
f->addArg(cc, "ctx");
f = mod->addFunc(mod->getByteptrType(), "FILE", (void *)fileAnn);
f->addArg(cc, "ctx");
f = mod->addFunc(mod->getByteptrType(), "LINE", (void *)lineAnn);
f->addArg(cc, "ctx");
f = mod->addFunc(mod->getVoidType(), "encoding", (void *)encodingAnn);
f->addArg(cc, "ctx");
f = mod->addFunc(mod->getVoidType(), "export_symbols",
(void *)export_symbolsAnn);
f->addArg(cc, "ctx");
// constants
mod->addConstant(mod->getIntType(), "TOK_", 0);
mod->addConstant(mod->getIntType(), "TOK_ANN", parser::Token::ann);
mod->addConstant(mod->getIntType(), "TOK_BITAND", parser::Token::bitAnd);
mod->addConstant(mod->getIntType(), "TOK_BITLSH", parser::Token::bitLSh);
mod->addConstant(mod->getIntType(), "TOK_BITOR", parser::Token::bitOr);
mod->addConstant(mod->getIntType(), "TOK_BITRSH", parser::Token::bitRSh);
mod->addConstant(mod->getIntType(), "TOK_BITXOR", parser::Token::bitXor);
mod->addConstant(mod->getIntType(), "TOK_BREAKKW",
parser::Token::breakKw
);
mod->addConstant(mod->getIntType(), "TOK_CLASSKW",
parser::Token::classKw
);
mod->addConstant(mod->getIntType(), "TOK_CONTINUEKW",
parser::Token::continueKw
);
mod->addConstant(mod->getIntType(), "TOK_DOLLAR",
parser::Token::dollar
);
mod->addConstant(mod->getIntType(), "TOK_FORKW", parser::Token::forKw);
mod->addConstant(mod->getIntType(), "TOK_ELSEKW", parser::Token::elseKw);
mod->addConstant(mod->getIntType(), "TOK_IFKW", parser::Token::ifKw);
mod->addConstant(mod->getIntType(), "TOK_IMPORTKW",
parser::Token::importKw
);
mod->addConstant(mod->getIntType(), "TOK_INKW", parser::Token::inKw);
mod->addConstant(mod->getIntType(), "TOK_ISKW", parser::Token::isKw);
mod->addConstant(mod->getIntType(), "TOK_NULLKW", parser::Token::nullKw);
mod->addConstant(mod->getIntType(), "TOK_ONKW", parser::Token::onKw);
mod->addConstant(mod->getIntType(), "TOK_OPERKW", parser::Token::operKw);
mod->addConstant(mod->getIntType(), "TOK_RETURNKW",
parser::Token::returnKw
);
mod->addConstant(mod->getIntType(), "TOK_WHILEKW",
parser::Token::whileKw
);
mod->addConstant(mod->getIntType(), "TOK_ASSIGN", parser::Token::assign);
mod->addConstant(mod->getIntType(), "TOK_ASSIGNAND",
parser::Token::assignAnd
);
mod->addConstant(mod->getIntType(), "TOK_ASSIGNASTERISK",
parser::Token::assignAsterisk
);
mod->addConstant(mod->getIntType(), "TOK_ASSIGNLSH",
parser::Token::assignLSh
);
mod->addConstant(mod->getIntType(), "TOK_ASSIGNOR",
parser::Token::assignOr
);
mod->addConstant(mod->getIntType(), "TOK_ASSIGNRSH",
parser::Token::assignRSh
);
mod->addConstant(mod->getIntType(), "TOK_ASSIGNXOR",
parser::Token::assignXor
);
mod->addConstant(mod->getIntType(), "TOK_ASSIGNMINUS",
parser::Token::assignMinus
);
mod->addConstant(mod->getIntType(), "TOK_ASSIGNPERCENT",
parser::Token::assignPercent
);
mod->addConstant(mod->getIntType(), "TOK_ASSIGNPLUS",
parser::Token::assignPlus
);
mod->addConstant(mod->getIntType(), "TOK_ASSIGNSLASH",
parser::Token::assignSlash
);
mod->addConstant(mod->getIntType(), "TOK_ASTERISK",
parser::Token::asterisk
);
mod->addConstant(mod->getIntType(), "TOK_BANG", parser::Token::bang);
mod->addConstant(mod->getIntType(), "TOK_COLON", parser::Token::colon);
mod->addConstant(mod->getIntType(), "TOK_COMMA", parser::Token::comma);
mod->addConstant(mod->getIntType(), "TOK_DECR", parser::Token::decr);
mod->addConstant(mod->getIntType(), "TOK_DEFINE", parser::Token::define);
mod->addConstant(mod->getIntType(), "TOK_DOT", parser::Token::dot);
mod->addConstant(mod->getIntType(), "TOK_END", parser::Token::end);
mod->addConstant(mod->getIntType(), "TOK_EQ", parser::Token::eq);
mod->addConstant(mod->getIntType(), "TOK_GE", parser::Token::ge);
mod->addConstant(mod->getIntType(), "TOK_GT", parser::Token::gt);
mod->addConstant(mod->getIntType(), "TOK_IDENT", parser::Token::ident);
mod->addConstant(mod->getIntType(), "TOK_INCR", parser::Token::incr);
mod->addConstant(mod->getIntType(), "TOK_INTEGER",
parser::Token::integer
);
mod->addConstant(mod->getIntType(), "TOK_LBRACKET",
parser::Token::lbracket
);
mod->addConstant(mod->getIntType(), "TOK_LCURLY", parser::Token::lcurly);
mod->addConstant(mod->getIntType(), "TOK_LE", parser::Token::le);
mod->addConstant(mod->getIntType(), "TOK_LPAREN", parser::Token::lparen);
mod->addConstant(mod->getIntType(), "TOK_LT", parser::Token::lt);
mod->addConstant(mod->getIntType(), "TOK_MINUS", parser::Token::minus);
mod->addConstant(mod->getIntType(), "TOK_NE", parser::Token::ne);
mod->addConstant(mod->getIntType(), "TOK_PERCENT",
parser::Token::percent
);
mod->addConstant(mod->getIntType(), "TOK_PLUS", parser::Token::plus);
mod->addConstant(mod->getIntType(), "TOK_QUEST", parser::Token::quest);
mod->addConstant(mod->getIntType(), "TOK_RBRACKET",
parser::Token::rbracket);
mod->addConstant(mod->getIntType(), "TOK_RCURLY", parser::Token::rcurly);
mod->addConstant(mod->getIntType(), "TOK_RPAREN", parser::Token::rparen);
mod->addConstant(mod->getIntType(), "TOK_SEMI", parser::Token::semi);
mod->addConstant(mod->getIntType(), "TOK_SLASH", parser::Token::slash);
mod->addConstant(mod->getIntType(), "TOK_STRING", parser::Token::string);
mod->addConstant(mod->getIntType(), "TOK_TILDE", parser::Token::tilde);
mod->addConstant(mod->getIntType(), "TOK_ISTRBEGIN",
parser::Token::istrBegin
);
mod->addConstant(mod->getIntType(), "TOK_ISTREND", parser::Token::istrEnd);
mod->addConstant(mod->getIntType(), "TOK_LOGICAND",
parser::Token::logicAnd
);
mod->addConstant(mod->getIntType(), "TOK_LOGICOR",
parser::Token::logicOr
);
mod->addConstant(mod->getIntType(), "TOK_FLOATLIT",
parser::Token::floatLit
);
mod->addConstant(mod->getIntType(), "TOK_OCTALLIT",
parser::Token::octalLit
);
mod->addConstant(mod->getIntType(), "TOK_HEXLIT", parser::Token::hexLit);
mod->addConstant(mod->getIntType(), "TOK_BINLIT", parser::Token::binLit);
mod->addConstant(mod->getIntType(), "TOK_POPERRCTX",
parser::Token::popErrCtx
);
mod->addConstant(mod->getIntType(), "SCOPE_MODULE", 0);
mod->addConstant(mod->getIntType(), "SCOPE_FUNCTION", 2);
mod->addConstant(mod->getIntType(), "SCOPE_CLASS", 3);
mod->addConstant(mod->getIntType(), "STATE_BASE", parser::Parser::st_base);
mod->addConstant(mod->getIntType(), "STATE_OPT_ELSE",
parser::Parser::st_optElse
);
mod->addConstant(mod->getIntType(), "PCB_FUNC_DEF",
parser::Parser::funcDef
);
mod->addConstant(mod->getIntType(), "PCB_FUNC_ENTER",
parser::Parser::funcEnter
);
mod->addConstant(mod->getIntType(), "PCB_FUNC_LEAVE",
parser::Parser::funcLeave
);
mod->addConstant(mod->getIntType(), "PCB_CLASS_DEF",
parser::Parser::classDef
);
mod->addConstant(mod->getIntType(), "PCB_CLASS_ENTER",
parser::Parser::classEnter
);
mod->addConstant(mod->getIntType(), "PCB_CLASS_LEAVE",
parser::Parser::classLeave
);
mod->addConstant(mod->getIntType(), "PCB_VAR_DEF",
parser::Parser::variableDef
);
mod->addConstant(mod->getIntType(), "PCB_EXPR_BEGIN",
parser::Parser::exprBegin
);
mod->addConstant(mod->getIntType(), "PCB_CONTROL_STMT",
parser::Parser::controlStmt
);
mod->addConstant(mod->getIntType(), "FUNCFLAG_STATIC",
model::FuncDef::explicitFlags
);
mod->addConstant(mod->getIntType(), "FUNCFLAG_FINAL",
model::FuncDef::explicitFlags | model::FuncDef::method
);
mod->addConstant(mod->getIntType(), "FUNCFLAG_ABSTRACT",
model::FuncDef::explicitFlags | model::FuncDef::abstract
);
mod->addConstant(mod->getIntType(), "CLASSFLAG_ABSTRACT",
model::FuncDef::explicitFlags |
model::TypeDef::abstractClass
);
}
} // namespace compiler
| C++ |
// Copyright 2010 Google Inc.
#ifndef _crack_compiler_Location_h_
#define _crack_compiler_Location_h_
#include "ext/RCObj.h"
namespace crack { namespace ext {
class Module;
}}
namespace parser {
class Location;
}
namespace compiler {
class Location : public crack::ext::RCObj {
friend void compiler::init(crack::ext::Module *mod);
private:
Location(const Location &other);
static const char *_getName(Location *inst);
static int _getLineNumber(Location *inst);
static void _bind(Location *inst);
static void _release(Location *inst);
public:
parser::Location *rep;
Location(const parser::Location &loc);
~Location();
/**
* Returns the file name of the location.
*/
const char *getName();
/**
* Returns the line number of the location.
*/
int getLineNumber();
};
} // namespace compiler
#endif
| C++ |
// Copyright 2010 Google Inc.
#ifndef _crack_compiler_CrackContext_h_
#define _crack_compiler_CrackContext_h_
namespace crack { namespace ext {
class Module;
}}
namespace parser {
class Parser;
class ParserCallback;
class Toker;
}
namespace model {
class Context;
}
namespace compiler {
class Annotation;
class Location;
class Token;
/**
* CrackContext is the argument for all annotations. It gives an annotation
* access to the internals of the compiler and parser.
*/
class CrackContext {
friend void compiler::init(crack::ext::Module *mod);
public:
typedef void (*AnnotationFunc)(CrackContext *);
private:
parser::Parser *parser;
parser::Toker *toker;
model::Context *context;
void *userData;
static void _inject(CrackContext *inst, char *sourceName,
int lineNumber,
char *code
);
static Token *_getToken(CrackContext *inst);
static void _putBack(CrackContext *inst, Token *tok);
static int _getScope(CrackContext *inst);
static void _storeAnnotation(CrackContext *inst, const char *name,
AnnotationFunc func
);
static void _storeAnnotation(CrackContext *inst, const char *name,
AnnotationFunc func,
void *userData
);
static Annotation *_getAnnotation(CrackContext *inst, const char *name);
static void *_getUserData(CrackContext *inst);
static void _error(CrackContext *inst, const char *text);
static void _error(CrackContext *inst, Token *tok, const char *text);
static void _warn(CrackContext *inst, const char *text);
static void _warn(CrackContext *inst, Token *tok, const char *text);
static void _pushErrorContext(CrackContext *inst, const char *text);
static void _popErrorContext(CrackContext *inst);
static int _getParseState(CrackContext *inst);
static parser::ParserCallback *_addCallback(CrackContext *inst,
int event,
AnnotationFunc func
);
static void _removeCallback(CrackContext *inst,
parser::ParserCallback *callback
);
static void _setNextFuncFlags(CrackContext *inst, int nextFuncFlags);
static Location *_getLocation(CrackContext *inst, const char *name,
int lineNumber
);
static Location *_getLocation(CrackContext *inst);
static void _continueIString(CrackContext *inst);
public:
enum Event { funcEnter, funcLeave };
CrackContext(parser::Parser *parser, parser::Toker *toker,
model::Context *context,
void *userData = 0
);
/**
* Inject a null terminated string into the tokenizer.
* The string will be tokenized and the tokens inserted into the
* stream before any existing tokens that have been pushed back.
*/
void inject(char *sourceName, int lineNumber, char *code);
/**
* Returns the next token from the tokenizer.
*/
Token *getToken();
/**
* Put the token back into the tokenizer - it will again be the next
* token returned by getToken().
*/
void putBack(Token *tok);
/**
* Returns the context scope.
*/
int getScope();
/**
* Stores a simple annotation function in the context.
*/
void storeAnnotation(const char *name, AnnotationFunc func);
/**
* Stores an annotation and user data in the context.
*/
void storeAnnotation(const char *name, AnnotationFunc func,
void *userData
);
/**
* Returns the named annotation, null if not found.
*/
Annotation *getAnnotation(const char *name);
/**
* Returns the user data associated with the annotation. User data
* can be stored in some types of Annotation objects and passed into
* the CrackContext when it is created.
*/
void *getUserData();
/**
* Generate a compiler error, use the location of the last token as
* the error location.
*/
void error(const char *text);
/**
* Generate a compiler error, use the location of the token as the
* error location.
*/
void error(Token *tok, const char *text);
/**
* Generate a compiler warning, use the location of the last token as
* the error location.
*/
void warn(const char *text);
/**
* Generate a compiler warning, use the location of the token as the
* error location.
*/
void warn(Token *tok, const char *text);
/**
* Push the string onto the context stack to be displayed for any
* error messages.
*/
void pushErrorContext(const char *text);
/**
* Pop the last string off of the error message context stack.
*/
void popErrorContext();
/**
* Returns the state of the parser.
*/
int getParseState();
/**
* Adds a callback for the specified event. Returns the callback id.
*/
parser::ParserCallback *addCallback(int event, AnnotationFunc func);
/**
* Remove the specified callback. "id" is the value returned from
* addCallback().
*/
void removeCallback(parser::ParserCallback *callback);
/**
* Set the flags for the next function. Valid values are
* FUNCFLAG_STATIC, FUNCFLAG_FINAL and FUNCFLAG_ABSTRACT.
*/
void setNextFuncFlags(int nextFuncFlags);
/**
* Set the flags for the next class. Valid values are
* CLASSFLAG_ABSTRACT.
*/
void setNextClassFlags(int nextClassFlags);
/** Create the specified location. */
Location *getLocation(const char *name, int lineNumber);
/** Returns the location of the last processed token. */
Location *getLocation();
/** Tells the tokenizer to resume parsing an i-string. */
void continueIString();
/**
* This is a back-door for things like the compiler-defined "export"
* annotation to get access to the underlying context object without
* us having to wrap the entire data model. It is not available to
* annotations written in crack.
*/
model::Context *getContext() { return context; }
};
} // namespace compiler
#endif
| C++ |
#include "Location.h"
#include "parser/Location.h"
using namespace compiler;
using namespace crack::ext;
Location::Location(const parser::Location &loc) {
rep = new parser::Location(loc);
}
Location::~Location() {
delete rep;
}
const char *Location::getName() {
return rep->getName();
}
int Location::getLineNumber() {
return rep->getLineNumber();
}
const char *Location::_getName(Location *inst) {
return inst->rep->getName();
}
int Location::_getLineNumber(Location *inst) {
return inst->rep->getLineNumber();
}
void Location::_bind(Location *inst) { inst->bind(); }
void Location::_release(Location *inst) { inst->release(); }
| C++ |
// Copyright 2010 Google Inc.
#include "compiler/Annotation.h"
#include "model/FuncAnnotation.h"
#include "model/PrimFuncAnnotation.h"
using namespace compiler;
void *Annotation::getUserData() {
model::PrimFuncAnnotation *pfa = model::PrimFuncAnnotationPtr::cast(rep);
if (pfa)
return pfa->getUserData();
else
return 0;
}
const char *Annotation::getName() {
return rep->name.c_str();
}
void *Annotation::getFunc() {
model::PrimFuncAnnotation *pfa = model::PrimFuncAnnotationPtr::cast(rep);
if (pfa)
return reinterpret_cast<void *>(pfa->getFunc());
else
return 0;
}
void *Annotation::_getUserData(Annotation *inst) {
model::PrimFuncAnnotation *pfa =
model::PrimFuncAnnotationPtr::cast(inst->rep);
if (pfa)
return pfa->getUserData();
else
return 0;
}
const char *Annotation::_getName(Annotation *inst) {
return inst->rep->name.c_str();
}
void *Annotation::_getFunc(Annotation *inst) {
model::PrimFuncAnnotation *pfa =
model::PrimFuncAnnotationPtr::cast(inst->rep);
if (pfa)
return reinterpret_cast<void *>(pfa->getFunc());
else
return 0;
}
| C++ |
// Copyright 2010 Google Inc.
#ifndef _crack_compiler_Annotation_h_
#define _crack_compiler_Annotation_h_
#include "ext/RCObj.h"
namespace crack { namespace ext {
class Module;
}}
namespace model {
class Annotation;
}
namespace compiler {
class Annotation : public crack::ext::RCObj {
friend void compiler::init(crack::ext::Module *mod);
private:
model::Annotation *rep;
static void *_getUserData(Annotation *inst);
static const char *_getName(Annotation *inst);
static void *_getFunc(Annotation *inst);
public:
Annotation(model::Annotation *rep) : rep(rep) {}
/**
* Returns the annotation's user data.
*/
void *getUserData();
/**
* Returns the annotation's name.
*/
const char *getName();
/**
* Returns the annotations function.
*/
void *getFunc();
};
} // namespace compiler
#endif
| C++ |
// Copyright 2010 Google Inc.
// contains the prototype for the init function of the built-in crack.compiler
// extension module.
#ifndef _compiler_init_h_
#define _compiler_init_h_
namespace crack { namespace ext {
class Module;
}}
namespace compiler {
void init(crack::ext::Module *mod);
}
#endif
| C++ |
// Copyright 2010 Google Inc.
#include "Token.h"
#include "parser/Token.h"
#include "Location.h"
using namespace compiler;
Token::Token(const parser::Token &tok) :
rep(new parser::Token(tok)),
loc(0) {
}
Token::Token(int type, const char *text, Location *loc) : loc(loc) {
rep = new parser::Token(static_cast<parser::Token::Type>(type), text,
*loc->rep
);
loc->bind();
}
Token *Token::create(int type, const char *text, Location *loc) {
return new Token(type, text, loc);
}
Token::~Token() {
delete rep;
if (loc)
loc->release();
}
bool Token::hasText(const char *text) {
return rep->getData() == text;
}
const char *Token::getText() {
return rep->getData().c_str();
}
int Token::getType() {
return rep->getType();
}
size_t Token::getTextSize() {
return rep->getData().size();
}
Location *Token::getLocation() {
if (!loc) {
loc = new Location(rep->getLocation());
loc->bind();
}
return loc;
}
bool Token::_hasText(Token *inst, const char *text) {
return inst->rep->getData() == text;
}
const char *Token::_getText(Token *inst) {
return inst->rep->getData().c_str();
}
int Token::_getType(Token *inst) {
return inst->rep->getType();
}
size_t Token::_getTextSize(Token *inst) {
return inst->rep->getData().size();
}
Location *Token::_getLocation(Token *inst) {
if (!inst->loc) {
inst->loc = new Location(inst->rep->getLocation());
inst->loc->bind();
}
return inst->loc;
}
void Token::_bind(Token *inst) { inst->bind(); }
void Token::_release(Token *inst) { inst->release(); }
#define IS_FUNC(name) \
bool Token::name() { return rep->name(); } \
bool Token::_##name(Token *inst) { return inst->rep->name(); }
IS_FUNC(isAlias)
IS_FUNC(isAnn)
IS_FUNC(isBoolAnd)
IS_FUNC(isBoolOr)
IS_FUNC(isCase)
IS_FUNC(isCatch)
IS_FUNC(isConst)
IS_FUNC(isIf)
IS_FUNC(isIn)
IS_FUNC(isImport)
IS_FUNC(isElse)
IS_FUNC(isLambda)
IS_FUNC(isModule)
IS_FUNC(isOper)
IS_FUNC(isOn)
IS_FUNC(isWhile)
IS_FUNC(isReturn)
IS_FUNC(isSwitch)
IS_FUNC(isThrow)
IS_FUNC(isTry)
IS_FUNC(isBreak)
IS_FUNC(isClass)
IS_FUNC(isContinue)
IS_FUNC(isDollar)
IS_FUNC(isNull)
IS_FUNC(isIdent)
IS_FUNC(isString)
IS_FUNC(isIstrBegin)
IS_FUNC(isIstrEnd)
IS_FUNC(isSemi)
IS_FUNC(isComma)
IS_FUNC(isColon)
IS_FUNC(isDecr)
IS_FUNC(isDefine)
IS_FUNC(isDot)
IS_FUNC(isIncr)
IS_FUNC(isAssign)
IS_FUNC(isLParen)
IS_FUNC(isRParen)
IS_FUNC(isLCurly)
IS_FUNC(isRCurly)
IS_FUNC(isLBracket)
IS_FUNC(isRBracket)
IS_FUNC(isInteger)
IS_FUNC(isFloat)
IS_FUNC(isOctal)
IS_FUNC(isHex)
IS_FUNC(isBinary)
IS_FUNC(isPlus)
IS_FUNC(isQuest)
IS_FUNC(isMinus)
IS_FUNC(isAsterisk)
IS_FUNC(isBang)
IS_FUNC(isSlash)
IS_FUNC(isPercent)
IS_FUNC(isNot)
IS_FUNC(isTilde)
IS_FUNC(isGT)
IS_FUNC(isLT)
IS_FUNC(isEQ)
IS_FUNC(isNE)
IS_FUNC(isGE)
IS_FUNC(isLE)
IS_FUNC(isEnd)
IS_FUNC(isLogicAnd)
IS_FUNC(isLogicOr)
IS_FUNC(isBinOp)
IS_FUNC(isAugAssign)
| C++ |
// Copyright 2010 Google Inc.
#include "CrackContext.h"
#include <stdlib.h>
#include <list>
#include <sstream>
#include "parser/Parser.h"
#include "parser/Toker.h"
#include "model/Context.h"
#include "model/Namespace.h"
#include "model/PrimFuncAnnotation.h"
#include "Token.h"
#include "Annotation.h"
#include "Location.h"
using namespace std;
using namespace compiler;
using namespace model;
namespace {
// Implements parser callback to wrap raw functions.
struct Callback : parser::ParserCallback {
parser::Parser::Event event;
CrackContext::AnnotationFunc func;
Callback(parser::Parser::Event event,
CrackContext::AnnotationFunc func
) :
event(event),
func(func) {
}
virtual void run(parser::Parser *parser, parser::Toker *toker,
model::Context *context
) {
CrackContext ctx(parser, toker, context);
func(&ctx);
}
};
}
CrackContext::CrackContext(parser::Parser *parser, parser::Toker *toker,
Context *context,
void *userData
) :
parser(parser),
toker(toker),
context(context),
userData(userData) {
}
void CrackContext::inject(char *sourceName, int lineNumber, char *code) {
istringstream iss(code);
parser::Toker tempToker(iss, sourceName, lineNumber);
list<parser::Token> tokens;
parser::Token tok;
while (!(tok = tempToker.getToken()).isEnd())
tokens.push_front(tok);
// transfer the tokens to the tokenizer
while (!tokens.empty()) {
toker->putBack(tokens.front());
tokens.pop_front();
}
}
Token *CrackContext::getToken() {
return new Token(toker->getToken());
}
void CrackContext::putBack(Token *tok) {
toker->putBack(*tok->rep);
}
int CrackContext::getScope() {
return context->scope;
}
void CrackContext::storeAnnotation(const char *name, AnnotationFunc func) {
context->compileNS->addDef(new PrimFuncAnnotation(name, func));
}
compiler::Annotation *CrackContext::getAnnotation(const char *name) {
model::Annotation *ann =
model::AnnotationPtr::rcast(context->compileNS->lookUp(name));
return ann ? new Annotation(ann) : 0;
}
void CrackContext::storeAnnotation(const char *name, AnnotationFunc func,
void *userData
) {
context->compileNS->addDef(new PrimFuncAnnotation(name, func,
userData
)
);
}
void *CrackContext::getUserData() {
return userData;
}
void CrackContext::error(const char *text) {
context->error(text, false);
}
void CrackContext::error(Token *tok, const char *text) {
context->error(tok->rep->getLocation(), text, false);
}
void CrackContext::warn(const char *text) {
context->warn(text);
}
void CrackContext::warn(Token *tok, const char *text) {
context->warn(tok->rep->getLocation(), text);
}
int CrackContext::getParseState() {
return parser->state;
}
void CrackContext::pushErrorContext(const char *text) {
context->pushErrorContext(text);
}
void CrackContext::popErrorContext() {
context->popErrorContext();
}
parser::ParserCallback *CrackContext::addCallback(
int event,
CrackContext::AnnotationFunc func
) {
parser::Parser::Event evt = static_cast<parser::Parser::Event>(event);
Callback *callback = new Callback(evt, func);
parser->addCallback(evt, callback);
return callback;
}
void CrackContext::removeCallback(parser::ParserCallback *callback) {
Callback *cb = dynamic_cast<Callback *>(callback);
parser::Parser::Event event =
static_cast<parser::Parser::Event>(cb->event);
if (parser->removeCallback(event, cb))
delete callback;
else
error("Attempted to remove a callback that wasn't registered.");
}
void CrackContext::setNextFuncFlags(int nextFuncFlags) {
context->nextFuncFlags = static_cast<FuncDef::Flags>(nextFuncFlags);
}
void CrackContext::setNextClassFlags(int nextClassFlags) {
context->nextClassFlags = static_cast<TypeDef::Flags>(nextClassFlags);
}
Location *CrackContext::getLocation(const char *name, int lineNumber) {
return new Location(toker->getLocationMap().getLocation(name, lineNumber));
}
Location *CrackContext::getLocation() {
return new Location(context->getLocation());
}
void CrackContext::continueIString() {
toker->continueIString();
}
void CrackContext::_inject(CrackContext *inst, char *sourceName, int lineNumber,
char *code
) {
istringstream iss(code);
parser::Toker tempToker(iss, sourceName, lineNumber);
list<parser::Token> tokens;
parser::Token tok;
while (!(tok = tempToker.getToken()).isEnd())
tokens.push_front(tok);
// transfer the tokens to the tokenizer
while (!tokens.empty()) {
inst->toker->putBack(tokens.front());
tokens.pop_front();
}
}
Token *CrackContext::_getToken(CrackContext *inst) {
return new Token(inst->toker->getToken());
}
void CrackContext::_putBack(CrackContext *inst, Token *tok) {
inst->toker->putBack(*tok->rep);
}
int CrackContext::_getScope(CrackContext *inst) {
return inst->context->scope;
}
void CrackContext::_storeAnnotation(CrackContext *inst, const char *name,
AnnotationFunc func
) {
inst->context->compileNS->addDef(new PrimFuncAnnotation(name, func));
}
compiler::Annotation *CrackContext::_getAnnotation(CrackContext *inst,
const char *name
) {
model::Annotation *ann =
model::AnnotationPtr::rcast(inst->context->compileNS->lookUp(name));
return ann ? new Annotation(ann) : 0;
}
void CrackContext::_storeAnnotation(CrackContext *inst, const char *name,
AnnotationFunc func,
void *userData
) {
inst->context->compileNS->addDef(new PrimFuncAnnotation(name, func,
userData
)
);
}
void *CrackContext::_getUserData(CrackContext *inst) {
return inst->userData;
}
void CrackContext::_error(CrackContext *inst, const char *text) {
inst->context->error(text, false);
}
void CrackContext::_error(CrackContext *inst, Token *tok, const char *text) {
inst->context->error(tok->rep->getLocation(), text, false);
}
void CrackContext::_warn(CrackContext *inst, const char *text) {
inst->context->warn(text);
}
void CrackContext::_warn(CrackContext *inst, Token *tok, const char *text) {
inst->context->warn(tok->rep->getLocation(), text);
}
int CrackContext::_getParseState(CrackContext *inst) {
return inst->parser->state;
}
void CrackContext::_pushErrorContext(CrackContext *inst, const char *text) {
inst->context->pushErrorContext(text);
}
void CrackContext::_popErrorContext(CrackContext *inst) {
inst->context->popErrorContext();
}
parser::ParserCallback *CrackContext::_addCallback(
CrackContext *inst,
int event,
CrackContext::AnnotationFunc func
) {
parser::Parser::Event evt = static_cast<parser::Parser::Event>(event);
Callback *callback = new Callback(evt, func);
inst->parser->addCallback(evt, callback);
return callback;
}
void CrackContext::_removeCallback(CrackContext *inst,
parser::ParserCallback *callback
) {
Callback *cb = dynamic_cast<Callback *>(callback);
parser::Parser::Event event =
static_cast<parser::Parser::Event>(cb->event);
if (inst->parser->removeCallback(event, cb))
delete callback;
else
inst->error("Attempted to remove a callback that wasn't registered.");
}
void CrackContext::_setNextFuncFlags(CrackContext *inst, int nextFuncFlags) {
inst->context->nextFuncFlags = static_cast<FuncDef::Flags>(nextFuncFlags);
}
Location *CrackContext::_getLocation(CrackContext *inst, const char *name,
int lineNumber
) {
return new Location(inst->toker->getLocationMap().getLocation(name,
lineNumber
)
);
}
Location *CrackContext::_getLocation(CrackContext *inst) {
return new Location(inst->context->getLocation());
}
void CrackContext::_continueIString(CrackContext *inst) {
inst->toker->continueIString();
}
| C++ |
// Copyright 2010 Google Inc.
#ifndef _crack_compiler_Token_h_
#define _crack_compiler_Token_h_
#include <stddef.h>
#include "ext/RCObj.h"
namespace crack { namespace ext {
class Module;
}}
namespace parser {
class Token;
}
namespace compiler {
class Location;
class Token : public crack::ext::RCObj {
friend void compiler::init(crack::ext::Module *mod);
private:
static bool _hasText(Token *inst, const char *text);
static const char *_getText(Token *inst);
static int _getType(Token *inst);
static size_t _getTextSize(Token *inst);
static Location *_getLocation(Token *inst);
static void _bind(Token *inst);
static void _release(Token *inst);
static bool _isAlias(Token *inst);
static bool _isAnn(Token *inst);
static bool _isBoolAnd(Token *inst);
static bool _isBoolOr(Token *inst);
static bool _isCase(Token *inst);
static bool _isCatch(Token *inst);
static bool _isConst(Token *inst);
static bool _isIf(Token *inst);
static bool _isImport(Token *inst);
static bool _isIn(Token *inst);
static bool _isElse(Token *inst);
static bool _isLambda(Token *inst);
static bool _isModule(Token *inst);
static bool _isOper(Token *inst);
static bool _isOn(Token *inst);
static bool _isWhile(Token *inst);
static bool _isReturn(Token *inst);
static bool _isSwitch(Token *inst);
static bool _isThrow(Token *inst);
static bool _isTry(Token *inst);
static bool _isBreak(Token *inst);
static bool _isClass(Token *inst);
static bool _isContinue(Token *inst);
static bool _isDollar(Token *inst);
static bool _isNull(Token *inst);
static bool _isIdent(Token *inst);
static bool _isString(Token *inst);
static bool _isIstrBegin(Token *inst);
static bool _isIstrEnd(Token *inst);
static bool _isSemi(Token *inst);
static bool _isComma(Token *inst);
static bool _isColon(Token *inst);
static bool _isDecr(Token *inst);
static bool _isDefine(Token *inst);
static bool _isDot(Token *inst);
static bool _isIncr(Token *inst);
static bool _isAssign(Token *inst);
static bool _isLParen(Token *inst);
static bool _isRParen(Token *inst);
static bool _isLCurly(Token *inst);
static bool _isRCurly(Token *inst);
static bool _isLBracket(Token *inst);
static bool _isRBracket(Token *inst);
static bool _isInteger(Token *inst);
static bool _isFloat(Token *inst);
static bool _isOctal(Token *inst);
static bool _isHex(Token *inst);
static bool _isBinary(Token *inst);
static bool _isPlus(Token *inst);
static bool _isQuest(Token *inst);
static bool _isMinus(Token *inst);
static bool _isAsterisk(Token *inst);
static bool _isBang(Token *inst);
static bool _isSlash(Token *inst);
static bool _isPercent(Token *inst);
static bool _isNot(Token *inst);
static bool _isTilde(Token *inst);
static bool _isGT(Token *inst);
static bool _isLT(Token *inst);
static bool _isEQ(Token *inst);
static bool _isNE(Token *inst);
static bool _isGE(Token *inst);
static bool _isLE(Token *inst);
static bool _isEnd(Token *inst);
static bool _isLogicAnd(Token *inst);
static bool _isLogicOr(Token *inst);
static bool _isBinOp(Token *inst);
static bool _isAugAssign(Token *inst);
public:
parser::Token *rep;
Location *loc;
Token(const parser::Token &tok);
Token(int type, const char *text, Location *loc);
~Token();
static Token *create(int type, const char *text, Location *loc);
/**
* Returns true if the token's text form is the same as the string
* specified.
*/
bool hasText(const char *text);
/**
* Returns the text of the token. For a string token, this will
* return the string contents.
*/
const char *getText();
/**
* Returns the token type.
*/
int getType();
/**
* Returns the total size of the text in bytes.
*/
size_t getTextSize();
Location *getLocation();
bool isAlias();
bool isAnn();
bool isBoolAnd();
bool isBoolOr();
bool isCase();
bool isCatch();
bool isConst();
bool isIf();
bool isImport();
bool isIn();
bool isElse();
bool isLambda();
bool isModule();
bool isOper();
bool isOn();
bool isWhile();
bool isReturn();
bool isSwitch();
bool isThrow();
bool isTry();
bool isBreak();
bool isClass();
bool isContinue();
bool isDollar();
bool isNull();
bool isIdent();
bool isString();
bool isIstrBegin();
bool isIstrEnd();
bool isSemi();
bool isComma();
bool isColon();
bool isDecr();
bool isDefine();
bool isDot();
bool isIncr();
bool isAssign();
bool isLParen();
bool isRParen();
bool isLCurly();
bool isRCurly();
bool isLBracket();
bool isRBracket();
bool isInteger();
bool isFloat();
bool isOctal();
bool isHex();
bool isBinary();
bool isPlus();
bool isQuest();
bool isMinus();
bool isAsterisk();
bool isBang();
bool isSlash();
bool isPercent();
bool isNot();
bool isTilde();
bool isGT();
bool isLT();
bool isEQ();
bool isNE();
bool isGE();
bool isLE();
bool isEnd();
bool isLogicAnd();
bool isLogicOr();
bool isBinOp();
bool isAugAssign();
};
} // namespace compiler
#endif
| C++ |
// Runtime support for directory access
// Copyright 2010 Shannon Weyrick <weyrick@mozek.us>
// Portions Copyright 2010 Google Inc.
#ifndef _runtime_Dir_h_
#define _runtime_Dir_h_
#include <dirent.h>
namespace crack { namespace runtime {
// needs to match dir.crk in runtime
#define CRACK_DTYPE_DIR 1
#define CRACK_DTYPE_FILE 2
#define CRACK_DTYPE_OTHER 3
// mirrored in crack
typedef struct {
const char* name;
int type;
} DirEntry;
// opaque to crack
typedef struct {
DIR* stream;
dirent* lowLevelEntry;
DirEntry currentEntry;
} Dir;
// exported interface
Dir* opendir(const char* name);
DirEntry* getDirEntry(Dir* d);
int closedir(Dir* d);
int readdir(Dir* d);
int fnmatch(const char* pattern, const char* string);
bool Dir_toBool(Dir *dir);
void *Dir_toVoidptr(Dir *dir);
}} // namespace crack::ext
#endif // _runtime_Dir_h_
| C++ |
// Copyright 2011 Google Inc.
#ifndef _crack_runtime_BorrowedExceptions_h_
#define _crack_runtime_BorrowedExceptions_h_
#include "ItaniumExceptionABI.h"
namespace crack { namespace runtime {
_Unwind_Reason_Code handleLsda(int version,
const uint8_t* lsda,
_Unwind_Action actions,
uint64_t exceptionClass,
struct _Unwind_Exception* exceptionObject,
_Unwind_Context *context);
}} // namespace crack::runtime
#endif
| C++ |
// Copyright 2010 Google Inc.
#ifndef _crack_runtime_Net_h_
#define _crack_runtime_Net_h_
#include <stdint.h>
#include <signal.h>
#include <poll.h>
#include <netdb.h>
#include <sys/un.h>
#ifndef UNIX_PATH_MAX
# define UNIX_PATH_MAX 108
#endif
namespace crack { namespace runtime {
struct Constants {
int crk_AF_UNIX,
crk_AF_LOCAL,
crk_AF_INET,
crk_AF_INET6,
crk_AF_IPX,
crk_AF_NETLINK,
crk_AF_X25,
crk_AF_AX25,
crk_AF_ATMPVC,
crk_AF_APPLETALK,
crk_AF_PACKET,
crk_SOCK_STREAM,
crk_SOCK_DGRAM,
crk_SOCK_SEQPACKET,
crk_SOCK_RAW,
crk_SOCK_RDM,
crk_SOCK_PACKET,
crk_SOCK_NONBLOCK,
crk_SOCK_CLOEXEC,
crk_SOL_SOCKET,
crk_SO_REUSEADDR,
crk_POLLIN,
crk_POLLOUT,
crk_POLLPRI,
crk_POLLERR,
crk_POLLHUP,
crk_POLLNVAL;
uint32_t crk_INADDR_ANY;
};
struct SockAddr {
int family;
};
struct SockAddrIn : public SockAddr {
uint32_t addr;
unsigned int port;
static void init1(SockAddrIn *inst, uint8_t a, uint8_t b, uint8_t c,
uint8_t d,
unsigned int port
);
static void init2(SockAddrIn *inst, uint32_t addr, unsigned int port);
static uint32_t crack_htonl(uint32_t val);
static uint32_t crack_ntohl(uint32_t val);
static uint16_t crack_htons(uint16_t val);
static uint16_t crack_ntohs(uint16_t val);
};
struct SockAddrUn : public SockAddr {
char path[UNIX_PATH_MAX];
static void init(SockAddrUn *inst, const char *path);
static const char *getPath(SockAddrUn *inst);
};
struct TimeVal {
int32_t secs, nsecs;
static void init(TimeVal *inst, int32_t secs0, int32_t nsecs0);
};
struct PollEvt {
int fd, events, revents;
};
Constants *getConstants();
uint32_t makeIPV4(uint8_t a, uint8_t b, uint8_t c, uint8_t d);
int connect(int s, SockAddr *addr);
int bind(int s, SockAddr *addr);
int accept(int s, SockAddr *addr);
int setsockopt_int(int fd, int level, int optname, int val);
sigset_t *SigSet_create();
void SigSet_destroy(sigset_t *sigmask);
int SigSet_empty(sigset_t *sigmask);
int SigSet_fill(sigset_t *sigmask);
int SigSet_add(sigset_t *sigmask, int signum);
int SigSet_del(sigset_t *sigmask, int signum);
int SigSet_has(sigset_t *sigmask, int signum);
pollfd *PollSet_create(unsigned int size);
void PollSet_copy(struct pollfd *dst, struct pollfd *src, unsigned int size);
void PollSet_destroy(struct pollfd *pollset);
void PollSet_set(struct pollfd *set, unsigned int index, int fd, int events,
int revents
);
void PollSet_get(struct pollfd *set, unsigned int index,
PollEvt *outputEntry
);
int PollSet_next(struct pollfd *set, unsigned int size, unsigned int index,
PollEvt *outputEntry
);
void PollSet_delete(struct pollfd *set, unsigned int size, unsigned int index);
int PollSet_poll(struct pollfd *fds, unsigned int nfds, TimeVal *tv,
sigset_t *sigmask
);
addrinfo *AddrInfo_create(const char *host, const char *service,
addrinfo *hints
);
void AddrInfo_free(addrinfo *info);
sockaddr_in *AddrInfo_getInAddr(addrinfo *ai);
struct PipeAddr {
int32_t flags, readfd, writefd;
static void init1(PipeAddr *pipe, int32_t flags);
static void init2(PipeAddr *pipe, int32_t flags, int32_t readfd, int32_t writefd);
};
}} // namespace crack::runtime
#endif
| C++ |
// Copyright 2010 Google Inc.
#include "Net.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <poll.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdint.h>
#include <malloc.h>
#include <errno.h>
#include <signal.h>
#include <assert.h>
#include <unistd.h>
#include <fcntl.h>
#include <iostream>
using namespace std;
namespace {
static void set_sockaddr_in(struct sockaddr_in *sa,
crack::runtime::SockAddrIn *addr
) {
sa->sin_family = AF_INET;
sa->sin_port = htons(addr->port);
sa->sin_addr.s_addr = htonl(addr->addr);
}
static void set_sockaddr_un(struct sockaddr_un *sa,
crack::runtime::SockAddrUn *addr
) {
sa->sun_family = AF_UNIX;
strcpy(sa->sun_path, addr->path);
}
typedef union {
sockaddr_in in;
sockaddr_un un;
} AddrUnion;
static socklen_t set_sockaddr(AddrUnion &addrs,
crack::runtime::SockAddr *addr
) {
socklen_t sz;
if (addr->family == AF_INET) {
set_sockaddr_in(&addrs.in,
static_cast<crack::runtime::SockAddrIn *>(addr));
sz = sizeof(addrs.in);
} else {
set_sockaddr_un(&addrs.un,
static_cast<crack::runtime::SockAddrUn *>(addr));
sz = sizeof(addrs.un);
}
return sz;
}
}
// our exported functions
namespace crack { namespace runtime {
void SockAddrIn::init1(SockAddrIn *inst, uint8_t a, uint8_t b, uint8_t c,
uint8_t d,
unsigned int port0
) {
inst->family = AF_INET;
inst->addr = makeIPV4(a, b, c, d);
inst->port = port0;
}
void SockAddrIn::init2(SockAddrIn *inst, uint32_t addr0, unsigned int port0) {
inst->family = AF_INET;
inst->addr = addr0;
inst->port = port0;
}
uint32_t SockAddrIn::crack_htonl(uint32_t val) {
return htonl(val);
}
uint32_t SockAddrIn::crack_ntohl(uint32_t val) {
return ntohl(val);
}
uint16_t SockAddrIn::crack_htons(uint16_t val) {
return htons(val);
}
uint16_t SockAddrIn::crack_ntohs(uint16_t val) {
return ntohs(val);
}
void SockAddrUn::init(SockAddrUn *inst, const char *path) {
inst->family = AF_UNIX;
strncpy(inst->path, path, UNIX_PATH_MAX);
}
const char *SockAddrUn::getPath(SockAddrUn *inst) {
return inst->path;
}
void TimeVal::init(TimeVal *inst, int32_t secs0, int32_t nsecs0) {
inst->secs = secs0;
inst->nsecs = nsecs0;
}
uint32_t makeIPV4(uint8_t a, uint8_t b, uint8_t c, uint8_t d) {
return (a << 24) | (b << 16) | (c << 8) | d;
}
int connect(int s, SockAddr *addr) {
AddrUnion addrs;
socklen_t sz = set_sockaddr(addrs, addr);
return ::connect(s, (sockaddr *)&addrs, sz);
}
int bind(int s, SockAddr *addr) {
AddrUnion addrs;
socklen_t sz = set_sockaddr(addrs, addr);
return ::bind(s, (sockaddr *)&addrs, sz);
}
int accept(int s, SockAddr *addr) {
AddrUnion addrs;
addrs.in.sin_family = addr->family;
socklen_t saSize = sizeof(addrs);
int newSock = ::accept(s, (sockaddr *)&addrs, &saSize);
if (newSock != -1) {
switch (addrs.in.sin_family) {
case AF_INET: {
SockAddrIn *in = static_cast<SockAddrIn *>(addr);
in->port = ntohs(addrs.in.sin_port);
in->addr = ntohl(addrs.in.sin_addr.s_addr);
break;
}
case AF_UNIX: {
SockAddrUn *un = static_cast<SockAddrUn *>(addr);
assert(un->family == AF_UNIX);
strcpy(un->path, addrs.un.sun_path);
break;
}
}
}
return newSock;
}
int setsockopt_int(int fd, int level, int optname, int val) {
return setsockopt(fd, level, optname, &val, sizeof(val));
}
pollfd *PollSet_create(unsigned int size) {
return (pollfd *)calloc(size, sizeof(struct pollfd));
}
void PollSet_copy(struct pollfd *dst, struct pollfd *src, unsigned int size) {
memcpy(dst, src, size * sizeof(struct pollfd));
}
void PollSet_destroy(struct pollfd *pollset) {
free(pollset);
}
void PollSet_set(struct pollfd *set, unsigned int index, int fd, int events,
int revents
) {
struct pollfd &elem = set[index];
elem.fd = fd;
elem.events = events;
elem.revents = revents;
}
void PollSet_get(struct pollfd *set, unsigned int index,
PollEvt *outputEntry
) {
struct pollfd &elem = set[index];
outputEntry->fd = elem.fd;
outputEntry->events = elem.fd;
outputEntry->revents = elem.fd;
}
// find the next poll entry that has an event in revents whose index is >=
// index. Makes it easy to iterate over the pollset. Returns the index of
// the item found, stores the entry info in outputEntry, -1 if no item was
// found.
int PollSet_next(struct pollfd *set, unsigned int size, unsigned int index,
PollEvt *outputEntry
) {
for (; index < size; ++index) {
pollfd *elem = &set[index];
if (elem->revents) {
outputEntry->fd = elem->fd;
outputEntry->events = elem->events;
outputEntry->revents = elem->revents;
return index;
}
}
// not found.
return -1;
}
void PollSet_delete(struct pollfd *set, unsigned int size, unsigned int index) {
memmove(set + index, set + index + 1,
(size - index - 1) * sizeof(struct pollfd)
);
}
int PollSet_poll(struct pollfd *fds, unsigned int nfds, TimeVal *tv,
sigset_t *sigmask
) {
if (tv) {
struct timespec ts = {tv->secs, tv->nsecs};
return ppoll(fds, nfds, &ts, sigmask);
} else {
return ppoll(fds, nfds, 0, sigmask);
}
}
sigset_t *SigSet_create() {
return (sigset_t *)malloc(sizeof(sigset_t));
}
void SigSet_destroy(sigset_t *sigmask) {
free(sigmask);
}
int SigSet_empty(sigset_t *sigmask) {
return sigemptyset(sigmask);
}
int SigSet_fill(sigset_t *sigmask) {
return sigfillset(sigmask);
}
int SigSet_add(sigset_t *sigmask, int signum) {
return sigaddset(sigmask, signum);
}
int SigSet_del(sigset_t *sigmask, int signum) {
return sigdelset(sigmask, signum);
}
int SigSet_has(sigset_t *sigmask, int signum) {
return sigismember(sigmask, signum);
}
addrinfo *AddrInfo_create(const char *host, const char *service,
addrinfo *hints
) {
addrinfo *result;
if (getaddrinfo(host, service, hints, &result))
return 0;
else
return result;
}
sockaddr_in *AddrInfo_getInAddr(addrinfo *ai) {
if (ai->ai_family == AF_INET)
return (sockaddr_in *)ai->ai_addr;
else
return 0;
}
void PipeAddr::init1(PipeAddr *pipeAddr, int32_t flags) {
int pipefd[2] = {-1, -1};
int errors = pipe(pipefd);
if (errors == 0) {
pipeAddr->flags=flags;
pipeAddr->readfd = int32_t(pipefd[0]);
pipeAddr->writefd = int32_t(pipefd[1]);
if (fcntl(pipefd[0], F_SETFL, flags)!=-1) return;
fcntl(pipefd[1], F_SETFL, flags);
}
}
void PipeAddr::init2(PipeAddr *pipe, int32_t flags, int32_t readfd, int32_t writefd) {
pipe->flags = flags;
pipe->readfd = readfd;
pipe->writefd = writefd;
}
}} // namespace crack::runtime
| C++ |
// Copyright 2011 Google Inc.
// runtime exception handling functions supporting the Itanium API
#include "Exceptions.h"
#include <stdlib.h>
#include <assert.h>
#include <iostream>
#include <dlfcn.h>
#include "debug/DebugTools.h"
#include "ItaniumExceptionABI.h"
#include "BorrowedExceptions.h"
using namespace std;
using namespace crack::runtime;
namespace crack { namespace runtime {
// per-thread exception object variable and a "once" variable to allow us to
// initialize it.
static pthread_key_t exceptionObjectKey;
static pthread_once_t exceptionObjectKeyOnce = PTHREAD_ONCE_INIT;
void deleteException(_Unwind_Exception *exc) {
if (runtimeHooks.exceptionReleaseFunc)
runtimeHooks.exceptionReleaseFunc(exc->user_data);
delete exc;
pthread_setspecific(crack::runtime::exceptionObjectKey, 0);
}
void initExceptionObjectKey() {
int rc = pthread_key_create(
&exceptionObjectKey,
reinterpret_cast<void (*)(void *)>(deleteException)
);
assert(rc == 0 && "Unable to create pthread key for exception object.");
}
}} // namespace crack::runtime
extern "C" _Unwind_Reason_Code __CrackExceptionPersonality(
int version,
_Unwind_Action actions,
uint64_t exceptionClass,
struct _Unwind_Exception *exceptionObject,
struct _Unwind_Context *context
) {
assert(version == 1 && "bad exception API version number");
#ifdef DEBUG
cerr << "Exception API, got actions = " << actions <<
" exception class: " << exceptionClass << endl;
#endif
exceptionObject->last_ip =
reinterpret_cast<void *>(_Unwind_GetIP(context));
if (runtimeHooks.exceptionPersonalityFunc)
runtimeHooks.exceptionPersonalityFunc(exceptionObject->user_data,
exceptionObject->last_ip,
exceptionClass,
actions
);
_Unwind_Reason_Code result;
result = handleLsda(version, _Unwind_GetLanguageSpecificData(context),
actions,
exceptionClass,
exceptionObject,
context
);
#ifdef DEBUG
cerr << "got past the lsda handler: " << result << endl;
#endif
return result;
}
static void __CrackExceptionCleanup(_Unwind_Reason_Code reason,
struct _Unwind_Exception *exc
) {
if (--exc->ref_count == 0) {
crack::runtime::deleteException(exc);
}
}
/** Function called by the "throw" statement. */
extern "C" void __CrackThrow(void *crackExceptionObject) {
pthread_once(&exceptionObjectKeyOnce,
crack::runtime::initExceptionObjectKey
);
_Unwind_Exception *uex =
reinterpret_cast<_Unwind_Exception *>(
pthread_getspecific(crack::runtime::exceptionObjectKey)
);
if (uex) {
// XXX what if the exception isn't a crack exception?
// we don't need an atomic reference count for these, they are thread
// specific.
++uex->ref_count;
// release the original exception object XXX need to give the crack
// library the option to associate the old exception with the new one.
if (runtimeHooks.exceptionReleaseFunc)
runtimeHooks.exceptionReleaseFunc(uex->user_data);
} else {
uex = new _Unwind_Exception();
uex->exception_class = crackClassId;
uex->exception_cleanup = __CrackExceptionCleanup;
uex->ref_count = 1;
int rc = pthread_setspecific(crack::runtime::exceptionObjectKey, uex);
assert(rc == 0 && "unable to store exception key");
}
uex->user_data = crackExceptionObject;
_Unwind_Reason_Code urc;
if (urc = _Unwind_RaiseException(uex)) {
cerr << "Failed to raise exception, reason code = " << urc << endl;
abort();
}
}
/**
* Function called to obtain the original crack exception object from the
* ABI's exception object.
*/
extern "C" void *__CrackGetException(_Unwind_Exception *uex) {
return uex->user_data;
}
extern "C" void __CrackCleanupException(_Unwind_Exception *uex) {
_Unwind_DeleteException(uex);
}
extern "C" void __CrackPrintPointer(void *pointer) {
cerr << "pointer is: " << pointer << endl;
}
// added this as part of the work-around for a tricky exception seg-fault.
extern "C" void __CrackNOP(void *ex) {}
extern "C" void __CrackBadCast(void *curType, void *newType) {
if (runtimeHooks.badCastFunc) {
runtimeHooks.badCastFunc(curType, newType);
} else {
cerr << "Invalid class cast." << endl;
abort();
}
}
/** Called at every stack frame during an exception unwind. */
extern "C" void __CrackExceptionFrame() {
if (runtimeHooks.exceptionFrameFunc) {
_Unwind_Exception *uex =
reinterpret_cast<_Unwind_Exception *>(
pthread_getspecific(crack::runtime::exceptionObjectKey)
);
runtimeHooks.exceptionFrameFunc(uex->user_data, uex->last_ip);
}
}
/** Called from the toplevel when there is an uncaught exception.
* Returns true if the exception was a crack exception.
*/
extern "C" bool __CrackUncaughtException() {
_Unwind_Exception *uex =
reinterpret_cast<_Unwind_Exception *>(
pthread_getspecific(crack::runtime::exceptionObjectKey)
);
if (uex->exception_class = crackClassId) {
if (runtimeHooks.exceptionUncaughtFunc)
runtimeHooks.exceptionUncaughtFunc(uex->user_data);
return true;
}
return false;
}
namespace crack { namespace runtime {
RuntimeHooks runtimeHooks = {0};
void registerHook(HookId hookId, void *hook) {
switch (hookId) {
case exceptionMatchFuncHook:
runtimeHooks.exceptionMatchFunc =
reinterpret_cast<ExceptionMatchFunc>(hook);
break;
case exceptionReleaseFuncHook:
runtimeHooks.exceptionReleaseFunc =
reinterpret_cast<ExceptionReleaseFunc>(hook);
break;
case badCastFuncHook:
runtimeHooks.badCastFunc = reinterpret_cast<BadCastFunc>(hook);
break;
case exceptionPersonalityFuncHook:
runtimeHooks.exceptionPersonalityFunc =
reinterpret_cast<ExceptionPersonalityFunc>(hook);
break;
case exceptionFrameFuncHook:
runtimeHooks.exceptionFrameFunc =
reinterpret_cast<ExceptionFrameFunc>(hook);
break;
case exceptionUncaughtFuncHook:
runtimeHooks.exceptionUncaughtFunc =
reinterpret_cast<ExceptionUncaughtFunc>(hook);
break;
default:
cerr << "Unknown runtime hook specified: " << hookId << endl;
}
}
}} // namespace crack::runtime
| C++ |
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
// Note: this code was mostly lifted from the LLVM ExceptionDemo.cpp file.
#include "BorrowedExceptions.h"
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>
#include <iostream>
#include "ItaniumExceptionABI.h"
#include "Exceptions.h"
#define DW_EH_PE_omit 0xff
#define DW_EH_PE_uleb128 0x01
#define DW_EH_PE_udata2 0x02
#define DW_EH_PE_udata4 0x03
#define DW_EH_PE_udata8 0x04
#define DW_EH_PE_sleb128 0x09
#define DW_EH_PE_sdata2 0x0A
#define DW_EH_PE_sdata4 0x0B
#define DW_EH_PE_sdata8 0x0C
#define DW_EH_PE_absptr 0x00
#define DW_EH_PE_pcrel 0x10
#define DW_EH_PE_textrel 0x20
#define DW_EH_PE_datarel 0x30
#define DW_EH_PE_funcrel 0x40
#define DW_EH_PE_aligned 0x50
#define DW_EH_PE_indirect 0x80
#define DW_EH_PE_omit 0xff
using std::cerr;
using std::endl;
namespace crack { namespace runtime {
/// Read a uleb128 encoded value and advance pointer
/// See Variable Length Data in:
/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
/// @param data reference variable holding memory pointer to decode from
/// @returns decoded value
static uintptr_t readULEB128(const uint8_t** data) {
uintptr_t result = 0;
uintptr_t shift = 0;
unsigned char byte;
const uint8_t* p = *data;
do {
byte = *p++;
result |= (byte & 0x7f) << shift;
shift += 7;
}
while (byte & 0x80);
*data = p;
return result;
}
/// Read a sleb128 encoded value and advance pointer
/// See Variable Length Data in:
/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
/// @param data reference variable holding memory pointer to decode from
/// @returns decoded value
static uintptr_t readSLEB128(const uint8_t** data) {
uintptr_t result = 0;
uintptr_t shift = 0;
unsigned char byte;
const uint8_t* p = *data;
do {
byte = *p++;
result |= (byte & 0x7f) << shift;
shift += 7;
}
while (byte & 0x80);
*data = p;
if ((byte & 0x40) && (shift < (sizeof(result) << 3))) {
result |= (~0 << shift);
}
return result;
}
/// Read a pointer encoded value and advance pointer
/// See Variable Length Data in:
/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
/// @param data reference variable holding memory pointer to decode from
/// @param encoding dwarf encoding type
/// @returns decoded value
static uintptr_t readEncodedPointer(const uint8_t** data, uint8_t encoding) {
uintptr_t result = 0;
const uint8_t* p = *data;
if (encoding == DW_EH_PE_omit)
return(result);
// first get value
switch (encoding & 0x0F) {
case DW_EH_PE_absptr:
result = *((uintptr_t*)p);
p += sizeof(uintptr_t);
break;
case DW_EH_PE_uleb128:
result = readULEB128(&p);
break;
// Note: This case has not been tested
case DW_EH_PE_sleb128:
result = readSLEB128(&p);
break;
case DW_EH_PE_udata2:
result = *((uint16_t*)p);
p += sizeof(uint16_t);
break;
case DW_EH_PE_udata4:
result = *((uint32_t*)p);
p += sizeof(uint32_t);
break;
case DW_EH_PE_udata8:
result = *((uint64_t*)p);
p += sizeof(uint64_t);
break;
case DW_EH_PE_sdata2:
result = *((int16_t*)p);
p += sizeof(int16_t);
break;
case DW_EH_PE_sdata4:
result = *((int32_t*)p);
p += sizeof(int32_t);
break;
case DW_EH_PE_sdata8:
result = *((int64_t*)p);
p += sizeof(int64_t);
break;
default:
// not supported
abort();
break;
}
// then add relative offset
switch (encoding & 0x70) {
case DW_EH_PE_absptr:
// do nothing
break;
case DW_EH_PE_pcrel:
result += (uintptr_t)(*data);
break;
case DW_EH_PE_textrel:
case DW_EH_PE_datarel:
case DW_EH_PE_funcrel:
case DW_EH_PE_aligned:
default:
// not supported
abort();
break;
}
// then apply indirection
if (encoding & DW_EH_PE_indirect) {
result = *((uintptr_t*)result);
}
*data = p;
return result;
}
static void *getTTypePtr(void **classInfo, int index, uint8_t ttypeEncoding) {
switch (ttypeEncoding & 0xF) {
case DW_EH_PE_absptr:
return classInfo[index];
case DW_EH_PE_udata4:
return (void *)((uint32_t *)classInfo)[index];
case DW_EH_PE_udata8:
return (void *)((uint64_t *)classInfo)[index];
default:
cerr << "Unexpected type pointer encoding type: " <<
ttypeEncoding << endl;
abort();
}
}
/// Deals with Dwarf actions matching our type infos.
/// Returns whether or not a dwarf emitted
/// action matches the supplied exception type. If such a match succeeds,
/// the resultAction argument will be set with > 0 index value. Only
/// corresponding llvm.eh.selector type info arguments, cleanup arguments
/// are supported. Filters are not supported.
/// See Variable Length Data in:
/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
/// Also see @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
/// @param resultAction reference variable which will be set with result
/// @param classInfo our array of type info pointers (to globals)
/// @param actionEntry index into above type info array or 0 (clean up).
/// We do not support filters.
/// @param exceptionClass exception class (_Unwind_Exception::exception_class)
/// of thrown exception.
/// @param exceptionObject thrown _Unwind_Exception instance.
/// @returns whether or not a type info was found. False is returned if only
/// a cleanup was found
static bool handleActionValue(int64_t *resultAction,
uint8_t ttypeEncoding,
void **classInfo,
uintptr_t actionEntry,
uint64_t exceptionClass,
struct _Unwind_Exception *exceptionObject) {
bool ret = false;
if (!resultAction ||
!exceptionObject ||
(exceptionClass != crackClassId))
return(ret);
// get the "crack exception object" which is the object actually thrown in
// the "throw" statement.
void *crackExceptionObject = exceptionObject->user_data;
#ifdef DEBUG
fprintf(stderr,
"handleActionValue(...): exceptionObject = <%p>, "
"excp = <%p>.\n",
exceptionObject,
excp);
#endif
const uint8_t *actionPos = (uint8_t*) actionEntry,
*tempActionPos;
int64_t typeOffset = 0,
actionOffset;
for (int i = 0; true; ++i) {
// Each emitted dwarf action corresponds to a 2 tuple of
// type info address offset, and action offset to the next
// emitted action.
typeOffset = readSLEB128(&actionPos);
tempActionPos = actionPos;
actionOffset = readSLEB128(&tempActionPos);
#ifdef DEBUG
fprintf(stderr,
"handleActionValue(...):typeOffset: <%lld>, "
"actionOffset: <%lld>.\n",
typeOffset,
actionOffset);
#endif
assert((typeOffset >= 0) &&
"handleActionValue(...):filters are not supported.");
// Note: A typeOffset == 0 implies that a cleanup llvm.eh.selector
// argument has been matched.
if (typeOffset > 0) {
// if we got an exception and there is no "match" function,
// translate it to an abort.
if (!runtimeHooks.exceptionMatchFunc) abort();
void *curClassType = getTTypePtr(classInfo, -typeOffset,
ttypeEncoding
);
if (runtimeHooks.exceptionMatchFunc(curClassType,
crackExceptionObject
)
) {
#ifdef DEBUG
fprintf(stderr,
"handleActionValue(...):actionValue <%d> found.\n",
i);
#endif
*resultAction = i + 1;
ret = true;
break;
}
}
#ifdef DEBUG
fprintf(stderr,
"handleActionValue(...):actionValue not found.\n");
#endif
if (!actionOffset)
break;
actionPos += actionOffset;
}
return(ret);
}
/// Deals with the Language specific data portion of the emitted dwarf code.
/// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
/// @param version unsupported (ignored), unwind version
/// @param lsda language specific data area
/// @param _Unwind_Action actions minimally supported unwind stage
/// (forced specifically not supported)
/// @param exceptionClass exception class (_Unwind_Exception::exception_class)
/// of thrown exception.
/// @param exceptionObject thrown _Unwind_Exception instance.
/// @param context unwind system context
/// @returns minimally supported unwinding control indicator
_Unwind_Reason_Code handleLsda(int version,
const uint8_t* lsda,
_Unwind_Action actions,
uint64_t exceptionClass,
struct _Unwind_Exception* exceptionObject,
_Unwind_Context *context) {
_Unwind_Reason_Code ret = _URC_CONTINUE_UNWIND;
if (!lsda)
return(ret);
#ifdef DEBUG
fprintf(stderr,
"handleLsda(...):lsda is non-zero.\n");
#endif
// Get the current instruction pointer and offset it before next
// instruction in the current frame which threw the exception.
uintptr_t pc = _Unwind_GetIP(context)-1;
// Get beginning current frame's code (as defined by the
// emitted dwarf code)
uintptr_t funcStart = _Unwind_GetRegionStart(context);
uintptr_t pcOffset = pc - funcStart;
void** classInfo = NULL;
// Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
// dwarf emission
// Parse LSDA header.
uint8_t lpStartEncoding = *lsda++;
if (lpStartEncoding != DW_EH_PE_omit) {
readEncodedPointer(&lsda, lpStartEncoding);
}
uint8_t ttypeEncoding = *lsda++;
uintptr_t classInfoOffset;
if (ttypeEncoding != DW_EH_PE_omit) {
// Calculate type info locations in emitted dwarf code which
// were flagged by type info arguments to llvm.eh.selector
// intrinsic
classInfoOffset = readULEB128(&lsda);
classInfo = (void **) (lsda + classInfoOffset);
}
// Walk call-site table looking for range that
// includes current PC.
uint8_t callSiteEncoding = *lsda++;
uint32_t callSiteTableLength = readULEB128(&lsda);
const uint8_t* callSiteTableStart = lsda;
const uint8_t* callSiteTableEnd = callSiteTableStart +
callSiteTableLength;
const uint8_t* actionTableStart = callSiteTableEnd;
const uint8_t* callSitePtr = callSiteTableStart;
bool foreignException = false;
while (callSitePtr < callSiteTableEnd) {
uintptr_t start = readEncodedPointer(&callSitePtr,
callSiteEncoding);
uintptr_t length = readEncodedPointer(&callSitePtr,
callSiteEncoding);
uintptr_t landingPad = readEncodedPointer(&callSitePtr,
callSiteEncoding);
// Note: Action value
uintptr_t actionEntry = readULEB128(&callSitePtr);
if (exceptionClass != crack::runtime::crackClassId) {
// We have been notified of a foreign exception being thrown,
// and we therefore need to execute cleanup landing pads
actionEntry = 0;
foreignException = true;
}
if (landingPad == 0) {
#ifdef DEBUG
fprintf(stderr,
"handleLsda(...): No landing pad found.\n");
#endif
continue; // no landing pad for this entry
}
if (actionEntry) {
actionEntry += ((uintptr_t) actionTableStart) - 1;
}
else {
#ifdef DEBUG
fprintf(stderr,
"handleLsda(...):No action table found.\n");
#endif
}
bool exceptionMatched = false;
if ((start <= pcOffset) && (pcOffset < (start + length))) {
#ifdef DEBUG
fprintf(stderr,
"handleLsda(...): Landing pad found.\n");
#endif
int64_t actionValue = 0;
if (actionEntry) {
exceptionMatched = handleActionValue
(
&actionValue,
ttypeEncoding,
classInfo,
actionEntry,
exceptionClass,
exceptionObject
);
}
if (!(actions & _UA_SEARCH_PHASE)) {
#ifdef DEBUG
fprintf(stderr,
"handleLsda(...): installed landing pad "
"context.\n");
#endif
// Found landing pad for the PC.
// Set Instruction Pointer to so we re-enter function
// at landing pad. The landing pad is created by the
// compiler to take two parameters in registers.
_Unwind_SetGR(context,
__builtin_eh_return_data_regno(0),
(uintptr_t)exceptionObject);
// Note: this virtual register directly corresponds
// to the return of the llvm.eh.selector intrinsic
if (!actionEntry || !exceptionMatched) {
// We indicate cleanup only
_Unwind_SetGR(context,
__builtin_eh_return_data_regno(1),
0);
}
else {
// Matched type info index of llvm.eh.selector intrinsic
// passed here.
_Unwind_SetGR(context,
__builtin_eh_return_data_regno(1),
actionValue);
}
// To execute landing pad set here
_Unwind_SetIP(context, funcStart + landingPad);
ret = _URC_INSTALL_CONTEXT;
}
else if (exceptionMatched) {
#ifdef DEBUG
fprintf(stderr,
"handleLsda(...): setting handler found.\n");
#endif
ret = _URC_HANDLER_FOUND;
}
else {
// Note: Only non-clean up handlers are marked as
// found. Otherwise the clean up handlers will be
// re-found and executed during the clean up
// phase.
#ifdef DEBUG
fprintf(stderr,
"handleLsda(...): cleanup handler found.\n");
#endif
}
break;
}
}
return(ret);
}
}} // namespace crack::runtime
| C++ |
// Copyright (C) 2010 Conrad D. Steenberg
// Lincensed under LGPLv2
#include <math.h>
#include <errno.h>
#include <fenv.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <stdio.h>
#include <string>
#include <dlfcn.h>
#include "ext/Module.h"
#include "ext/Func.h"
using namespace crack::ext;
using namespace std;
// This version of the code does not wrap the math functions, but needs to specify
// their symbol names in addFunc
// Conversely symbols defined in a non-secondary library must _not_ be specified
#ifndef WRAP_SECONDARY_SYMBOLS
namespace crack { namespace runtime {
// Argument name definitions
enum arg_values{ VALUE, ANGLE, ENUMERATOR, DIVISOR, POWER, SIGN, X, Y, DIRECTION};
const char *arg_names[]={"value", "angle", "enumerator", "divisor", "power",
"sign", "x", "y", "direction"};
// Function type definitions
typedef float (OneFuncFloat)(float);
typedef float (TwoFuncFloat)(float, float);
typedef int (OneMacroFuncFloat)(float);
#if FLT_EVAL_METHOD==0
// double and float are distinct types
typedef double (OneFuncDouble)(double);
typedef double (TwoFuncDouble)(double, double);
typedef int (OneMacroFuncDouble)(double);
#endif
// Structs to hold function and constant info
typedef struct _one_name_struct{
const char *funcname;
const char *cname;
arg_values argname;
} one_name_struct;
typedef struct _two_name_struct{
const char *funcname;
arg_values argname1;
arg_values argname2;
} two_name_struct;
typedef struct _double_constant_struct{
const char *name;
const double value;
} double_constant_struct;
typedef struct _int_constant_struct{
const char *name;
const int value;
} int_constant_struct;
// -----------------------------------------------------------------------------
const double_constant_struct double_constants[] = {
{"HUGE_VAL", HUGE_VAL},
{"INFINITY", INFINITY},
{"NAN", NAN},
{NULL, 0}
};
const int_constant_struct int_constants[]={{"ERANGE", ERANGE},
{"EINVAL", EINVAL},
{"ENOMEM", ENOMEM},
{"FP_INFINITE", FP_INFINITE},
{"FP_NAN", FP_NAN},
{"FP_NORMAL", FP_NORMAL},
{"FP_SUBNORMAL", FP_SUBNORMAL},
{"FP_ZERO", FP_ZERO},
{"FP_ILOGB0", FP_ILOGB0},
{"FP_ILOGBNAN", FP_ILOGBNAN},
{"ALL_EXCEPT", FE_ALL_EXCEPT},
{"INVALID", FE_INVALID},
{"DIVBYZERO", FE_DIVBYZERO},
{"OVERFLOW", FE_OVERFLOW},
{"UNDERFLOW", FE_UNDERFLOW},
{NULL, 0}};
// -----------------------------------------------------------------------------
// Functions that take a single float argument
const one_name_struct one_names[]={
{"sin", "sin", ANGLE}, {"cos", "cos", ANGLE},
{"tan", "tan", ANGLE}, {"sinh", "sinh", ANGLE},
{"cosh", "cosh", ANGLE}, {"tanh", "tanh", ANGLE},
{"asin", "asin", VALUE}, {"acos", "acos", VALUE},
{"atan", "atan", VALUE}, {"asinh", "asinh", VALUE},
{"acosh", "acosh", VALUE}, {"atanh", "atanh", VALUE},
{"exp", "exp", VALUE}, {"exp2", "exp2", VALUE},
{"log", "log", VALUE}, {"abs", "fabs", VALUE},
{"log10", "log10", VALUE}, {"log1p", "log1p", VALUE},
{"log2", "log2", VALUE}, {"cbrt", "cbrt", VALUE},
{"sqrt", "sqrt", VALUE}, {"erf", "erf", VALUE},
{"erfc", "erfc", VALUE}, {"lgamma", "lgamma", VALUE},
{"tgamma", "tgamma", VALUE}, {"ceil", "ceil", VALUE},
{"floor", "floor", VALUE}, {"nearbyint", "nearbyint", VALUE},
{"rint", "rint", VALUE}, {"round", "round", VALUE},
{"trunc", "trunc", VALUE}, {"expm1", "expm1", VALUE},
{NULL, NULL, VALUE}
};
// Functions that take 2 float arguments
const two_name_struct two_names[]={
{"fmod", ENUMERATOR, DIVISOR},
{"remainder", ENUMERATOR, DIVISOR},
{"copysign", VALUE, SIGN},
{"nextafter", VALUE, DIRECTION},
{"hypot", X, Y},
{"fdim", VALUE, DIRECTION},
{"pow", VALUE, POWER}, {NULL, VALUE, VALUE}
};
// Macros that take a single argument
const char *one_macro_names[]={"fpclassify", "isfinite", "isinf", "isnan",
"isnormal", "sign", "ilogb", NULL};
OneFuncFloat *one_funcs[]= { sinf, cosf,
tanf, sinhf,
coshf, tanhf,
asinf, acosf,
atanf, asinhf,
acoshf, atanhf,
expf, exp2f,
logf, fabsf,
log10f, log1pf,
log2f, cbrtf,
sqrtf, erff,
erfcf, lgammaf,
tgammaf,ceilf,
floorf, nearbyintf,
rintf, roundf,
truncf, expm1f, NULL
};
// Functions that take two arguments
// Some of these are already implemented by the compiler
TwoFuncFloat *two_funcs[]= { fmodf, remainderf,
copysignf, nextafterf, hypotf,
fdimf, powf, NULL
};
// Bindings for macros that take one argument
int crk_fpclassify(float x){
return fpclassify(x);
}
int crk_isfinite(float x){
return isfinite(x);
}
int crk_isinf(float x){
return isinf(x);
}
int crk_isnan(float x){
return isnan(x);
}
int crk_isnormal(float x){
return isnormal(x);
}
int crk_signbit(float x){
return signbit(x);
}
OneMacroFuncFloat *one_macros[]={crk_fpclassify, crk_isfinite,
crk_isinf, crk_isnan,
crk_isnormal,
crk_signbit, ilogbf, NULL};
// -----------------------------------------------------------------------------
#if FLT_EVAL_METHOD==0
OneFuncDouble *one_funcs_double[]= { sin, cos,
tan, sinh,
cosh, tanh,
asin, acos,
atan, asinh,
acosh, atanh,
exp, exp2,
fabs, log,
log10, log1p,
log2, cbrt,
sqrt, erf,
erfc, lgamma,
tgamma,ceil,
floor, nearbyint,
rint, round,
trunc, expm1, NULL
};
TwoFuncDouble *two_funcs_double[]={ fmod, remainder,
copysign, nextafter, hypot,
fdim, pow, NULL};
// Bindings for macros that take one argument
int crk_fpclassify_double(double x){
return fpclassify(x);
}
int crk_isfinite_double(double x){
return isfinite(x);
}
int crk_isinf_double(double x){
return isinf(x);
}
int crk_isnan_double(double x){
return isnan(x);
}
int crk_isnormal_double(double x){
return isnormal(x);
}
int crk_signbit_double(double x){
return signbit(x);
}
int crk_get_errno(){
return errno;
}
void crk_set_errno(int value){
errno=value;
}
int crk_strtoi(char *s){
errno = 0;
return (int)strtol(s, (char**)NULL, 0);
}
float crk_strtof(char *s){
errno = 0;
return (float)strtof(s, (char**)NULL);
}
float crk_strtod(char *s){
errno = 0;
return (double)strtod(s, (char**)NULL);
}
OneMacroFuncDouble *one_macros_double[]={ crk_fpclassify_double, crk_isfinite_double,
crk_isinf_double, crk_isinf_double,
crk_isnan_double, crk_isnormal_double,
crk_signbit_double, ilogb, NULL
};
#endif
u_int64_t crk_gettimeofday(void){
struct timeval crk_timeval;
gettimeofday(&crk_timeval, NULL);
return (unsigned long)(crk_timeval.tv_sec*1000000 + crk_timeval.tv_usec); // Time in usecs
}
//------------------------------------------------------------------------------
void math_init(Module *mod) {
int i, j, numtypes=3;
char buffer[100];
char symbol_buffer[100];
char postfixes[][5] = {"", "f", "32", "64", ""};
char symbol_postfixes[][5] = {"f", "f", "f", "", ""};
Type *functypes[] = {mod->getFloatType(), mod->getFloatType(),
mod->getFloat32Type(), mod->getFloat64Type(),
mod->getFloat64Type()};
Func *func, *funcd;
#if FLT_EVAL_METHOD==0
numtypes=3;
#endif
// One argument functions
for(i=0;one_funcs[i];i++){
for (j=0; j<numtypes; j++){
strcpy(buffer, one_names[i].funcname);
strcat(buffer, postfixes[j]);
strcpy(symbol_buffer, one_names[i].cname);
strcat(symbol_buffer, symbol_postfixes[j]);
func = mod->addFunc(functypes[j], buffer,
(void *) one_funcs[i], symbol_buffer);
func->addArg(functypes[j], arg_names[one_names[i].argname]);
}
#if FLT_EVAL_METHOD==0
// double and float are distinct types
for (j=numtypes; j<5; j++){
strcpy(buffer, one_names[i].funcname);
strcat(buffer, postfixes[j]);
strcpy(symbol_buffer, one_names[i].cname);
strcat(symbol_buffer, symbol_postfixes[j]);
funcd = mod->addFunc(functypes[j], buffer,
(void *) one_funcs_double[i], symbol_buffer);
funcd->addArg(functypes[j], arg_names[one_names[i].argname]);
}
#endif
}
for(i=0;one_macros[i];i++){
for (j=0; j<numtypes; j++){
strcpy(buffer, one_macro_names[i]);
strcat(buffer, postfixes[j]);
func = mod->addFunc(mod->getIntType(), buffer,
(void *) one_macros[i]);
func->addArg(functypes[j], "value");
}
#if FLT_EVAL_METHOD==0
// double and float are distinct types
for (j=numtypes; j<5; j++){
strcpy(buffer, one_macro_names[i]);
strcat(buffer, postfixes[j]);
funcd = mod->addFunc(mod->getIntType(), one_macro_names[i],
(void *) one_macros_double[i]);
funcd->addArg(functypes[j], "value");
}
#endif
}
// Two argument functions
for(i=0;two_funcs[i];i++){
for (j=0; j<numtypes; j++){
strcpy(buffer, two_names[i].funcname);
strcat(buffer, postfixes[j]);
strcpy(symbol_buffer, one_names[i].funcname);
strcat(symbol_buffer, symbol_postfixes[j]);
func = mod->addFunc(functypes[j], buffer,
(void *) two_funcs[i], symbol_buffer);
func->addArg(functypes[j], arg_names[two_names[i].argname1]);
func->addArg(functypes[j], arg_names[two_names[i].argname2]);
}
#if FLT_EVAL_METHOD==0
// double and float are distinct types
for (j=numtypes; j<5; j++){
strcpy(buffer, two_names[i].funcname);
strcat(buffer, postfixes[j]);
strcpy(symbol_buffer, one_names[i].funcname);
strcat(symbol_buffer, symbol_postfixes[j]);
funcd = mod->addFunc(functypes[j], two_names[i].funcname,
(void *) two_funcs_double[i], symbol_buffer);
funcd->addArg(functypes[j], arg_names[two_names[i].argname1]);
funcd->addArg(functypes[j], arg_names[two_names[i].argname2]);
}
#endif
}
// Add constants to module
for (i=0; double_constants[i].name;i++){
mod->addConstant(mod->getFloat64Type(), double_constants[i].name,
double_constants[i].value);
}
for (i=0; int_constants[i].name;i++){
mod->addConstant(mod->getIntType(), int_constants[i].name,
int_constants[i].value);
}
// Math error handling
func = mod->addFunc(mod->getIntType(), "clearexcept", (void *) feclearexcept);
func->addArg(mod->getIntType(), "errors");
func = mod->addFunc(mod->getIntType(), "testexcept", (void *) fetestexcept);
func->addArg(mod->getIntType(), "errors");
// Some utility functions
// Get and set errno
Func *get_errno_func = mod->addFunc(mod->getIntType(), "errno", (void *)crk_get_errno);
Func *set_errno_func = mod->addFunc(mod->getVoidType(), "setErrno", (void *)crk_set_errno);
set_errno_func->addArg(mod->getIntType(), "value");
// atoi
Func *atoi_func = mod->addFunc(mod->getIntType(), "atoi", (void *)atoi);
atoi_func->addArg(mod->getByteptrType(), "str");
// strtoi
Func *strtoi_func = mod->addFunc(mod->getIntType(), "strtoi", (void *)crk_strtoi);
strtoi_func->addArg(mod->getByteptrType(), "str");
// strtof
Func *strtof_func = mod->addFunc(mod->getFloatType(), "strtof", (void *)crk_strtof);
strtof_func->addArg(mod->getByteptrType(), "str");
// atof like strtof, but no error checking
Func *atof_func = mod->addFunc(mod->getFloatType(), "atof", (void *)atof);
atof_func->addArg(mod->getByteptrType(), "str");
// strtod
Func *strtod_func = mod->addFunc(mod->getFloat64Type(), "strtod", (void *)crk_strtod);
strtod_func->addArg(mod->getByteptrType(), "str");
// gettimofday wrapper
Func* time_func = mod->addFunc(mod->getUint64Type(), "usecs", (void *)crk_gettimeofday);
}
}} // namespace crack::runtime
#else
// Version of the code that wraps all the math functions and do not specify symbol
// names anywhere
namespace crack { namespace runtime {
// Argument name definitions
enum arg_values{ VALUE, ANGLE, ENUMERATOR, DIVISOR, POWER, SIGN, X, Y, DIRECTION};
const char *arg_names[]={"value", "angle", "enumerator", "divisor", "power",
"sign", "x", "y", "direction"};
// Function type definitions
typedef float (OneFuncFloat)(float);
typedef float (TwoFuncFloat)(float, float);
typedef int (OneMacroFuncFloat)(float);
#if FLT_EVAL_METHOD==0
// double and float are distinct types
typedef double (OneFuncDouble)(double);
typedef double (TwoFuncDouble)(double, double);
typedef int (OneMacroFuncDouble)(double);
#endif
// Structs to hold function and constant info
typedef struct _one_name_struct{
const char *funcname;
arg_values argname;
} one_name_struct;
typedef struct _two_name_struct{
const char *funcname;
arg_values argname1;
arg_values argname2;
} two_name_struct;
typedef struct _double_constant_struct{
const char *name;
const double value;
} double_constant_struct;
typedef struct _int_constant_struct{
const char *name;
const int value;
} int_constant_struct;
// -----------------------------------------------------------------------------
const double_constant_struct double_constants[] = {
{"HUGE_VAL", HUGE_VAL},
{"INFINITY", INFINITY},
{"NAN", NAN},
{NULL, 0}
};
const int_constant_struct int_constants[]={{"ERANGE", ERANGE},
{"EINVAL", EINVAL},
{"ENOMEM", ENOMEM},
{"FP_INFINITE", FP_INFINITE},
{"FP_NAN", FP_NAN},
{"FP_NORMAL", FP_NORMAL},
{"FP_SUBNORMAL", FP_SUBNORMAL},
{"FP_ZERO", FP_ZERO},
{"FP_ILOGB0", FP_ILOGB0},
{"FP_ILOGBNAN", FP_ILOGBNAN},
{"ALL_EXCEPT", FE_ALL_EXCEPT},
{"INVALID", FE_INVALID},
{"DIVBYZERO", FE_DIVBYZERO},
{"OVERFLOW", FE_OVERFLOW},
{"UNDERFLOW", FE_UNDERFLOW},
{NULL, 0}};
// -----------------------------------------------------------------------------
// Functions that take a single float argument
const one_name_struct one_names[]={
{"sin", ANGLE}, {"cos", ANGLE},
{"tan", ANGLE}, {"sinh", ANGLE},
{"cosh", ANGLE}, {"tanh", ANGLE},
{"asin", VALUE}, {"acos", VALUE},
{"atan", VALUE}, {"asinh", VALUE},
{"acosh", VALUE}, {"atanh", VALUE},
{"exp", VALUE}, {"exp2", VALUE},
{"log", VALUE}, {"abs", VALUE},
{"log10", VALUE}, {"log1p", VALUE},
{"log2", VALUE}, {"cbrt", VALUE},
{"sqrt", VALUE}, {"erf", VALUE},
{"erfc", VALUE}, {"lgamma", VALUE},
{"tgamma", VALUE}, {"ceil", VALUE},
{"floor", VALUE}, {"nearbyint", VALUE},
{"rint", VALUE}, {"round", VALUE},
{"trunc", VALUE}, {"expm1", VALUE},
{NULL, VALUE}
};
// Functions that take 2 float arguments
const two_name_struct two_names[]={
{"fmod", ENUMERATOR, DIVISOR},
{"remainder", ENUMERATOR, DIVISOR},
{"copysign", VALUE, SIGN},
{"nextafter", VALUE, DIRECTION},
{"hypot", X, Y},
{"fdim", VALUE, DIRECTION},
{"pow", VALUE, POWER}, {NULL, VALUE, VALUE}
};
// Macros that take a single argument
const char *one_macro_names[]={"fpclassify", "isfinite", "isinf", "isnan",
"isnormal", "sign", "ilogb", NULL};
#define one_funcs_impl_float(fname) \
float crack_##fname(float arg) { return fname(arg);}
one_funcs_impl_float(sinf)
one_funcs_impl_float(cosf)
one_funcs_impl_float(tanf)
one_funcs_impl_float(sinhf)
one_funcs_impl_float(coshf)
one_funcs_impl_float(tanhf)
one_funcs_impl_float(asinf)
one_funcs_impl_float(acosf)
one_funcs_impl_float(atanf)
one_funcs_impl_float(asinhf)
one_funcs_impl_float(acoshf)
one_funcs_impl_float(atanhf)
one_funcs_impl_float(expf)
one_funcs_impl_float(exp2f)
one_funcs_impl_float(logf)
one_funcs_impl_float(fabsf)
one_funcs_impl_float(log10f)
one_funcs_impl_float(log1pf)
one_funcs_impl_float(log2f)
one_funcs_impl_float(cbrtf)
one_funcs_impl_float(sqrtf)
one_funcs_impl_float(erff)
one_funcs_impl_float(erfcf)
one_funcs_impl_float(lgammaf)
one_funcs_impl_float(tgammaf)
one_funcs_impl_float(ceilf)
one_funcs_impl_float(floorf)
one_funcs_impl_float(nearbyintf)
one_funcs_impl_float(rintf)
one_funcs_impl_float(roundf)
one_funcs_impl_float(truncf)
one_funcs_impl_float(expm1f)
OneFuncFloat *one_funcs[]= { crack_sinf, crack_cosf,
crack_tanf, crack_sinhf,
crack_coshf, crack_tanhf,
crack_asinf, crack_acosf,
crack_atanf, crack_asinhf,
crack_acoshf, crack_atanhf,
crack_expf, crack_exp2f,
crack_logf, crack_fabsf,
crack_log10f, crack_log1pf,
crack_log2f, crack_cbrtf,
crack_sqrtf, crack_erff,
crack_erfcf, crack_lgammaf,
crack_tgammaf, crack_ceilf,
crack_floorf, crack_nearbyintf,
crack_rintf, crack_roundf,
crack_truncf, crack_expm1f, NULL
};
// Functions that take two arguments
// Some of these are already implemented by the compiler
TwoFuncFloat *two_funcs[]= { fmodf, remainderf,
copysignf, nextafterf, hypotf,
fdimf, powf, NULL
};
// Bindings for macros that take one argument
int crk_fpclassify(float x){
return fpclassify(x);
}
int crk_isfinite(float x){
return isfinite(x);
}
int crk_isinf(float x){
return isinf(x);
}
int crk_isnan(float x){
return isnan(x);
}
int crk_isnormal(float x){
return isnormal(x);
}
int crk_signbit(float x){
return signbit(x);
}
OneMacroFuncFloat *one_macros[]={crk_fpclassify, crk_isfinite,
crk_isinf, crk_isnan,
crk_isnormal,
crk_signbit, ilogbf, NULL};
// -----------------------------------------------------------------------------
#if FLT_EVAL_METHOD==0
#define one_funcs_impl(fname) \
double crack_##fname(double arg) { return fname(arg);}
#define two_funcs_impl(fname) \
double crack_##fname(double arg1, double arg2) { return fname(arg1, arg2);}
one_funcs_impl(sin)
one_funcs_impl(cos)
one_funcs_impl(tan)
one_funcs_impl(sinh)
one_funcs_impl(cosh)
one_funcs_impl(tanh)
one_funcs_impl(asin)
one_funcs_impl(acos)
one_funcs_impl(atan)
one_funcs_impl(asinh)
one_funcs_impl(acosh)
one_funcs_impl(atanh)
one_funcs_impl(exp)
one_funcs_impl(exp2)
one_funcs_impl(fabs)
one_funcs_impl(log)
one_funcs_impl(log10)
one_funcs_impl(log1p)
one_funcs_impl(log2)
one_funcs_impl(cbrt)
one_funcs_impl(sqrt)
one_funcs_impl(erf)
one_funcs_impl(erfc)
one_funcs_impl(lgamma)
one_funcs_impl(tgamma)
one_funcs_impl(ceil)
one_funcs_impl(floor)
one_funcs_impl(nearbyint)
one_funcs_impl(rint)
one_funcs_impl(round)
one_funcs_impl(trunc)
one_funcs_impl(expm1)
OneFuncDouble *one_funcs_double[]= { crack_sin, crack_cos,
crack_tan, crack_sinh,
crack_cosh, crack_tanh,
crack_asin, crack_acos,
crack_atan, crack_asinh,
crack_acosh, crack_atanh,
crack_exp, crack_exp2,
crack_fabs, crack_log,
crack_log10, crack_log1p,
crack_log2, crack_cbrt,
crack_sqrt, crack_erf,
crack_erfc, crack_lgamma,
crack_tgamma, crack_ceil,
crack_floor, crack_nearbyint,
crack_rint, crack_round,
crack_trunc, crack_expm1, NULL
};
two_funcs_impl(fmod)
two_funcs_impl(remainder)
two_funcs_impl(copysign)
two_funcs_impl(nextafter)
two_funcs_impl(hypot)
two_funcs_impl(fdim)
two_funcs_impl(pow)
TwoFuncDouble *two_funcs_double[]={ crack_fmod, crack_remainder,
crack_copysign, crack_nextafter,
crack_hypot, crack_fdim, crack_pow, NULL};
// Bindings for macros that take one argument
int crk_fpclassify_double(double x){
return fpclassify(x);
}
int crk_isfinite_double(double x){
return isfinite(x);
}
int crk_isinf_double(double x){
return isinf(x);
}
int crk_isnan_double(double x){
return isnan(x);
}
int crk_isnormal_double(double x){
return isnormal(x);
}
int crk_signbit_double(double x){
return signbit(x);
}
int crk_get_errno(){
return errno;
}
void crk_set_errno(int value){
errno=value;
}
int crk_strtoi(char *s){
errno = 0;
return (int)strtol(s, (char**)NULL, 0);
}
float crk_strtof(char *s){
errno = 0;
return (float)strtof(s, (char**)NULL);
}
float crk_strtod(char *s){
errno = 0;
return (double)strtod(s, (char**)NULL);
}
OneMacroFuncDouble *one_macros_double[]={ crk_fpclassify_double, crk_isfinite_double,
crk_isinf_double, crk_isinf_double,
crk_isnan_double, crk_isnormal_double,
crk_signbit_double, ilogb, NULL
};
#endif
u_int64_t crk_gettimeofday(void){
struct timeval crk_timeval;
gettimeofday(&crk_timeval, NULL);
return (int64_t)(crk_timeval.tv_sec*1000000 + crk_timeval.tv_usec); // Time in usecs
}
//------------------------------------------------------------------------------
void math_init(Module *mod) {
int i, j, numtypes=4;
char buffer[100];
char symbol_buffer[100];
char postfixes[][5] = {"", "f", "32", "64", ""};
char symbol_postfixes[][5] = {"f", "f", "f", "", ""};
Type *functypes[] = {mod->getFloatType(), mod->getFloatType(),
mod->getFloat32Type(), mod->getFloat64Type(),
mod->getFloat64Type()};
Func *func, *funcd;
#if FLT_EVAL_METHOD==0
numtypes=3;
#endif
// One argument functions
for(i=0;one_funcs[i];i++){
for (j=0; j<numtypes; j++){
strcpy(buffer, one_names[i].funcname);
strcat(buffer, postfixes[j]);
func = mod->addFunc(functypes[j], buffer,
(void *) one_funcs[i]);
func->addArg(functypes[j], arg_names[one_names[i].argname]);
}
#if FLT_EVAL_METHOD==0
// double and float are distinct types
for (j=numtypes; j<5; j++){
strcpy(buffer, one_names[i].funcname);
strcat(buffer, postfixes[j]);
funcd = mod->addFunc(functypes[j], buffer,
(void *) one_funcs_double[i]);
funcd->addArg(functypes[j], arg_names[one_names[i].argname]);
}
#endif
}
for(i=0;one_macros[i];i++){
for (j=0; j<numtypes; j++){
strcpy(buffer, one_macro_names[i]);
strcat(buffer, postfixes[j]);
func = mod->addFunc(mod->getIntType(), buffer,
(void *) one_macros[i]);
func->addArg(functypes[j], "value");
}
#if FLT_EVAL_METHOD==0
// double and float are distinct types
for (j=numtypes; j<5; j++){
strcpy(buffer, one_macro_names[i]);
strcat(buffer, postfixes[j]);
funcd = mod->addFunc(mod->getIntType(), one_macro_names[i],
(void *) one_macros_double[i]);
funcd->addArg(functypes[j], "value");
}
#endif
}
// Two argument functions
for(i=0;two_funcs[i];i++){
for (j=0; j<numtypes; j++){
strcpy(buffer, two_names[i].funcname);
strcat(buffer, postfixes[j]);
func = mod->addFunc(functypes[j], buffer,
(void *) two_funcs[i]);
func->addArg(functypes[j], arg_names[two_names[i].argname1]);
func->addArg(functypes[j], arg_names[two_names[i].argname2]);
}
#if FLT_EVAL_METHOD==0
// double and float are distinct types
for (j=numtypes; j<5; j++){
strcpy(buffer, two_names[i].funcname);
strcat(buffer, postfixes[j]);
funcd = mod->addFunc(functypes[j], two_names[i].funcname,
(void *) two_funcs_double[i]);
funcd->addArg(functypes[j], arg_names[two_names[i].argname1]);
funcd->addArg(functypes[j], arg_names[two_names[i].argname2]);
}
#endif
}
// Add constants to module
for (i=0; double_constants[i].name;i++){
mod->addConstant(mod->getFloat64Type(), double_constants[i].name,
double_constants[i].value);
}
for (i=0; int_constants[i].name;i++){
mod->addConstant(mod->getIntType(), int_constants[i].name,
int_constants[i].value);
}
// Math error handling
func = mod->addFunc(mod->getIntType(), "clearexcept", (void *) feclearexcept);
func->addArg(mod->getIntType(), "errors");
func = mod->addFunc(mod->getIntType(), "testexcept", (void *) fetestexcept);
func->addArg(mod->getIntType(), "errors");
// Some utility functions
// Get and set errno
Func *get_errno_func = mod->addFunc(mod->getIntType(), "errno", (void *)crk_get_errno);
Func *set_errno_func = mod->addFunc(mod->getVoidType(), "setErrno", (void *)crk_set_errno);
set_errno_func->addArg(mod->getIntType(), "value");
// atoi
Func *atoi_func = mod->addFunc(mod->getIntType(), "atoi", (void *)atoi);
atoi_func->addArg(mod->getByteptrType(), "str");
// strtoi
Func *strtoi_func = mod->addFunc(mod->getIntType(), "strtoi", (void *)crk_strtoi);
strtoi_func->addArg(mod->getByteptrType(), "str");
// strtof
Func *strtof_func = mod->addFunc(mod->getFloatType(), "strtof", (void *)crk_strtof);
strtof_func->addArg(mod->getByteptrType(), "str");
// atof like strtof, but no error checking
Func *atof_func = mod->addFunc(mod->getFloatType(), "atof", (void *)atof);
atof_func->addArg(mod->getByteptrType(), "str");
// strtod
Func *strtod_func = mod->addFunc(mod->getFloat64Type(), "strtod", (void *)crk_strtod);
strtod_func->addArg(mod->getByteptrType(), "str");
// gettimofday wrapper
Func* time_func = mod->addFunc(mod->getInt64Type(), "usecs", (void *)crk_gettimeofday);
}
}} // namespace crack::runtime
#endif
| C++ |
// Copyright 2011 Google Inc.
#ifndef _ItaniumExceptionABI_h_
#define _ItaniumExceptionABI_h_
#define __STDC_CONSTANT_MACROS 1
#define __STDC_LIMIT_MACROS 1
#include <stdint.h>
namespace crack { namespace runtime {
// System C++ ABI unwind types from:
// http://refspecs.freestandards.org/abi-eh-1.21.html
// for now we're just going to define the entire Itanium exception API here
// (since there's no standard header file for it)
enum _Unwind_Action {
_UA_SEARCH_PHASE = 1,
_UA_CLEANUP_PHASE = 2,
_UA_HANDLER_FRAME = 4,
_UA_FORCE_UNWIND = 8
};
enum _Unwind_Reason_Code {
_URC_NO_REASON = 0,
_URC_FOREIGN_EXCEPTION_CAUGHT = 1,
_URC_FATAL_PHASE2_ERROR = 2,
_URC_FATAL_PHASE1_ERROR = 3,
_URC_NORMAL_STOP = 4,
_URC_END_OF_STACK = 5,
_URC_HANDLER_FOUND = 6,
_URC_INSTALL_CONTEXT = 7,
_URC_CONTINUE_UNWIND = 8
};
struct _Unwind_Exception;
typedef void (*_Unwind_Exception_Cleanup_Fn)(_Unwind_Reason_Code reason,
struct _Unwind_Exception *exc
);
struct _Unwind_Exception {
uint64_t exception_class;
_Unwind_Exception_Cleanup_Fn exception_cleanup;
uint64_t private_1, private_2;
// crack-specific reference count and user data (points to the exception
// object).
unsigned int ref_count;
void *user_data;
// the last IP address that the exception personality function got called
// for.
void *last_ip;
} __attribute__((__aligned__));
struct _Unwind_Context;
extern "C" uint8_t *_Unwind_GetLanguageSpecificData(_Unwind_Context *context);
extern "C" uint64_t _Unwind_GetIP(_Unwind_Context *context);
extern "C" uint64_t _Unwind_GetRegionStart(_Unwind_Context *context);
extern "C" void _Unwind_SetGR(struct _Unwind_Context *context, int index,
uint64_t new_value
);
extern "C" void _Unwind_SetIP(struct _Unwind_Context *context,
uint64_t new_value
);
extern "C" _Unwind_Reason_Code _Unwind_RaiseException(_Unwind_Exception *ex);
extern "C" void _Unwind_DeleteException (_Unwind_Exception *ex);
// end of borrowed exception API
// some crack-specific stuff put here out of laziness.
const uint64_t crackClassId = UINT64_C(0x537075674372616b); // "SpugCrak"
}} // namespace crack::runtime
#endif
| C++ |
// Copyright (C) 2010 Conrad D. Steenberg
// Lincensed under LGPLv3
#include "ext/Module.h"
#include "ext/Func.h"
namespace crack { namespace runtime {
void math_init(crack::ext::Module *mod);
}
}
| C++ |
// Runtime support
// Copyright 2010 Shannon Weyrick <weyrick@mozek.us>
#ifndef _runtime_Util_h_
#define _runtime_Util_h_
#include <stdint.h>
namespace crack { namespace runtime {
char* strerror(void);
int float_str(double, char* buf, unsigned int size);
unsigned int rand(unsigned int low, unsigned int high);
void puts(char *str);
void __putc(char byte);
void __die(const char *message);
void printfloat(float val);
void printint(int val);
void printint64(int64_t val);
void printuint64(uint64_t val);
int is_file(const char *path);
bool fileExists(const char *path);
int setNonBlocking(int fd, int val);
int setUtimes(const char *path, int64_t atv_usecs, int64_t mtv_usecs, bool now);
}}
#endif // _runtime_Util_h_
| C++ |
// Copyright 2011 Google Inc.
// header for the exceptions subsystem of the runtime
#define __STDC_CONSTANT_MACROS 1
#define __STDC_LIMIT_MACROS 1
#include <stdint.h>
namespace crack { namespace runtime {
/**
* The exception match function is called to check if an exception object is a
* member of the specified exception type.
* @param exceptionType the crack exception's class object.
* @param exceptionObject the crack exception thrown (the value passed in the
* "throw" clause.
*/
typedef int (*ExceptionMatchFunc)(void *exceptionType, void *exceptionObject);
/**
* The bad cast function is called when a typecast is called on an object that
* is not an instance of the type we're casting it to.
*/
typedef void (*BadCastFunc)(void *curClass, void *newClass);
/**
* The exception release function is called during exception cleanup to allow
* the library to do an "oper release" on the exception object.
*/
typedef void (*ExceptionReleaseFunc)(void *crackExceptionObj);
/**
* This function is called when the runtime's exception personality function
* is called on a crack exception during a cleanup or exception handler action.
* It is used to give the library a chance to attach stack trace information
* to the exception.
* @param address the IP address in the current exception frame that the
* was passed to the original personality function.
* @param itaniumExceptionClass an identifier defining the language that raised
* the exception
* @param actions the set of actions that the personality function was called
* with.
*/
typedef void (*ExceptionPersonalityFunc)(void *crackExceptionObj,
void *address,
uint64_t itaniumExceptionClass,
int actions
);
/**
* This function is called when we the system leaves a frame during exception
* processing. Unlike the exception personality function, it is guaranteed to
* be called only once per frame.
*/
typedef void (*ExceptionFrameFunc)(void *crackExceptionObj,
void *adddress
);
/**
* Called by the toplevel exception handler for an exception that was not
* caught.
*/
typedef void (*ExceptionUncaughtFunc)(void *crackExceptionObj);
enum HookId {
exceptionMatchFuncHook,
badCastFuncHook,
exceptionReleaseFuncHook,
exceptionPersonalityFuncHook,
exceptionFrameFuncHook,
exceptionUncaughtFuncHook,
numHooks
};
/**
* The runtime hooks function holds pointers to elements defined in the
* language that need to be used by code in the runtime.
*/
struct RuntimeHooks {
ExceptionMatchFunc exceptionMatchFunc;
BadCastFunc badCastFunc;
ExceptionReleaseFunc exceptionReleaseFunc;
ExceptionPersonalityFunc exceptionPersonalityFunc;
ExceptionFrameFunc exceptionFrameFunc;
ExceptionUncaughtFunc exceptionUncaughtFunc;
};
extern RuntimeHooks runtimeHooks;
/**
* Crack-importable function to allow you to register a hook.
*/
void registerHook(HookId hookId, void *hook);
}} // namespace crack::runtime
| C++ |
// Runtime support
// Copyright 2010 Shannon Weyrick <weyrick@mozek.us>
#include "Util.h"
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <utime.h>
#include <unistd.h>
#include <fcntl.h>
namespace crack { namespace runtime {
static bool rseeded = false;
char* strerror(void) {
return ::strerror(errno);
}
// note, not to be used for security purposes
unsigned int rand(unsigned int low, unsigned int high) {
if (!rseeded) {
srand(time(NULL));
rseeded = true;
}
int r = ::rand() % (high-low+1)+low;
return r;
}
// this is temporary until we implement float printing in crack
// assumes caller allocates and owns buffer
int float_str(double d, char* buf, unsigned int size) {
return snprintf(buf, size, "%f", d);
}
void puts(char *str) {
::puts(str);
}
void __putc(char byte) {
::putchar(byte);
}
void __die(const char *message) {
std::cout << message << std::endl;
abort();
}
void printfloat(float val) {
std::cout << val << std::flush;
}
void printint(int val) {
std::cout << val << std::flush;
}
void printint64(int64_t val) {
std::cout << val << std::flush;
}
void printuint64(uint64_t val) {
std::cout << val << std::flush;
}
int is_file(const char *path) {
struct stat sb;
if (stat(path, &sb) == -1)
return 0;
return S_ISREG(sb.st_mode);
}
bool fileExists(const char *path) {
struct stat st;
return stat(path, &st) == 0;
}
int setNonBlocking(int fd, int val) {
int flags = fcntl(fd, F_GETFL);
if (flags < 0)
return -1;
if (val)
flags |= O_NONBLOCK;
else
flags &= ~O_NONBLOCK;
return fcntl(fd, F_SETFL, flags);
}
int setUtimes(const char *path,
int64_t atv_usecs,
int64_t mtv_usecs,
bool now
) {
if (!path){
errno = ENOENT;
return -1;
}
if (now)
return utimes(path, NULL);
struct timeval times[2];
int retval;
times[0].tv_sec = atv_usecs/1000000;
times[0].tv_usec = atv_usecs%1000000;
times[1].tv_sec = atv_usecs/1000000;
times[1].tv_usec = atv_usecs%1000000;
return utimes(path, times);
}
}}
| C++ |
// Copyright 2011 Shannon Weyrick <weyrick@mozek.us>
#include "Process.h"
#include "ext/Module.h"
#include "ext/Func.h"
#include "ext/Type.h"
#include <vector>
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
using namespace crack::ext;
namespace crack { namespace runtime {
// returns the exit status if exited, or the signal that killed or stopped
// the process in the most sig byte with a bit flag set in 9 or 10 depending
// on how it was signaled, or bit 8 set for "still running"
int waitProcess(int pid, int noHang) {
// UNIX
int status, retPid;
retPid = waitpid(pid, &status, (noHang)?WNOHANG:0);
if (noHang && retPid == 0)
return CRK_PROC_STILL_RUNNING;
if (WIFEXITED(status)) {
return CRK_PROC_EXITED | WEXITSTATUS(status);
}
else if (WIFSIGNALED(status)) {
return CRK_PROC_KILLED | WTERMSIG(status);
}
else if (WIFSTOPPED(status)) {
return CRK_PROC_STOPPED | WSTOPSIG(status);
}
else {
perror("waitpid");
return -1;
}
// END UNIX
}
void signalProcess(int pid, int sig) {
// UNIX
kill(pid, sig);
// END UNIX
}
void closeProcess(PipeDesc *pd) {
if (close(pd->stdin) == -1)
perror("close pipe failed: stdin");
if (close(pd->stdout) == -1)
perror("close pipe failed: stdout");
if (close(pd->stderr) == -1)
perror("close pipe failed: stderr");
}
int runChildProcess(const char **argv,
const char **env,
PipeDesc *pd
) {
assert(pd && "no PipeDesc passed");
// UNIX
// set to unreadable initially
pd->stdin = -1;
pd->stdout = -1;
pd->stderr = -1;
int pipes[3][2]; // 0,1,2 (in,out,err) x 0,1 (read,write)
// verify the binary exists and is executable, otherwise we fail before fork
struct stat sb;
if (stat(argv[0], &sb) == -1)
return -1;
if (!S_ISREG(sb.st_mode) ||
sb.st_size == 0 ||
((sb.st_mode & S_IXUSR == 0) ||
(sb.st_mode & S_IXGRP == 0) ||
(sb.st_mode & S_IXOTH == 0)))
return -1;
// create pipes
// XXX check pd to see which pipes we should make, if any
for (int i = 0; i < 3; i++) {
if (pipe(pipes[i]) == -1) {
perror("pipe failed");
return -1;
}
}
pid_t p = fork();
switch (p) {
case -1:
perror("fork failed");
return -1;
case 0:
// child
if (close(pipes[0][1]) == -1) { // child stdin write close
perror("close - child 0");
return -1;
}
if (pipes[0][0] != STDIN_FILENO) {
dup2(pipes[0][0], STDIN_FILENO);
close(pipes[0][0]);
}
if (close(pipes[1][0]) == -1) { // child stdout read close
perror("close - child 1");
return -1;
}
if (pipes[1][1] != STDOUT_FILENO) {
dup2(pipes[1][1], STDOUT_FILENO);
close(pipes[1][1]);
}
if (close(pipes[2][0]) == -1) { // child stderr read close
perror("close - child 2");
return -1;
}
if (pipes[2][1] != STDERR_FILENO) {
dup2(pipes[2][1], STDERR_FILENO);
close(pipes[2][1]);
}
// XXX close all handles > 2?
if (env) {
execve(argv[0],
const_cast<char* const*>(argv),
const_cast<char* const*>(env));
}
else {
execvp(argv[0], const_cast<char* const*>(argv));
}
// if we get here, exec failed
exit(-1);
default:
// parent
if (close(pipes[0][0]) == -1) { // parent stdin read close
perror("close - parent 0");
return -1;
}
if (close(pipes[1][1]) == -1) { // parent stdout write close
perror("close - parent 1");
return -1;
}
if (close(pipes[2][1]) == -1) { // parent stderr write close
perror("close - parent 2");
return -1;
}
// return pipes[0][1] as writeable fd (to child stdin)
// return pipes[1][0] as readable fd (from child stdout)
// return pipes[2][0] as readable fd (from child stderr)
pd->stdin = pipes[0][1];
pd->stdout = pipes[1][0];
pd->stderr = pipes[2][0];
return p;
}
// END UNIX
}
}} // namespace crack::runtime
| C++ |
// Copyright 2011 Shannon Weyrick <weyrick@mozek.us>
namespace crack { namespace runtime {
#define CRK_PROC_STILL_RUNNING 1 << 8
#define CRK_PROC_KILLED 1 << 9
#define CRK_PROC_STOPPED 1 << 10
#define CRK_PROC_EXITED 1 << 11
#define PIPE_STDIN 1
#define PIPE_STDOUT 1 << 1
#define PIPE_STDERR 1 << 2
typedef struct {
int flags;
int stdin;
int stdout;
int stderr;
} PipeDesc;
int runChildProcess(const char **argv,
const char **env,
PipeDesc *pd);
void closeProcess(PipeDesc *pd);
int waitProcess(int pid, int noHang);
void signalProcess(int pid, int sig);
} }
| C++ |
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <sys/time.h>
#include <stdio.h>
typedef struct tm InternalDate;
InternalDate *crk_create_date(){
return (InternalDate *)calloc(1, sizeof(InternalDate));
}
InternalDate *crk_localtime(InternalDate *d, int64_t t){
const time_t lt = (const time_t)t;
return localtime_r(<, d);
}
InternalDate *crk_localtime_now(InternalDate *now){
struct timeval tv;
gettimeofday(&tv, NULL);
return localtime_r(&(tv.tv_sec), now);
}
InternalDate *crk_gmtime(InternalDate *d, int64_t t){
const time_t gt = (const time_t)t;
return gmtime_r(>, d);
}
InternalDate *crk_gmtime_now(InternalDate *now){
struct timeval tv;
gettimeofday(&tv, NULL);
return gmtime_r(&(tv.tv_sec), now);
}
void crk_epoch(InternalDate *epoch){
epoch->tm_year = 70;
epoch->tm_mon = 0;
epoch->tm_mday = 1;
epoch->tm_hour = 0;
epoch->tm_min = 0;
epoch->tm_sec = 0;
}
char *crk_ctime_r(int64_t t, char * buf){
const time_t lt = (const time_t)t;
return ctime_r(<, buf);
}
char **get_environ(){
return environ;
}
#include "ext/Module.h"
#include "ext/Type.h"
#include "ext/Func.h"
extern "C"
void crack_runtime_time_rinit() {
return;
}
extern "C"
void crack_runtime_time_cinit(crack::ext::Module *mod) {
crack::ext::Func *f;
crack::ext::Type *type_Class = mod->getClassType();
crack::ext::Type *type_void = mod->getVoidType();
crack::ext::Type *type_voidptr = mod->getVoidptrType();
crack::ext::Type *type_bool = mod->getBoolType();
crack::ext::Type *type_byteptr = mod->getByteptrType();
crack::ext::Type *type_byte = mod->getByteType();
crack::ext::Type *type_int32 = mod->getInt32Type();
crack::ext::Type *type_int64 = mod->getInt64Type();
crack::ext::Type *type_uint32 = mod->getUint32Type();
crack::ext::Type *type_uint64 = mod->getUint64Type();
crack::ext::Type *type_int = mod->getIntType();
crack::ext::Type *type_uint = mod->getUintType();
crack::ext::Type *type_intz = mod->getIntzType();
crack::ext::Type *type_uintz = mod->getUintzType();
crack::ext::Type *type_float32 = mod->getFloat32Type();
crack::ext::Type *type_float64 = mod->getFloat64Type();
crack::ext::Type *type_float = mod->getFloatType();
crack::ext::Type *type_InternalDate = mod->addType("InternalDate", sizeof(InternalDate));
type_InternalDate->addInstVar(type_int, "tm_sec",
CRACK_OFFSET(InternalDate, tm_sec));
type_InternalDate->addInstVar(type_int, "tm_min",
CRACK_OFFSET(InternalDate, tm_min));
type_InternalDate->addInstVar(type_int, "tm_hour",
CRACK_OFFSET(InternalDate, tm_hour));
type_InternalDate->addInstVar(type_int, "tm_mday",
CRACK_OFFSET(InternalDate, tm_mday));
type_InternalDate->addInstVar(type_int, "tm_mon",
CRACK_OFFSET(InternalDate, tm_mon));
type_InternalDate->addInstVar(type_int, "tm_year",
CRACK_OFFSET(InternalDate, tm_year));
type_InternalDate->addInstVar(type_int, "tm_wday",
CRACK_OFFSET(InternalDate, tm_wday));
type_InternalDate->addInstVar(type_int, "tm_yday",
CRACK_OFFSET(InternalDate, tm_yday));
type_InternalDate->addInstVar(type_int, "tm_isdst",
CRACK_OFFSET(InternalDate, tm_isdst));
type_InternalDate->addInstVar(type_int64, "tm_gmtoff",
CRACK_OFFSET(InternalDate, tm_gmtoff));
type_InternalDate->addInstVar(type_byteptr, "tm_zone",
CRACK_OFFSET(InternalDate, tm_zone));
f = type_InternalDate->addConstructor("init",
(void *)crk_create_date
);
f = type_InternalDate->addMethod(type_int64, "getSeconds",
(void *)mktime
);
f = type_InternalDate->addMethod(type_void, "setLocalSeconds",
(void *)crk_localtime
);
f->addArg(type_int64, "t");
f = type_InternalDate->addMethod(type_void, "setLocalNow",
(void *)crk_localtime_now
);
f = type_InternalDate->addMethod(type_void, "setUTCSeconds",
(void *)crk_gmtime
);
f->addArg(type_int64, "t");
f = type_InternalDate->addMethod(type_void, "setUTCNow",
(void *)crk_gmtime_now
);
f = type_InternalDate->addMethod(type_void, "setEpoch",
(void *)crk_epoch
);
f = type_InternalDate->addMethod(type_void, "_toBufferRaw",
(void *)asctime_r
);
f->addArg(type_byteptr, "buf");
type_InternalDate->finish();
crack::ext::Type *array = mod->getType("array");
crack::ext::Type *array_pbyteptr_q;
{
std::vector<crack::ext::Type *> params(1);
params[0] = type_byteptr;
array_pbyteptr_q = array->getSpecialization(params);
}
f = mod->addFunc(type_int64, "mktime",
(void *)mktime
);
f->addArg(type_InternalDate, "d");
f = mod->addFunc(type_InternalDate, "localtime",
(void *)crk_localtime
);
f->addArg(type_InternalDate, "d");
f->addArg(type_int64, "t");
f = mod->addFunc(type_InternalDate, "localtime_now",
(void *)crk_localtime_now
);
f->addArg(type_InternalDate, "now");
f = mod->addFunc(type_InternalDate, "gmtime_now",
(void *)crk_gmtime_now
);
f->addArg(type_InternalDate, "now");
f = mod->addFunc(type_InternalDate, "gmtime",
(void *)crk_gmtime
);
f->addArg(type_InternalDate, "now");
f->addArg(type_int64, "t");
f = mod->addFunc(type_void, "epoch",
(void *)crk_epoch
);
f->addArg(type_InternalDate, "epoch");
f = mod->addFunc(type_byteptr, "asctime",
(void *)asctime_r
);
f->addArg(type_InternalDate, "d");
f->addArg(type_byteptr, "buf");
f = mod->addFunc(type_byteptr, "ctime",
(void *)crk_ctime_r
);
f->addArg(type_int64, "seconds");
f->addArg(type_byteptr, "buf");
f = mod->addFunc(type_uintz, "strftime",
(void *)strftime
);
f->addArg(type_byteptr, "s");
f->addArg(type_uintz, "max");
f->addArg(type_byteptr, "format");
f->addArg(type_InternalDate, "d");
f = mod->addFunc(array_pbyteptr_q, "get_environ",
(void *)get_environ
);
f = mod->addFunc(type_int, "putenv",
(void *)putenv
);
f->addArg(type_byteptr, "keyvalue");
f = mod->addFunc(type_byteptr, "getenv",
(void *)getenv
);
f->addArg(type_byteptr, "name");
f = mod->addFunc(type_int, "setenv",
(void *)setenv
);
f->addArg(type_byteptr, "name");
f->addArg(type_byteptr, "value");
f->addArg(type_int, "overwrite");
f = mod->addFunc(type_int, "unsetenv",
(void *)unsetenv
);
f->addArg(type_byteptr, "name");
}
| C++ |
// Runtime support for directory access
// Copyright 2010 Shannon Weyrick <weyrick@mozek.us>
// Portions Copyright 2010 Google Inc.
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <fnmatch.h>
#include <string.h>
#include <libgen.h>
#include <stddef.h>
#include "Dir.h"
namespace crack { namespace runtime {
// XXX see http://womble.decadent.org.uk/readdir_r-advisory.html
// for a warning on using readdir_r and how to calculate len
Dir* opendir(const char* name) {
DIR* d = ::opendir(name);
if (!d)
return NULL;
Dir* cd = (Dir*)malloc(sizeof(Dir));
assert(cd && "bad malloc");
cd->stream = d;
// this len calculation courtesy of linux readdir manpage
size_t len = offsetof(dirent, d_name) +
pathconf(name, _PC_NAME_MAX) + 1;
cd->lowLevelEntry = (dirent*)malloc(len);
assert(cd->lowLevelEntry && "bad malloc");
return cd;
}
DirEntry* getDirEntry(Dir* d) {
assert(d && "null dir pointer");
return &d->currentEntry;
}
int closedir(Dir* d) {
assert(d && "null dir pointer");
::closedir(d->stream);
free(d->lowLevelEntry);
free(d);
}
int readdir(Dir* d) {
assert(d && "null dir pointer");
dirent* result;
int r = readdir_r(d->stream, d->lowLevelEntry, &result);
assert(!r && "error in readdir");
// end of stream
if (!result)
return 0;
// TODO make portable
d->currentEntry.name = d->lowLevelEntry->d_name;
if (d->lowLevelEntry->d_type == DT_DIR)
d->currentEntry.type = CRACK_DTYPE_DIR;
else if (d->lowLevelEntry->d_type == DT_REG)
d->currentEntry.type = CRACK_DTYPE_FILE;
else
d->currentEntry.type = CRACK_DTYPE_OTHER;
return 1;
}
int fnmatch(const char* pattern, const char* string) {
return ::fnmatch(pattern, string, 0);
}
bool Dir_toBool(Dir *dir) {
return dir;
}
void *Dir_toVoidptr(Dir *dir) {
return dir;
}
}} // namespace crack::runtime
| C++ |
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <fcntl.h>
#include <libgen.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/mman.h>
#include <netinet/in.h>
#include <netdb.h>
#include <signal.h>
#include <errno.h>
#include <unistd.h>
#include "debug/DebugTools.h"
#include "ext/Func.h"
#include "ext/Module.h"
#include "ext/Type.h"
#include "Dir.h"
#include "Util.h"
#include "Net.h"
#include "Math.h"
#include "Exceptions.h"
#include "Process.h"
using namespace crack::ext;
extern "C" bool __CrackUncaughtException();
extern "C" void crack_runtime_time_cinit(crack::ext::Module *mod);
// stat() appears to have some funny linkage issues in native mode so we wrap
// it in a normal function.
extern "C" int crack_runtime_stat(const char *path, struct stat *buf) {
return stat(path, buf);
}
extern "C"
void crack_runtime_rinit(void) {
return;
}
extern "C" void crack_runtime_cinit(Module *mod) {
Type *byteptrType = mod->getByteptrType();
Type *boolType = mod->getBoolType();
Type *intType = mod->getIntType();
Type *intzType = mod->getIntzType();
Type *uintzType = mod->getUintzType();
Type *uint16Type = mod->getUint16Type();
Type *uint32Type = mod->getUint32Type();
Type *int16Type = mod->getInt16Type();
Type *int32Type = mod->getInt32Type();
Type *int64Type = mod->getInt64Type();
Type *uintType = mod->getUintType();
Type *byteType = mod->getByteType();
Type *voidType = mod->getVoidType();
Type *voidptrType = mod->getVoidptrType();
Type *baseArrayType = mod->getType("array");
// array[byteptr]
Type *byteptrArrayType;
{
std::vector<Type *> params(1);
params[0] = byteptrType;
byteptrArrayType = baseArrayType->getSpecialization(params);
}
byteptrArrayType->finish();
Type *cdentType = mod->addType("DirEntry",
sizeof(crack::runtime::DirEntry)
);
cdentType->addInstVar(byteptrType, "name",
CRACK_OFFSET(crack::runtime::DirEntry, name)
);
cdentType->addInstVar(intType, "type",
CRACK_OFFSET(crack::runtime::DirEntry, type)
);
cdentType->finish();
Type *cdType = mod->addType("Dir", sizeof(crack::runtime::Dir));
// XXX should this be part of addType?
cdType->addMethod(boolType, "oper to .builtin.bool",
(void *)crack::runtime::Dir_toBool
);
cdType->finish();
Func *f = mod->addFunc(cdType, "opendir", (void *)crack::runtime::opendir);
f->addArg(byteptrType, "name");
f = mod->addFunc(cdentType, "getDirEntry",
(void *)crack::runtime::getDirEntry
);
f->addArg(cdType, "d");
f = mod->addFunc(intType, "closedir", (void *)crack::runtime::closedir);
f->addArg(cdType, "d");
f = mod->addFunc(intType, "readdir", (void *)crack::runtime::readdir);
f->addArg(cdType, "d");
f = mod->addFunc(intType, "fnmatch", (void *)crack::runtime::fnmatch);
f->addArg(byteptrType, "pattern");
f->addArg(byteptrType, "string");
f = mod->addFunc(byteptrType, "basename", (void *)basename, "basename");
f->addArg(byteptrType, "path");
f = mod->addFunc(byteptrType, "dirname", (void *)dirname, "dirname");
f->addArg(byteptrType, "path");
f = mod->addFunc(intType, "is_file", (void *)crack::runtime::is_file);
f->addArg(byteptrType, "path");
f = mod->addFunc(boolType, "fileExists",
(void *)crack::runtime::fileExists
);
f->addArg(byteptrType, "path");
Type *statType = mod->addType("Stat", sizeof(struct stat));
statType->addInstVar(intType, "st_dev", CRACK_OFFSET(struct stat, st_dev));
statType->addInstVar(intType, "st_ino", CRACK_OFFSET(struct stat, st_ino));
statType->addInstVar(intType, "st_mode", CRACK_OFFSET(struct stat, st_mode));
statType->addInstVar(intType, "st_nlink",
CRACK_OFFSET(struct stat, st_nlink)
);
statType->addInstVar(intType, "st_uid", CRACK_OFFSET(struct stat, st_uid));
statType->addInstVar(intType, "st_gid", CRACK_OFFSET(struct stat, st_gid));
statType->addInstVar(intType, "st_rdev", CRACK_OFFSET(struct stat, st_rdev));
statType->addInstVar(intType, "st_size", CRACK_OFFSET(struct stat, st_size));
statType->addInstVar(intType, "st_blksize",
CRACK_OFFSET(struct stat, st_blksize)
);
statType->addInstVar(intType, "st_blocks",
CRACK_OFFSET(struct stat, st_blocks)
);
statType->addInstVar(intType, "st_atime",
CRACK_OFFSET(struct stat, st_atime)
);
statType->addInstVar(intType, "st_mtime",
CRACK_OFFSET(struct stat, st_mtime)
);
statType->addInstVar(intType, "st_ctime",
CRACK_OFFSET(struct stat, st_ctime)
);
statType->addConstructor();
statType->finish();
mod->addConstant(intType, "S_IFMT", S_IFMT);
mod->addConstant(intType, "S_IFSOCK", S_IFSOCK);
mod->addConstant(intType, "S_IFLNK", S_IFLNK);
mod->addConstant(intType, "S_IFREG", S_IFREG);
mod->addConstant(intType, "S_IFBLK", S_IFBLK);
mod->addConstant(intType, "S_IFDIR", S_IFDIR);
mod->addConstant(intType, "S_IFCHR", S_IFCHR);
mod->addConstant(intType, "S_IFIFO", S_IFIFO);
mod->addConstant(intType, "S_ISUID", S_ISUID);
mod->addConstant(intType, "S_ISGID", S_ISGID);
mod->addConstant(intType, "S_ISVTX", S_ISVTX);
mod->addConstant(intType, "S_IRWXU", S_IRWXU);
mod->addConstant(intType, "S_IRUSR", S_IRUSR);
mod->addConstant(intType, "S_IWUSR", S_IWUSR);
mod->addConstant(intType, "S_IXUSR", S_IXUSR);
mod->addConstant(intType, "S_IRWXG", S_IRWXG);
mod->addConstant(intType, "S_IRGRP", S_IRGRP);
mod->addConstant(intType, "S_IWGRP", S_IWGRP);
mod->addConstant(intType, "S_IXGRP", S_IXGRP);
mod->addConstant(intType, "S_IRWXO", S_IRWXO);
mod->addConstant(intType, "S_IROTH", S_IROTH);
mod->addConstant(intType, "S_IWOTH", S_IWOTH);
mod->addConstant(intType, "S_IXOTH", S_IXOTH);
f = mod->addFunc(intType, "stat", (void *)crack_runtime_stat,
"crack_runtime_stat"
);
f->addArg(byteptrType, "path");
f->addArg(statType, "buf");
f = mod->addFunc(intType, "fileRemove", (void *)remove);
f->addArg(byteptrType, "path");
f = mod->addFunc(intType, "mkdir", (void *)mkdir);
f->addArg(byteptrType, "path");
f->addArg(intType, "mode");
mod->addConstant(intType, "EACCESS", EACCES);
mod->addConstant(intType, "EBADF", EBADF);
mod->addConstant(intType, "EEXIST", EEXIST);
mod->addConstant(intType, "EFAULT", EFAULT);
mod->addConstant(intType, "ELOOP", ELOOP);
mod->addConstant(intType, "ENAMETOOLONG", ENAMETOOLONG);
mod->addConstant(intType, "ENOENT", ENOENT);
mod->addConstant(intType, "ENOMEM", ENOMEM);
mod->addConstant(intType, "ENOTDIR", ENOTDIR);
mod->addConstant(intType, "EOVERFLOW", EOVERFLOW);
f = mod->addFunc(byteptrType, "c_strerror",
(void *)crack::runtime::strerror
);
f = mod->addFunc(mod->getIntType(), "float_str",
(void *)crack::runtime::float_str
);
f->addArg(mod->getFloat64Type(), "val");
f->addArg(byteptrType, "buf");
f->addArg(mod->getUintType(), "size");
f = mod->addFunc(uintType, "rand",
(void *)crack::runtime::rand
);
f->addArg(mod->getUintType(), "low");
f->addArg(mod->getUintType(), "high");
f = mod->addFunc(intType, "random", (void *)random);
f = mod->addFunc(voidType, "srandom", (void *)srandom);
f->addArg(uintType, "seed");
f = mod->addFunc(byteptrType, "initstate", (void *)initstate);
f->addArg(uintType, "seed");
f->addArg(byteptrType, "state");
f->addArg(uintType, "n");
f = mod->addFunc(byteptrType, "setstate", (void *)setstate);
f->addArg(byteptrType, "state");
f = mod->addFunc(byteptrType, "puts",
(void *)crack::runtime::puts
);
f->addArg(mod->getByteptrType(), "str");
f = mod->addFunc(byteptrType, "putc",
(void *)crack::runtime::__putc
);
f->addArg(mod->getByteType(), "byte");
f = mod->addFunc(byteptrType, "__die",
(void *)crack::runtime::__die
);
f->addArg(mod->getByteptrType(), "message");
f = mod->addFunc(byteptrType, "printfloat",
(void *)crack::runtime::printfloat
);
f->addArg(mod->getFloatType(), "val");
f = mod->addFunc(byteptrType, "printint",
(void *)crack::runtime::printint
);
f->addArg(mod->getIntType(), "val");
f = mod->addFunc(byteptrType, "printint64",
(void *)crack::runtime::printint64
);
f->addArg(mod->getInt64Type(), "val");
f = mod->addFunc(byteptrType, "printuint64",
(void *)crack::runtime::printint64
);
f->addArg(mod->getUint64Type(), "val");
// normal file open and close.
f = mod->addFunc(intType, "open", (void *)open);
f->addArg(byteptrType, "pathname");
f->addArg(intType, "mode");
f = mod->addFunc(intType, "open", (void *)open);
f->addArg(byteptrType, "pathname");
f->addArg(intType, "flags");
f->addArg(intType, "mode");
f = mod->addFunc(intType, "creat", (void *)open);
f->addArg(byteptrType, "pathname");
f->addArg(intType, "mode");
f = mod->addFunc(intType, "unlink", (void *)unlink);
f->addArg(byteptrType, "pathname");
f = mod->addFunc(byteptrType, "tempnam", (void *)tempnam);
f->addArg(byteptrType, "prefix");
f->addArg(byteptrType, "dir");
mod->addConstant(intType, "O_RDONLY", O_RDONLY);
mod->addConstant(intType, "O_WRONLY", O_WRONLY);
mod->addConstant(intType, "O_RDWR", O_RDWR);
mod->addConstant(intType, "O_APPEND", O_APPEND);
mod->addConstant(intType, "O_ASYNC", O_ASYNC);
mod->addConstant(intType, "O_CREAT", O_CREAT);
mod->addConstant(intType, "O_TRUNC", O_TRUNC);
mod->addConstant(intType, "O_NONBLOCK", O_NONBLOCK);
f = mod->addFunc(byteptrType, "getcwd", (void *)getcwd);
f->addArg(byteptrType, "buffer");
f->addArg(uintzType, "size");
mod->addConstant(uintzType, "PATH_MAX", PATH_MAX);
f = mod->addFunc(intType, "chdir", (void *)chdir);
f->addArg(byteptrType, "path");
// Net
mod->addConstant(intType, "AF_UNIX", AF_UNIX);
mod->addConstant(intType, "AF_LOCAL", AF_LOCAL);
mod->addConstant(intType, "AF_INET", AF_INET);
mod->addConstant(intType, "AF_INET6", AF_INET6);
mod->addConstant(intType, "AF_IPX", AF_IPX);
mod->addConstant(intType, "AF_NETLINK", AF_NETLINK);
mod->addConstant(intType, "AF_X25", AF_X25);
mod->addConstant(intType, "AF_AX25", AF_AX25);
mod->addConstant(intType, "AF_ATMPVC", AF_ATMPVC);
mod->addConstant(intType, "AF_APPLETALK", AF_APPLETALK);
mod->addConstant(intType, "AF_PACKET", AF_PACKET);
mod->addConstant(intType, "SOCK_STREAM", SOCK_STREAM);
mod->addConstant(intType, "SOCK_DGRAM", SOCK_DGRAM);
mod->addConstant(intType, "SOCK_SEQPACKET", SOCK_SEQPACKET);
mod->addConstant(intType, "SOCK_RAW", SOCK_RAW);
mod->addConstant(intType, "SOCK_RDM", SOCK_RDM);
mod->addConstant(intType, "SOCK_PACKET", SOCK_PACKET);
// If these flags are not defined, set them to 0
#ifndef SOCK_NONBLOCK
#define SOCK_NONBLOCK 0
#endif
mod->addConstant(intType, "SOCK_NONBLOCK", SOCK_NONBLOCK);
#ifndef SOCK_CLOEXEC
#define SOCK_CLOEXEC 0
#endif
mod->addConstant(intType, "SOCK_CLOEXEC", SOCK_CLOEXEC);
mod->addConstant(intType, "SOL_SOCKET", SOL_SOCKET);
mod->addConstant(intType, "SO_REUSEADDR", SO_REUSEADDR);
mod->addConstant(intType, "POLLIN", POLLIN);
mod->addConstant(intType, "POLLOUT", POLLOUT);
mod->addConstant(intType, "POLLPRI", POLLPRI);
mod->addConstant(intType, "POLLERR", POLLERR);
mod->addConstant(intType, "POLLHUP", POLLHUP);
mod->addConstant(intType, "POLLNVAL", POLLNVAL);
mod->addConstant(uint32Type, "INADDR_ANY", static_cast<int>(INADDR_ANY));
mod->addConstant(intType, "EAGAIN", EAGAIN);
mod->addConstant(intType, "EWOULDBLOCK", EWOULDBLOCK);
f = mod->addFunc(uint32Type, "makeIPV4",
(void*)crack::runtime::makeIPV4);
f->addArg(byteType, "a");
f->addArg(byteType, "b");
f->addArg(byteType, "c");
f->addArg(byteType, "d");
// begin SockAddr
Type *sockAddrType = mod->addType("SockAddr", sizeof(sockaddr));
sockAddrType->addConstructor();
sockAddrType->addInstVar(intType, "family",
CRACK_OFFSET(sockaddr, sa_family)
);
sockAddrType->finish();
// end SockAddr
// begin SockAddrIn
Type *sockAddrInType = mod->addType("SockAddrIn",
sizeof(sockaddr_in) - sizeof(sockaddr)
);
sockAddrInType->addBase(sockAddrType);
sockAddrInType->addInstVar(uint32Type, "addr",
CRACK_OFFSET(sockaddr_in, sin_addr.s_addr)
);
sockAddrInType->addInstVar(uint16Type, "port",
CRACK_OFFSET(sockaddr_in, sin_port)
);
f = sockAddrInType->addConstructor(
"init",
(void *)&crack::runtime::SockAddrIn::init1
);
f->addArg(byteType, "a");
f->addArg(byteType, "b");
f->addArg(byteType, "c");
f->addArg(byteType, "d");
f->addArg(intType, "port");
f = sockAddrInType->addConstructor(
"init",
(void *)&crack::runtime::SockAddrIn::init2
);
f->addArg(uint32Type, "addr");
f->addArg(uintType, "port");
f = sockAddrInType->addStaticMethod(
uint32Type,
"htonl",
(void *)&crack::runtime::SockAddrIn::crack_htonl
);
f->addArg(uint32Type, "val");
f = sockAddrInType->addStaticMethod(
uint32Type,
"ntohl",
(void *)&crack::runtime::SockAddrIn::crack_ntohl
);
f->addArg(uint32Type, "val");
f = sockAddrInType->addStaticMethod(
uintType,
"htons",
(void *)&crack::runtime::SockAddrIn::crack_htons
);
f->addArg(uintType, "val");
f = sockAddrInType->addStaticMethod(
uintType,
"ntohs",
(void *)&crack::runtime::SockAddrIn::crack_ntohs
);
f->addArg(uintType, "val");
sockAddrInType->finish();
// end SockAddrIn
// begin SockAddrIn
Type *sockAddrUnType = mod->addType("SockAddrUn",
sizeof(sockaddr_un) - sizeof(sockaddr)
);
sockAddrUnType->addBase(sockAddrType);
f = sockAddrUnType->addConstructor(
"init",
(void *)&crack::runtime::SockAddrUn::init
);
f->addArg(byteptrType, "path");
sockAddrUnType->addMethod(byteptrType, "getPath",
(void *)&crack::runtime::SockAddrUn::getPath
);
sockAddrUnType->finish();
// end SockAddrUn
f = mod->addFunc(intType, "connect", (void *)crack::runtime::connect);
f->addArg(intType, "s");
f->addArg(sockAddrType, "addr");
f = mod->addFunc(intType, "bind",
(void *)crack::runtime::bind
);
f->addArg(intType, "s");
f->addArg(sockAddrType, "addr");
f = mod->addFunc(intType, "accept",
(void *)crack::runtime::accept
);
f->addArg(intType, "s");
f->addArg(sockAddrType, "addr");
f = mod->addFunc(intType, "setsockopt",
(void *)crack::runtime::setsockopt_int
);
f->addArg(intType, "s");
f->addArg(intType, "level");
f->addArg(intType, "optname");
f->addArg(intType, "val");
// begin PollEvt
Type *pollEventType = mod->addType("PollEvt",
sizeof(crack::runtime::PollEvt));
pollEventType->addInstVar(intType, "fd",
CRACK_OFFSET(crack::runtime::PollEvt, fd)
);
pollEventType->addInstVar(intType, "events",
CRACK_OFFSET(crack::runtime::PollEvt, events)
);
pollEventType->addInstVar(intType, "revents",
CRACK_OFFSET(crack::runtime::PollEvt, revents)
);
pollEventType->addConstructor();
pollEventType->finish();
// end PollEvent
// begin TimeVal
Type *timeValType = mod->addType("TimeVal",
sizeof(crack::runtime::TimeVal)
);
timeValType->addInstVar(int32Type, "secs",
CRACK_OFFSET(crack::runtime::TimeVal, secs)
);
timeValType->addInstVar(int32Type, "nsecs",
CRACK_OFFSET(crack::runtime::TimeVal, nsecs)
);
f = timeValType->addConstructor("init",
(void *)&crack::runtime::TimeVal::init
);
f->addArg(int32Type, "secs");
f->addArg(int32Type, "nsecs");
f = timeValType->addMethod(voidType, "setToNow",
(void *)gettimeofday
);
f->addArg(voidptrType, "tz");
timeValType->finish();
// end TimeVal
// begin Pipe
Type *pipeType = mod->addType("PipeAddr", sizeof(crack::runtime::PipeAddr));
pipeType->addInstVar(int32Type, "flags",
CRACK_OFFSET(crack::runtime::PipeAddr, flags)
);
pipeType->addInstVar(int32Type, "readfd",
CRACK_OFFSET(crack::runtime::PipeAddr, readfd)
);
pipeType->addInstVar(int32Type, "writefd",
CRACK_OFFSET(crack::runtime::PipeAddr, writefd)
);
f = pipeType->addConstructor("init",
(void *)&crack::runtime::PipeAddr::init1
);
f->addArg(int32Type, "flags");
f = pipeType->addConstructor("init",
(void *)&crack::runtime::PipeAddr::init2
);
f->addArg(int32Type, "flags");
f->addArg(int32Type, "readfd");
f->addArg(int32Type, "writefd");
pipeType->finish();
// end Pipe
// begin SigSet
Type *sigSetType = mod->addType("SigSet", 0);
f = sigSetType->addStaticMethod(sigSetType, "oper new",
(void *)crack::runtime::SigSet_create
);
f = sigSetType->addMethod(voidType, "destroy",
(void *)crack::runtime::SigSet_destroy
);
f = sigSetType->addMethod(voidType, "empty",
(void *)crack::runtime::SigSet_empty
);
f = sigSetType->addMethod(voidType, "fill",
(void *)crack::runtime::SigSet_fill
);
f = sigSetType->addMethod(voidType, "add",
(void *)crack::runtime::SigSet_add
);
f->addArg(intType, "signum");
f = sigSetType->addMethod(voidType, "del",
(void *)crack::runtime::SigSet_del
);
f->addArg(intType, "signum");
f = sigSetType->addMethod(voidType, "has",
(void *)crack::runtime::SigSet_has
);
f->addArg(intType, "signum");
sigSetType->finish();
// end SigSet
// begin PollSet
Type *pollSetType = mod->addType("PollSet", 0);
f = pollSetType->addStaticMethod(pollSetType, "oper new",
(void *)&crack::runtime::PollSet_create
);
f->addArg(uintType, "size");
f = pollSetType->addMethod(voidType, "copy",
(void *)crack::runtime::PollSet_copy
);
f->addArg(pollSetType, "src");
f->addArg(uintType, "size");
f = pollSetType->addMethod(voidType, "destroy",
(void *)crack::runtime::PollSet_destroy
);
f = pollSetType->addMethod(voidType, "set",
(void *)crack::runtime::PollSet_set
);
f->addArg(uintType, "index");
f->addArg(intType, "fd");
f->addArg(intType, "events");
f->addArg(intType, "revents");
f = pollSetType->addMethod(voidType, "get",
(void *)crack::runtime::PollSet_get
);
f->addArg(uintType, "index");
f->addArg(pollEventType, "event");
f = pollSetType->addMethod(intType, "next",
(void *)crack::runtime::PollSet_next
);
f->addArg(uintType, "size");
f->addArg(uintType, "index");
f->addArg(pollEventType, "outputEntry");
f = pollSetType->addMethod(intType, "delete",
(void *)crack::runtime::PollSet_delete
);
f->addArg(uintType, "size");
f->addArg(uintType, "index");
f = pollSetType->addMethod(intType, "poll",
(void *)crack::runtime::PollSet_poll
);
f->addArg(uintType, "nfds");
f->addArg(timeValType, "tv");
f->addArg(sigSetType, "sigmask");
pollSetType->finish();
// end PollSet
// addrinfo
Type *addrinfoType = mod->addType("AddrInfo", sizeof(addrinfo));
f = addrinfoType->addStaticMethod(addrinfoType, "oper new",
(void *)&crack::runtime::AddrInfo_create
);
f->addArg(byteptrType, "node");
f->addArg(byteptrType, "service");
f->addArg(addrinfoType, "hints");
f = addrinfoType->addMethod(voidType, "free",
(void *)freeaddrinfo
);
f->addArg(addrinfoType, "addr");
f = addrinfoType->addMethod(sockAddrInType, "getInAddr",
(void *)crack::runtime::AddrInfo_getInAddr
);
addrinfoType->addInstVar(intType, "ai_flags",
CRACK_OFFSET(addrinfo, ai_flags)
);
addrinfoType->addInstVar(intType, "ai_family",
CRACK_OFFSET(addrinfo, ai_family)
);
addrinfoType->addInstVar(intType, "ai_socktype",
CRACK_OFFSET(addrinfo, ai_socktype)
);
addrinfoType->addInstVar(intType, "ai_protocol",
CRACK_OFFSET(addrinfo, ai_protocol)
);
addrinfoType->addInstVar(uintzType, "ai_addrlen",
CRACK_OFFSET(addrinfo, ai_addrlen)
);
addrinfoType->addInstVar(sockAddrType, "ai_addr",
CRACK_OFFSET(addrinfo, ai_addr)
);
addrinfoType->addInstVar(byteptrType, "ai_canonname",
CRACK_OFFSET(addrinfo, ai_canonname)
);
addrinfoType->addInstVar(addrinfoType, "ai_next",
CRACK_OFFSET(addrinfo, ai_next)
);
addrinfoType->finish();
// end addrinfo
// misc C functions
f = mod->addFunc(intType, "close", (void *)close, "close");
f->addArg(intType, "fd");
f = mod->addFunc(intType, "socket", (void *)socket, "socket");
f->addArg(intType, "domain");
f->addArg(intType, "type");
f->addArg(intType, "protocol");
f = mod->addFunc(intType, "listen", (void *)listen, "listen");
f->addArg(intType, "fd");
f->addArg(intType, "backlog");
f = mod->addFunc(intType, "send", (void *)send, "send");
f->addArg(intType, "fd");
f->addArg(byteptrType, "buf");
f->addArg(uintType, "size");
f->addArg(intType, "flags");
f = mod->addFunc(intType, "recv", (void *)recv, "recv");
f->addArg(intType, "fd");
f->addArg(byteptrType, "buf");
f->addArg(uintType, "size");
f->addArg(intType, "flags");
f = mod->addFunc(voidType, "abort", (void *)abort, "abort");
f = mod->addFunc(voidType, "free", (void *)free, "free");
f->addArg(voidptrType, "size");
f = mod->addFunc(voidType, "strcpy", (void *)strcpy, "strcpy");
f->addArg(byteptrType, "dst");
f->addArg(byteptrType, "src");
f = mod->addFunc(uintType, "strlen", (void *)strlen, "strlen");
f->addArg(byteptrType, "str");
f = mod->addFunc(byteptrType, "malloc", (void *)malloc, "malloc");
f->addArg(uintType, "size");
f = mod->addFunc(byteptrType, "memcpy", (void *)memcpy, "memcpy");
f->addArg(byteptrType, "dst");
f->addArg(byteptrType, "src");
f->addArg(uintType, "size");
f = mod->addFunc(byteptrType, "memset", (void *)memset, "memset");
f->addArg(byteptrType, "dst");
f->addArg(byteType, "c");
f->addArg(uintType, "size");
f = mod->addFunc(intType, "memcmp", (void *)memcmp, "memcmp");
f->addArg(byteptrType, "a");
f->addArg(byteptrType, "b");
f->addArg(uintType, "size");
f = mod->addFunc(byteptrType, "memmove", (void *)memmove, "memmove");
f->addArg(byteptrType, "dst");
f->addArg(byteptrType, "src");
f->addArg(uintType, "size");
Type *cFileType = mod->addType("CFile", 0);
cFileType->finish();
f = mod->addFunc(cFileType, "fopen", (void *)fopen, "fopen");
f->addArg(byteptrType, "path");
f->addArg(byteptrType, "mode");
f = mod->addFunc(intType, "fclose", (void *)fclose, "close");
f->addArg(cFileType, "fp");
f = mod->addFunc(intType, "fileno", (void *)fileno, "fileno");
f->addArg(cFileType, "fp");
f = mod->addFunc(intType, "read", (void *)read, "read");
f->addArg(intType, "fd");
f->addArg(byteptrType, "buf");
f->addArg(uintType, "count");
f = mod->addFunc(intType, "write", (void *)write, "write");
f->addArg(intType, "fd");
f->addArg(byteptrType, "buf");
f->addArg(uintType, "count");
f = mod->addFunc(intType, "utimes", (void *)crack::runtime::setUtimes);
f->addArg(byteptrType, "path");
f->addArg(int64Type, "atime");
f->addArg(int64Type, "mtime");
f->addArg(boolType, "now");
f = mod->addFunc(voidType, "exit", (void *)exit, "exit");
f->addArg(intType, "status");
f = mod->addFunc(intType, "setNonBlocking",
(void *)crack::runtime::setNonBlocking);
f->addArg(intType, "fd");
f->addArg(boolType, "val");
// mmap
f = mod->addFunc(voidptrType, "mmap", (void *)mmap, "mmap");
f->addArg(voidptrType, "start");
f->addArg(uintzType, "length");
f->addArg(intType, "prot");
f->addArg(intType, "flags");
f->addArg(intType, "fd");
f->addArg(uintzType, "offset");
// munmap
f = mod->addFunc(intType, "munmap", (void *)mmap, "munmap");
f->addArg(voidptrType, "start");
f->addArg(uintzType, "length");
// mmap protection flags
mod->addConstant(intType, "PROT_NONE", PROT_NONE);
mod->addConstant(intType, "PROT_EXEC", PROT_EXEC);
mod->addConstant(intType, "PROT_READ", PROT_READ);
mod->addConstant(intType, "PROT_WRITE", PROT_WRITE);
mod->addConstant(intType, "PROT_NONE", PROT_NONE);
// mmap mapping flags
mod->addConstant(intType, "MAP_FIXED", MAP_FIXED);
mod->addConstant(intType, "MAP_SHARED", MAP_SHARED);
mod->addConstant(intType, "MAP_PRIVATE", MAP_PRIVATE);
// Add math functions
crack::runtime::math_init(mod);
// Add time functions
crack_runtime_time_cinit(mod);
// add exception functions
mod->addConstant(intType, "EXCEPTION_MATCH_FUNC",
crack::runtime::exceptionMatchFuncHook
);
mod->addConstant(intType, "BAD_CAST_FUNC",
crack::runtime::badCastFuncHook
);
mod->addConstant(intType, "EXCEPTION_RELEASE_FUNC",
crack::runtime::exceptionReleaseFuncHook
);
mod->addConstant(intType, "EXCEPTION_PERSONALITY_FUNC",
crack::runtime::exceptionPersonalityFuncHook
);
mod->addConstant(intType, "EXCEPTION_FRAME_FUNC",
crack::runtime::exceptionFrameFuncHook
);
mod->addConstant(intType, "EXCEPTION_UNCAUGHT_FUNC",
crack::runtime::exceptionUncaughtFuncHook
);
f = mod->addFunc(voidType, "registerHook",
(void *)crack::runtime::registerHook
);
f->addArg(intType, "hookId");
f->addArg(voidptrType, "hook");
// This shouldn't need to be registered, but as it stands, runtime just
// gets loaded like any other module in JIT mode and this is resolved at
// runtime.
mod->addFunc(mod->getBoolType(), "__CrackUncaughtException",
(void *)__CrackUncaughtException
);
// Process support
mod->addConstant(intType, "SIGABRT", SIGABRT);
mod->addConstant(intType, "SIGALRM", SIGALRM);
mod->addConstant(intType, "SIGBUS" , SIGBUS);
mod->addConstant(intType, "SIGCHLD", SIGCHLD);
mod->addConstant(intType, "SIGCLD" , SIGCLD);
mod->addConstant(intType, "SIGCONT", SIGCONT);
mod->addConstant(intType, "SIGFPE" , SIGFPE);
mod->addConstant(intType, "SIGHUP" , SIGHUP);
mod->addConstant(intType, "SIGILL" , SIGILL);
mod->addConstant(intType, "SIGINT" , SIGINT);
mod->addConstant(intType, "SIGIO" , SIGIO);
mod->addConstant(intType, "SIGIOT" , SIGIOT);
mod->addConstant(intType, "SIGKILL", SIGKILL);
mod->addConstant(intType, "SIGPIPE", SIGPIPE);
mod->addConstant(intType, "SIGPOLL", SIGPOLL);
mod->addConstant(intType, "SIGPROF", SIGPROF);
mod->addConstant(intType, "SIGPWF" , SIGPWR);
mod->addConstant(intType, "SIGQUIT", SIGQUIT);
mod->addConstant(intType, "SIGSEGV", SIGSEGV);
mod->addConstant(intType, "SIGSTOP", SIGSTOP);
mod->addConstant(intType, "SIGSYS" , SIGSYS);
mod->addConstant(intType, "SIGTERM", SIGTERM);
mod->addConstant(intType, "SIGTRAP", SIGTRAP);
mod->addConstant(intType, "SIGTSTP", SIGTSTP);
mod->addConstant(intType, "SIGTTIN", SIGTTIN);
mod->addConstant(intType, "SIGURG" , SIGURG);
mod->addConstant(intType, "SIGUSR1", SIGUSR1);
mod->addConstant(intType, "SIGUSR2", SIGUSR2);
mod->addConstant(intType, "SIGVTALRM", SIGVTALRM);
mod->addConstant(intType, "SIGWINCH" , SIGWINCH);
mod->addConstant(intType, "SIGXCPU", SIGXCPU);
mod->addConstant(intType, "SIGXFSZ", SIGXFSZ);
Type *cpipeType = mod->addType("PipeDesc",
sizeof(crack::runtime::PipeDesc)
);
cpipeType->addInstVar(intType, "flags",
CRACK_OFFSET(crack::runtime::PipeDesc, flags)
);
cpipeType->addInstVar(intType, "stdin",
CRACK_OFFSET(crack::runtime::PipeDesc, stdin)
);
cpipeType->addInstVar(intType, "stdout",
CRACK_OFFSET(crack::runtime::PipeDesc, stdout)
);
cpipeType->addInstVar(intType, "stderr",
CRACK_OFFSET(crack::runtime::PipeDesc, stderr)
);
cpipeType->addConstructor();
cpipeType->finish();
f = mod->addFunc(intType, "runChildProcess",
(void *)&crack::runtime::runChildProcess);
f->addArg(byteptrArrayType, "argv");
f->addArg(byteptrArrayType, "env");
f->addArg(cpipeType, "pipes");
f = mod->addFunc(intType, "closeProcess",
(void *)&crack::runtime::closeProcess);
f->addArg(cpipeType, "pipes");
f = mod->addFunc(intType, "waitProcess",
(void *)&crack::runtime::waitProcess);
f->addArg(intType, "pid");
f->addArg(intType, "noHang");
f = mod->addFunc(voidType, "signalProcess",
(void *)&crack::runtime::signalProcess);
f->addArg(intType, "pid");
f->addArg(intType, "sig");
// debug support
f = mod->addFunc(voidType, "getLocation",
(void *)&crack::debug::getLocation
);
f->addArg(voidptrType, "address");
f->addArg(byteptrArrayType, "info");
f = mod->addFunc(voidType, "registerFuncTable",
(void *)&crack::debug::registerFuncTable
);
f->addArg(byteptrArrayType, "funcTable");
}
| C++ |
// Copyright 2010 Google Inc.
#include "Crack.h"
#include <string.h>
#include "builder/Builder.h"
#include "model/Construct.h"
#include "model/Context.h"
#include "model/OverloadDef.h"
using namespace std;
using namespace model;
using namespace builder;
Crack::Crack(void) :
initialized(false),
options(new builder::BuilderOptions()),
noBootstrap(false),
useGlobalLibs(true),
emitMigrationWarnings(false) {
}
void Crack::addToSourceLibPath(const string &path) {
assert(construct && "no call to setBuilder");
construct->addToSourceLibPath(path);
if (construct->compileTimeConstruct)
construct->compileTimeConstruct->addToSourceLibPath(path);
}
void Crack::setArgv(int argc, char **argv) {
assert(construct && "no call to setBuilder");
construct->rootBuilder->setArgv(argc, argv);
}
void Crack::setBuilder(Builder *builder) {
builder->options = options;
construct = new Construct(builder);
}
void Crack::setCompileTimeBuilder(Builder *builder) {
assert(construct && "no call to setBuilder");
assert(builder->isExec() && "builder cannot be used compile time");
// we make a new options here, because compile time dump should be turned
// so that compile time modules can run instead of dump
// so that the _main_ builder can generate the correct ir to dump
builder->options = new BuilderOptions(*options.get());
builder->options->dumpMode = false;
construct->compileTimeConstruct = new Construct(builder, construct.get());
}
bool Crack::init() {
if (!initialized) {
assert(construct && "no call to setBuilder");
Construct *ctc = construct->compileTimeConstruct.get();
// finalize the search path
if (useGlobalLibs) {
construct->addToSourceLibPath(".");
construct->addToSourceLibPath(CRACKLIB);
// XXX please refactor me
if (ctc) {
ctc->addToSourceLibPath(".");
ctc->addToSourceLibPath(CRACKLIB);
}
}
// initialize the compile-time construct first
if (ctc) {
ctc->migrationWarnings = emitMigrationWarnings;
ctc->loadBuiltinModules();
if (!noBootstrap && !ctc->loadBootstrapModules())
return false;
}
// pass the emitMigrationWarnings flag down to the global data.
construct->migrationWarnings = emitMigrationWarnings;
construct->loadBuiltinModules();
if (!noBootstrap && !construct->loadBootstrapModules())
return false;
initialized = true;
}
return true;
}
int Crack::runScript(std::istream &src, const std::string &name) {
if (!init())
return 1;
options->optionMap["mainUnit"] = name;
if (options->optionMap.find("out") == options->optionMap.end()) {
if (name.substr(name.size() - 4) == ".crk")
options->optionMap["out"] = name.substr(0, name.size() - 4);
else
// no extension - add one to the output file to distinguish it
// from the script.
options->optionMap["out"] = name + ".bin";
}
construct->runScript(src, name);
}
void Crack::callModuleDestructors() {
// run through all of the destructors backwards.
for (vector<ModuleDefPtr>::reverse_iterator ri =
construct->loadedModules.rbegin();
ri != construct->loadedModules.rend();
++ri
)
(*ri)->callDestructor();
}
void Crack::printStats(std::ostream &out) {
construct->stats->write(out);
if (construct->compileTimeConstruct)
construct->compileTimeConstruct->stats->write(out);
}
| C++ |
// Copyright 2010 Google Inc.
// XXX do we really need 3 reference counting mechanisms???
#ifndef _crack_ext_RCObj_h
#define _crack_ext_RCObj_h
namespace crack { namespace ext {
class RCObj {
protected:
unsigned int refCount;
public:
RCObj() : refCount(1) {}
virtual ~RCObj();
/**
* Increments the reference count of the object.
*/
void bind() { if (this) ++refCount; }
/**
* Decrements the reference count of the object, deleting it if it
* drops to zero.
*/
void release() { if (this && !--refCount) delete this; }
};
}}
#endif
| C++ |
// Copyright 2011 Shannon Weyrick <weyrick@mozek.us>
#include "Stub.h"
using namespace crack::ext;
// Func
void Func::setBody(const std::string&) { }
std::string Func::body() const { return std::string(); }
void Func::setIsVariadic(bool isVariadic) { }
bool Func::isVariadic() const { return false; }
void Func::setVWrap(bool vwrapEnabled) { }
bool Func::getVWrap() const { return false; }
void Func::setSymbolName(const std::string &name) { }
void Func::addArg(Type *type, const std::string &name) { }
void Func::finish() { }
// Module
Module::Module(model::Context *context) { }
Type *Module::getClassType() { }
Type *Module::getVoidType() { }
Type *Module::getVoidptrType() { }
Type *Module::getBoolType() { }
Type *Module::getByteptrType() { }
Type *Module::getByteType() { }
Type *Module::getInt16Type() { }
Type *Module::getInt32Type() { }
Type *Module::getInt64Type() { }
Type *Module::getUint16Type() { }
Type *Module::getUint32Type() { }
Type *Module::getUint64Type() { }
Type *Module::getIntType() { }
Type *Module::getUintType() { }
Type *Module::getIntzType() { }
Type *Module::getUintzType() { }
Type *Module::getFloat32Type() { }
Type *Module::getFloat64Type() { }
Type *Module::getFloatType() { }
Type *Module::getVTableBaseType() { }
Type *Module::getObjectType() { }
Type *Module::getStringType() { }
Type *Module::getStaticStringType() { }
Type *Module::getOverloadType() { }
Type *Module::getType(const char *name) { }
Type *Module::addType(const char *name, size_t instSize, bool hasVTable) { }
Type *Module::addForwardType(const char *name, size_t instSize) { }
Func *Module::addFunc(Type *returnType, const char *name, void *funcPtr,
const char *symbolName) { }
Func *Module::addFunc(Type *returnType, const char *name,
const std::string& body) { }
void Module::addConstant(Type *type, const std::string &name, double val) { }
void Module::addConstant(Type *type, const std::string &name, int64_t val) { }
void Module::addConstant(Type *type, const std::string &name, int val) { }
void Module::inject(const std::string&) { }
void Module::finish() { }
// Type
void Type::checkFinished() { }
void Type::addBase(Type *base) { }
void Type::addInstVar(Type *type, const std::string &name, size_t offset) { }
Func *Type::addMethod(Type *returnType, const std::string &name,
void *funcPtr
) { };
Func *Type::addMethod(Type *returnType, const std::string &name,
const std::string& body
) { }
Func *Type::addConstructor(const char *name, void *funcPtr) { };
Func *Type::addConstructor(const std::string& body) { }
Func *Type::addStaticMethod(Type *returnType, const std::string &name,
void *funcPtr
) { };
Func *Type::addStaticMethod(Type *returnType, const std::string &name,
const std::string& body
) { }
Type *Type::getSpecialization(const std::vector<Type *> ¶ms) { };
void Type::finish() { };
| C++ |
// Copyright 2010 Google Inc.
// Extension library Module class.
#ifndef _crack_ext_Module_h_
#define _crack_ext_Module_h_
#include <stdint.h>
#include <map>
#include <string>
#include <vector>
namespace model {
class Context;
class VarDef;
};
namespace crack { namespace ext {
class Func;
class Type;
class ModuleImpl;
class Module {
friend class Func;
friend class Type;
private:
enum BuiltinType {
classType,
voidType,
voidptrType,
boolType,
byteptrType,
byteType,
int16Type,
int32Type,
int64Type,
uint16Type,
uint32Type,
uint64Type,
intType,
uintType,
intzType,
uintzType,
float32Type,
float64Type,
floatType,
vtableBaseType,
objectType,
stringType,
staticStringType,
overloadType,
endSentinel
};
model::Context *context;
Type *builtinTypes[endSentinel];
std::vector<Func *> funcs;
std::vector<model::VarDef *> vars;
typedef std::map<std::string, Type *> TypeMap;
TypeMap types;
bool finished;
protected:
Type *addTypeWorker(const char *name, size_t instSize, bool forward,
bool hasVTable
);
public:
Module(model::Context *context);
~Module();
// functions to get the primitive types
Type *getClassType();
Type *getVoidType();
Type *getVoidptrType();
Type *getBoolType();
Type *getByteptrType();
Type *getByteType();
Type *getInt16Type();
Type *getInt32Type();
Type *getInt64Type();
Type *getUint16Type();
Type *getUint32Type();
Type *getUint64Type();
Type *getIntType();
Type *getUintType();
Type *getUintzType();
Type *getIntzType();
Type *getFloat32Type();
Type *getFloat64Type();
Type *getFloatType();
Type *getVTableBaseType();
Type *getObjectType();
Type *getStringType();
Type *getStaticStringType();
Type *getOverloadType();
Type *getType(const char *name);
Type *addType(const char *name, size_t instSize,
bool hasVTable = false
);
Type *addForwardType(const char *name, size_t instSize);
Func *addFunc(Type *returnType, const char *name, void *funcPtr,
const char *symbolName=0);
Func *addFunc(Type *returnType, const char *name, const std::string& body = std::string());
void addConstant(Type *type, const std::string &name, double val);
void addConstant(Type *type, const std::string &name, int64_t val);
void addConstant(Type *type, const std::string &name, int val) {
addConstant(type, name, static_cast<int64_t>(val));
}
void inject(const std::string& code);
/**
* finish the module (extension init funcs need not call this, it will
* be called automatically by the loader).
*/
void finish();
};
}} // namespace crack::ext
#endif
| C++ |
// Copyright 2010 Google Inc.
#include "Func.h"
#include "model/ArgDef.h"
#include "model/CleanupFrame.h"
#include "model/Context.h"
#include "model/FuncDef.h"
#include "model/Initializers.h"
#include "model/ResultExpr.h"
#include "model/VarRef.h"
#include "builder/Builder.h"
#include "parser/Toker.h"
#include "parser/Parser.h"
#include "Module.h"
#include "Type.h"
#include <sstream>
using namespace crack::ext;
using namespace std;
using namespace model;
using namespace builder;
using namespace parser;
namespace crack { namespace ext {
struct Arg {
Type *type;
string name;
Arg(Type *type, const string &name) :
type(type),
name(name) {
}
};
}}
void Func::addArg(Type *type, const string &name) {
assert(!finished &&
"Attempted to add an argument to a finished function."
);
args.push_back(new Arg(type, name));
}
void Func::setIsVariadic(bool isVariadic)
{
if (isVariadic) {
flags = static_cast<Func::Flags>(flags | Func::variadic);
} else {
flags = static_cast<Func::Flags>(flags & ~Func::variadic);
}
}
bool Func::isVariadic() const
{
return flags & Func::variadic;
}
void Func::setVWrap(bool vwrapEnabled) {
if (vwrapEnabled)
flags = static_cast<Func::Flags>(flags | vwrap);
else
flags = static_cast<Func::Flags>(flags & ~vwrap);
}
bool Func::getVWrap() const {
return flags & vwrap;
}
void Func::setVirtual(bool virtualizedEnabled) {
if (virtualizedEnabled)
flags = static_cast<Func::Flags>(flags | virtualized);
else
flags = static_cast<Func::Flags>(flags & ~virtualized);
}
// gets the "virtualized" flag
bool Func::getVirtual() const {
return flags & virtualized;
}
void Func::setBody(const std::string& body)
{
funcBody = body;
}
std::string Func::body() const
{
return funcBody;
}
void Func::finish() {
if (finished || !context)
return;
// if this is a composite context, get the parent context for cases where
// we need it directly.
ContextPtr realCtx = context->getDefContext();
// we're going to need this
TypeDef *voidType = context->construct->voidType.get();
Builder &builder = context->builder;
std::vector<ArgDefPtr> realArgs(args.size());
for (int i = 0; i < args.size(); ++i) {
args[i]->type->checkFinished();
realArgs[i] = builder.createArgDef(args[i]->type->typeDef,
args[i]->name
);
}
FuncDefPtr funcDef;
FuncDefPtr override;
// XXX the functionality in checkForExistingDef() should be refactored out
// of the parser.
if (flags & method && !(flags & constructor)) {
std::istringstream emptyStream;
Toker toker(emptyStream, name.c_str());
Parser parser(toker, context);
LocationMap locMap;
Token nameTok(Token::ident, name, locMap.getLocation(name.c_str(), 0));
VarDefPtr existingDef = parser.checkForExistingDef(nameTok, name, true);
override = parser.checkForOverride(existingDef.get(), realArgs, context->ns.get(), nameTok, name);
}
// if we have a function pointer, create a extern function for it
if (funcPtr) {
// if this is a vwrap, use an internal name for the function so as not
// to conflict with the actual virtual function we're creating
string externName;
if (flags & vwrap) {
externName = name + ":vwrap";
} else if (override) {
// if this is an override, create a wrapper function
externName = name + ":impl";
} else {
externName = name;
}
funcDef =
builder.createExternFunc(*realCtx,
static_cast<FuncDef::Flags>(flags &
funcDefFlags
),
externName,
returnType->typeDef,
(flags & method) ? receiverType : 0,
realArgs,
funcPtr,
(symbolName.empty()) ? 0 :
symbolName.c_str()
);
// inline the function body in the constructor; reduces overhead
} else if (!funcBody.empty() && !(flags & constructor)) {
ContextPtr funcContext = context->createSubContext(Context::local);
funcContext->returnType = returnType->typeDef;
funcContext->toplevel = true;
if (flags & method) {
// create the "this" variable
ArgDefPtr thisDef =
context->builder.createArgDef(receiverType, "this");
funcContext->addDef(thisDef.get());
}
funcDef =
context->builder.emitBeginFunc(*funcContext,
static_cast<FuncDef::Flags>(flags & funcDefFlags),
name,
returnType->typeDef,
realArgs,
override.get()
);
for (int i = 0; i < realArgs.size(); ++i) {
funcContext->addDef(realArgs[i].get());
}
std::istringstream bodyStream(funcBody);
Toker toker(bodyStream, name.c_str());
Parser parser(toker, funcContext.get());
parser.parse();
if (returnType->typeDef->matches(*voidType)) {
funcContext->builder.emitReturn(*funcContext, 0);
}
funcContext->builder.emitEndFunc(*funcContext, funcDef.get());
}
if (funcDef) {
VarDefPtr storedDef = context->addDef(funcDef.get(), receiverType);
// check for a static method, add it to the meta-class
if (realCtx->scope == Context::instance) {
TypeDef *type = TypeDefPtr::arcast(realCtx->ns);
if (type != type->type.get())
type->type->addAlias(storedDef.get());
}
}
if (flags & constructor) {
ContextPtr funcContext = context->createSubContext(Context::local);
funcContext->toplevel = true;
// create the "this" variable
ArgDefPtr thisDef =
context->builder.createArgDef(receiverType, "this");
funcContext->addDef(thisDef.get());
VarRefPtr thisRef = funcContext->builder.createVarRef(thisDef.get());
// emit the function
FuncDefPtr newFunc = context->builder.emitBeginFunc(*funcContext,
FuncDef::method,
"oper init",
voidType,
realArgs,
override.get()
);
// emit the initializers
Initializers inits;
receiverType->emitInitializers(*funcContext, &inits);
// if we got a function, emit a call to it.
if (funcDef) {
FuncCallPtr call = context->builder.createFuncCall(funcDef.get());
call->receiver = thisRef;
// populate the arg list with references to the existing args
for (int i = 0; i < realArgs.size(); ++i) {
VarRefPtr ref =
context->builder.createVarRef(realArgs[i].get());
call->args.push_back(ref.get());
}
funcContext->createCleanupFrame();
call->emit(*funcContext)->handleTransient(*funcContext);
funcContext->closeCleanupFrame();
} else if (!funcBody.empty()) {
for (int i = 0; i < realArgs.size(); ++i) {
funcContext->addDef(realArgs[i].get());
}
std::istringstream bodyStream(funcBody);
Toker toker(bodyStream, name.c_str());
Parser parser(toker, funcContext.get());
parser.parse();
}
// close it off
funcContext->builder.emitReturn(*funcContext, 0);
funcContext->builder.emitEndFunc(*funcContext, newFunc.get());
context->addDef(newFunc.get(), receiverType);
receiverType->createNewFunc(*realCtx, newFunc.get());
// is this a virtual wrapper class?
} else if ((flags & vwrap) || override) {
if (flags & vwrap) {
assert(wrapperClass && "class wrapper not specified for wrapped func");
}
ContextPtr funcContext = context->createSubContext(Context::local);
funcContext->returnType = returnType->typeDef;
funcContext->toplevel = true;
// create the "this" variable
ArgDefPtr thisDef =
context->builder.createArgDef((flags & vwrap) ? wrapperClass : receiverType, "this");
funcContext->addDef(thisDef.get());
VarRefPtr thisRef = funcContext->builder.createVarRef(thisDef.get());
// emit the function
FuncDef::Flags realFlags = FuncDef::method | FuncDef::virtualized;
FuncDefPtr newFunc = context->builder.emitBeginFunc(*funcContext,
realFlags,
name,
returnType->typeDef,
realArgs,
override.get()
);
// copy the args into the context.
for (int i = 0; i < realArgs.size(); ++i) {
funcContext->addDef(realArgs[i].get());
}
// create a call to the real function
FuncCallPtr call = context->builder.createFuncCall(funcDef.get());
call->receiver = thisRef;
for (int i = 0; i < realArgs.size(); ++i) {
VarRefPtr ref =
funcContext->builder.createVarRef(realArgs[i].get());
call->args.push_back(ref);
}
if (returnType->typeDef != voidType) {
funcContext->builder.emitReturn(*funcContext, call.get());
} else {
call->emit(*funcContext)->handleTransient(*funcContext);
funcContext->builder.emitReturn(*funcContext, 0);
}
funcContext->builder.emitEndFunc(*funcContext, newFunc.get());
context->addDef(newFunc.get(), (flags & vwrap) ? wrapperClass : receiverType);
}
finished = true;
}
| C++ |
// Copyright 2010 Google Inc.
#include "Module.h"
#include <string.h>
#include <sstream>
#include "builder/Builder.h"
#include "model/ConstVarDef.h"
#include "model/Context.h"
#include "model/FloatConst.h"
#include "model/IntConst.h"
#include "model/Namespace.h"
#include "model/OverloadDef.h"
#include "parser/Toker.h"
#include "parser/Parser.h"
#include "Type.h"
#include "Func.h"
using namespace std;
using namespace crack::ext;
using namespace parser;
using namespace model;
Module::Module(Context *context) : context(context), finished(false) {
memset(builtinTypes, 0, sizeof(builtinTypes));
}
Module::~Module() {
int i;
// cleanup the builtin types
for (i = 0; i < sizeof(builtinTypes) / sizeof(Type *); ++i)
delete builtinTypes[i];
// cleanup new or looked up types
for (TypeMap::iterator iter = types.begin(); iter != types.end(); ++iter)
delete iter->second;
// cleanup the funcs
for (i = 0; i < funcs.size(); ++i)
delete funcs[i];
}
#define GET_TYPE(capName, lowerName) \
Type *Module::get##capName##Type() { \
return builtinTypes[lowerName##Type] ? \
builtinTypes[lowerName##Type] : \
(builtinTypes[lowerName##Type] = \
new Type(this, context->construct->lowerName##Type.get())); \
}
GET_TYPE(Class, class)
GET_TYPE(Void, void)
GET_TYPE(Voidptr, voidptr)
GET_TYPE(Bool, bool)
GET_TYPE(Byteptr, byteptr)
GET_TYPE(Byte, byte)
GET_TYPE(Int16, int16)
GET_TYPE(Int32, int32)
GET_TYPE(Int64, int64)
GET_TYPE(Int, int)
GET_TYPE(Intz, intz)
GET_TYPE(Uint16, uint16)
GET_TYPE(Uint32, uint32)
GET_TYPE(Uint64, uint64)
GET_TYPE(Uint, uint)
GET_TYPE(Uintz, uintz)
GET_TYPE(Float32, float32)
GET_TYPE(Float64, float64)
GET_TYPE(Float, float)
GET_TYPE(VTableBase, vtableBase)
GET_TYPE(Object, object)
GET_TYPE(String, string)
GET_TYPE(StaticString, staticString)
namespace {
// internal type for types with vtables.
class VTableType : public Type {
private:
string proxyName;
public:
VTableType(Module *module, const string &name, Context *context,
size_t size,
TypeDef *typeDef = 0
) :
Type(module, name + ":ExtUser", context, size, typeDef),
proxyName(name) {
}
// propagate all constructors from 'inner' to 'outer'
void propagateConstructors(Context &context, TypeDef *inner,
TypeDef *outer
) {
OverloadDefPtr constructors =
OverloadDefPtr::rcast(inner->lookUp("oper init"));
if (!constructors)
return;
for (OverloadDef::FuncList::iterator fi =
constructors->beginTopFuncs();
fi != constructors->endTopFuncs();
++fi
) {
// create the init function, wrap it in an "oper new"
FuncDefPtr operInit =
outer->createOperInit(context, (*fi)->args);
outer->createNewFunc(context, operInit.get());
}
}
virtual void finish() {
if (isFinished())
return;
// finish the inner class
Type::finish();
TypeDef::TypeVec bases;
bases.reserve(2);
bases.push_back(module->getVTableBaseType()->typeDef);
bases.push_back(typeDef);
// create the subcontext and emit the beginning of the class.
Context *ctx = impl->context;
ContextPtr clsCtx =
new Context(ctx->builder, Context::instance, ctx, 0,
ctx->compileNS.get()
);
TypeDefPtr td =
ctx->builder.emitBeginClass(*clsCtx, proxyName, bases, 0);
td->aliasBaseMetaTypes();
// wrap all of the constructors
propagateConstructors(*clsCtx, typeDef, td.get());
// wrap all of the vwrapped methods
for (FuncVec::iterator fi = impl->funcs.begin();
fi != impl->funcs.end();
++fi
) {
if ((*fi)->getVWrap()) {
setClasses(*fi, typeDef, td.get(), clsCtx.get());
(*fi)->finish();
}
}
ctx->builder.emitEndClass(*clsCtx);
// replace the inner type with the outer type (we can be cavalier
// about discarding the reference here because Type::finish()
// should have assigned this to a variable)
typeDef = td.get();
ctx->ns->addDef(typeDef);
}
};
} // anon namespace
Type *Module::getType(const char *name) {
// try looking it up in the map, first
TypeMap::iterator iter = types.find(name);
if (iter != types.end())
return iter->second;
TypeDefPtr rawType = TypeDefPtr::rcast(context->ns->lookUp(name));
assert(rawType && "Requested type not found");
// Create a new type, add it to the map.
Type *type = new Type(this, rawType.get());
types[name] = type;
return type;
}
Type *Module::addTypeWorker(const char *name, size_t instSize, bool forward,
bool hasVTable
) {
TypeMap::iterator i = types.find(name);
bool found = (i != types.end());
if (found && !(i->second->typeDef && i->second->typeDef->forward)) {
std::cerr << "Type " << name << " already registered!" << std::endl;
assert(false);
}
Type *result;
if (forward) {
// we can't currently combine forward and hasVTable because our inner
// TypeDef changes for a vtable class.
assert(!hasVTable);
result = new Type(this, name, context, instSize,
context->createForwardClass(name).get()
);
} else if (hasVTable) {
result = new VTableType(this, name, context, instSize, 0);
} else {
result = new Type(this, name, context, instSize);
}
types[name] = result;
return result;
}
Type *Module::addType(const char *name, size_t instSize, bool hasVTable) {
return Module::addTypeWorker(name, instSize, false, hasVTable);
}
Type *Module::addForwardType(const char *name, size_t instSize) {
return Module::addTypeWorker(name, instSize, true, false);
}
Func *Module::addFunc(Type *returnType, const char *name, void *funcPtr,
const char *symbolName) {
assert(!finished && "Attempting to add a function to a finished module.");
returnType->checkFinished();
Func *f = new Func(context, returnType, name, funcPtr, Func::noFlags);
if (symbolName)
f->setSymbolName(symbolName);
funcs.push_back(f);
return f;
}
Func* Module::addFunc(Type* returnType, const char* name, const std::string& body)
{
assert(!finished && "Attempting to add a function to a finished module.");
returnType->checkFinished();
Func *f = new Func(context, returnType, name, body, Func::noFlags);
funcs.push_back(f);
return f;
}
void Module::addConstant(Type *type, const std::string &name, double val) {
type->checkFinished();
FloatConstPtr valObj =
context->builder.createFloatConst(*context, val, type->typeDef);
vars.push_back(new ConstVarDef(type->typeDef, name, valObj));
}
void Module::addConstant(Type *type, const std::string &name, int64_t val) {
type->checkFinished();
IntConstPtr valObj =
context->builder.createIntConst(*context, val, type->typeDef);
vars.push_back(new ConstVarDef(type->typeDef, name, valObj));
}
void Module::inject(const std::string& code)
{
std::istringstream codeStream(code);
Toker toker(codeStream, "injected code");
Parser parser(toker, context);
parser.parse();
}
void Module::finish() {
// no-op if this is already finished
if (finished)
return;
for (int i = 0; i < funcs.size(); ++i)
funcs[i]->finish();
// add the variable definitions to the context.
for (int i = 0; i < vars.size(); ++i)
context->ns->addDef(vars[i]);
finished = true;
}
| C++ |
// Copyright 2010 Google Inc.
#include "RCObj.h"
using namespace crack::ext;
RCObj::~RCObj() {}
| C++ |
// Copyright 2010 Google Inc.
#ifndef _crack_ext_Type_h_
#define _crack_ext_Type_h_
#include <string>
#include <vector>
#include "Var.h"
namespace model {
class Context;
class TypeDef;
}
namespace crack { namespace ext {
class Func;
class Module;
class Type {
friend class Func;
friend class Module;
public:
typedef std::vector<Func *> FuncVec;
private:
typedef std::vector<Type *> TypeVec;
// Impl holds everything that we need to create a new type
struct Impl {
std::string name;
model::Context *context;
TypeVec bases;
FuncVec funcs;
VarMap instVars;
VarVec instVarVec;
size_t instSize;
Impl(const std::string &name,
model::Context *context,
size_t instSize
) :
name(name),
context(context),
instSize(instSize) {
}
~Impl();
};
Type(Module *module, model::TypeDef *typeDef) :
module(module),
typeDef(typeDef),
impl(0),
finished(false) {
}
Type(Module *module, const std::string &name,
model::Context *context,
size_t instSize
) :
typeDef(0),
module(module),
impl(new Impl(name, context, instSize)),
finished(false) {
}
// verify that the type has been initilized (has a non-null impl)
void checkInitialized();
// verify that the type has been "finished" (presumably before using
// it).
void checkFinished();
protected:
bool finished;
Module *module;
Impl *impl;
Type(Module *module, const std::string &name,
model::Context *context,
size_t instSize,
model::TypeDef *typeDef) :
typeDef(typeDef),
module(module),
impl(new Impl(name, context, instSize)),
finished(false) {
}
~Type();
bool isFinished() const;
void setClasses(Func *f, model::TypeDef *base, model::TypeDef *wrapper,
model::Context *context);
public:
// this is public, it sucks. Don't use it.
model::TypeDef *typeDef;
/**
* Add a new base class.
* The new base must not already be in the class' ancestry.
*/
void addBase(Type *base);
/**
* Add an instance variable.
*/
void addInstVar(Type *type, const std::string &name, size_t offset);
/**
* Add a new method to the class and returns it.
* @return the new method.
* @param returnType the method's return type
* @param name the method name
* @param funcPtr the C function that implements the method. The
* first parameter of this function should be an instance of
* the type.
*/
Func *addMethod(Type *returnType, const std::string &name,
void *funcPtr
);
/**
* Add a new method to the class and returns it.
* @return the new method.
* @param returnType the method's return type
* @param name the method name
* @param body the function body
*/
Func *addMethod(Type *returnType, const std::string &name,
const std::string& body = std::string()
);
/**
* Add a new constructor.
* If 'name' and 'funcPtr' are not null, the should be the name and
* function pointer of a function with args as those to be added to
* the constructor. This function will be called in the body of the
* constructor with the constructor's arguments.
* Default initializers will be called prior to the function.
*/
Func *addConstructor(const char *name = 0, void *funcPtr = 0);
/**
* Add a new constructor.
* This function will be called in the body of the
* constructor with the constructor's arguments.
* Default initializers will be called prior to the function.
*/
Func *addConstructor(const std::string& body);
/**
* Add a new static method to the class and returns it. Static
* methods have no implicit "this" parameter.
* @return the new method.
* @param returnType the method's return type
* @param name the method name
* @param funcPtr the C function that implements the method. The
* first parameter of this function should be an instance of
* the type.
*/
Func *addStaticMethod(Type *returnType, const std::string &name,
void *funcPtr
);
/**
* Add a new static method to the class and returns it. Static
* methods have no implicit "this" parameter.
* @return the new method.
* @param returnType the method's return type
* @param name the method name
* @param body the function body
*/
Func *addStaticMethod(Type *returnType, const std::string &name,
const std::string& body = std::string()
);
/**
* Returns a specialization of the type for the given parameters.
*/
Type *getSpecialization(const std::vector<Type *> ¶ms);
/**
* Mark the new type as "finished"
*/
virtual void finish();
};
}} // namespace crack::ext
#endif
| C++ |
// Copyright 2010 Google Inc.
#ifndef _crack_ext_Var_h_
#define _crack_ext_Var_h_
#include <map>
#include <string>
namespace crack { namespace ext {
class Module;
class Type;
// opaque Var class.
class Var {
friend class Module;
friend class Type;
private:
Type *type;
std::string name;
size_t offset;
Var(Type *type, const std::string &name, size_t offset = 0) :
type(type),
name(name),
offset(offset) {
}
};
typedef std::map<std::string, Var *> VarMap;
typedef std::vector<Var *> VarVec;
}} // namespace crack::ext
// macro to calculate the offset of an instance variable
#define CRACK_OFFSET(type, field) \
reinterpret_cast<size_t>(&(reinterpret_cast<type *>(0))->field)
#endif
| C++ |
// Copyright 2011 Google Inc.
#ifndef _crack_ext_util_h_
#define _crack_ext_util_h_
namespace crack { namespace ext {
/**
* Returns the crack proxy object for an object that we know to be wrapped in
* a proxy.
*/
template <typename T>
inline T *getCrackProxy(void *wrapped) {
return reinterpret_cast<T *>(
reinterpret_cast<void **>(wrapped) - 1
);
}
}} // namespace crack::ext
#endif
| C++ |
// Copyright 2010 Google Inc.
#ifndef _crack_ext_Func_h_
#define _crack_ext_Func_h_
#include <string>
#include <vector>
namespace model {
class Context;
class TypeDef;
}
namespace crack { namespace ext {
struct Arg;
class Module;
class Type;
class Func {
friend class Module;
friend class Type;
public:
enum Flags {
noFlags = 0,
method = 1,
virtualized = 2,
variadic = 8,
// mask for flags that map to FuncDef flags.
funcDefFlags = 15,
// flags that don't map to FuncDef flags.
constructor = 1024,
vwrap = 2048
};
private:
model::Context *context;
// receiver type gets set for methods, wrapperClass gets set for
// vwrapped types.
model::TypeDef *receiverType, *wrapperClass;
Type *returnType;
std::string name;
std::string symbolName;
void *funcPtr;
std::vector<Arg *> args;
std::string funcBody;
// these must match the values in FuncDef::Flags
Flags flags;
bool finished;
Func(model::Context *context, Type *returnType, std::string name,
void *funcPtr,
Flags flags
) :
context(context),
receiverType(0),
wrapperClass(0),
returnType(returnType),
name(name),
funcPtr(funcPtr),
flags(flags),
finished(false) {
}
Func(model::Context *context, Type *returnType, std::string name,
const std::string& body,
Flags flags
) :
context(context),
receiverType(0),
wrapperClass(0),
returnType(returnType),
name(name),
funcPtr(0),
funcBody(body),
flags(flags),
finished(false) {
}
public:
// specify a symbol name for this function, which will be used in
// low level IR to resolve calls to this function. if it's not
// specified, at attempt is made to reverse it from the function
// pointer
void setSymbolName(const std::string &name) { symbolName = name; }
// add a new argument to the function.
void addArg(Type *type, const std::string &name);
// sets whether the Func maps to a variadic function
void setIsVariadic(bool isVariadic);
// gets whether the Func maps to a variadic function
bool isVariadic() const;
// sets the "vwrap" flag, which indicates that the function is a
// virtual that wraps a call to another function.
void setVWrap(bool vwrapEnabled);
// gets the "vwrap" flag.
bool getVWrap() const;
// sets the "virtualized" flag
void setVirtual(bool virtualizedEnabled);
// gets the "virtualized" flag
bool getVirtual() const;
// sets the function body; sets funcPtr to 0
void setBody(const std::string& body);
// returns the function body
std::string body() const;
// finish the definition of the function (this will be called
// automatically by Module::finish())
void finish();
};
inline Func::Flags operator |(Func::Flags a, Func::Flags b) {
return static_cast<Func::Flags>(static_cast<int>(a) |
static_cast<int>(b)
);
}
}} // namespace crack::ext
#endif
| C++ |
// Copyright 2010 Google Inc., Shannon Weyrick <weyrick@mozek.us>
//
// This is a simple stub that defines the public extension interface used
// during compile-time extension initialization. This stub is only used when
// linking AOT crack binaries to resolve the (unused at runtime) init functions.
// This is somewhat of a hack, and may be better replaced by a scheme that
// keeps the compile-time portions of extension init (i.e. type definitions, etc)
// separate from the runtime portions.
#ifndef _crack_ext_Stub_h_
#define _crack_ext_Stub_h_
#include <string>
#include <stdint.h>
#include <vector>
namespace model {
class Context;
}
namespace crack { namespace ext {
struct Arg;
class Module;
class Func;
class Type;
class Func {
public:
void setBody(const std::string&);
std::string body() const;
void setIsVariadic(bool isVariadic);
bool isVariadic() const;
void setVWrap(bool vwrapEnabled);
bool getVWrap() const;
void setSymbolName(const std::string &name);
void addArg(Type *type, const std::string &name);
void finish();
};
class Module {
public:
Module(model::Context *context);
Type *getClassType();
Type *getVoidType();
Type *getVoidptrType();
Type *getBoolType();
Type *getByteptrType();
Type *getByteType();
Type *getInt16Type();
Type *getInt32Type();
Type *getInt64Type();
Type *getUint16Type();
Type *getUint32Type();
Type *getUint64Type();
Type *getIntType();
Type *getUintType();
Type *getIntzType();
Type *getUintzType();
Type *getFloat32Type();
Type *getFloat64Type();
Type *getFloatType();
Type *getVTableBaseType();
Type *getObjectType();
Type *getStringType();
Type *getStaticStringType();
Type *getOverloadType();
Type *getType(const char *name);
Type *addType(const char *name, size_t instSize, bool hasVTable);
Type *addForwardType(const char *name, size_t instSize);
Func *addFunc(Type *returnType, const char *name, void *funcPtr,
const char *symbolName=0);
Func *addFunc(Type *returnType, const char *name, const std::string& body = std::string());
void addConstant(Type *type, const std::string &name, double val);
void addConstant(Type *type, const std::string &name, int64_t val);
void addConstant(Type *type, const std::string &name, int val);
void inject(const std::string& code);
void finish();
};
class Type {
private:
void checkFinished();
public:
void addBase(Type *base);
void addInstVar(Type *type, const std::string &name, size_t offset);
Func *addMethod(Type *returnType, const std::string &name,
void *funcPtr
);
Func *addMethod(Type *returnType, const std::string &name,
const std::string& body = std::string()
);
Func *addConstructor(const char *name = 0, void *funcPtr = 0);
Func *addConstructor(const std::string& body);
Func *addStaticMethod(Type *returnType, const std::string &name,
void *funcPtr
);
Func *addStaticMethod(Type *returnType, const std::string &name,
const std::string& body = std::string()
);
Type *getSpecialization(const std::vector<Type *> ¶ms);
void finish();
};
}} // namespace crack::ext
#endif
| C++ |
// Copyright 2010 Google Inc.
#include "Type.h"
#include <assert.h>
#include <iostream>
#include "builder/Builder.h"
#include "model/CompositeNamespace.h"
#include "model/Context.h"
#include "model/TypeDef.h"
#include "Func.h"
#include "Module.h"
using namespace crack::ext;
using namespace model;
using namespace std;
Type::Impl::~Impl() {
// we don't have to clean up "bases" - since these are types, they should
// get cleaned up by the module.
// clean up the funcs
for (FuncVec::iterator i = funcs.begin(); i != funcs.end(); ++i)
delete *i;
// clean up the inst vars
for (VarMap::iterator vi = instVars.begin(); vi != instVars.end(); ++vi)
delete vi->second;
}
Type::~Type() {
if (impl)
delete impl;
}
void Type::checkInitialized() {
if (!impl) {
std::cerr << "Attempting to add attributes to forward type"
<< "." << std::endl;
assert(false);
}
}
void Type::checkFinished() {
if (!typeDef) {
std::cerr << "Attempting to make use of unfinished type";
if (impl) std::cerr << " " << impl->name;
std::cerr << std::endl;
assert(false);
}
}
void Type::addBase(Type *base) {
base->checkFinished();
impl->bases.push_back(base);
}
void Type::addInstVar(Type *type, const std::string &name, size_t offset) {
checkInitialized();
if (impl->instVars.find(name) != impl->instVars.end()) {
std::cerr << "variable " << name << " already exists." << endl;
assert(false);
}
Var *var = new Var(type, name, offset);
impl->instVars[name] = var;
impl->instVarVec.push_back(var);
}
Func *Type::addMethod(Type *returnType, const std::string &name,
void *funcPtr
) {
checkInitialized();
Func *result = new Func(0, returnType, name, funcPtr, Func::method);
impl->funcs.push_back(result);
return result;
}
Func* Type::addMethod(Type* returnType, const std::string& name,
const std::string& body
)
{
checkInitialized();
Func *result = new Func(0, returnType, name, body, Func::method);
impl->funcs.push_back(result);
return result;
}
Func *Type::addConstructor(const char *name, void *funcPtr) {
checkInitialized();
Func *result = new Func(0, module->getVoidType(), name ? name : "",
funcPtr,
Func::constructor | Func::method
);
impl->funcs.push_back(result);
return result;
}
Func* Type::addConstructor(const std::string& body) {
checkInitialized();
Func *result = new Func(0, module->getVoidType(), "",
body,
Func::constructor | Func::method
);
impl->funcs.push_back(result);
return result;
}
Func *Type::addStaticMethod(Type *returnType, const std::string &name,
void *funcPtr
) {
checkInitialized();
Func *result = new Func(0, returnType, name, funcPtr, Func::noFlags);
impl->funcs.push_back(result);
return result;
}
Func* Type::addStaticMethod(Type* returnType, const std::string& name,
const std::string& body
) {
checkInitialized();
Func *result = new Func(0, returnType, name, body, Func::noFlags);
impl->funcs.push_back(result);
return result;
}
Type *Type::getSpecialization(const vector<Type *> ¶ms) {
checkFinished();
TypeDef::TypeVecObjPtr innerParams = new TypeDef::TypeVecObj;
for (int i = 0; i < params.size(); ++i) {
params[i]->checkFinished();
innerParams->push_back(params[i]->typeDef);
}
TypeDefPtr spec = typeDef->getSpecialization(*module->context,
innerParams.get());
// see if it's cached in the module
Module::TypeMap::iterator iter = module->types.find(spec->getFullName());
if (iter != module->types.end())
return iter->second;
Type *type = new Type(module, spec.get());
module->types[spec->getFullName()] = type;
return type;
}
bool Type::isFinished() const {
return finished || (!impl && typeDef && !typeDef->forward);
}
void Type::setClasses(Func *f, model::TypeDef *base, model::TypeDef *wrapper,
model::Context *context
) {
f->receiverType = base;
f->wrapperClass = wrapper;
f->context = context;
}
void Type::finish() {
// ignore this if we're already finished.
if (isFinished())
return;
Context *ctx = impl->context;
// construct the list of bases
vector<TypeDefPtr> bases;
vector<TypeDefPtr> ancestors; // keeps track of all ancestors
for (TypeVec::iterator i = impl->bases.begin(); i != impl->bases.end();
++i
) {
// make sure we apply the same constraints as for a parsed class.
(*i)->checkFinished();
(*i)->typeDef->addToAncestors(*ctx, ancestors);
bases.push_back((*i)->typeDef);
}
// create the subcontext and emit the beginning of the class.
ContextPtr clsCtx = new Context(ctx->builder, Context::instance, ctx, 0,
ctx->compileNS.get()
);
TypeDefPtr td =
ctx->builder.emitBeginClass(*clsCtx, impl->name, bases, typeDef);
typeDef = td.get();
typeDef->aliasBaseMetaTypes();
// create a lexical context which delegates to both the class context and
// the parent context.
NamespacePtr lexicalNS =
new CompositeNamespace(typeDef, ctx->ns.get());
ContextPtr lexicalContext =
clsCtx->createSubContext(Context::composite, lexicalNS.get());
// emit the variables
for (int vi = 0; vi < impl->instVarVec.size(); ++vi) {
Var *var = impl->instVarVec[vi];
Type *type = var->type;
type->checkFinished();
VarDefPtr varDef =
clsCtx->builder.createOffsetField(*clsCtx, type->typeDef,
var->name,
var->offset
);
clsCtx->ns->addDef(varDef.get());
}
// emit all of the method defs
for (FuncVec::iterator fi = impl->funcs.begin(); fi != impl->funcs.end();
++fi
) {
// bind the class to the function, if it's not VWrapped, bind the
// context to it and finish it. VWrapped functions get finished in
// the outer class.
(*fi)->receiverType = typeDef;
if (!(*fi)->getVWrap()) {
(*fi)->context = lexicalContext.get();
(*fi)->finish();
}
}
// pad the class to the instance size
typeDef->padding = impl->instSize;
ctx->builder.emitEndClass(*clsCtx);
if (!typeDef->getOwner())
ctx->ns->addDef(typeDef);
finished = true;
}
| C++ |
// Copyright 2010 Google Inc.
#ifndef _Crack_h_
#define _Crack_h_
#include "builder/BuilderOptions.h"
#include <map>
#include <vector>
#include <spug/RCPtr.h>
#define CRACK_VERSION_STRING "0.6"
namespace model {
SPUG_RCPTR(Construct);
SPUG_RCPTR(Context);
SPUG_RCPTR(ModuleDef);
}
namespace builder {
SPUG_RCPTR(Builder);
}
/**
* High-level wrapper around the crack executor. Use this whenever possible
* for embedding.
*/
class Crack {
private:
// the root context contains all of the builtin types and functions
// that are visible from all modules.
model::ContextPtr rootContext;
// the primary construct.
model::ConstructPtr construct;
// keeps init() from doing its setup stuff twice.
bool initialized;
bool init();
public:
// builder specific options
builder::BuilderOptionsPtr options;
// if true, don not load the bootstrapping modules before running a
// script. This changes some of the language semantics: constant
// strings become byteptr's and classes without explicit ancestors
// will not be derived from object.
bool noBootstrap;
// if true, add the global installed libary path to the library search
// path prior to running anything.
bool useGlobalLibs;
// if true, emit warnings when the code has elements with semantic
// differences from the last version of the language.
bool emitMigrationWarnings;
Crack(void);
// ~Crack();
public:
/**
* Adds the given path to the source library path - 'path' is a
* colon separated list of directories.
*/
void addToSourceLibPath(const std::string &path);
/**
* Set the program's arg list (this should be done prior to calling
* runScript()).
*/
void setArgv(int argc, char **argv);
/**
* set the main builder for compiling runtime code
*/
void setBuilder(builder::Builder *builder);
/**
* Set the builder to be used by the compiler for annotation modules.
*/
void setCompileTimeBuilder(builder::Builder *builder);
/**
* Run the specified script. Catches all parse exceptions, returns
* an exit code, which will be non-zero if a parse error occurred and
* should eventually be settable by the application.
*
* @param src the script's source stream.
* @param name the script's name (for use in error reporting and
* script module creation).
*/
int runScript(std::istream &src, const std::string &name);
/**
* Call the module destructors for all loaded modules in the reverse
* order that they were loaded. This should be done before
* terminating.
*/
void callModuleDestructors();
/**
* print compile time stats to the given stream
*/
void printStats(std::ostream &out);
};
#endif
| C++ |
// Copyright 2009-2011 Google Inc., Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_Builder_h_
#define _builder_Builder_h_
#include <stdint.h>
#include <spug/RCPtr.h>
#include "BuilderOptions.h"
#include "model/FuncCall.h" // for FuncCall::ExprVec
#include "model/FuncDef.h" // for FuncDef::Flags
#include "model/ImportedDef.h"
namespace model {
class AllocExpr;
class AssignExpr;
class Branchpoint;
SPUG_RCPTR(ArgDef);
SPUG_RCPTR(ModuleDef);
SPUG_RCPTR(CleanupFrame);
SPUG_RCPTR(Branchpoint);
class Context;
SPUG_RCPTR(FuncCall);
SPUG_RCPTR(IntConst);
SPUG_RCPTR(FloatConst);
class NullConst;
SPUG_RCPTR(StrConst);
SPUG_RCPTR(TernaryExpr);
SPUG_RCPTR(TypeDef);
SPUG_RCPTR(VarDef);
SPUG_RCPTR(VarRef);
class FuncCall;
};
namespace builder {
SPUG_RCPTR(Builder);
/** Abstract base class for builders. Builders generate code. */
class Builder : public spug::RCBase {
public:
BuilderOptionsPtr options;
Builder(): options(0) { }
/**
* This gets called on the "root builder" everytime a new module gets
* loaded and the new builder . Derived classes may either create a
* new Builder instance or return the existing one.
*/
virtual BuilderPtr createChildBuilder() = 0;
virtual model::ResultExprPtr emitFuncCall(
model::Context &context,
model::FuncCall *funcCall
) = 0;
virtual model::ResultExprPtr emitStrConst(model::Context &context,
model::StrConst *strConst
) = 0;
virtual model::ResultExprPtr emitIntConst(model::Context &context,
model::IntConst *val
) = 0;
virtual model::ResultExprPtr emitFloatConst(model::Context &context,
model::FloatConst *val
) = 0;
/**
* Emits a null of the specified type.
*/
virtual model::ResultExprPtr emitNull(model::Context &context,
model::NullConst *nullExpr
) = 0;
/**
* Emit an allocator for the specified type.
*/
virtual model::ResultExprPtr emitAlloc(model::Context &context,
model::AllocExpr *allocExpr,
model::Expr *countExpr = 0
) = 0;
/**
* Emit a test for non-zero. This is the default for emitting
* conditionals expressions.
*/
virtual void emitTest(model::Context &context,
model::Expr *expr
) = 0;
/**
* Emit the beginning of an "if" statement, returns a Branchpoint that
* must be passed to the subsequent emitElse() or emitEndIf().
*/
virtual model::BranchpointPtr emitIf(model::Context &context,
model::Expr *cond) = 0;
/**
* Emits an "else" statement.
* @params pos the branchpoint returned from the original emitIf().
* @param terminal true if the "if" clause was terminal.
* @returns a branchpoint to be passed to the subsequent emitEndIf().
*/
virtual model::BranchpointPtr
emitElse(model::Context &context,
model::Branchpoint *pos,
bool terminal
) = 0;
/**
* Closes off an "if" statement emitted by emitIf().
* @param pos a branchpoint returned from the last emitIf() or
* emitElse().
* @param terminal true if the last clause (if or else) was terminal.
*/
virtual void emitEndIf(model::Context &context,
model::Branchpoint *pos,
bool terminal
) = 0;
/**
* Create a ternary expression object.
*/
virtual model::TernaryExprPtr createTernary(model::Context &context,
model::Expr *cond,
model::Expr *trueVal,
model::Expr *falseVal,
model::TypeDef *type
) = 0;
/**
* Emit a ternary operator expression.
* @param cond the conditional expression.
* @param expr the expression to emit.
*/
virtual model::ResultExprPtr emitTernary(model::Context &context,
model::TernaryExpr *expr
) = 0;
/**
* Emits a "while" statement.
* @param cond the conditional expression.
* @returns a Branchpoint to be passed into the emitEndWhile()
*/
virtual model::BranchpointPtr
emitBeginWhile(model::Context &context,
model::Expr *cond,
bool gotPostLoop
) = 0;
/**
* Emits the end of the "while" statement.
* @param pos the branchpoint object returned from the emitWhile().
*/
virtual void emitEndWhile(model::Context &context,
model::Branchpoint *pos,
bool isTerminal
) = 0;
/**
* Emit code to be called at the end of the while loop.
* All code emitted after this will be called after the completion of
* the body of the loop regardless of whether a continue statement was
* invoked.
* This must be called between emitBeginWhile() and emitEndWhile().
* The "gotPostLoop" argument to the emitBeginWhile() must be true.
*/
virtual void emitPostLoop(model::Context &context,
model::Branchpoint *pos,
bool isTerminal
) = 0;
/**
* Emit the code for a break statement (branch to the end of the
* enclosing while/for/switch).
* @param branch branchpoint for the loop we're breaking out of.
*/
virtual void emitBreak(model::Context &context,
model::Branchpoint *branch
) = 0;
/**
* Emit the code for the continue statement (branch to the beginning
* of the enclosing while/for).
* @param branch branchpoint for the loop we're breaking out of.
*/
virtual void emitContinue(model::Context &context,
model::Branchpoint *branch
) = 0;
/**
* Returns a forward definition for a function.
*/
virtual model::FuncDefPtr
createFuncForward(model::Context &context,
model::FuncDef::Flags flags,
const std::string &name,
model::TypeDef *returnType,
const std::vector<model::ArgDefPtr> &args,
model::FuncDef *override
) = 0;
/**
* Create a forward defintion for a class.
*/
virtual model::TypeDefPtr
createClassForward(model::Context &context,
const std::string &name
) = 0;
/**
* Start a new function definition.
* @param args the function argument list.
* @param existing either the virtual base function that we are
* overriding or the forward declaration that we are implementing,
* null if this is not an override or forward-declared.
*/
virtual model::FuncDefPtr
emitBeginFunc(model::Context &context,
model::FuncDef::Flags flags,
const std::string &name,
model::TypeDef *returnType,
const std::vector<model::ArgDefPtr> &args,
model::FuncDef *existing
) = 0;
/**
* Emit the end of a function definition.
*/
virtual void emitEndFunc(model::Context &context,
model::FuncDef *funcDef) = 0;
/**
* Create an external primitive function reference.
*/
virtual model::FuncDefPtr
createExternFunc(model::Context &context,
model::FuncDef::Flags flags,
const std::string &name,
model::TypeDef *returnType,
model::TypeDef *receiverType,
const std::vector<model::ArgDefPtr> &args,
void *cfunc,
const char *symbolName=0
) = 0;
/**
* Emit the beginning of a class definition.
* The context should be the context of the new class.
*/
virtual model::TypeDefPtr
emitBeginClass(model::Context &context,
const std::string &name,
const std::vector<model::TypeDefPtr> &bases,
model::TypeDef *forwardDef
) = 0;
/**
* Emit the end of a class definitiion.
* The context should be the context of the class.
*/
virtual void emitEndClass(model::Context &context) = 0;
/**
* Emit a return statement.
* @params expr an expression or null if we are returning void.
*/
virtual void emitReturn(model::Context &context,
model::Expr *expr) = 0;
/**
* Emit the beginning of a try block. Try/catch statements are
* roughly emitted as:
* bpos = emitBeginTry()
* emitCatch(bpos)
* emitCatch(bpos)
* emitEndTry(bpos);
*/
virtual model::BranchpointPtr emitBeginTry(model::Context &context
) = 0;
/**
* Emit a catch clause.
* 'context' should be a context that was marked as a catch
* context using setCatchBranchpoint() for the code between
* emitBeginTry() and the first emitCatch().
* @param terminal true if the last catch block (or try block for the
* first catch) is terminal.
* @returns an expression that can be used to initialize the exception
* variable.
*/
virtual model::ExprPtr emitCatch(model::Context &context,
model::Branchpoint *branchpoint,
model::TypeDef *catchType,
bool terminal
) = 0;
/**
* Close off an existing try block.
* The rules for 'context' in emitCatch() apply.
* @param terminal true if the last catch block (or try block for the
* first catch) is terminal.
*/
virtual void emitEndTry(model::Context &context,
model::Branchpoint *branchpoint,
bool terminal
) = 0;
/**
* Called in a catch block to give the builder the opportunity to add
* an exception cleanup to the cleanup frame for the block. Builders
* can use this to cleanup whatever special housekeeping data they
* need for the exception.
*/
virtual void emitExceptionCleanup(model::Context &context) = 0;
/** Emit an exception "throw" */
virtual void emitThrow(model::Context &context,
model::Expr *expr
) = 0;
/**
* Emits a variable definition and returns a new VarDef object for the
* variable.
* @param staticScope true if the "static" keyword was applied to the
* definition.
*/
virtual model::VarDefPtr emitVarDef(
model::Context &container,
model::TypeDef *type,
const std::string &name,
model::Expr *initializer = 0,
bool staticScope = false
) = 0;
/**
* Creates an "offset field" - this is a special kind of instance
* variable that resised at a specific offset from the instance base
* pointer. These are used for mapping instance variables in
* extension objects.
*/
virtual model::VarDefPtr createOffsetField(model::Context &context,
model::TypeDef *type,
const std::string &name,
size_t offset
) = 0;
virtual model::ArgDefPtr createArgDef(model::TypeDef *type,
const std::string &name
) = 0;
/**
* @param squashVirtual If true, call a virtualized function
* directly, without the use of the vtable (causes virtualized to be
* set to false, regardless of whether funcDef is virtual).
*/
virtual model::FuncCallPtr
createFuncCall(model::FuncDef *func,
bool squashVirtual = false
) = 0;
virtual model::VarRefPtr
createVarRef(model::VarDef *varDef) = 0;
/**
* Create a field references - field references obtain the value of a
* class instance variable, so the type of the returned expression
* will be the same as the type of the varDef.
*/
virtual model::VarRefPtr
createFieldRef(model::Expr *aggregate,
model::VarDef *varDef
) = 0;
/**
* Create a field assignment.
* @param aggregate the aggregate containing the field.
* @param assign the assignment expression.
*/
virtual model::ResultExprPtr emitFieldAssign(model::Context &context,
model::Expr *aggregate,
model::AssignExpr *assign
) = 0;
/**
* Create a new module.
* @param context the module context.
* @param name the module's canonical name.
* @param path the full path to the existing source on disk
* @param owner the module's owner - this should be null unless the
* module is being defined inside another module that it depends on.
*/
virtual model::ModuleDefPtr createModule(model::Context &context,
const std::string &name,
const std::string &path,
model::ModuleDef *owner
) = 0;
virtual void closeModule(model::Context &context,
model::ModuleDef *modDef
) = 0;
/**
* Materialize a module from a builder specific cache. Returns NULL in
* the event of a cache miss.
* @param context the module context.
* @param canonicalName the module's canonical name.
* @param owner the module's owner - this should be null unless the
* module is being defined inside another module that it depends on.
* @return a module that has been loaded from the cache, or null if
* unavailable
*/
virtual model::ModuleDefPtr materializeModule(
model::Context &context,
const std::string &canonicalName,
model::ModuleDef *owner
) = 0;
/**
* Create a new cleanup frame.
*/
virtual model::CleanupFramePtr
createCleanupFrame(model::Context &context) = 0;
/**
* Close all of the cleanup frames.
* This is a signal to the builder to emit all of the cleanup code
* for the context.
*/
virtual void closeAllCleanups(model::Context &context) = 0;
virtual model::StrConstPtr createStrConst(model::Context &context,
const std::string &val) = 0;
virtual model::IntConstPtr createIntConst(model::Context &context,
int64_t val,
model::TypeDef *type = 0
) = 0;
virtual model::IntConstPtr createUIntConst(model::Context &context,
uint64_t val,
model::TypeDef *type = 0
) = 0;
virtual model::FloatConstPtr createFloatConst(model::Context &context,
double val,
model::TypeDef *type = 0
) = 0;
/**
* register the primitive types and functions into a .builtin module,
* which is returned.
*/
virtual model::ModuleDefPtr registerPrimFuncs(model::Context &context
) = 0;
/**
* Load the named shared library, returning a handle suitable for
* retrieving symbols from the library using the local mechanism
*/
virtual void *loadSharedLibrary(const std::string &name) = 0;
/**
* Load the named shared library, store the addresses for the symbols
* as StubDef's in 'context'.
*/
virtual void importSharedLibrary(const std::string &name,
const model::ImportedDefVec &symbols,
model::Context &context,
model::Namespace *ns
) = 0;
/**
* This is called for every symbol that is imported into a module.
* Implementations should do whatever processing is necessary.
*/
virtual void registerImportedDef(model::Context &context,
model::VarDef *varDef
) = 0;
/**
* This is called once per imported module, to allow the builder
* to emit any required initialization instructions for the imported
* module, i.e. to emit a call to run its top level code
*/
virtual void initializeImport(model::ModuleDef*,
const model::ImportedDefVec &symbols,
bool annotation) = 0;
/**
* Provides the builder with access to the program's argument list.
*/
virtual void setArgv(int argc, char **argv) = 0;
/**
* Called after all modules have been parsed/run. Only called
* on root builder, not children
*/
virtual void finishBuild(model::Context &context) = 0;
/**
* If a builder can directly execute functions from modules it builds,
* e.g. via JIT, then this will return true
*/
virtual bool isExec() = 0;
// XXX hack to emit all vtable initializers until we get constructor
// composition.
virtual void emitVTableInit(model::Context &context,
model::TypeDef *typeDef
) = 0;
};
} // namespace builder
#endif
| C++ |
// Copyright 2010 Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_llvm_Native_h_
#define _builder_llvm_Native_h_
#include <vector>
#include <string>
namespace llvm {
class Module;
class Value;
}
namespace builder {
class BuilderOptions;
namespace mvll {
// create main entry IR
void createMain(llvm::Module *mod, const BuilderOptions *o,
llvm::Value *vtableBaseTypeBody,
const std::string &mainModuleName
);
// optimize a single unit (module)
void optimizeUnit(llvm::Module *module, int optimizeLevel);
// link time optimizations
void optimizeLink(llvm::Module *module, bool verify);
// generate native object file and link to create native binary
void nativeCompile(llvm::Module *module,
const builder::BuilderOptions *o,
const std::vector<std::string> &sharedLibs,
const std::vector<std::string> &libPaths);
} // end namespace builder::vmll
} // end namespace builder
#endif
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_llvm_BFuncDef_h_
#define _builder_llvm_BFuncDef_h_
#include "model/FuncDef.h"
#include "model/Namespace.h"
#include "spug/check.h"
#include "LLVMBuilder.h"
#include "BTypeDef.h"
namespace llvm {
class Function;
}
namespace builder {
namespace mvll {
SPUG_RCPTR(BFuncDef);
class BFuncDef : public model::FuncDef {
private:
// this holds the function object for the last module to request
// it.
llvm::Function *rep;
public:
// low level symbol name as used by llvm::Function *rep
// this should be empty, unless it needs to link against an external symbol
// when it's empty, rep->name will default to the crack canonical name,
// which is the normal case for user defined functions in crack land
// when it's set, rep->name will always be equal to this. it should be
// set when we're pointing to e.g. a C function or C++ function from a
// loaded extension
std::string symbolName;
// for a virtual function, this is the vtable slot position.
unsigned vtableSlot;
// for a virtual function, this holds the ancestor class that owns
// the vtable pointer
BTypeDefPtr vtableBase;
BFuncDef(FuncDef::Flags flags, const std::string &name,
size_t argCount
) :
model::FuncDef(flags, name, argCount),
rep(0),
symbolName(),
vtableSlot(0) {
}
/**
* If our owner gets set, update the LLVM symbol name to reflect
* the full canonical name
*/
void setOwner(model::Namespace *o);
/**
* Returns the module-specific Function object for the function.
*/
llvm::Function *getRep(LLVMBuilder &builder);
/**
* Set the low-level function.
*/
void setRep(llvm::Function *newRep) {
SPUG_CHECK(!rep,
"Representation for function " << name <<
" already defined."
);
rep = newRep;
}
virtual void *getFuncAddr(Builder &builder);
};
} // end namespace builder::vmll
} // end namespace builder
#endif
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_llvm_Incompletes_h_
#define _builder_llvm_Incompletes_h_
#include "PlaceholderInstruction.h"
#include "model/Context.h"
#include "model/TypeDef.h"
#include <vector>
// for reasons I don't understand, we have to specialize the OperandTraits
// templates in the llvm namespace.
namespace builder { namespace mvll {
class BTypeDef;
class BFuncDef;
class IncompleteInstVarRef;
class IncompleteInstVarAssign;
class IncompleteCatchSelector;
class IncompleteNarrower;
class IncompleteVTableInit;
class IncompleteSpecialize;
class IncompleteVirtualFunc;
class IncompleteSizeOf;
} }
namespace llvm {
template<>
struct OperandTraits<builder::mvll::IncompleteInstVarRef> :
FixedNumOperandTraits<builder::mvll::IncompleteInstVarRef, 1> {
};
template<>
struct OperandTraits<builder::mvll::IncompleteInstVarAssign> :
FixedNumOperandTraits<builder::mvll::IncompleteInstVarAssign, 2> {
};
template<>
struct OperandTraits<builder::mvll::IncompleteCatchSelector> :
FixedNumOperandTraits<builder::mvll::IncompleteCatchSelector, 0> {
};
template<>
struct OperandTraits<builder::mvll::IncompleteNarrower> :
FixedNumOperandTraits<builder::mvll::IncompleteNarrower, 1> {
};
template<>
struct OperandTraits<builder::mvll::IncompleteVTableInit> :
FixedNumOperandTraits<builder::mvll::IncompleteVTableInit, 1> {
};
template<>
struct OperandTraits<builder::mvll::IncompleteSpecialize> :
FixedNumOperandTraits<builder::mvll::IncompleteSpecialize, 1> {
};
template<>
struct OperandTraits<builder::mvll::IncompleteVirtualFunc> :
VariadicOperandTraits<builder::mvll::IncompleteVirtualFunc, 1> {
};
template<>
struct OperandTraits<builder::mvll::IncompleteSizeOf> :
VariadicOperandTraits<builder::mvll::IncompleteSizeOf, 1> {
};
class BasicBlock;
class Type;
class Value;
class Use;
class Instruction;
}
// This is from llvm/OperandTraits.h. It's reproduced here because that
// version assumes use within the llvm namespace
#define CRACK_DECLARE_TRANSPARENT_OPERAND_ACCESSORS(VALUECLASS) \
public: \
inline VALUECLASS *getOperand(unsigned) const; \
inline void setOperand(unsigned, VALUECLASS*); \
inline op_iterator op_begin(); \
inline const_op_iterator op_begin() const; \
inline op_iterator op_end(); \
inline const_op_iterator op_end() const; \
protected: \
template <int> inline llvm::Use &Op(); \
template <int> inline const llvm::Use &Op() const; \
public: \
inline unsigned getNumOperands() const
namespace builder {
namespace mvll {
SPUG_RCPTR(BFieldDefImpl);
/** an incomplete reference to an instance variable. */
class IncompleteInstVarRef : public PlaceholderInstruction {
private:
BFieldDefImplPtr fieldImpl;
public:
// allocate space for 1 operand
void *operator new(size_t s);
IncompleteInstVarRef(llvm::Type *type,
llvm::Value *aggregate,
BFieldDefImpl *fieldImpl,
llvm::BasicBlock *parent
);
IncompleteInstVarRef(llvm::Type *type,
llvm::Value *aggregate,
BFieldDefImpl *fieldImpl,
llvm::Instruction *insertBefore = 0
);
virtual llvm::Instruction *clone_impl() const;
virtual void insertInstructions(llvm::IRBuilder<> &builder);
CRACK_DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
};
class IncompleteInstVarAssign : public PlaceholderInstruction {
private:
BFieldDefImplPtr fieldDefImpl;
public:
// allocate space for 2 operands
void *operator new(size_t s);
IncompleteInstVarAssign(llvm::Type *type,
llvm::Value *aggregate,
BFieldDefImpl *fieldDefImpl,
llvm::Value *rval,
llvm::BasicBlock *parent
);
IncompleteInstVarAssign(llvm::Type *type,
llvm::Value *aggregate,
BFieldDefImpl *fieldDefImpl,
llvm::Value *rval,
llvm::Instruction *insertBefore = 0
);
virtual llvm::Instruction *clone_impl() const;
virtual void insertInstructions(llvm::IRBuilder<> &builder);
CRACK_DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
};
class IncompleteCatchSelector : public PlaceholderInstruction {
private:
llvm::Value *personalityFunc;
public:
// pointers to the type implementation globals, which are set on
// completion of the catch clause.
std::vector<llvm::Value *> *typeImpls;
// allocate space for 0 operands
// NOTE: We don't make use of any of the operand magic because none of the
// associated value objects should be replacable. If you start seeing
// value breakage in the exception selectors, look here because that
// assumption has probably been violated.
void *operator new(size_t s);
IncompleteCatchSelector(llvm::Type *type,
llvm::Value *personalityFunc,
llvm::BasicBlock *parent
);
IncompleteCatchSelector(llvm::Type *type,
llvm::Value *personalityFunc,
llvm::Instruction *insertBefore = 0
);
~IncompleteCatchSelector();
virtual llvm::Instruction *clone_impl() const;
virtual void insertInstructions(llvm::IRBuilder<> &builder);
CRACK_DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
};
/**
* A placeholder for a "narrower" - a GEP instruction that provides
* pointer to a base class from a derived class.
*/
class IncompleteNarrower : public PlaceholderInstruction {
private:
BTypeDef *startType, *ancestor;
public:
// allocate space for 1 operand
void *operator new(size_t s);
IncompleteNarrower(llvm::Value *aggregate,
BTypeDef *startType,
BTypeDef *ancestor,
llvm::BasicBlock *parent
);
IncompleteNarrower(llvm::Value *aggregate,
BTypeDef *startType,
BTypeDef *ancestor,
llvm::Instruction *insertBefore = 0
);
virtual llvm::Instruction *clone_impl() const;
/**
* Emits the GEP instructions to narrow 'inst' from 'type' to
* 'ancestor'. Returns the resulting end-value.
*/
static llvm::Value *emitGEP(llvm::IRBuilder<> &builder,
BTypeDef *type,
BTypeDef *ancestor,
llvm::Value *inst
);
virtual void insertInstructions(llvm::IRBuilder<> &builder);
CRACK_DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
};
class IncompleteVTableInit : public PlaceholderInstruction {
public:
// allocate space for 1 operand
void *operator new(size_t s);
// we can make these raw pointers, the type _must_ be in existence
// during the lifetime of this object.
BTypeDef *aggregateType;
BTypeDef *vtableBaseType;
IncompleteVTableInit(BTypeDef *aggregateType,
llvm::Value *aggregate,
BTypeDef *vtableBaseType,
llvm::BasicBlock *parent
);
IncompleteVTableInit(BTypeDef *aggregateType,
llvm::Value *aggregate,
BTypeDef *vtableBaseType,
llvm::Instruction *insertBefore = 0
);
virtual llvm::Instruction *clone_impl() const;
// emit the code to initialize the first VTable in btype.
void emitInitOfFirstVTable(llvm::IRBuilder<> &builder,
BTypeDef *btype,
llvm::Value *inst,
llvm::Constant *vtable
);
// emit the code to initialize all vtables in an object.
void emitVTableInit(llvm::IRBuilder<> &builder,
BTypeDef *btype,
llvm::Value *inst
);
virtual void insertInstructions(llvm::IRBuilder<> &builder);
CRACK_DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
};
class IncompleteVirtualFunc : public PlaceholderInstruction {
private:
BTypeDef *vtableBaseType;
BFuncDef *funcDef;
llvm::BasicBlock *normalDest, *unwindDest;
/**
* Returns the first vtable pointer in the instance layout, casted
* to finalVTableType.
*
* @param builder the builder in which to generate the GEPs
* @param vtableBaseType the type object for the global VTableBase
* class
* @param finalVTableType the type that we need to cast the
* VTable to.
* @param curType the current type of 'inst'
* @param inst the instance that we are retrieving the vtable for.
*/
static llvm::Value *getVTableReference(llvm::IRBuilder<> &builder,
BTypeDef *vtableBaseType,
llvm::Type *finalVTableType,
BTypeDef *curType,
llvm::Value *inst
);
static llvm::Value *innerEmitCall(llvm::IRBuilder<> &builder,
BTypeDef *vtableBaseType,
BFuncDef *funcDef,
llvm::Value *receiver,
const std::vector<llvm::Value *> &args,
llvm::BasicBlock *normalDest,
llvm::BasicBlock *unwindDest
);
void init(llvm::Value *receiver, const std::vector<llvm::Value *> &args);
IncompleteVirtualFunc(BTypeDef *vtableBaseType,
BFuncDef *funcDef,
llvm::Value *receiver,
const std::vector<llvm::Value *> &args,
llvm::BasicBlock *parent,
llvm::BasicBlock *normalDest,
llvm::BasicBlock *unwindDest
);
IncompleteVirtualFunc(BTypeDef *vtableBaseType,
BFuncDef *funcDef,
llvm::Value *receiver,
const std::vector<llvm::Value *> &args,
llvm::BasicBlock *normalDest,
llvm::BasicBlock *unwindDest,
llvm::Instruction *insertBefore = 0
);
IncompleteVirtualFunc(BTypeDef *vtableBaseType,
BFuncDef *funcDef,
llvm::Use *operands,
unsigned numOperands,
llvm::BasicBlock *normalDest,
llvm::BasicBlock *unwindDest
);
public:
virtual llvm::Instruction *clone_impl() const;
virtual void insertInstructions(llvm::IRBuilder<> &builder);
static llvm::Value *emitCall(model::Context &context,
BFuncDef *funcDef,
llvm::Value *receiver,
const std::vector<llvm::Value *> &args,
llvm::BasicBlock *normalDest,
llvm::BasicBlock *unwindDest
);
CRACK_DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
};
/**
* Instruction that does an un-GEP - widens from a base class to a
* derived class.
s */
class IncompleteSpecialize : public PlaceholderInstruction {
private:
Value *value;
model::TypeDef::AncestorPath ancestorPath;
public:
// allocate space for 1 operand
void *operator new(size_t s);
virtual llvm::Instruction *clone_impl() const;
/**
* ancestorPath: path from the target class to the ancestor that
* value is referencing an instance of.
*/
IncompleteSpecialize(llvm::Type *type,
llvm::Value *value,
const model::TypeDef::AncestorPath &ancestorPath,
llvm::Instruction *insertBefore = 0
);
IncompleteSpecialize(llvm::Type *type,
llvm::Value *value,
const model::TypeDef::AncestorPath &ancestorPath,
llvm::BasicBlock *parent
);
static Value *emitSpecializeInner(
llvm::IRBuilder<> &builder,
llvm::Type *type,
llvm::Value *value,
const model::TypeDef::AncestorPath &ancestorPath
);
virtual void insertInstructions(llvm::IRBuilder<> &builder);
// Utility function - emits the specialize instructions if the
// target class is defined, emits a placeholder instruction if it
// is not.
static Value *emitSpecialize(
model::Context &context,
BTypeDef *type,
llvm::Value *value,
const model::TypeDef::AncestorPath &ancestorPath
);
CRACK_DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
};
class IncompleteSizeOf : public PlaceholderInstruction {
private:
llvm::Type *type, *intType;
public:
// allocate space for 0 operands
void *operator new(size_t s);
virtual llvm::Instruction *clone_impl() const;
IncompleteSizeOf(llvm::Type *type,
llvm::Type *intType,
llvm::Instruction *insertBefore = 0
);
IncompleteSizeOf(llvm::Type *type,
llvm::Type *intType,
llvm::BasicBlock *parent
);
static llvm::Value *emitInner(llvm::Type *type, llvm::Type *intType,
llvm::IRBuilder<> &builder
);
virtual void insertInstructions(llvm::IRBuilder<> &builder);
// Emit the sizeof instructions if the type is finished, creates the
// placeholders if not.
static Value *emitSizeOf(model::Context &context,
BTypeDef *type,
llvm::Type *intType
);
CRACK_DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
};
} // end namespace builder::vmll
} // end namespace builder
#endif
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_llvm_FunctionTypeDef_h_
#define _builder_llvm_FunctionTypeDef_h_
#include "model/Context.h"
#include "BTypeDef.h"
#include <string>
namespace llvm {
class Type;
}
namespace builder {
namespace mvll {
class FunctionTypeDef : public BTypeDef {
public:
FunctionTypeDef(model::TypeDef *metaType,
const std::string &name,
llvm::Type *rep
);
// specializations of array types actually create a new type
// object.
virtual model::TypeDef *getSpecialization(model::Context &context,
TypeVecObj *types
);
};
} // end namespace builder::vmll
} // end namespace builder
#endif
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_llvm_BFieldRef_h_
#define _builder_llvm_BFieldRef_h_
#include "model/VarRef.h"
#include "model/Expr.h"
#include "model/Context.h"
#include "model/ResultExpr.h"
namespace model {
class VarDef;
}
namespace builder {
namespace mvll {
class BFieldRef : public model::VarRef {
public:
model::ExprPtr aggregate;
BFieldRef(model::Expr *aggregate, model::VarDef *varDef) :
aggregate(aggregate),
VarRef(varDef) {
}
model::ResultExprPtr emit(model::Context &context);
};
} // end namespace builder::vmll
} // end namespace builder
#endif
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#include "FuncBuilder.h"
#include "BFuncDef.h"
#include "VarDefs.h"
#include "model/ResultExpr.h"
#include <llvm/LLVMContext.h>
using namespace llvm;
using namespace model;
using namespace std;
using namespace builder::mvll;
FuncBuilder::FuncBuilder(Context &context, FuncDef::Flags flags,
BTypeDef *returnType,
const string &name,
size_t argCount,
Function::LinkageTypes linkage
) :
context(context),
returnType(returnType),
funcDef(new BFuncDef(flags, name, argCount)),
linkage(linkage),
argIndex(0) {
funcDef->returnType = returnType;
funcDef->ns = context.ns;
}
void FuncBuilder::finish(bool storeDef) {
size_t argCount = funcDef->args.size();
assert(argIndex == argCount);
vector<Type *> llvmArgs(argCount +
(receiverType ? 1 : 0)
);
// create the array of LLVM arguments
int i = 0;
if (receiverType)
llvmArgs[i++] = receiverType->rep;
for (vector<ArgDefPtr>::iterator iter = funcDef->args.begin();
iter != funcDef->args.end();
++iter, ++i
)
llvmArgs[i] = BTypeDefPtr::rcast((*iter)->type)->rep;
// register the function with LLVM
Type *rawRetType = returnType->rep ? returnType->rep :
Type::getVoidTy(getGlobalContext());
FunctionType *llvmFuncType =
FunctionType::get(rawRetType, llvmArgs,
funcDef->flags & FuncDef::variadic);
LLVMBuilder &builder =
dynamic_cast<LLVMBuilder &>(context.builder);
Function *func = Function::Create(llvmFuncType,
linkage,
funcDef->getFullName(),
builder.module
);
func->setCallingConv(llvm::CallingConv::C);
if (!funcDef->symbolName.empty())
func->setName(funcDef->symbolName);
// back-fill builder data and set arg names
Function::arg_iterator llvmArg = func->arg_begin();
vector<ArgDefPtr>::const_iterator crackArg =
funcDef->args.begin();
if (receiverType) {
llvmArg->setName("this");
// add the implementation to the "this" var
if (!(funcDef->flags & FuncDef::abstract)) {
receiver = context.ns->lookUp("this");
assert(receiver &&
"missing 'this' variable in the context of a "
"function with a receiver"
);
funcDef->thisArg = receiver;
receiver->impl = new BArgVarDefImpl(llvmArg);
}
++llvmArg;
}
for (; llvmArg != func->arg_end(); ++llvmArg, ++crackArg) {
llvmArg->setName((*crackArg)->name);
// need the address of the value here because it is going
// to be used in a "load" context.
(*crackArg)->impl = new BArgVarDefImpl(llvmArg);
}
// store the LLVM function in the table for the module
builder.setModFunc(funcDef.get(), func);
// get or create the type registered for the function
BTypeDefPtr crkFuncType = builder.getFuncType(context, funcDef.get(),
llvmFuncType
);
funcDef->type = crkFuncType;
// create an implementation object to return the function
// pointer
funcDef->impl = new BConstDefImpl(func);
funcDef->setRep(func);
if (storeDef)
context.addDef(funcDef.get());
}
void FuncBuilder::addArg(const char *name, TypeDef *type) {
assert(argIndex <= funcDef->args.size());
funcDef->args[argIndex++] = new ArgDef(type, name);
}
void FuncBuilder::setArgs(const vector<ArgDefPtr> &args) {
assert(argIndex == 0 && args.size() == funcDef->args.size());
argIndex = args.size();
funcDef->args = args;
}
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_llvm_BFuncPtr_h_
#define _builder_llvm_BFuncPtr_h_
#include "model/FuncDef.h"
#include "llvm/Value.h"
namespace llvm {
class Function;
}
namespace builder {
namespace mvll {
SPUG_RCPTR(BFuncPtr);
class BFuncPtr : public model::FuncDef {
public:
// this holds the function pointer
llvm::Value *rep;
BFuncPtr(llvm::Value *r, size_t argCount) :
model::FuncDef(FuncDef::noFlags, r->getNameStr(), argCount),
rep(r) { }
virtual void *getFuncAddr(builder::Builder &builder) {
assert(0 && "getFuncAddr called on BFuncPtr");
}
};
} // end namespace builder::vmll
} // end namespace builder
#endif
| C++ |
// Copyright 2010 Google Inc.
#include "PlaceholderInstruction.h"
using namespace llvm;
using namespace builder::mvll;
void PlaceholderInstruction::fix() {
IRBuilder<> builder(getParent(), this);
insertInstructions(builder);
this->eraseFromParent();
// ADD NO CODE AFTER SELF-DELETION.
}
| C++ |
// Copyright 2011 Google Inc
#ifndef _builder_llvm_BJitModuleDef_h_
#define _builder_llvm_BJitModuleDef_h_
#include "BModuleDef.h"
namespace builder { namespace mvll {
SPUG_RCPTR(BJitModuleDef);
/**
* Specialized Module object for the jit builder - includes an "owner", owned
* modules are closed as part of the owner's closing. A module with an owner
* is a "sub-module" of the owner.
*
* This mechanism is necessary for ephemeral modules, which can reference
* incomplete types from the modules they are spawned from.
*/
class BJitModuleDef : public BModuleDef {
public:
// Closer stores all of the infromation necessary to close a
// sub-module.
SPUG_RCPTR(Closer);
class Closer : public spug::RCBase {
private:
model::ContextPtr context;
BJitModuleDefPtr moduleDef;
LLVMJitBuilderPtr builder;
public:
Closer(model::Context *context,
BJitModuleDef *moduleDef,
LLVMJitBuilder *builder
) :
context(context),
moduleDef(moduleDef),
builder(builder) {
}
void close() {
moduleDef->recursiveClose(*context, builder.get());
}
};
// modules to close during our own closing.
std::vector<CloserPtr> subModules;
BJitModuleDefPtr owner;
BJitModuleDef(const std::string &canonicalName,
model::Namespace *parent,
llvm::Module *rep0,
BJitModuleDef *owner
) :
BModuleDef(canonicalName, parent, rep0),
owner(owner) {
}
void recursiveClose(model::Context &context, LLVMJitBuilder *builder) {
// closing for real - close all of my sub-modules
for (int i = 0; i < subModules.size(); ++i)
subModules[i]->close();
// and do the real close
builder->innerCloseModule(context, this);
}
void closeOrDefer(model::Context &context, LLVMJitBuilder *builder) {
// if we've got an owner, defer our close until his close
if (owner) {
CloserPtr closer = new Closer(&context, this, builder);
owner->subModules.push_back(closer);
} else {
recursiveClose(context, builder);
}
}
};
}} // end namespace builder::vmll
#endif
| C++ |
// Copyright 2011 Shannon Weyrick <weyrick@mozek.us>
#include "Cacher.h"
#include "BModuleDef.h"
#include "model/Deserializer.h"
#include "model/Generic.h"
#include "model/GlobalNamespace.h"
#include "model/Namespace.h"
#include "model/OverloadDef.h"
#include "model/Serializer.h"
#include "model/NullConst.h"
#include "model/ConstVarDef.h"
#include "spug/check.h"
#include <assert.h>
#include <sstream>
#include <vector>
#include <llvm/Module.h>
#include <llvm/Support/IRBuilder.h>
#include <llvm/Support/ToolOutputFile.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include <llvm/Support/FormattedStream.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/system_error.h>
#include <llvm/LLVMContext.h>
#include "model/EphemeralImportDef.h"
#include "builder/BuilderOptions.h"
#include "builder/util/CacheFiles.h"
#include "builder/util/SourceDigest.h"
#include "LLVMBuilder.h"
#include "VarDefs.h"
#include "BFuncDef.h"
#include "Consts.h"
#include "StructResolver.h"
using namespace llvm;
using namespace llvm::sys;
using namespace builder::mvll;
using namespace std;
using namespace model;
// metadata version
const std::string Cacher::MD_VERSION = "1";
namespace {
ConstantInt *constInt(int c) {
return ConstantInt::get(Type::getInt32Ty(getGlobalContext()), c);
}
}
Function *Cacher::getEntryFunction() {
NamedMDNode *node = modDef->rep->getNamedMetadata("crack_entry_func");
if (!node)
cerr << "in module: " << modDef->name << endl;
assert(node && "no crack_entry_func");
MDNode *funcNode = node->getOperand(0);
assert(funcNode && "malformed crack_entry_func");
Function *func = dyn_cast<Function>(funcNode->getOperand(0));
assert(func && "entry function not LLVM Function!");
func->Materialize();
return func;
}
void Cacher::getExterns(std::vector<std::string> &symList) {
assert(symList.size() == 0 && "invalid or nonempty symList");
NamedMDNode *externs = modDef->rep->getNamedMetadata("crack_externs");
assert(externs && "no crack_externs node");
if (externs->getNumOperands()) {
MDString *sym;
MDNode *symNode = externs->getOperand(0);
for (int i = 0; i < symNode->getNumOperands(); ++i) {
sym = dyn_cast<MDString>(symNode->getOperand(i));
assert(sym && "malformed crack_externs");
symList.push_back(sym->getString().str());
}
}
}
void Cacher::addNamedStringNode(const string &key, const string &val) {
vector<Value *> dList;
NamedMDNode *node;
node = modDef->rep->getOrInsertNamedMetadata(key);
dList.push_back(MDString::get(getGlobalContext(), val));
node->addOperand(MDNode::get(getGlobalContext(), dList));
}
string Cacher::getNamedStringNode(const std::string &key) {
NamedMDNode *node;
MDNode *mnode;
MDString *str;
node = modDef->rep->getNamedMetadata(key);
assert(node && "missing required named string node");
mnode = node->getOperand(0);
assert(mnode && "malformed string node 1");
str = dyn_cast<MDString>(mnode->getOperand(0));
assert(str && "malformed string node 2");
return str->getString().str();
}
MDNode *Cacher::writeEphemeralImport(BModuleDef *mod) {
vector<Value *> dList;
// operand 0: symbol name (unecessary)
dList.push_back(MDString::get(getGlobalContext(), mod->name));
// operand 1: symbol type
dList.push_back(constInt(Cacher::ephemeralImport));
// operand 2: canonical name
dList.push_back(MDString::get(getGlobalContext(), mod->getFullName()));
// operand 3: digest
dList.push_back(MDString::get(getGlobalContext(), mod->digest.asHex()));
return MDNode::get(getGlobalContext(), dList);
}
void Cacher::writeMetadata() {
// encode metadata into the bitcode
addNamedStringNode("crack_md_version", Cacher::MD_VERSION);
addNamedStringNode("crack_origin_digest", modDef->digest.asHex());
addNamedStringNode("crack_origin_path", modDef->sourcePath);
vector<Value *> dList;
NamedMDNode *node;
Module *module = modDef->rep;
// crack_imports: operand list points to import nodes
node = module->getOrInsertNamedMetadata("crack_imports");
for (BModuleDef::ImportListType::const_iterator iIter =
modDef->importList.begin();
iIter != modDef->importList.end();
++iIter
) {
// op 1: canonical name
dList.push_back(MDString::get(getGlobalContext(),
(*iIter).first->getFullName()));
// op 2: digest
dList.push_back(MDString::get(getGlobalContext(),
(*iIter).first->digest.asHex()));
// op 3..n: symbols to be imported (aliased)
for (ImportedDefVec::const_iterator sIter = (*iIter).second.begin();
sIter != (*iIter).second.end();
++sIter) {
dList.push_back(MDString::get(getGlobalContext(), sIter->local));
dList.push_back(MDString::get(getGlobalContext(), sIter->source));
}
node->addOperand(MDNode::get(getGlobalContext(), dList));
dList.clear();
}
// crack_shlib_imports: operand list points to shared lib import nodes
node = module->getOrInsertNamedMetadata("crack_shlib_imports");
for (BModuleDef::ShlibImportListType::const_iterator iIter =
modDef->shlibImportList.begin();
iIter != modDef->shlibImportList.end();
++iIter
) {
// op 1: shared lib name
dList.push_back(MDString::get(getGlobalContext(),
(*iIter).first));
// op 2..n: symbols to be imported
for (ImportedDefVec::const_iterator sIter = (*iIter).second.begin();
sIter != (*iIter).second.end();
++sIter) {
dList.push_back(MDString::get(getGlobalContext(), sIter->local));
dList.push_back(MDString::get(getGlobalContext(), sIter->source));
}
node->addOperand(MDNode::get(getGlobalContext(), dList));
dList.clear();
}
// crack_externs: these we need to resolve upon load. in the JIT, that means
// global mappings. we need to resolve functions and globals
node = module->getOrInsertNamedMetadata("crack_externs");
// functions
for (LLVMBuilder::ModFuncMap::const_iterator i =
builder->moduleFuncs.begin();
i != builder->moduleFuncs.end();
++i) {
// only include it if it's a decl, and not abstract
if (!i->second->isDeclaration() ||
i->first->flags & FuncDef::abstract)
continue;
Namespace *owningNS = i->first->getOwner();
assert(owningNS && "no owner");
// skips anything in builtin namespace
if (owningNS->getNamespaceName().substr(0,8) == ".builtin") {
continue;
}
// and it's defined in another module
// but skip externals from extensions, since these are found by
// the jit through symbol searching the process
ModuleDefPtr owningModule = owningNS->getModule();
if ((owningModule && owningModule->fromExtension) ||
(owningNS == modDef->getParent(0).get())) {
continue;
}
dList.push_back(MDString::get(getGlobalContext(), i->second->getNameStr()));
}
// globals
for (LLVMBuilder::ModVarMap::const_iterator i = builder->moduleVars.begin();
i != builder->moduleVars.end();
++i) {
if (!i->second->isDeclaration())
continue;
dList.push_back(MDString::get(getGlobalContext(), i->second->getNameStr()));
}
if (dList.size()) {
node->addOperand(MDNode::get(getGlobalContext(), dList));
dList.clear();
}
// crack_defs: the symbols defined in this module that we need to rebuild
// at compile time in order to use this cached module to compile fresh code
// from
writeNamespace(modDef.get());
//module->dump();
}
void Cacher::writeNamespace(Namespace *ns) {
OverloadDef *ol;
TypeDef *td;
TypeDef *owner = dynamic_cast<TypeDef*>(ns);
NamedMDNode *node = modDef->rep->getOrInsertNamedMetadata("crack_defs");
for (Namespace::VarDefVec::const_iterator i = ns->beginOrderedForCache();
i != ns->endOrderedForCache();
++i) {
if (ol = OverloadDefPtr::rcast(*i)) {
for (OverloadDef::FuncList::const_iterator f = ol->beginTopFuncs();
f != ol->endTopFuncs();
++f) {
// skip aliases
if ((*f)->getOwner() == ns) {
MDNode *n = writeFuncDef((*f).get(), owner);
if (n)
node->addOperand(n);
}
}
} else {
// skip aliases
if ((*i)->getOwner() != ns)
continue;
if (td = TypeDefPtr::rcast(*i)) {
MDNode *typeNode = writeTypeDef(td);
if (typeNode) {
node->addOperand(typeNode);
writeNamespace(td);
}
} else if (EphemeralImportDef *mod =
EphemeralImportDefPtr::rcast(*i)) {
BModuleDefPtr bmod = BModuleDefPtr::arcast(mod->module);
node->addOperand(writeEphemeralImport(bmod.get()));
} else {
// VarDef
// XXX hack to not write exStruct
if ((*i)->name == ":exStruct")
continue;
if ((*i)->isConstant())
node->addOperand(writeConstant((*i).get(), owner));
else
node->addOperand(writeVarDef((*i).get(), owner));
}
}
}
}
MDNode *Cacher::writeTypeDef(model::TypeDef* t) {
if (options->verbosity >= 2)
cerr << "writing type " << t->getFullName() << " in module " <<
modDef->getNamespaceName() <<
endl;
BTypeDef *bt = dynamic_cast<BTypeDef *>(t);
assert((bt || t->generic) && "not BTypeDef");
vector<Value *> dList;
// operand 0: symbol name (not canonical)
dList.push_back(MDString::get(getGlobalContext(), t->name));
// operand 1: symbol type
dList.push_back(constInt(t->generic ? Cacher::generic : Cacher::type));
// operand 2: if this is a generic, operand 2 is the serialized generic
// value. Otherwise it is the initializer.
if (t->generic) {
ostringstream tmp;
model::Serializer ser(tmp);
t->genericInfo->serialize(ser);
dList.push_back(MDString::get(getGlobalContext(), tmp.str()));
} else {
dList.push_back(Constant::getNullValue(bt->rep));
}
// operand 3: metatype type (name string)
TypeDef *metaClass = t->type.get();
assert(metaClass && "no meta class");
dList.push_back(MDString::get(getGlobalContext(), metaClass->name));
// operand 4: metatype type (null initializer)
Type *metaTypeRep = BTypeDefPtr::acast(metaClass)->rep;
dList.push_back(Constant::getNullValue(metaTypeRep));
// operand 5: parent class namespace, relevant to nested classes.
Namespace *ownerNS = t->getOwner();
if (dynamic_cast<BTypeDef*>(ownerNS)) {
dList.push_back(MDString::get(getGlobalContext(), ownerNS->getNamespaceName()));
}
else {
dList.push_back(NULL);
}
// register in canonical map for subsequent cache loads
if (bt)
context->construct->registerDef(bt);
else
context->construct->registerDef(t);
context->construct->registerDef(metaClass);
return MDNode::get(getGlobalContext(), dList);
}
MDNode *Cacher::writeFuncDef(FuncDef *sym, TypeDef *owner) {
vector<Value *> dList;
// operand 0: symbol name (not canonical)
dList.push_back(MDString::get(getGlobalContext(), sym->name));
// operand 1: symbol type
if (owner)
dList.push_back(constInt(Cacher::method));
else
dList.push_back(constInt(Cacher::function));
// operand 2: llvm rep
BFuncDef *bf = BFuncDefPtr::cast(sym);
if (bf)
dList.push_back(bf->getRep(*builder));
else {
//cout << "skipping " << sym->name << "\n";
//dList.push_back(NULL);
return NULL;
}
// operand 3: typedef owner
if (owner)
dList.push_back(MDString::get(getGlobalContext(),
owner->getFullName()));
else
dList.push_back(NULL);
// operand 4: funcdef flags
dList.push_back(constInt(sym->flags));
// operand 5: return type
dList.push_back(MDString::get(getGlobalContext(),
sym->returnType->getFullName()));
// operand 6..ARITY: pairs of parameter symbol names and their types
for (ArgVec::const_iterator i = sym->args.begin();
i != sym->args.end();
++i) {
dList.push_back(MDString::get(getGlobalContext(), (*i)->name));
dList.push_back(MDString::get(getGlobalContext(),
(*i)->type->getFullName()));
}
// we register with the cache map because a cached module may be
// on this depended one for this run
// skip for abstract functions though, since they have no body
if ((bf->flags & FuncDef::abstract) == 0) {
builder->registerDef(*context, sym);
}
return MDNode::get(getGlobalContext(), dList);
}
MDNode *Cacher::writeConstant(VarDef *sym, TypeDef *owner) {
vector<Value *> dList;
BTypeDef *type = dynamic_cast<BTypeDef *>(sym->type.get());
// int and float will be ConstVarDef so we can get at the value
ConstVarDef *ivar = dynamic_cast<ConstVarDef *>(sym);
// operand 0: symbol name (not canonical)
dList.push_back(MDString::get(getGlobalContext(), sym->name));
// operand 1: symbol type
dList.push_back(constInt(Cacher::constant));
// operand 2: int or float value, if we have one
if (ivar) {
BIntConst *bi = dynamic_cast<BIntConst *>(ivar->expr.get());
if (bi) {
dList.push_back(bi->rep);
}
else {
BFloatConst *bf = dynamic_cast<BFloatConst *>(ivar->expr.get());
assert(bf && "unknown ConstVarDef: not int or float");
dList.push_back(bf->rep);
}
}
else {
// const object, no rep
dList.push_back(NULL);
}
// operand 3: type name
dList.push_back(MDString::get(getGlobalContext(),
type->getFullName()));
/*
// operand 4: typedef owner (XXX future?)
if (owner)
dList.push_back(MDString::get(getGlobalContext(), owner->name));
else
dList.push_back(NULL);
*/
// we register with the cache map because a cached module may be
// on this depended one for this run
builder->registerDef(*context, sym);
return MDNode::get(getGlobalContext(), dList);
}
MDNode *Cacher::writeVarDef(VarDef *sym, TypeDef *owner) {
vector<Value *> dList;
BTypeDef *type = dynamic_cast<BTypeDef *>(sym->type.get());
assert(type && "writeVarDef: no type");
BGlobalVarDefImpl *gvar = dynamic_cast<BGlobalVarDefImpl *>(sym->impl.get());
BInstVarDefImpl *ivar = dynamic_cast<BInstVarDefImpl *>(sym->impl.get());
assert(gvar || ivar && "not global or instance");
// operand 0: symbol name (not canonical)
dList.push_back(MDString::get(getGlobalContext(), sym->name));
// operand 1: symbol type
if (owner)
dList.push_back(constInt(Cacher::member));
else
dList.push_back(constInt(Cacher::global));
// operand 2: llvm rep (gvar) or null val (instance var)
if (gvar)
dList.push_back(gvar->getRep(*builder));
else
dList.push_back(Constant::getNullValue(type->rep));
// operand 3: type name
if (options->verbosity > 2)
cerr << "Writing variable type " << type->getFullName() << endl;
dList.push_back(MDString::get(getGlobalContext(), type->getFullName()));
// operand 4: typedef owner
if (owner)
dList.push_back(MDString::get(getGlobalContext(),
owner->getFullName()));
else
dList.push_back(NULL);
// operand 5: instance var index
if (!gvar)
dList.push_back(constInt(ivar->index));
else
dList.push_back(NULL);
// we register with the cache map because a cached module may be
// on this depended one for this run
builder->registerDef(*context, sym);
return MDNode::get(getGlobalContext(), dList);
}
bool Cacher::readImports() {
MDNode *mnode;
MDString *cname, *digest, *localStr, *sourceStr;
SourceDigest iDigest;
BModuleDefPtr m;
VarDefPtr symVal;
NamedMDNode *imports = modDef->rep->getNamedMetadata("crack_imports");
assert(imports && "missing crack_imports node");
for (int i = 0; i < imports->getNumOperands(); ++i) {
mnode = imports->getOperand(i);
// op 1: canonical name
cname = dyn_cast<MDString>(mnode->getOperand(0));
assert(cname && "malformed import node: canonical name");
// op 2: source digest
digest = dyn_cast<MDString>(mnode->getOperand(1));
assert(digest && "malformed import node: digest");
iDigest = SourceDigest::fromHex(digest->getString().str());
// load this module. if the digest doesn't match, we miss.
// note module may come from cache or parser, we won't know
m = context->construct->loadModule(cname->getString().str());
if (!m || m->digest != iDigest)
return false;
// op 3..n: imported (namespace aliased) symbols from m
assert(mnode->getNumOperands() % 2 == 0);
for (unsigned si = 2; si < mnode->getNumOperands();) {
localStr = dyn_cast<MDString>(mnode->getOperand(si++));
sourceStr = dyn_cast<MDString>(mnode->getOperand(si++));
assert(localStr && "malformed import node: missing local name");
assert(sourceStr && "malformed import node: missing source name");
symVal = m->lookUp(sourceStr->getString().str());
// if we failed to lookup the symbol, then something is wrong
// with our digest mechanism
assert(symVal.get() && "import: inconsistent state");
modDef->addAlias(localStr->getString().str(), symVal.get());
}
}
imports = modDef->rep->getNamedMetadata("crack_shlib_imports");
assert(imports && "missing crack_shlib_imports node");
ImportedDefVec symList;
for (int i = 0; i < imports->getNumOperands(); ++i) {
mnode = imports->getOperand(i);
// op 1: lib name
cname = dyn_cast<MDString>(mnode->getOperand(0));
assert(cname && "malformed shlib import node: lib name");
// op 2..n: imported symbols from m
for (unsigned si = 1; si < mnode->getNumOperands(); ++si) {
localStr = dyn_cast<MDString>(mnode->getOperand(si));
sourceStr = dyn_cast<MDString>(mnode->getOperand(si));
assert(localStr && "malformed shlib import node: local name");
assert(sourceStr && "malformed shlib import node: source name");
shlibImported[localStr->getString().str()] = true;
symList.push_back(ImportedDef(localStr->getString().str(),
sourceStr->getString().str()
)
);
}
builder->importSharedLibrary(cname->getString().str(), symList,
*context, modDef.get()
);
}
return true;
}
TypeDefPtr Cacher::resolveType(const string &name) {
TypeDefPtr td =
TypeDefPtr::rcast(context->construct->getRegisteredDef(name));
if (!td) {
// is it a generic?
int i;
for (i = 0; i < name.size(); ++i)
if (name[i] == '[') break;
SPUG_CHECK(i != name.size(), "type " << name << " not found");
// resolve the basic type
TypeDefPtr generic = resolveType(name.substr(0, i));
// read the paramters
TypeDef::TypeVecObjPtr parms = new TypeDef::TypeVecObj;
while (name[i++] != ']') {
int start = i;
for (; name[i] != ']' && name[i] != ','; ++i);
parms->push_back(resolveType(name.substr(start, i - start)));
}
return generic->getSpecialization(*context, parms.get());
}
if (options->verbosity > 2)
cerr << " type " << td->name << " is " <<
td->getFullName() << " and owner is " <<
td->getOwner()->getNamespaceName() <<
" original name is " << name <<
endl;
return td;
}
void Cacher::readVarDefGlobal(const std::string &sym,
llvm::Value *rep,
llvm::MDNode *mnode) {
// rep for gvar is the actual global
// operand 3: type name
MDString *typeStr = dyn_cast<MDString>(mnode->getOperand(3));
assert(typeStr && "readVarDefGlobal: invalid type string");
if (options->verbosity > 2)
cerr << "loading global " << sym << " of type " <<
typeStr->getString().str() << endl;
TypeDefPtr td = resolveType(typeStr->getString().str());
GlobalVariable *lg = dyn_cast<GlobalVariable>(rep);
assert(lg && "readVarDefGlobal: not GlobalVariable rep");
BGlobalVarDefImpl *impl = new BGlobalVarDefImpl(lg);
// the member def itself
VarDef *g = new VarDef(td.get(), sym);
g->impl = impl;
modDef->addDef(g);
builder->registerDef(*context, g);
}
void Cacher::readConstant(const std::string &sym,
llvm::Value *rep,
llvm::MDNode *mnode) {
VarDef *cnst;
// operand 3: type
MDString *typeStr = dyn_cast<MDString>(mnode->getOperand(3));
assert(typeStr && "readConstant: invalid type string");
TypeDefPtr td = resolveType(typeStr->getString().str());
assert(td && "readConstant: type not found");
if (rep) {
ConstVarDef *cvar;
if (rep->getType()->isIntegerTy()) {
ConstantInt *ival = dyn_cast<ConstantInt>(rep);
assert(ival && "not ConstantInt");
Expr *iexpr = new BIntConst(BTypeDefPtr::arcast(td),
ival->getLimitedValue());
cvar = new ConstVarDef(td.get(), sym, iexpr);
}
else {
assert(rep->getType()->isFloatingPointTy() && "not int or float");
ConstantFP *fval = dyn_cast<ConstantFP>(rep);
assert(fval && "not ConstantFP");
Expr *iexpr = new BFloatConst(BTypeDefPtr::arcast(td),
// XXX convertToDouble?? llvm asserts
fval->getValueAPF().convertToFloat());
cvar = new ConstVarDef(td.get(), sym, iexpr);
}
cnst = cvar;
}
else {
// class
cnst = new VarDef(td.get(), sym);
cnst->constant = true;
}
// the member def itself
modDef->addDef(cnst);
builder->registerDef(*context, cnst);
}
void Cacher::readVarDefMember(const std::string &sym,
llvm::Value *rep,
llvm::MDNode *mnode) {
// rep for instance var is null val for member type
// XXX rep unused?
// operand 3: member type name
MDString *typeStr = dyn_cast<MDString>(mnode->getOperand(3));
assert(typeStr && "readVarDefMember: invalid type string");
TypeDefPtr td = resolveType(typeStr->getString().str());
if (!td)
cerr << "Type " << typeStr->getString().str() <<
" not found in module " << modDef->name << endl;
assert(td && "readVarDefMember: type not found");
// operand 4: type owner (class we're a member of)
MDString *ownerStr = dyn_cast<MDString>(mnode->getOperand(4));
assert(ownerStr && "readVarDefMember: invalid owner");
TypeDefPtr otd = resolveType(ownerStr->getString().str());
// operand 5: instance var index
ConstantInt *index = dyn_cast<ConstantInt>(mnode->getOperand(5));
assert(index && "readVarDefMember: no index");
BInstVarDefImpl *impl = new BInstVarDefImpl(index->getLimitedValue());
// the member def itself
VarDefPtr mbr = new VarDef(td.get(), sym);
mbr->impl = impl;
otd->addDef(mbr.get());
}
BTypeDefPtr Cacher::readMetaType(MDNode *mnode) {
// operand 3: metatype type (name string)
MDString *cname = dyn_cast<MDString>(mnode->getOperand(3));
assert(cname && "invalid metatype name");
// operand 4: metatype type (null initializer)
Value *mtrep = mnode->getOperand(4);
BTypeDefPtr metaType = new BTypeDef(0,
cname->getString().str(),
mtrep->getType(),
true,
0 /* nextVTableslot */
);
return metaType;
}
void Cacher::finishType(TypeDef *type, BTypeDef *metaType, NamespacePtr owner) {
// tie the meta-class to the class
if (metaType)
metaType->meta = type;
// make the class default to initializing to null
type->defaultInitializer = new NullConst(type);
type->complete = true;
owner->addDef(type);
}
void Cacher::readTypeDef(const std::string &sym,
llvm::Value *rep,
llvm::MDNode *mnode) {
PointerType *p = cast<PointerType>(rep->getType());
StructType *s = cast<StructType>(p->getElementType());
BTypeDefPtr metaType = readMetaType(mnode);
// operand 5: parent class namespace, relevant to nested classes.
NamespacePtr owner = modDef; // by default, module owns the type
Value *pcStr = mnode->getOperand(5);
if (pcStr) {
MDString *parentClass = dyn_cast<MDString>(pcStr);
assert(parentClass && "parentClass not string");
TypeDefPtr pType = resolveType(parentClass->getString().str());
assert(pType && "can't find parent class");
owner = NamespacePtr::arcast(pType);
}
BTypeDefPtr type = new BTypeDef(metaType.get(),
sym,
rep->getType(),
true,
0 /* nextVTableslot */
);
finishType(type.get(), metaType.get(), owner);
assert(type->getOwner());
if (s->getName().str() != type->getFullName()) {
// if the type name does not match the structure name, we have the
// following scenario:
// A is cached, depends on type in B
// B is cached, defines type A wants
// A is loaded first, bitcode contains structure def from B with
// canonical name. Because it was loaded first, it goes into the LLVM
// context first. When B is loaded and the same canonical structure is
// loaded, it gets the postfix.
// The problem is, although A turned out to be the "authoritative" name
// for the struct according to LLVM context, it's not the authoritative place
// that it is defined in crack. So, we lookup the old one and remove the name.
// Then we set the struct name on ours (the authoritative location, because
// the crack type is defined here) to the proper canonical name without
// the postfix.
// old, nonauthoritative struct
StructType *old = modDef->rep->getTypeByName(type->getFullName());
// old must exist since otherwise we would have matched our sym name
// already
assert(old);
// we're also expecting that it matches the canonical name, which we
// want to steal
assert(old->getName() == type->getFullName());
//cout << "old name: " << old->getName().str() << "\n";
// remove the old name
old->setName("");
// steal canonical name to make our type authoritative
s->setName(type->getFullName());
//cout << "s name: " << s->getName().str() << "\n";
// now force a conflict so that the _old_ name is postfixed, and it
// will get cleaned up on a subsequent ResolveStruct run
old->setName(type->getFullName());
//cout << "old name now: " << old->getName().str() << "\n";
assert(old->getName() != s->getName());
}
assert(s->getName().str() == type->getFullName()
&& "structure name didn't match canonical");
// retrieve the class implementation pointer
GlobalVariable *impl = modDef->rep->getGlobalVariable(type->getFullName());
type->impl = new BGlobalVarDefImpl(impl);
type->classInst =
modDef->rep->getGlobalVariable(type->getFullName() + ":body");
context->construct->registerDef(type.get());
}
void Cacher::readGenericTypeDef(const std::string &sym,
llvm::Value *rep,
llvm::MDNode *mnode) {
BTypeDefPtr metaType = readMetaType(mnode);
TypeDefPtr type = new TypeDef(metaType.get(), sym, true);
// read the generic info
string srcString = dyn_cast<MDString>(rep)->getString();
istringstream srcStream(srcString);
model::Deserializer src(srcStream);
type->genericInfo = Generic::deserialize(src);
type->generic = new TypeDef::SpecializationCache();
// store the module namespace in the generic info
// XXX should also be storing the compile namespace
type->genericInfo->ns = modDef.get();
type->genericInfo->compileNS = new GlobalNamespace(0, "");
finishType(type.get(), metaType.get(), modDef);
assert(type->getOwner());
context->construct->registerDef(type.get());
}
void Cacher::readEphemeralImport(MDNode *mnode) {
MDString *canName = dyn_cast<MDString>(mnode->getOperand(2));
SPUG_CHECK(canName, "Canonical name not specified for import.");
MDString *digest = dyn_cast<MDString>(mnode->getOperand(3));
SPUG_CHECK(digest, "Digest not specified for import.");
BModuleDefPtr mod =
context->construct->loadModule(canName->getString().str());
SPUG_CHECK(mod->digest == SourceDigest::fromHex(digest->getString().str()),
"XXX Module digestfrom import doesn't match");
}
void Cacher::readFuncDef(const std::string &sym,
llvm::Value *rep,
llvm::MDNode *mnode) {
assert(rep && "no rep");
// if this symbol was defined in a shared library, skip reading
// XXX this may change depending on how exporting of second order symbols
// works out in the cache.
if (shlibImported.find(sym) != shlibImported.end())
return;
// operand 3: typedef owner (if exists)
MDString *ownerStr(0);
if (mnode->getOperand(3))
ownerStr = dyn_cast<MDString>(mnode->getOperand(3));
// operand 4: func flags
ConstantInt *flags = dyn_cast<ConstantInt>(mnode->getOperand(4));
assert(flags && "malformed def node: function flags");
// operand 5: return type
MDString *rtStr = dyn_cast<MDString>(mnode->getOperand(5));
assert(rtStr && "malformed def node: function return type");
// llvm function
Function *f = dyn_cast<Function>(rep);
assert(f && "malformed def node: llvm rep not function");
// model funcdef
// note we don't use FunctionBuilder here because we already have an
// llvm rep
size_t bargCount = f->getArgumentList().size();
FuncDef::Flags bflags = (FuncDef::Flags)flags->getLimitedValue();
if (bflags & FuncDef::method)
// if method, we adjust the BFuncDef for "this", which exists in
// llvm arguments but is only implied in BFuncDef
bargCount--;
BFuncDef *newF = new BFuncDef(bflags,
sym,
bargCount);
newF->setRep(f);
NamespacePtr owner;
if (ownerStr)
owner = resolveType(ownerStr->getString().str());
else
owner = modDef;
newF->setOwner(owner.get());
newF->ns = owner;
newF->returnType = resolveType(rtStr->getString().str());;
if (mnode->getNumOperands() > 4) {
MDString *aSym, *aTypeStr;
VarDefPtr aTypeV;
TypeDefPtr aType;
// operand 6..arity: function parameter names and types
for (int i = 6, ai=0; i < mnode->getNumOperands(); i+=2, ++ai) {
aSym = dyn_cast<MDString>(mnode->getOperand(i));
assert(aSym && "function arg: missing symbol");
aTypeStr = dyn_cast<MDString>(mnode->getOperand(i+1));
assert(aTypeStr && "function arg: missing type");
aType = resolveType(aTypeStr->getString().str());
newF->args[ai] = new ArgDef(aType.get(), aSym->getString().str());
}
}
// if not abstract, register
if ((bflags & FuncDef::abstract) == 0) {
builder->registerDef(*context, newF);
}
OverloadDef *o(0);
VarDefPtr vd = owner->lookUp(sym);
if (vd)
o = OverloadDefPtr::rcast(vd);
// at this point o may be null here if 1) vd is null 2) vd is not an
// overloaddef. 2 can happen when a function is overriding an existing
// definition
if (!vd || !o) {
o = new OverloadDef(sym);
o->addFunc(newF);
owner->addDef(o);
}
else if (o) {
o->addFunc(newF);
}
else {
assert(0 && "readFuncDef: maybe unreachable");
}
}
void Cacher::readDefs() {
MDNode *mnode;
MDString *mstr;
string sym;
Value *rep;
NamedMDNode *imports = modDef->rep->getNamedMetadata("crack_defs");
assert(imports && "missing crack_defs node");
// first pass: read all of the types
for (int i = 0; i < imports->getNumOperands(); ++i) {
mnode = imports->getOperand(i);
// operand 0: symbol name
mstr = dyn_cast<MDString>(mnode->getOperand(0));
assert(mstr && "malformed def node: symbol name");
sym = mstr->getString().str();
// operand 1: symbol type
ConstantInt *type = dyn_cast<ConstantInt>(mnode->getOperand(1));
assert(type && "malformed def node: symbol type");
// operand 2: llvm rep
rep = mnode->getOperand(2);
//assert(rep && "malformed def node: llvm rep");
int nodeType = type->getLimitedValue();
switch (nodeType) {
case Cacher::type:
readTypeDef(sym, rep, mnode);
break;
case Cacher::generic:
readGenericTypeDef(sym, rep, mnode);
break;
case Cacher::ephemeralImport:
readEphemeralImport(mnode);
break;
case Cacher::global:
readVarDefGlobal(sym, rep, mnode);
break;
case Cacher::function:
case Cacher::method:
readFuncDef(sym, rep, mnode);
break;
case Cacher::member:
readVarDefMember(sym, rep, mnode);
break;
case Cacher::constant:
readConstant(sym, rep, mnode);
break;
default:
assert(0 && "unhandled def type");
}
}
}
bool Cacher::readMetadata() {
string snode;
// register everything in the builtin module if we haven't already
if (!context->construct->getRegisteredDef(".builtin.int")) {
// for some reason, we have two levels of ancestry in builtin.
Namespace *bi = context->construct->builtinMod.get();
while (bi) {
for (Namespace::VarDefMap::iterator iter = bi->beginDefs();
iter != bi->endDefs();
++iter
) {
if (TypeDefPtr typeDef = TypeDefPtr::rcast(iter->second))
context->construct->registerDef(typeDef.get());
}
bi = bi->getParent(0).get();
}
}
// first check metadata version
snode = getNamedStringNode("crack_md_version");
if (snode != Cacher::MD_VERSION)
return false;
modDef->sourcePath = getNamedStringNode("crack_origin_path");
modDef->digest = SourceDigest::fromFile(modDef->sourcePath);
// compare the digest stored in the bitcode against the current
// digest of the source file on disk. if they don't match, we miss
snode = getNamedStringNode("crack_origin_digest");
SourceDigest bcDigest = SourceDigest::fromHex(snode);
if (bcDigest != modDef->digest)
return false;
// import list
// if readImports returns false, then one of our dependencies has
// changed on disk and our own cache therefore fails
if (!readImports())
return false;
// var defs
readDefs();
// cache hit
return true;
}
void Cacher::writeBitcode(const string &path) {
Module *module = modDef->rep;
std::string Err;
unsigned OpenFlags = 0;
OpenFlags |= raw_fd_ostream::F_Binary;
tool_output_file *FDOut = new tool_output_file(path.c_str(),
Err,
OpenFlags);
if (!Err.empty()) {
cerr << Err << '\n';
delete FDOut;
return;
}
{
formatted_raw_ostream FOS(FDOut->os());
// llvm bitcode
WriteBitcodeToFile(module, FOS);
}
// note FOS needs to destruct before we can keep
FDOut->keep();
delete FDOut;
}
void Cacher::resolveStructs(llvm::Module *module) {
// resolve duplicate structs to those already existing in our type
// system. this solves issues when using separate bitcode modules
// without using the llvm linker
StructResolver resolver(module);
// first we get the list we have to resolve
// then we lookup the canonical version of each one to create
// the map
StructResolver::StructMapType typeMap;
StructResolver::StructListType dSet = resolver.getDisjointStructs();
for (StructResolver::StructListType::iterator i = dSet.begin();
i != dSet.end(); ++i) {
int pos = i->first.rfind(".");
string canonical = i->first.substr(0, pos);
// XXX big hack. meta's are created implicitly by class defs, so their
// corresponding class defs have to come first in this list else the
// metas won't exist in resolveType. defer them?
if (canonical.find("meta") != string::npos) {
//cout << "XXXXXXXXX skipping meta: " << canonical << "\n";
continue;
}
TypeDefPtr td = resolveType(canonical);
BTypeDef *bt = dynamic_cast<BTypeDef *>(td.get());
assert(bt);
// we want to map the struct (the ContainedType), not the pointer to it
PointerType *a = dyn_cast<PointerType>(bt->rep);
assert(a && "expected a PointerType");
// most classes are single indirection pointers-to-struct, but we have
// to special case VTableBase which is **
if (canonical == ".builtin.VTableBase") {
a = cast<PointerType>(a->getElementType());
}
StructType *left = dyn_cast<StructType>(i->second);
assert(left);
StructType *right = dyn_cast<StructType>(a->getElementType());
assert(right);
assert(left != right);
//cout << "struct map [" << left->getName().str() << "] to [" << right->getName().str() << "]\n";
typeMap[i->second] = a->getElementType();
}
// finally, we resolve using our map. this replaces all instances of
// the conflicting type from this module, with the original one actually
// in our type system
if (!typeMap.empty())
resolver.run(&typeMap);
else
cout << "resolveStructs: typemap was empty\n";
}
Cacher::Cacher(model::Context &c, builder::BuilderOptions *o,
BModuleDef *m
) :
modDef(m),
parentContext(c),
options(o) {
}
BModuleDefPtr Cacher::maybeLoadFromCache(const string &canonicalName) {
// create a builder and module context
builder =
LLVMBuilderPtr::rcast(parentContext.builder.createChildBuilder());
context = new Context(*builder, Context::module, &parentContext,
new GlobalNamespace(parentContext.ns.get(),
canonicalName
),
0 // no compile namespace necessary
);
context->toplevel = true;
string cacheFile = getCacheFilePath(options, canonicalName, "bc");
if (cacheFile.empty())
return NULL;
if (options->verbosity >= 2)
cerr << "[" << canonicalName << "] cache: maybeLoad "
<< cacheFile << endl;
OwningPtr<MemoryBuffer> fileBuf;
if (error_code ec = MemoryBuffer::getFile(cacheFile.c_str(), fileBuf)) {
if (options->verbosity >= 2)
cerr << "[" << canonicalName <<
"] cache: not cached or inaccessible" << endl;
return NULL;
}
string errMsg;
Module *module = getLazyBitcodeModule(fileBuf.take(),
getGlobalContext(),
&errMsg);
if (!module) {
fileBuf.reset();
if (options->verbosity >= 1)
cerr << "[" << canonicalName <<
"] cache: exists but unable to load bitcode" << endl;
return NULL;
}
// if we get here, we've loaded bitcode successfully
modDef = builder->instantiateModule(*context, canonicalName, module);
builder->module = module;
if (readMetadata()) {
// after reading our metadata and defining types, we
// resolve all disjoint structs from our bitcode to those
// already in the crack type system
resolveStructs(module);
// cache hit
if (options->verbosity >= 2)
cerr << "[" << canonicalName <<
"] cache materialized" << endl;
}
else {
// during meta data read, we determined we will miss
// ensure any named structs from the module that we miss on do not
// remain in the llvm context struct namespace
// XXX is this necessary? a module delete doesn't appear to affect
// the llvmcontext
vector<StructType*> namedStructs;
module->findUsedStructTypes(namedStructs);
for (int i=0; i < namedStructs.size(); ++i) {
if (namedStructs[i]->hasName())
namedStructs[i]->setName("");
}
}
return modDef;
}
void Cacher::saveToCache() {
// we can reuse the existing context and builder for this
context = &parentContext;
builder = LLVMBuilderPtr::cast(&parentContext.builder);
assert(modDef && "empty modDef for saveToCache");
// XXX These are the kinds of modules that get excluded by virtue of this
// logic:
// - internals (crack.compiler)
// - implicit parent modules (directories containing modules)
// - stub modules for shared libraries
// in all cases, we should probably be caching them.
// XXX modDef->sourcePath should be a relative path, not absolute. That
// means we need to search the library path for it.
if (modDef->sourcePath.empty() || Construct::isDir(modDef->sourcePath))
return;
string cacheFile = getCacheFilePath(options, modDef->getFullName(), "bc");
if (cacheFile.empty()) {
if (options->verbosity >= 1)
cerr << "unable to find writable directory for cache, won't cache: "
<< modDef->sourcePath
<< endl;
return;
}
if (options->verbosity >= 2)
cerr << "[" << modDef->getFullName() << "] cache: saved from "
<< modDef->sourcePath
<< " to file: " << cacheFile << endl;
// digest the source file
modDef->digest = SourceDigest::fromFile(modDef->sourcePath);
writeMetadata();
writeBitcode(cacheFile);
}
| C++ |
// Copyright 2011 Google Inc
#include "BModuleDef.h"
#include "model/EphemeralImportDef.h"
using namespace model;
using namespace builder::mvll;
void BModuleDef::recordDependency(ModuleDef *other) {
// quit if the dependency already is recorded
for (VarDefVec::iterator depi = orderedForCache.begin();
depi != orderedForCache.end();
++depi
) {
EphemeralImportDef *modDef;
if ((modDef = EphemeralImportDefPtr::rcast(*depi)) &&
modDef->module == other
)
return;
}
EphemeralImportDefPtr def = new EphemeralImportDef(other);
def->setOwner(this);
orderedForCache.push_back(def.get());
} | C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_llvm_Consts_h_
#define _builder_llvm_Consts_h_
#include "model/StrConst.h"
#include "model/IntConst.h"
#include "model/FloatConst.h"
#include <string>
namespace llvm {
class Value;
class Module;
}
namespace model {
class TypeDef;
}
namespace builder {
namespace mvll {
class BTypeDef;
SPUG_RCPTR(BStrConst);
class BStrConst : public model::StrConst {
public:
// XXX need more specific type?
llvm::Value *rep;
llvm::Module *module;
BStrConst(model::TypeDef *type, const std::string &val);
};
class BIntConst : public model::IntConst {
public:
llvm::Value *rep;
BIntConst(BTypeDef *type, int64_t val);
BIntConst(BTypeDef *type, uint64_t val);
virtual model::IntConstPtr create(int64_t val);
virtual model::IntConstPtr create(uint64_t val);
};
class BFloatConst : public model::FloatConst {
public:
llvm::Value *rep;
BFloatConst(BTypeDef *type, double val);
virtual model::FloatConstPtr create(double val) const;
};
} // end namespace builder::vmll
} // end namespace builder
#endif
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#include "BFuncDef.h"
#include "BTypeDef.h"
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/GlobalVariable.h>
#include <llvm/Module.h>
#include "model/Context.h"
#include "model/OverloadDef.h"
#include "PlaceholderInstruction.h"
#include "VTableBuilder.h"
using namespace model;
using namespace std;
using namespace builder::mvll;
using namespace llvm;
void BTypeDef::getDependents(std::vector<TypeDefPtr> &deps) {
for (IncompleteChildVec::iterator iter = incompleteChildren.begin();
iter != incompleteChildren.end();
++iter
)
deps.push_back(iter->first);
}
// add all of my virtual functions to 'vtb'
void BTypeDef::extendVTables(VTableBuilder &vtb) {
// find all of the virtual functions
for (Namespace::VarDefMap::iterator varIter = beginDefs();
varIter != endDefs();
++varIter
) {
BFuncDef *funcDef = BFuncDefPtr::rcast(varIter->second);
if (funcDef && (funcDef->flags & FuncDef::virtualized)) {
vtb.add(funcDef);
continue;
}
// check for an overload (if it's not an overload, assume that
// it's not a function). Iterate over all of the overloads at
// the top level - the parent classes have
// already had their shot at extendVTables, and we don't want
// their overloads to clobber ours.
OverloadDef *overload =
OverloadDefPtr::rcast(varIter->second);
if (overload)
for (OverloadDef::FuncList::iterator fiter =
overload->beginTopFuncs();
fiter != overload->endTopFuncs();
++fiter
)
if ((*fiter)->flags & FuncDef::virtualized)
vtb.add(BFuncDefPtr::arcast(*fiter));
}
}
/**
* Create all of the vtables for 'type'.
*
* @param vtb the vtable builder
* @param name the name stem for the VTable global variables.
* @param vtableBaseType the global vtable base type.
* @param firstVTable if true, we have not yet discovered the first
* vtable in the class schema.
*/
void BTypeDef::createAllVTables(VTableBuilder &vtb, const string &name,
bool firstVTable
) {
// if this is VTableBase, we need to create the VTable.
// This is a special case: we should only get here when
// initializing VTableBase's own vtable.
if (this == vtb.vtableBaseType)
vtb.createVTable(this, name, true);
// iterate over the base classes, construct VTables for all
// ancestors that require them.
for (TypeVec::iterator baseIter = parents.begin();
baseIter != parents.end();
++baseIter
) {
BTypeDef *base = BTypeDefPtr::arcast(*baseIter);
// if the base class is VTableBase, we've hit bottom -
// construct the initial vtable and store the first vtable
// type if this is it.
if (base == vtb.vtableBaseType) {
vtb.createVTable(this, name, firstVTable);
// otherwise, if the base has a vtable, create all of its
// vtables
} else if (base->hasVTable) {
if (firstVTable)
base->createAllVTables(vtb, name, firstVTable);
else
base->createAllVTables(vtb,
name + ':' + base->getFullName(),
firstVTable
);
}
firstVTable = false;
}
// we must either have ancestors with vtables or be vtable base.
assert(!firstVTable || this == vtb.vtableBaseType);
// add my functions to their vtables
extendVTables(vtb);
}
void BTypeDef::addBaseClass(BTypeDef *base) {
++fieldCount;
parents.push_back(base);
if (base->hasVTable)
hasVTable = true;
}
void BTypeDef::addPlaceholder(PlaceholderInstruction *inst) {
assert(!complete && "Adding placeholder to a completed class");
placeholders.push_back(inst);
}
BTypeDef *BTypeDef::findFirstVTable(BTypeDef *vtableBaseType) {
// special case - if this is VTableBase, it is its own first vtable
// (normally it is the first class to derive from VTableBase that is the
// first vtable).
if (this == vtableBaseType)
return this;
// check the parents
for (TypeVec::iterator parent = parents.begin();
parent != parents.end();
++parent
)
if (parent->get() == vtableBaseType) {
return this;
} else if ((*parent)->hasVTable) {
BTypeDef *par = BTypeDefPtr::arcast(*parent);
return par->findFirstVTable(vtableBaseType);
}
cerr << "class is " << name << endl;
assert(false && "Failed to find first vtable");
}
GlobalVariable *BTypeDef::getClassInstRep(Module *module,
ExecutionEngine *execEng
) {
if (classInst->getParent() == module) {
return classInst;
} else {
GlobalVariable *gvar =
cast<GlobalVariable>(
module->getGlobalVariable(classInst->getName())
);
if (!gvar) {
gvar = new GlobalVariable(*module, classInst->getType(),
true, // is constant
GlobalValue::ExternalLinkage,
0, // initializer: null for externs
classInst->getName()
);
// if there's an execution engine, do the pointer hookup
if (execEng) {
void *p = execEng->getPointerToGlobal(classInst);
execEng->addGlobalMapping(gvar, p);
}
}
return gvar;
}
}
void BTypeDef::addDependent(BTypeDef *type, Context *context) {
incompleteChildren.push_back(pair<BTypeDefPtr, ContextPtr>(type, context));
}
void BTypeDef::fixIncompletes(Context &context) {
// construct the vtable if necessary
if (hasVTable) {
VTableBuilder vtableBuilder(
dynamic_cast<LLVMBuilder*>(&context.builder),
BTypeDefPtr::arcast(context.construct->vtableBaseType)
);
createAllVTables(
vtableBuilder,
".vtable." + context.parent->ns->getNamespaceName() + "." + name
);
vtableBuilder.emit(this);
}
// fix-up all of the placeholder instructions
for (vector<PlaceholderInstruction *>::iterator iter =
placeholders.begin();
iter != placeholders.end();
++iter
)
(*iter)->fix();
placeholders.clear();
// fix up all incomplete children
for (IncompleteChildVec::iterator iter = incompleteChildren.begin();
iter != incompleteChildren.end();
++iter
)
iter->first->fixIncompletes(*iter->second);
incompleteChildren.clear();
complete = true;
}
| C++ |
// Copyright 2009 Google Inc.
#ifndef _builder_LLVMBuilder_h_
#define _builder_LLVMBuilder_h_
#include <map>
#include <llvm/Support/IRBuilder.h>
#include "builder/Builder.h"
#include "BTypeDef.h"
#include "BBuilderContextData.h"
namespace llvm {
class Module;
class Function;
class BasicBlock;
class Type;
class Value;
class Function;
};
namespace builder {
namespace mvll {
SPUG_RCPTR(BHeapVarDefImpl);
class DebugInfo;
class FuncBuilder;
class BModuleDef;
SPUG_RCPTR(LLVMBuilder);
class LLVMBuilder : public Builder {
protected:
llvm::Function *callocFunc;
DebugInfo *debugInfo;
BTypeDefPtr exStructType;
// emit all cleanups for context and all parent contextts up to the
// level of the function
void emitFunctionCleanups(model::Context &context);
// stores primitive function pointers
std::map<llvm::Function *, void *> primFuncs;
LLVMBuilderPtr rootBuilder;
BTypeDef *getExStructType() {
if (rootBuilder)
return rootBuilder->exStructType.get();
else
return exStructType.get();
}
/**
* Creates a new LLVM module and initializes all of the exception
* handling declarations that need to be present. Assigns the
* 'module' instance variable to the new module.
*/
void createLLVMModule(const std::string &name);
void initializeMethodInfo(model::Context &context,
model::FuncDef::Flags flags,
model::FuncDef *existing,
BTypeDef *&classType,
FuncBuilder &funcBuilder
);
/**
* JIT builder uses this to map GlobalValue* to their JITed versions,
* Linked builder ignores this, as these are resolved during the link
* instead. It is called from getModFunc and getModVar
*/
virtual void addGlobalFuncMapping(llvm::Function*,
llvm::Function*) { }
virtual void addGlobalFuncMapping(llvm::Function*,
void*) { }
/**
* possibly bind the module to an execution engine
* called in base llvmbuilder only from registerPrimFuncs
*/
virtual void engineBindModule(BModuleDef *moduleDef) { }
/**
* let the engine "finish" a module before running/linking/dumping
* called in base llvmbuilder only from registerPrimFuncs
*/
virtual void engineFinishModule(BModuleDef *moduleDef) { }
/**
* common module initialization that happens in all builders
* during createModule. includes some functions that need to be
* defined in each module.
*/
void createModuleCommon(model::Context &context);
/**
* common module initialization that happens in all builders
* during initializeImport
*/
void initializeImportCommon(model::ModuleDef* m,
const model::ImportedDefVec &symbols
);
/**
* get a realpath source path for the module
*/
std::string getSourcePath(const std::string &path);
/**
* Gets the first unwind block for the context, emitting the whole
* cleanup chain if necessary.
*/
llvm::BasicBlock *getUnwindBlock(model::Context &context);
/**
* Clears all cached cleanup blocks associated with the context (this
* exists to deal with the module level init and delete functions,
* which both run against the module context).
*/
void clearCachedCleanups(model::Context &context);
/** Creates special hidden variables used by the generated code. */
void createSpecialVar(model::Namespace *ns, model::TypeDef *type,
const std::string &name
);
/** Creates the "start blocks" for the current function. */
void createFuncStartBlocks(const std::string &name);
/**
* Create a following block and cleanup block for an Invoke
* instruction given the context.
*/
void getInvokeBlocks(model::Context &context,
llvm::BasicBlock *&followingBlock,
llvm::BasicBlock *&cleanupBlock
);
/**
* Insures that the class body global is present in the current module.
*/
virtual void fixClassInstRep(BTypeDef *type) = 0;
public:
// currently experimenting with making these public to give objects in
// LLVMBuilder.cc's anonymous internal namespace access to them. It
// seems to be cutting down on the amount of code necessary to do this.
BModuleDef *bModDef;
llvm::Module *module;
llvm::Function *func;
llvm::Type *llvmVoidPtrType;
llvm::IRBuilder<> builder;
llvm::Value *lastValue;
llvm::BasicBlock *funcBlock;
llvm::Function *exceptionPersonalityFunc;
// keeps track of the Function object for the FuncDef in the builder's
// module.
typedef std::map<model::FuncDef *, llvm::Function *> ModFuncMap;
ModFuncMap moduleFuncs;
// keeps track of the GlobalVariable object for the VarDef in the
// builder's module.
typedef std::map<model::VarDefImpl *, llvm::GlobalVariable *> ModVarMap;
ModVarMap moduleVars;
static int argc;
static char **argv;
// the list of types that need to be fixed when the meta-class has
// been defined.
std::vector<BTypeDefPtr> deferMetaClass;
/**
* Instantiates the BModuleDef subclass appropriate for the builder.
*/
virtual BModuleDef *instantiateModule(model::Context &context,
const std::string &name,
llvm::Module *module
);
/**
* Returns true if cleanups should be suppressed (i.e. after a throw)
*/
bool suppressCleanups();
void narrow(model::TypeDef *curType, model::TypeDef *ancestor);
void setModFunc(model::FuncDef *funcDef, llvm::Function *func) {
moduleFuncs[funcDef] = func;
}
llvm::Function *getModFunc(model::FuncDef *funcDef,
llvm::Function *funcRep);
void setModVar(model::VarDefImpl *varDef, llvm::GlobalVariable *var) {
moduleVars[varDef] = var;
}
llvm::GlobalVariable *getModVar(model::VarDefImpl *varDef,
llvm::GlobalVariable *gvar
);
BTypeDefPtr getFuncType(model::Context &context,
model::FuncDef *funcDef,
llvm::Type *llvmFuncType
);
BHeapVarDefImplPtr createLocalVar(BTypeDef *tp, llvm::Value *&var,
llvm::Value *initVal = 0
);
BTypeDefPtr createClass(model::Context &context,
const std::string &name,
unsigned int nextVTableSlot
);
virtual void *getFuncAddr(llvm::Function *func) = 0;
/** Creates an expresion to cleanup the current exception. */
void emitExceptionCleanupExpr(model::Context &context);
/**
* Create a landing pad block.
* @param next the block after the landing pad
* @param cdata catch data or null if this is not a catch context.
*/
llvm:: BasicBlock *createLandingPad(
model::Context &context,
llvm::BasicBlock *next,
BBuilderContextData::CatchData *cdata
);
virtual void addGlobalVarMapping(llvm::GlobalValue *decl,
llvm::GlobalValue *externalDef
) {
}
LLVMBuilder();
virtual model::ResultExprPtr emitFuncCall(
model::Context &context,
model::FuncCall *funcCall
);
virtual model::ResultExprPtr emitStrConst(model::Context &context,
model::StrConst *strConst
);
virtual model::ResultExprPtr emitIntConst(model::Context &context,
model::IntConst *val
);
virtual model::ResultExprPtr emitFloatConst(model::Context &context,
model::FloatConst *val
);
virtual model::ResultExprPtr emitNull(model::Context &context,
model::NullConst *nullExpr
);
virtual model::ResultExprPtr emitAlloc(model::Context &context,
model::AllocExpr *allocExpr,
model::Expr *countExpr
);
virtual void emitTest(model::Context &context,
model::Expr *expr
);
virtual model::BranchpointPtr emitIf(model::Context &context,
model::Expr *cond);
model::BranchpointPtr labeledIf(model::Context &context,
model::Expr *cond,
const char* tLabel=0,
const char* fLabel=0,
bool condInCleanupFrame=true
);
virtual model::BranchpointPtr
emitElse(model::Context &context,
model::Branchpoint *pos,
bool terminal
);
virtual void emitEndIf(model::Context &context,
model::Branchpoint *pos,
bool terminal
);
virtual model::TernaryExprPtr createTernary(model::Context &context,
model::Expr *cond,
model::Expr *trueVal,
model::Expr *falseVal,
model::TypeDef *type
);
virtual model::ResultExprPtr emitTernary(model::Context &context,
model::TernaryExpr *expr
);
virtual model::BranchpointPtr
emitBeginWhile(model::Context &context,
model::Expr *cond,
bool gotPostBlock
);
virtual void emitEndWhile(model::Context &context,
model::Branchpoint *pos,
bool isTerminal
);
virtual void emitPostLoop(model::Context &context,
model::Branchpoint *pos,
bool isTerminal
);
virtual void emitBreak(model::Context &context,
model::Branchpoint *branch
);
virtual void emitContinue(model::Context &context,
model::Branchpoint *branch
);
virtual model::BranchpointPtr emitBeginTry(model::Context &context);
virtual model::ExprPtr emitCatch(model::Context &context,
model::Branchpoint *branchpoint,
model::TypeDef *catchType,
bool terminal
);
virtual void emitEndTry(model::Context &context,
model::Branchpoint *branchpoint,
bool terminal
);
virtual void emitExceptionCleanup(model::Context &context);
virtual void emitThrow(model::Context &context,
model::Expr *expr
);
virtual model::FuncDefPtr
createFuncForward(model::Context &context,
model::FuncDef::Flags flags,
const std::string &name,
model::TypeDef *returnType,
const std::vector<model::ArgDefPtr> &args,
model::FuncDef *override
);
virtual model::TypeDefPtr
createClassForward(model::Context &context,
const std::string &name
);
virtual model::FuncDefPtr
emitBeginFunc(model::Context &context,
model::FuncDef::Flags flags,
const std::string &name,
model::TypeDef *returnType,
const std::vector<model::ArgDefPtr> &args,
model::FuncDef *existing
);
virtual void emitEndFunc(model::Context &context,
model::FuncDef *funcDef);
virtual model::FuncDefPtr
createExternFunc(model::Context &context,
model::FuncDef::Flags flags,
const std::string &name,
model::TypeDef *returnType,
model::TypeDef *receiverType,
const std::vector<model::ArgDefPtr> &args,
void *cfunc,
const char *symbolName=0
);
virtual model::TypeDefPtr
emitBeginClass(model::Context &context,
const std::string &name,
const std::vector<model::TypeDefPtr> &bases,
model::TypeDef *forwardDef
);
virtual void emitEndClass(model::Context &context);
virtual void emitReturn(model::Context &context,
model::Expr *expr);
virtual model::VarDefPtr emitVarDef(model::Context &container,
model::TypeDef *type,
const std::string &name,
model::Expr *initializer,
bool staticScope
);
virtual model::VarDefPtr createOffsetField(model::Context &context,
model::TypeDef *type,
const std::string &name,
size_t offset
);
// for definitions, we're going to just let the builder be a factory
// so that it can tie whatever special information it wants to the
// definition.
virtual model::FuncCallPtr
createFuncCall(model::FuncDef *func, bool squashVirtual);
virtual model::ArgDefPtr createArgDef(model::TypeDef *type,
const std::string &name
);
virtual model::VarRefPtr createVarRef(model::VarDef *varDef);
virtual model::VarRefPtr
createFieldRef(model::Expr *aggregate,
model::VarDef *varDef
);
virtual model::ResultExprPtr emitFieldAssign(model::Context &context,
model::Expr *aggregate,
model::AssignExpr *assign
);
virtual model::CleanupFramePtr
createCleanupFrame(model::Context &context);
virtual void closeAllCleanups(model::Context &context);
virtual model::StrConstPtr createStrConst(model::Context &context,
const std::string &val);
virtual model::IntConstPtr createIntConst(model::Context &context,
int64_t val,
model::TypeDef *type = 0
);
virtual model::IntConstPtr createUIntConst(model::Context &context,
uint64_t val,
model::TypeDef *type = 0
);
virtual model::FloatConstPtr createFloatConst(model::Context &context,
double val,
model::TypeDef *type = 0
);
virtual model::ModuleDefPtr registerPrimFuncs(model::Context &context);
virtual void *loadSharedLibrary(const std::string &name);
virtual void importSharedLibrary(const std::string &name,
const model::ImportedDefVec &symbols,
model::Context &context,
model::Namespace *ns
);
virtual void registerImportedDef(model::Context &context,
model::VarDef *varDef
);
// used by Cacher for maintaining a global (cross module)
// cache map of vardefs. this is not part of the base Builder
// interface
virtual void registerDef(model::Context &context,
model::VarDef *varDef
) { }
virtual void setArgv(int argc, char **argv);
// internal functions used by our VarDefImpl to generate the
// appropriate variable references.
void emitMemVarRef(model::Context &context, llvm::Value *val);
void emitArgVarRef(model::Context &context, llvm::Value *val);
// XXX hack to emit all vtable initializers until we get constructor
// composition.
virtual void emitVTableInit(model::Context &context,
model::TypeDef *typeDef
);
};
} // namespace builder::mvll
} // namespace builder
#endif
| C++ |
// Copyright 2011 Google Inc.
#include "BBuilderContextData.h"
#include <llvm/BasicBlock.h>
#include <llvm/Function.h>
#include <llvm/GlobalVariable.h>
#include <llvm/Intrinsics.h>
#include <llvm/LLVMContext.h>
#include <llvm/Module.h>
#include <llvm/Support/IRBuilder.h>
#include "model/Expr.h"
#include "BTypeDef.h"
#include "Incompletes.h"
#include "VarDefs.h"
using namespace std;
using namespace llvm;
using namespace builder::mvll;
using namespace model;
Value *
BBuilderContextData::getExceptionLandingPadResult(IRBuilder<> &builder) {
VarDefPtr exStructVar = context->ns->lookUp(":exStruct");
BHeapVarDefImplPtr exStructImpl =
BHeapVarDefImplPtr::rcast(exStructVar->impl);
return
builder.CreateLoad(builder.CreateConstGEP2_32(exStructImpl->rep, 0, 0));
}
BasicBlock *BBuilderContextData::getUnwindBlock(Function *func) {
if (!unwindBlock) {
unwindBlock = BasicBlock::Create(getGlobalContext(), "unwind", func);
IRBuilder<> b(unwindBlock);
Module *mod = func->getParent();
Function *f = mod->getFunction("__CrackExceptionFrame");
if (f)
b.CreateCall(f);
// create the resume instruction
Value *exObj = getExceptionLandingPadResult(b);
// XXX We used to create an "unwind" instruction here, but that seems
// to cause a problem when creating a module with dependencies on
// classes in an unfinished module, as we can do when specializing a
// generic. The problem is that _Unwind_Resume is resolved from the
// incorrect module.
// To deal with this, we create an explicit call to _Unwind_Resume.
// The only problem here is that we have to call llvm.eh.exception to
// obtain the exception object, even though we might already have one.
LLVMContext &lctx = getGlobalContext();
Constant *c = mod->getOrInsertFunction("_Unwind_Resume",
Type::getVoidTy(lctx),
Type::getInt8PtrTy(lctx),
NULL
);
f = cast<Function>(c);
b.CreateCall(f, exObj);
b.CreateUnreachable();
}
// assertion to make sure this is the right unwind block
if (unwindBlock->getParent() != func) {
string bdataFunc = unwindBlock->getParent()->getName();
string curFunc = func->getName();
cerr << "bad function for unwind block, got " <<
bdataFunc << " expected " << curFunc << endl;
assert(false);
}
return unwindBlock;
}
void BBuilderContextData::CatchData::populateClassImpls(
vector<Value *> &values,
Module *module
) {
for (int i = 0; i < catches.size(); ++i)
values.push_back(catches[i].type->getClassInstRep(module, 0));
}
void BBuilderContextData::CatchData::fixAllSelectors(Module *module) {
// fix all of the incomplete selector functions now that we have all of
// the catch clauses.
for (vector<IncompleteCatchSelector *>::iterator iter = selectors.begin();
iter != selectors.end();
++iter
) {
// get all of the class implementation objects into a Value vector
vector<Value *> typeImpls;
populateClassImpls(typeImpls, module);
// fix the incomplete selector
(*iter)->typeImpls = &typeImpls;
(*iter)->fix();
}
// fix the switch instruction
Type *int32Ty = Type::getInt32Ty(getGlobalContext());
for (int i = 0; i < catches.size(); ++i) {
ConstantInt *index =
cast<ConstantInt>(ConstantInt::get(int32Ty, i + 1));
switchInst->addCase(index, catches[i].block);
}
// do the same for all nested try/catches
for (int childIndex = 0; childIndex < nested.size(); ++childIndex) {
CatchData &child = *nested[childIndex];
// add all of the branches from the parent that the child won't already
// catch
vector<CatchBranch> catchesToAdd;
for (int i = 0; i < catches.size(); ++i) {
CatchBranch &branch = catches[i];
for (int j = 0; j < child.catches.size(); ++j)
if (!branch.type->isDerivedFrom(child.catches[j].type.get()))
catchesToAdd.push_back(branch);
for (int j = 0; j < catchesToAdd.size(); ++j)
child.catches.push_back(catchesToAdd[j]);
}
// fix all of the selectors in the child
child.fixAllSelectors(module);
}
}
| C++ |
// Copyright 2010 Google Inc.
#ifndef _builder_llvm_PlaceholderInstruction_h_
#define _builder_llvm_PlaceholderInstruction_h_
#include <llvm/Instruction.h>
#include <llvm/Support/IRBuilder.h>
namespace builder { namespace mvll {
/**
* This is a special instruction that serves as a placeholder for
* operations where we dereference incomplete types. These get stored in
* a block and subsequently replaced with a reference to the actual type.
*/
class PlaceholderInstruction : public llvm::Instruction {
public:
PlaceholderInstruction(llvm::Type *type,
llvm::BasicBlock *parent,
llvm::Use *ops = 0,
unsigned opCount = 0
) :
Instruction(type, OtherOpsEnd + 1, ops, opCount, parent) {
}
PlaceholderInstruction(llvm::Type *type,
llvm::Instruction *insertBefore = 0,
llvm::Use *ops = 0,
unsigned opCount = 0
) :
Instruction(type, OtherOpsEnd + 1, ops, opCount,
insertBefore
) {
}
/** Replace the placeholder with a real instruction. */
void fix();
virtual void insertInstructions(llvm::IRBuilder<> &builder) = 0;
};
}} // namespace builder::mvll
#endif
| C++ |
// Copyright 2011 Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_llvm_Cacher_h_
#define _builder_llvm_Cacher_h_
#include "model/Context.h"
#include <string>
#include <vector>
#include <map>
namespace llvm {
class Module;
class MDNode;
class Value;
class Function;
}
namespace model {
class Namespace;
class TypeDef;
class VarDef;
}
namespace builder {
class BuilderOptions;
namespace mvll {
SPUG_RCPTR(BModuleDef);
SPUG_RCPTR(BTypeDef);
SPUG_RCPTR(LLVMBuilder);
class Cacher {
static const std::string MD_VERSION;
enum DefTypes {
global = 0,
function,
member,
method,
type,
constant,
generic,
ephemeralImport
};
BModuleDefPtr modDef;
model::ContextPtr context;
model::Context &parentContext;
builder::BuilderOptions *options;
builder::mvll::LLVMBuilderPtr builder;
// vardefs which were created as a result of shared lib import
// we skip these in crack_defs
std::map<std::string, bool> shlibImported;
protected:
void addNamedStringNode(const std::string &key, const std::string &val);
std::string getNamedStringNode(const std::string &key);
void writeNamespace(model::Namespace* ns);
llvm::MDNode *writeTypeDef(model::TypeDef* t);
llvm::MDNode *writeConstant(model::VarDef *, model::TypeDef *owner);
llvm::MDNode *writeVarDef(model::VarDef *, model::TypeDef *owner);
llvm::MDNode *writeFuncDef(model::FuncDef *, model::TypeDef *owner);
llvm::MDNode *writeEphemeralImport(BModuleDef *mod);
void readConstant(const std::string &, llvm::Value *, llvm::MDNode *);
void readVarDefMember(const std::string &, llvm::Value *, llvm::MDNode *);
model::TypeDefPtr resolveType(const std::string &name);
void readVarDefGlobal(const std::string &, llvm::Value *, llvm::MDNode *);
void readFuncDef(const std::string &, llvm::Value *, llvm::MDNode *);
BTypeDefPtr readMetaType(llvm::MDNode *mnode);
void finishType(model::TypeDef *type, BTypeDef *metaType,
model::NamespacePtr owner);
void readTypeDef(const std::string &, llvm::Value *, llvm::MDNode *);
void readGenericTypeDef(const std::string &, llvm::Value *, llvm::MDNode *);
void readEphemeralImport(llvm::MDNode *mnode);
void resolveStructs(llvm::Module *);
void writeBitcode(const std::string &path);
bool readImports();
void readDefs();
void writeMetadata();
bool readMetadata();
public:
Cacher(model::Context &c, builder::BuilderOptions *o,
BModuleDef *m = NULL
);
llvm::Function *getEntryFunction();
void getExterns(std::vector<std::string> &symList);
BModuleDefPtr maybeLoadFromCache(const std::string &canonicalName);
void saveToCache();
};
} // end namespace builder::vmll
} // end namespace builder
#endif
| C++ |
// Copyright 2009-2011 Google Inc., Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_LLVMLinkerBuilder_h_
#define _builder_LLVMLinkerBuilder_h_
#include "LLVMBuilder.h"
#include <vector>
namespace llvm {
class Linker;
class BasicBlock;
}
namespace builder {
namespace mvll {
class BModuleDef;
SPUG_RCPTR(LLVMLinkerBuilder);
class LLVMLinkerBuilder : public LLVMBuilder {
private:
typedef std::vector<builder::mvll::BModuleDef *> ModuleListType;
llvm::Linker *linker;
ModuleListType *moduleList;
llvm::BasicBlock *mainInsert;
std::vector<std::string> sharedLibs;
ModuleListType *addModule(BModuleDef *mp);
llvm::Function *emitAggregateCleanup(llvm::Module *module);
protected:
virtual void engineFinishModule(BModuleDef *moduleDef);
virtual void fixClassInstRep(BTypeDef *type);
public:
LLVMLinkerBuilder(void) : linker(0),
moduleList(0),
mainInsert(0),
sharedLibs() { }
virtual void *getFuncAddr(llvm::Function *func);
virtual void finishBuild(model::Context &context);
virtual BuilderPtr createChildBuilder();
virtual model::ModuleDefPtr createModule(model::Context &context,
const std::string &name,
const std::string &path,
model::ModuleDef *owner
);
virtual void initializeImport(model::ModuleDef*,
const model::ImportedDefVec &symbols,
bool annotation);
virtual void *loadSharedLibrary(const std::string &name);
virtual void closeModule(model::Context &context,
model::ModuleDef *module
);
virtual bool isExec() { return false; }
virtual model::ModuleDefPtr materializeModule(
model::Context &context,
const std::string &canonicalName,
model::ModuleDef *owner
);
};
} } // namespace
#endif
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#include "BFuncDef.h"
#include "model/Context.h"
#include "builder/llvm/LLVMBuilder.h"
#include <string>
#include <llvm/Function.h>
using namespace builder::mvll;
void BFuncDef::setOwner(model::Namespace *o) {
owner = o;
fullName.clear();
// if an overridden symbolName isn't set, we use the canonical name
if (symbolName.empty())
rep->setName(getFullName());
}
llvm::Function * BFuncDef::getRep(LLVMBuilder &builder) {
// load the function for the correct module, but not for abstract methods
// (that would result in an "extern" method for an abstract method, which
// is an unresolved external)
if (!(flags & FuncDef::abstract) && rep->getParent() != builder.module)
return builder.getModFunc(this, rep);
else
return rep;
}
// only used for annotation functions
void *BFuncDef::getFuncAddr(Builder &builder) {
LLVMBuilder &b = dynamic_cast<LLVMBuilder&>(builder);
return b.getFuncAddr(getRep(b));
}
| C++ |
// Copyright 2011 Google Inc
#include "LLVMValueExpr.h"
#include "model/Context.h"
#include "BResultExpr.h"
#include "LLVMBuilder.h"
using namespace model;
using namespace builder::mvll;
ResultExprPtr LLVMValueExpr::emit(Context &context) {
LLVMBuilder &builder = dynamic_cast<LLVMBuilder &>(context.builder);
builder.lastValue = value;
return new BResultExpr(this, value);
}
void LLVMValueExpr::writeTo(std::ostream &out) const {
out << "LLVMValueExpr(" << value << ")";
}
bool LLVMValueExpr::isProductive() const {
return false;
}
| C++ |
// Copyright 2011 Google Inc., Shannon Weyrick <weyrick@mozek.us>
#include "LLVMJitBuilder.h"
#include "BJitModuleDef.h"
#include "DebugInfo.h"
#include "BTypeDef.h"
#include "model/Context.h"
#include "FuncBuilder.h"
#include "Utils.h"
#include "BBuilderContextData.h"
#include "debug/DebugTools.h"
#include "Cacher.h"
#include "spug/check.h"
#include <llvm/LLVMContext.h>
#include <llvm/LinkAllPasses.h>
#include <llvm/Analysis/Verifier.h>
#include <llvm/PassManager.h>
#include <llvm/Target/TargetData.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Target/TargetOptions.h>
#include <llvm/Analysis/Verifier.h>
#include <llvm/Assembly/PrintModulePass.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/JIT.h> // link in the JIT
#include <llvm/Module.h>
#include <llvm/IntrinsicInst.h>
#include <llvm/Intrinsics.h>
#include <llvm/Support/Debug.h>
using namespace std;
using namespace llvm;
using namespace model;
using namespace builder;
using namespace builder::mvll;
ModuleDefPtr LLVMJitBuilder::registerPrimFuncs(model::Context &context) {
ModuleDefPtr mod = LLVMBuilder::registerPrimFuncs(context);
if (!options->cacheMode)
return mod;
BModuleDefPtr bMod = BModuleDefPtr::rcast(mod);
// if we're caching, register .builtin definitions in the cache
ensureCacheMap();
for (Module::iterator iter = module->begin();
iter != module->end();
++iter
) {
if (!iter->isDeclaration()) {
cacheMap->insert(CacheMapType::value_type(iter->getName().str(),
iter));
}
}
return bMod;
}
void LLVMJitBuilder::engineBindModule(BModuleDef *moduleDef) {
// note, this->module and moduleDef->rep should be ==
bindJitModule(moduleDef->rep);
if (options->dumpMode)
dump();
}
void LLVMJitBuilder::setupCleanup(BModuleDef *moduleDef) {
Function *delFunc = module->getFunction(":cleanup");
if (delFunc) {
void *addr = execEng->getPointerToFunction(delFunc);
SPUG_CHECK(addr, "Unable to resolve cleanup function");
moduleDef->cleanup = reinterpret_cast<void (*)()>(addr);
}
}
void LLVMJitBuilder::engineFinishModule(BModuleDef *moduleDef) {
// note, this->module and moduleDef->rep should be ==
// XXX right now, only checking for > 0, later perhaps we can
// run specific optimizations at different levels
if (options->optimizeLevel) {
// optimize
llvm::PassManager passMan;
// Set up the optimizer pipeline. Start with registering info about how
// the target lays out data structures.
passMan.add(new llvm::TargetData(*execEng->getTargetData()));
// Promote allocas to registers.
passMan.add(createPromoteMemoryToRegisterPass());
// Do simple "peephole" optimizations and bit-twiddling optzns.
passMan.add(llvm::createInstructionCombiningPass());
// Reassociate expressions.
passMan.add(llvm::createReassociatePass());
// Eliminate Common SubExpressions.
passMan.add(llvm::createGVNPass());
// Simplify the control flow graph (deleting unreachable blocks, etc).
passMan.add(llvm::createCFGSimplificationPass());
passMan.run(*moduleDef->rep);
}
setupCleanup(moduleDef);
// if we have a cacher, make sure that all globals are registered there.
if (options->cacheMode) {
// make sure we have a cache map
ensureCacheMap();
Module *module = moduleDef->rep;
for (Module::global_iterator iter = module->global_begin();
iter != module->global_end();
++iter
) {
if (cacheMap->find(iter->getName()) == cacheMap->end())
cacheMap->insert(CacheMapType::value_type(iter->getName(),
iter
)
);
}
}
// mark the module as finished
moduleDef->rep->getOrInsertNamedMetadata("crack_finished");
}
void LLVMJitBuilder::fixClassInstRep(BTypeDef *type) {
type->getClassInstRep(module, execEng);
}
BModuleDef *LLVMJitBuilder::instantiateModule(model::Context &context,
const std::string &name,
llvm::Module *owner
) {
return new BJitModuleDef(name, context.ns.get(), owner, 0);
}
ExecutionEngine *LLVMJitBuilder::bindJitModule(Module *mod) {
if (execEng) {
execEng->addModule(mod);
} else {
if (rootBuilder)
execEng = LLVMJitBuilderPtr::cast(rootBuilder.get())->bindJitModule(mod);
else {
llvm::JITEmitDebugInfo = true;
llvm::JITExceptionHandling = true;
// XXX only available in debug builds of llvm?
//if (options->verbosity > 3)
// llvm::DebugFlag = true;
// we have to specify all of the arguments for this so we can turn
// off "allocate globals with code." In addition to being
// deprecated in the docs for this function, this option causes
// seg-faults when we allocate globals under certain conditions.
InitializeNativeTarget();
execEng = ExecutionEngine::create(mod,
false, // force interpreter
0, // error string
CodeGenOpt::Default, // opt lvl
false // alloc globals with code
);
}
}
return execEng;
}
void LLVMJitBuilder::addGlobalFuncMapping(Function* pointer,
Function* real) {
// if the module containing the original function has been finished, just
// add the global mapping.
if (real->getParent()->getNamedMetadata("crack_finished")) {
void *realAddr = execEng->getPointerToFunction(real);
SPUG_CHECK(realAddr,
"no address for function " << string(real->getName()));
execEng->addGlobalMapping(pointer, realAddr);
} else {
// push this on the list of externals - we used to assign a global mapping
// for these right here, but that only works if we're guaranteed that an
// imported module is closed before any of its functions are used by the
// importer, and that is no longer the case after generics and ephemeral
// modules.
externals.push_back(pair<Function *, Function *>(pointer, real));
}
}
void LLVMJitBuilder::addGlobalFuncMapping(Function* pointer,
void* real) {
execEng->addGlobalMapping(pointer, real);
}
void LLVMJitBuilder::addGlobalVarMapping(GlobalValue* pointer,
GlobalValue* real) {
execEng->addGlobalMapping(pointer, execEng->getPointerToGlobal(real));
}
void *LLVMJitBuilder::getFuncAddr(llvm::Function *func) {
void *addr = execEng->getPointerToFunction(func);
SPUG_CHECK(addr,
"Unable to resolve function " << string(func->getName()));
return addr;
}
void LLVMJitBuilder::run() {
int (*fptr)() = (int (*)())execEng->getPointerToFunction(func);
SPUG_CHECK(fptr, "no address for function " << string(func->getName()));
fptr();
}
BuilderPtr LLVMJitBuilder::createChildBuilder() {
LLVMJitBuilder *result = new LLVMJitBuilder();
result->rootBuilder = rootBuilder ? rootBuilder : this;
result->llvmVoidPtrType = llvmVoidPtrType;
result->options = options;
return result;
}
ModuleDefPtr LLVMJitBuilder::createModule(Context &context,
const string &name,
const string &path,
ModuleDef *owner
) {
assert(!module);
LLVMContext &lctx = getGlobalContext();
createLLVMModule(name);
if (options->debugMode) {
debugInfo = new DebugInfo(module, name);
}
// create a context data object
BBuilderContextData::get(&context);
string mainFuncName = name + ":main";
llvm::Constant *c =
module->getOrInsertFunction(mainFuncName, Type::getVoidTy(lctx),
NULL
);
func = llvm::cast<llvm::Function>(c);
func->setCallingConv(llvm::CallingConv::C);
createFuncStartBlocks(mainFuncName);
createModuleCommon(context);
bindJitModule(module);
bModDef =
new BJitModuleDef(name, context.ns.get(), module,
owner ? BJitModuleDefPtr::acast(owner) : 0
);
bModDef->sourcePath = getSourcePath(path);
return bModDef;
}
void LLVMJitBuilder::cacheModule(Context &context, ModuleDef *mod) {
assert(BModuleDefPtr::cast(mod)->rep == module);
// encode main function location in bitcode metadata
vector<Value *> dList;
NamedMDNode *node;
node = module->getOrInsertNamedMetadata("crack_entry_func");
dList.push_back(func);
node->addOperand(MDNode::get(getGlobalContext(), dList));
Cacher c(context, context.construct->rootBuilder->options.get(),
BModuleDefPtr::cast(mod));
c.saveToCache();
}
void LLVMJitBuilder::innerCloseModule(Context &context, ModuleDef *moduleDef) {
// if there was a top-level throw, we could already have a terminator.
// Generate a return instruction if not.
if (!builder.GetInsertBlock()->getTerminator())
builder.CreateRetVoid();
// emit the cleanup function
// since the cleanups have to be emitted against the module context, clear
// the unwind blocks so we generate them for the del function.
clearCachedCleanups(context);
Function *mainFunc = func;
LLVMContext &lctx = getGlobalContext();
llvm::Constant *c =
module->getOrInsertFunction(":cleanup", Type::getVoidTy(lctx), NULL);
func = llvm::cast<llvm::Function>(c);
func->setCallingConv(llvm::CallingConv::C);
// create a new exStruct variable for this context
createFuncStartBlocks(":cleanup");
createSpecialVar(context.ns.get(), getExStructType(), ":exStruct");
closeAllCleanupsStatic(context);
builder.CreateRetVoid();
// restore the main function
func = mainFunc;
// work around for an LLVM bug: When doing one of its internal exception
// handling passes, LLVM can insert llvm.eh.exception() intrinsics with
// calls to an llvm.eh.exception() function that are not part of the
// module. So this loop replaces all such calls with the correct instance
// of the function.
Function *ehEx = getDeclaration(module, Intrinsic::eh_exception);
for (Module::iterator funcIter = module->begin(); funcIter != module->end();
++funcIter
)
for (Function::iterator block = funcIter->begin();
block != funcIter->end();
++block
)
for (BasicBlock::iterator inst = block->begin();
inst != block->end();
++inst
) {
IntrinsicInst *intrInst;
if ((intrInst = dyn_cast<IntrinsicInst>(inst)) &&
intrInst->getIntrinsicID() == Intrinsic::eh_exception &&
intrInst->getCalledFunction() != ehEx
)
intrInst->setCalledFunction(ehEx);
}
// XXX in the future, only verify if we're debugging
// if (debugInfo)
verifyModule(*module, llvm::PrintMessageAction);
// let jit or linker finish module before run/link
engineFinishModule(BModuleDefPtr::cast(moduleDef));
// store primitive functions from an extension
if (moduleDef->fromExtension) {
for (map<Function *, void *>::iterator iter = primFuncs.begin();
iter != primFuncs.end();
++iter)
addGlobalFuncMapping(iter->first, iter->second);
}
if (debugInfo)
delete debugInfo;
// resolve all externals
for (int i = 0; i < externals.size(); ++i) {
void *realAddr = execEng->getPointerToFunction(externals[i].second);
SPUG_CHECK(realAddr,
"no address for function " <<
string(externals[i].second->getName())
);
execEng->addGlobalMapping(externals[i].first, realAddr);
}
externals.clear();
// build the debug tables
Module::FunctionListType &funcList = module->getFunctionList();
for (Module::FunctionListType::iterator funcIter = funcList.begin();
funcIter != funcList.end();
++funcIter
) {
string name = funcIter->getName();
if (!funcIter->isDeclaration())
crack::debug::registerDebugInfo(
execEng->getPointerToGlobal(funcIter),
name,
"", // file name
0 // line number
);
}
doRunOrDump(context);
if (rootBuilder->options->cacheMode)
cacheModule(context, moduleDef);
}
void LLVMJitBuilder::doRunOrDump(Context &context) {
// dump or run the module depending on the mode.
if (rootBuilder->options->statsMode)
context.construct->stats->switchState(ConstructStats::run);
if (options->dumpMode)
dump();
if (!options->dumpMode || !context.construct->compileTimeConstruct)
run();
if (rootBuilder->options->statsMode)
context.construct->stats->switchState(ConstructStats::build);
}
void LLVMJitBuilder::closeModule(Context &context, ModuleDef *moduleDef) {
assert(module);
BJitModuleDefPtr::acast(moduleDef)->closeOrDefer(context, this);
}
void LLVMJitBuilder::dump() {
PassManager passMan;
passMan.add(llvm::createPrintModulePass(&llvm::outs()));
passMan.run(*module);
}
void LLVMJitBuilder::ensureCacheMap() {
// make sure cacheMap is initialized
// a single copy of the map exists in the rootBuilder
if (!cacheMap) {
if (rootBuilder) {
LLVMJitBuilder *rb = LLVMJitBuilderPtr::cast(rootBuilder.get());
if (rb->cacheMap)
cacheMap = rb->cacheMap;
else
cacheMap = rb->cacheMap = new CacheMapType();
} else {
// this is the root builder
cacheMap = new CacheMapType();
}
}
}
void LLVMJitBuilder::registerDef(Context &context, VarDef *varDef) {
// here we keep track of which external functions and globals came from
// which module, so we can do a mapping in cacheMode
if (!options->cacheMode)
return;
ensureCacheMap();
// get rep from either a BFuncDef or varDef->impl global, then use that as
// value to cacheMap
BGlobalVarDefImpl *bgbl;
BFuncDef *fd;
LLVMBuilder &builder = dynamic_cast<LLVMBuilder &>(context.builder);
if (varDef->impl && (bgbl = BGlobalVarDefImplPtr::rcast(varDef->impl))) {
// global
cacheMap->insert(
CacheMapType::value_type(
varDef->getFullName(),
dyn_cast<GlobalValue>(bgbl->getRep(builder))
)
);
} else if (fd = BFuncDefPtr::cast(varDef)) {
// funcdef
cacheMap->insert(
CacheMapType::value_type(varDef->getFullName(),
fd->getRep(builder)
)
);
} else {
//assert(0 && "registerDef: unknown varDef type");
// this happens in a call from parser (not cacher) on e.g. classes,
// which we don't care about here
return;
}
}
model::ModuleDefPtr LLVMJitBuilder::materializeModule(
Context &context,
const string &canonicalName,
ModuleDef *owner
) {
Cacher c(context, options.get());
BModuleDefPtr bmod = c.maybeLoadFromCache(canonicalName);
if (bmod) {
// we materialized a module from bitcode cache
// find the main function
module = bmod->rep;
// entry function
func = c.getEntryFunction();
engineBindModule(bmod.get());
ensureCacheMap();
// try to resolve unresolved globals from the cache
for (Module::const_global_iterator iter = module->global_begin();
iter != module->global_end();
++iter
) {
if (iter->isDeclaration()) {
// now find the defining module
CacheMapType::const_iterator globalDefIter =
cacheMap->find(iter->getName());
if (globalDefIter != cacheMap->end()) {
void *realAddr =
execEng->getPointerToGlobal(globalDefIter->second);
assert(realAddr && "unable to resolve global");
execEng->addGlobalMapping(iter, realAddr);
}
}
}
// now try to resolve functions
for (Module::const_iterator iter = module->begin();
iter != module->end();
++iter
) {
if (iter->isDeclaration() &&
!iter->isMaterializable()) {
// now find the defining module
CacheMapType::const_iterator globalDefIter =
cacheMap->find(iter->getName());
if (globalDefIter != cacheMap->end()) {
Function *f = dyn_cast<Function>(globalDefIter->second);
void *realAddr = execEng->getPointerToFunction(f);
SPUG_CHECK(realAddr,
"Unable to resolve function " <<
string(f->getName())
);
execEng->addGlobalMapping(iter, realAddr);
}
}
}
setupCleanup(bmod.get());
doRunOrDump(context);
}
return bmod;
}
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_llvm_Ops_h_
#define _builder_llvm_Ops_h_
#include "model/FuncCall.h"
#include "model/FuncDef.h"
#include "model/Context.h"
#include "model/ResultExpr.h"
namespace model {
class TypeDef;
}
namespace builder {
namespace mvll {
class BTypeDef;
// primitive operations
SPUG_RCPTR(OpDef);
class OpDef : public model::FuncDef {
public:
OpDef(model::TypeDef *resultType, model::FuncDef::Flags flags,
const std::string &name,
size_t argCount
) :
FuncDef(flags, name, argCount) {
// XXX we don't have a function type for these
returnType = resultType;
}
virtual model::FuncCallPtr createFuncCall() = 0;
virtual void *getFuncAddr(Builder &builder) {
return 0;
}
};
class BinOpDef : public OpDef {
public:
BinOpDef(model::TypeDef *argType,
model::TypeDef *resultType,
const std::string &name,
bool isMethod = false,
bool reversed = false
);
virtual model::FuncCallPtr createFuncCall() = 0;
};
class UnOpDef : public OpDef {
public:
UnOpDef(model::TypeDef *resultType, const std::string &name) :
OpDef(resultType, model::FuncDef::method, name, 0) {
}
};
// No-op call returns its receiver or argument. This is used for oper new's
// to avoid doing any conversions if the type is already correct.
class NoOpCall : public model::FuncCall {
public:
NoOpCall(model::FuncDef *def) : model::FuncCall(def) {}
virtual model::ResultExprPtr emit(model::Context &context);
};
class BitNotOpCall : public model::FuncCall {
public:
BitNotOpCall(model::FuncDef *def) : FuncCall(def) {}
virtual model::ResultExprPtr emit(model::Context &context);
virtual model::ExprPtr foldConstants();
};
class BitNotOpDef : public OpDef {
public:
BitNotOpDef(BTypeDef *resultType, const std::string &name,
bool isMethod = false
);
virtual model::FuncCallPtr createFuncCall() {
return new BitNotOpCall(this);
}
};
class LogicAndOpCall : public model::FuncCall {
public:
LogicAndOpCall(model::FuncDef *def) : FuncCall(def) {}
virtual model::ResultExprPtr emit(model::Context &context);
};
class LogicAndOpDef : public BinOpDef {
public:
LogicAndOpDef(model::TypeDef *argType, model::TypeDef *resultType) :
BinOpDef(argType, resultType, "oper &&") {
}
virtual model::FuncCallPtr createFuncCall() {
return new LogicAndOpCall(this);
}
};
class LogicOrOpCall : public model::FuncCall {
public:
LogicOrOpCall(model::FuncDef *def) : FuncCall(def) {}
virtual model::ResultExprPtr emit(model::Context &context);
};
class LogicOrOpDef : public BinOpDef {
public:
LogicOrOpDef(model::TypeDef *argType, model::TypeDef *resultType) :
BinOpDef(argType, resultType, "oper ||") {
}
virtual model::FuncCallPtr createFuncCall() {
return new LogicOrOpCall(this);
}
};
class NegOpCall : public model::FuncCall {
public:
NegOpCall(model::FuncDef *def) : FuncCall(def) {}
virtual model::ResultExprPtr emit(model::Context &context);
virtual model::ExprPtr foldConstants();
};
class NegOpDef : public OpDef {
public:
NegOpDef(BTypeDef *resultType, const std::string &name,
bool isMethod
);
virtual model::FuncCallPtr createFuncCall() {
return new NegOpCall(this);
}
};
class FNegOpCall : public model::FuncCall {
public:
FNegOpCall(model::FuncDef *def) : FuncCall(def) {}
virtual model::ResultExprPtr emit(model::Context &context);
virtual model::ExprPtr foldConstants();
};
class FNegOpDef : public OpDef {
public:
FNegOpDef(BTypeDef *resultType, const std::string &name, bool isMethod);
virtual model::FuncCallPtr createFuncCall() {
return new FNegOpCall(this);
}
};
class FunctionPtrOpDef : public OpDef {
public:
FunctionPtrOpDef(model::TypeDef *resultType,
size_t argCount) :
OpDef(resultType, FuncDef::method, "oper call", argCount) {
type = resultType;
}
virtual model::FuncCallPtr createFuncCall();
};
class FunctionPtrCall : public model::FuncCall {
public:
FunctionPtrCall(model::FuncDef *def) : FuncCall(def) {}
virtual model::ResultExprPtr emit(model::Context &context);
virtual bool isProductive() const { return true; }
};
template<class T>
class GeneralOpDef : public OpDef {
public:
GeneralOpDef(model::TypeDef *resultType, model::FuncDef::Flags flags,
const std::string &name,
size_t argCount
) :
OpDef(resultType, flags, name, argCount) {
type = resultType;
}
virtual model::FuncCallPtr createFuncCall() {
return new T(this);
}
};
class NoOpDef : public GeneralOpDef<NoOpCall> {
public:
NoOpDef(model::TypeDef *resultType, const std::string &name) :
GeneralOpDef<NoOpCall>(resultType, model::FuncDef::method, name,
0
) {
}
};
class ArrayGetItemCall : public model::FuncCall {
public:
ArrayGetItemCall(model::FuncDef *def) : FuncCall(def) {}
virtual model::ResultExprPtr emit(model::Context &context);
virtual bool isProductive() const { return false; }
};
class ArraySetItemCall : public model::FuncCall {
public:
ArraySetItemCall(model::FuncDef *def) : FuncCall(def) {}
virtual model::ResultExprPtr emit(model::Context &context);
virtual bool isProductive() const { return false; }
};
class ArrayAllocCall : public model::FuncCall {
public:
ArrayAllocCall(model::FuncDef *def) : FuncCall(def) {}
virtual model::ResultExprPtr emit(model::Context &context);
};
// implements pointer arithmetic
class ArrayOffsetCall : public model::FuncCall {
public:
ArrayOffsetCall(model::FuncDef *def) : FuncCall(def) {}
virtual model::ResultExprPtr emit(model::Context &context);
};
/** Operator to convert simple types to booleans. */
class BoolOpCall : public model::FuncCall {
public:
BoolOpCall(model::FuncDef *def) : FuncCall(def) {}
virtual model::ResultExprPtr emit(model::Context &context);
};
class BoolOpDef : public UnOpDef {
public:
BoolOpDef(model::TypeDef *resultType, const std::string &name) :
UnOpDef(resultType, name) {
}
virtual model::FuncCallPtr createFuncCall() {
return new BoolOpCall(this);
}
};
class FBoolOpCall : public model::FuncCall {
public:
FBoolOpCall(model::FuncDef *def) : FuncCall(def) {}
virtual model::ResultExprPtr emit(model::Context &context);
};
class FBoolOpDef : public UnOpDef {
public:
FBoolOpDef(model::TypeDef *resultType, const std::string &name) :
UnOpDef(resultType, name) {
}
virtual model::FuncCallPtr createFuncCall() {
return new FBoolOpCall(this);
}
};
/** Operator to convert any pointer type to void. */
class VoidPtrOpCall : public model::FuncCall {
public:
VoidPtrOpCall(model::FuncDef *def) : FuncCall(def) {}
virtual model::ResultExprPtr emit(model::Context &context);
};
/** Operator to convert a pointer to an integer. */
class PtrToIntOpCall : public model::FuncCall {
public:
PtrToIntOpCall(model::FuncDef *def) : FuncCall(def) {}
virtual model::ResultExprPtr emit(model::Context &context);
};
class VoidPtrOpDef : public UnOpDef {
public:
VoidPtrOpDef(model::TypeDef *resultType) :
UnOpDef(resultType, "oper to .builtin.voidptr") {
}
virtual model::FuncCallPtr createFuncCall() {
return new VoidPtrOpCall(this);
}
};
class UnsafeCastCall : public model::FuncCall {
public:
UnsafeCastCall(model::FuncDef *def) :
FuncCall(def) {
}
virtual model::ResultExprPtr emit(model::Context &context);
virtual bool isProductive() const {
return false;
}
};
class UnsafeCastDef : public OpDef {
public:
UnsafeCastDef(model::TypeDef *resultType);
// Override "matches()" so that the function matches any single
// argument call.
virtual bool matches(model::Context &context,
const std::vector< model::ExprPtr > &vals,
std::vector< model::ExprPtr > &newVals,
model::FuncDef::Convert convertFlag
) {
if (vals.size() != 1)
return false;
if (convert)
newVals = vals;
return true;
}
virtual model::FuncCallPtr createFuncCall() {
return new UnsafeCastCall(this);
}
};
#define UNOP_DEF(opCode) \
class opCode##OpCall : public model::FuncCall { \
public: \
opCode##OpCall(model::FuncDef *def) : model::FuncCall(def) {} \
\
virtual model::ResultExprPtr emit(model::Context &context); \
}; \
\
class opCode##OpDef : public UnOpDef { \
public: \
opCode##OpDef(model::TypeDef *resultType, \
const std::string &name) : \
UnOpDef(resultType, name) { \
} \
\
virtual model::FuncCallPtr createFuncCall() { \
return new opCode##OpCall(this); \
} \
};
#define BINOP_DEF(prefix, op) \
class prefix##OpDef : public BinOpDef { \
public: \
prefix##OpDef(model::TypeDef *argType, \
model::TypeDef *resultType = 0, \
bool isMethod = false, \
bool reversed = false \
) : \
BinOpDef(argType, resultType ? resultType : argType, \
"oper " op, \
isMethod, \
reversed \
) { \
} \
\
virtual model::FuncCallPtr createFuncCall() { \
return new prefix##OpCall(this); \
} \
};
#define BINOPD(prefix, op) \
class prefix##OpCall : public model::FuncCall { \
public: \
prefix##OpCall(model::FuncDef *def) : \
FuncCall(def) { \
} \
\
virtual model::ResultExprPtr emit(model::Context &context); \
}; \
BINOP_DEF(prefix, op)
#define BINOPDF(prefix, op) \
class prefix##OpCall : public model::FuncCall { \
public: \
prefix##OpCall(model::FuncDef *def) : \
FuncCall(def) { \
} \
\
virtual model::ResultExprPtr emit(model::Context &context); \
virtual model::ExprPtr foldConstants(); \
}; \
BINOP_DEF(prefix, op)
// Binary Ops
BINOPDF(Add, "+");
BINOPDF(Sub, "-");
BINOPDF(Mul, "*");
BINOPDF(SDiv, "/");
BINOPDF(UDiv, "/");
BINOPDF(SRem, "%"); // Note: C'99 defines '%' as the remainder, not modulo
BINOPDF(URem, "%"); // the sign is that of the dividend, not divisor.
BINOPDF(Or, "|");
BINOPDF(And, "&");
BINOPDF(Xor, "^");
BINOPDF(Shl, "<<");
BINOPDF(LShr, ">>");
BINOPDF(AShr, ">>");
BINOPDF(AddR, "r+");
BINOPDF(SubR, "r-");
BINOPDF(MulR, "r*");
BINOPDF(SDivR, "r/");
BINOPDF(UDivR, "r/");
BINOPDF(SRemR, "r%");
BINOPDF(URemR, "r%");
BINOPDF(OrR, "r|");
BINOPDF(AndR, "r&");
BINOPDF(XorR, "r^");
BINOPDF(ShlR, "r<<");
BINOPDF(LShrR, "r>>");
BINOPDF(AShrR, "r>>");
BINOPD(ICmpEQ, "==");
BINOPD(ICmpNE, "!=");
BINOPD(ICmpSGT, ">");
BINOPD(ICmpSLT, "<");
BINOPD(ICmpSGE, ">=");
BINOPD(ICmpSLE, "<=");
BINOPD(ICmpUGT, ">");
BINOPD(ICmpULT, "<");
BINOPD(ICmpUGE, ">=");
BINOPD(ICmpULE, "<=");
BINOPD(ICmpEQR, "==");
BINOPD(ICmpNER, "!=");
BINOPD(ICmpSGTR, "r>");
BINOPD(ICmpSLTR, "r<");
BINOPD(ICmpSGER, "r>=");
BINOPD(ICmpSLER, "r<=");
BINOPD(ICmpUGTR, "r>");
BINOPD(ICmpULTR, "r<");
BINOPD(ICmpUGER, "r>=");
BINOPD(ICmpULER, "r<=");
BINOPDF(FAdd, "+");
BINOPDF(FSub, "-");
BINOPDF(FMul, "*");
BINOPDF(FDiv, "/");
BINOPDF(FRem, "%");
BINOPDF(FAddR, "r+");
BINOPDF(FSubR, "r-");
BINOPDF(FMulR, "r*");
BINOPDF(FDivR, "r/");
BINOPDF(FRemR, "r%");
BINOPD(Is, "is");
BINOPD(FCmpOEQ, "==");
BINOPD(FCmpONE, "!=");
BINOPD(FCmpOGT, ">");
BINOPD(FCmpOLT, "<");
BINOPD(FCmpOGE, ">=");
BINOPD(FCmpOLE, "<=");
BINOPD(FCmpOEQR, "==");
BINOPD(FCmpONER, "!=");
BINOPD(FCmpOGTR, ">");
BINOPD(FCmpOLTR, "<");
BINOPD(FCmpOGER, ">=");
BINOPD(FCmpOLER, "<=");
// Type Conversion Ops
UNOP_DEF(SExt);
UNOP_DEF(ZExt);
UNOP_DEF(FPExt);
UNOP_DEF(SIToFP);
UNOP_DEF(UIToFP);
UNOP_DEF(Trunc);
UNOP_DEF(PreIncrInt);
UNOP_DEF(PreDecrInt);
UNOP_DEF(PostIncrInt);
UNOP_DEF(PostDecrInt);
#define FPTRUNCOP_DEF(opCode) \
class opCode##OpCall : public model::FuncCall { \
public: \
opCode##OpCall(model::FuncDef *def) : FuncCall(def) {} \
\
virtual model::ResultExprPtr emit(model::Context &context); \
}; \
class opCode##OpDef : public UnOpDef { \
public: \
opCode##OpDef(model::TypeDef *resultType, \
const std::string &name \
) : \
UnOpDef(resultType, name) { \
} \
\
virtual model::FuncCallPtr createFuncCall() { \
return new opCode##OpCall(this); \
\
} \
};
// Floating Point Truncating Ops
FPTRUNCOP_DEF(FPTrunc)
FPTRUNCOP_DEF(FPToSI)
FPTRUNCOP_DEF(FPToUI)
// define a floating point truncation definition so we can use this as either
// an explicit constructor or an implicit "oper to" for converting to the
// 'float' PDNT.
} // end namespace builder::vmll
} // end namespace builder
#endif
| C++ |
/*
* Some of this code is based on llc and llvm-ld from the LLVM tools suite.
* It is used by permission under the University of Illinois/NCSA Open Source
* License.
*
* Copyright (c) 2003-2010 University of Illinois at Urbana-Champaign.
*
* Other parts Copyright 2010-2011 Shannon Weyrick <weyrick@mozek.us>
*
*/
#include "Native.h"
#include "builder/BuilderOptions.h"
#include <llvm/LLVMContext.h>
#include <llvm/Module.h>
#include <llvm/PassManager.h>
#include <llvm/Pass.h>
#include <llvm/ADT/Triple.h>
#include <llvm/Support/FormattedStream.h>
#include <llvm/LinkAllPasses.h>
#include <llvm/Target/TargetData.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Support/TargetRegistry.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/DerivedTypes.h>
#include <llvm/Instructions.h>
#include <llvm/Linker.h>
#include <llvm/Support/Program.h>
#include <llvm/Support/PathV1.h>
#include <llvm/Support/Host.h>
#include <llvm/Support/IRBuilder.h>
#include <llvm/Support/ToolOutputFile.h>
#include <llvm/Analysis/Verifier.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
using namespace llvm;
using namespace llvm::sys;
using namespace builder;
using namespace std;
extern char **environ;
namespace builder { namespace mvll {
static void PrintCommand(const std::vector<const char*> &args) {
std::vector<const char*>::const_iterator I = args.begin(), E = args.end();
for (; I != E; ++I)
if (*I)
//cerr << "'" << *I << "'" << " ";
cerr << *I << " ";
cerr << "\n";
}
/// GenerateNative - generates a native object file from the
/// specified bitcode file.
///
static int GenerateNative(const std::string &OutputFilename,
const std::string &InputFilename,
const vector<std::string> &LibPaths,
const Linker::ItemList &LinkItems,
const sys::Path &gcc, char ** const envp,
std::string& ErrMsg,
bool is64Bit,
int verbosity) {
// Run GCC to assemble and link the program into native code.
//
// Note:
// We can't just assemble and link the file with the system assembler
// and linker because we don't know where to put the _start symbol.
// GCC mysteriously knows how to do it.
std::vector<std::string> args;
args.push_back(gcc.c_str());
args.push_back("-O3");
if (is64Bit)
args.push_back("-m64");
args.push_back("-o");
args.push_back(OutputFilename);
args.push_back(InputFilename);
args.push_back("-Wl,--add-needed");
// Add in the library and framework paths
if (verbosity > 2) {
cerr << "Native link paths:" << endl;
// verbose linker
args.push_back("-Wl,--verbose");
}
for (unsigned index = 0; index < LibPaths.size(); index++) {
if (verbosity > 2)
cerr << LibPaths[index] << endl;
args.push_back("-L" + LibPaths[index]);
// XXX we add all lib paths as rpaths as well. this can potentially
// cause conflicts where foo/baz.so and bar/baz.so exist as crack
// extensions, but the runtime loader loads foo/baz.so for both since
// it shows up first matching the rpath. this needs a better fix.
char *rp = realpath(LibPaths[index].c_str(), NULL);
if (!rp) {
switch (errno) {
case EACCES:
case ELOOP:
case ENAMETOOLONG:
case ENOENT:
case ENOTDIR:
break;
default:
perror("realpath");
}
continue;
} else {
args.push_back("-Wl,-rpath=" + string(rp));
free(rp);
}
}
// Add in the libraries to link.
if (verbosity > 2)
cerr << "Native link libraries:" << endl;
for (unsigned index = 0; index < LinkItems.size(); index++)
if (LinkItems[index].first != "crtend") {
if (verbosity > 2)
cerr << LinkItems[index].first << endl;
if (LinkItems[index].second)
args.push_back("-l" + LinkItems[index].first);
else
args.push_back(LinkItems[index].first);
}
// Now that "args" owns all the std::strings for the arguments, call the c_str
// method to get the underlying string array. We do this game so that the
// std::string array is guaranteed to outlive the const char* array.
std::vector<const char *> Args;
for (unsigned i = 0, e = args.size(); i != e; ++i)
Args.push_back(args[i].c_str());
Args.push_back(0);
if (verbosity) {
cerr << "Generating Native Executable With:\n";
PrintCommand(Args);
}
// Run the compiler to assembly and link together the program.
int R = sys::Program::ExecuteAndWait(
gcc, &Args[0], 0, 0, 0, 0, &ErrMsg);
return R;
}
/*
define i32 @main(i32 %argc, i8** %argv) nounwind {
%1 = alloca i32, align 4
%2 = alloca i32, align 4
%3 = alloca i8**, align 8
store i32 0, i32* %1
store i32 %argc, i32* %2, align 4
store i8** %argv, i8*** %3, align 8
XXX entry XXX
XXX cleanup XXX
%5 = load i32* %1
ret i32 %5
}
*/
void createMain(llvm::Module *mod, const BuilderOptions *o,
llvm::Value *vtableBaseTypeBody,
const string &mainModuleName
) {
Function *scriptEntry = mod->getFunction(mainModuleName + ":main");
assert(scriptEntry && "no main source file specified");
// main cleanup function we insert into main() function, after script
// is done
Function *mainCleanup = mod->getFunction("main:cleanup");
assert(mainCleanup && "no cleanup function");
Function *crackLangInit = mod->getFunction("crack.lang:main");
// Type Definitions
// argc
std::vector<Type *>main_args;
IntegerType *argcType = IntegerType::get(mod->getContext(), 32);
main_args.push_back(argcType);
// argv
PointerType* pc = PointerType::get(
IntegerType::get(mod->getContext(), 8), 0);
PointerType* argvType = PointerType::get(pc, 0);
main_args.push_back(argvType);
// int main(int, char**)
FunctionType* main_func_ty = FunctionType::get(
IntegerType::get(mod->getContext(), 32),
main_args,
/*isVarArg=*/false);
// global argc and argv, which our __getArgv and __getArgc functions
// will return. these are set by main
GlobalVariable *gargc =
new GlobalVariable(*mod, argcType, false,
GlobalValue::PrivateLinkage,
Constant::getNullValue(argcType),
"global_argc"
);
GlobalVariable *gargv =
new GlobalVariable(*mod, argvType, false,
GlobalValue::PrivateLinkage,
Constant::getNullValue(argvType),
"global_argv"
);
// Function Declarations
Function* func_main = Function::Create(
main_func_ty,
GlobalValue::ExternalLinkage,
"main", mod);
func_main->setCallingConv(CallingConv::C);
// result value constant
// XXX this needs to adjust when we start allowing return values
ConstantInt* retValConst = ConstantInt::get(
mod->getContext(), APInt(32, StringRef("0"), 10));
// Function Definitions
// Function: main (func_main)
{
Function::arg_iterator args = func_main->arg_begin();
Value* int32_argc = args++;
int32_argc->setName("argc");
Value* ptr_argv = args++;
ptr_argv->setName("argv");
BasicBlock* label_13 = BasicBlock::Create(mod->getContext(), "entry",
func_main,0);
BasicBlock *cleanupBlock = BasicBlock::Create(mod->getContext(),
"cleanup",
func_main
),
*lpBlock = BasicBlock::Create(mod->getContext(),
"lp",
func_main
),
*endBlock = BasicBlock::Create(mod->getContext(),
"end",
func_main
),
*lpPostCleanupBlock = BasicBlock::Create(mod->getContext(),
"lp",
func_main
);
// alloc return value, argc, argv
AllocaInst* ptr_14 = new AllocaInst(
IntegerType::get(mod->getContext(), 32), "", label_13);
new StoreInst(retValConst, ptr_14, false, label_13);
new StoreInst(int32_argc, gargc, false, label_13);
new StoreInst(ptr_argv, gargv, false, label_13);
IRBuilder<> builder(label_13);
// call crack.lang init function
// note if crackLangInit isn't set, we skip it. this happens for
// non bootstrapped scripts
if (crackLangInit) {
BasicBlock *block = BasicBlock::Create(mod->getContext(),
"main",
func_main
);
builder.CreateInvoke(crackLangInit, block, lpBlock);
builder.SetInsertPoint(block);
}
// call main script initialization function
builder.CreateInvoke(scriptEntry, cleanupBlock, lpBlock);
// cleanup function
builder.SetInsertPoint(cleanupBlock);
builder.CreateInvoke(mainCleanup, endBlock, lpPostCleanupBlock);
// exception handling stuff
Function *crkExFunc = mod->getFunction("__CrackExceptionPersonality");
Type *i8PtrType = builder.getInt8PtrTy();
Type *exStructType =
StructType::get(i8PtrType, builder.getInt32Ty(), NULL);
BasicBlock *uncaughtHandlerBlock =
BasicBlock::Create(mod->getContext(), "uncaught_exception",
func_main
);
// first landing pad does cleanups
builder.SetInsertPoint(lpBlock);
LandingPadInst *lp =
builder.CreateLandingPad(exStructType, crkExFunc, 1);
lp->addClause(Constant::getNullValue(i8PtrType));
builder.CreateInvoke(mainCleanup, uncaughtHandlerBlock,
lpPostCleanupBlock
);
// get our uncaught exception function (for some reason this doesn't
// work when we do it from anywhere else)
FunctionType *funcType =
FunctionType::get(Type::getInt1Ty(mod->getContext()), false);
Constant *uncaughtFuncConst =
mod->getOrInsertFunction("__CrackUncaughtException", funcType);
Function *uncaughtFunc = cast<Function>(uncaughtFuncConst);
// post cleanup landing pad
builder.SetInsertPoint(lpPostCleanupBlock);
lp = builder.CreateLandingPad(exStructType, crkExFunc, 1);
lp->addClause(Constant::getNullValue(i8PtrType));
builder.CreateBr(uncaughtHandlerBlock);
// uncaught exception handler
builder.SetInsertPoint(uncaughtHandlerBlock);
builder.CreateCall(uncaughtFunc);
builder.CreateBr(endBlock);
// return value
builder.SetInsertPoint(endBlock);
LoadInst* int32_21 = builder.CreateLoad(ptr_14);
builder.CreateRet(int32_21);
}
// now fill in the bodies of the __getArgv and __getArgc functions
// these simply return the values of the globals we setup in main
// int puts(char *)
std::vector<Type *>args;
FunctionType *argv_ftype = FunctionType::get(
argvType,
args, false);
FunctionType* argc_ftype = FunctionType::get(
argcType,
args, false);
Constant *c = mod->getOrInsertFunction("__getArgv", argv_ftype);
Function *f = llvm::cast<llvm::Function>(c);
IRBuilder<> builder(mod->getContext());
builder.SetInsertPoint(BasicBlock::Create(mod->getContext(), "", f));
Value *v = builder.CreateLoad(gargv);
builder.CreateRet(v);
c = mod->getOrInsertFunction("__getArgc", argc_ftype);
f = llvm::cast<llvm::Function>(c);
builder.SetInsertPoint(BasicBlock::Create(mod->getContext(), "", f));
v = builder.CreateLoad(gargc);
builder.CreateRet(v);
}
void optimizeLink(llvm::Module *module, bool verify) {
// see llvm's opt tool
// module pass manager
PassManager Passes;
// Add an appropriate TargetData instance for this module...
TargetData *TD = 0;
const std::string &ModuleDataLayout = module->getDataLayout();
if (!ModuleDataLayout.empty())
TD = new TargetData(ModuleDataLayout);
if (TD)
Passes.add(TD);
// createStandardLTOPasses(&Passes, /*Internalize=*/ false,
// /*RunInliner=*/ false, // XXX breaks exceptions
// /*VerifyEach=*/ verify);
// createStandardAliasAnalysisPasses(&Passes);
Passes.add(createTypeBasedAliasAnalysisPass());
Passes.add(createBasicAliasAnalysisPass());
// Now that composite has been compiled, scan through the module, looking
// for a main function. If main is defined, mark all other functions
// internal.
// Passes.add(createInternalizePass(true));
// Propagate constants at call sites into the functions they call. This
// opens opportunities for globalopt (and inlining) by substituting function
// pointers passed as arguments to direct uses of functions.
Passes.add(createIPSCCPPass());
// Now that we internalized some globals, see if we can hack on them!
Passes.add(createGlobalOptimizerPass());
// Linking modules together can lead to duplicated global constants, only
// keep one copy of each constant...
Passes.add(createConstantMergePass());
// Remove unused arguments from functions...
Passes.add(createDeadArgEliminationPass());
// Reduce the code after globalopt and ipsccp. Both can open up significant
// simplification opportunities, and both can propagate functions through
// function pointers. When this happens, we often have to resolve varargs
// calls, etc, so let instcombine do this.
Passes.add(createInstructionCombiningPass());
// Inline small functions
// Passes.add(createFunctionInliningPass());
Passes.add(createPruneEHPass()); // Remove dead EH info.
// Optimize globals again if we ran the inliner.
// Passes.add(createGlobalOptimizerPass());
Passes.add(createGlobalDCEPass()); // Remove dead functions.
// If we didn't decide to inline a function, check to see if we can
// transform it to pass arguments by value instead of by reference.
Passes.add(createArgumentPromotionPass());
// The IPO passes may leave cruft around. Clean up after them.
Passes.add(createInstructionCombiningPass());
Passes.add(createJumpThreadingPass());
// Break up allocas
Passes.add(createScalarReplAggregatesPass());
// Run a few AA driven optimizations here and now, to cleanup the code.
Passes.add(createFunctionAttrsPass()); // Add nocapture.
Passes.add(createGlobalsModRefPass()); // IP alias analysis.
Passes.add(createLICMPass()); // Hoist loop invariants.
Passes.add(createGVNPass()); // Remove redundancies.
Passes.add(createMemCpyOptPass()); // Remove dead memcpys.
// Nuke dead stores.
Passes.add(createDeadStoreEliminationPass());
// Cleanup and simplify the code after the scalar optimizations.
Passes.add(createInstructionCombiningPass());
Passes.add(createJumpThreadingPass());
// Delete basic blocks, which optimization passes may have killed.
Passes.add(createCFGSimplificationPass());
// Now that we have optimized the program, discard unreachable functions.
Passes.add(createGlobalDCEPass());
// the old code used to inject a verify after every pass, for now we save
// some time by doing the verify once at the end.
if (verify)
Passes.add(createVerifierPass());
Passes.run(*module);
}
// optimize
void optimizeUnit(llvm::Module *module, int optimizeLevel) {
// see llvm's opt tool
// module pass manager
PassManager Passes;
// Add an appropriate TargetData instance for this module...
TargetData *TD = 0;
const std::string &ModuleDataLayout = module->getDataLayout();
if (!ModuleDataLayout.empty())
TD = new TargetData(ModuleDataLayout);
if (TD)
Passes.add(TD);
// function pass manager
OwningPtr<PassManager> FPasses;
FPasses.reset(new PassManager());
if (TD)
FPasses->add(new TargetData(*TD));
if (optimizeLevel > 0) {
FPasses->add(createCFGSimplificationPass());
FPasses->add(createScalarReplAggregatesPass());
FPasses->add(createEarlyCSEPass());
}
llvm::Pass *InliningPass = 0;
/*
// XXX inlining currently breaks exceptions
if (optimizeLevel > 1) {
unsigned Threshold = 200;
if (optimizeLevel > 2)
Threshold = 250;
InliningPass = createFunctionInliningPass(Threshold);
} else {
InliningPass = createAlwaysInlinerPass();
}
*/
// createStandardModulePasses(&Passes, optimizeLevel,
// /*OptimizeSize=*/ false,
// /*UnitAtATime*/ true,
// /*UnrollLoops=*/ optimizeLevel > 1,
// /*SimplifyLibCalls*/ true,
// /*HaveExceptions=*/ true,
// InliningPass);
Passes.add(createGlobalOptimizerPass()); // Optimize out global vars
Passes.add(createIPSCCPPass()); // IP SCCP
Passes.add(createDeadArgEliminationPass()); // Dead argument elimination
Passes.add(createInstructionCombiningPass()); // Clean up after IPCP & DAE
Passes.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
// Start of CallGraph SCC passes.
Passes.add(createPruneEHPass()); // Remove dead EH info
// if (InliningPass)
// Passes.add(InliningPass);
Passes.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
if (optimizeLevel > 2)
Passes.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
// Start of function pass.
// Break up aggregate allocas, using SSAUpdater.
Passes.add(createScalarReplAggregatesPass(-1, false));
Passes.add(createEarlyCSEPass()); // Catch trivial redundancies
Passes.add(createSimplifyLibCallsPass()); // Library Call Optimizations
Passes.add(createJumpThreadingPass()); // Thread jumps.
Passes.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
Passes.add(createCFGSimplificationPass()); // Merge & remove BBs
Passes.add(createInstructionCombiningPass()); // Combine silly seq's
Passes.add(createTailCallEliminationPass()); // Eliminate tail calls
Passes.add(createCFGSimplificationPass()); // Merge & remove BBs
Passes.add(createReassociatePass()); // Reassociate expressions
Passes.add(createLoopRotatePass()); // Rotate Loop
Passes.add(createLICMPass()); // Hoist loop invariants
Passes.add(createLoopUnswitchPass(optimizeLevel < 3));
Passes.add(createInstructionCombiningPass());
Passes.add(createIndVarSimplifyPass()); // Canonicalize indvars
Passes.add(createLoopIdiomPass()); // Recognize idioms like memset.
Passes.add(createLoopDeletionPass()); // Delete dead loops
if (optimizeLevel > 1)
Passes.add(createLoopUnrollPass()); // Unroll small loops
Passes.add(createInstructionCombiningPass()); // Clean up after the unroller
if (optimizeLevel > 1)
Passes.add(createGVNPass()); // Remove redundancies
Passes.add(createMemCpyOptPass()); // Remove memcpy / form memset
Passes.add(createSCCPPass()); // Constant prop with SCCP
// Run instcombine after redundancy elimination to exploit opportunities
// opened up by them.
Passes.add(createInstructionCombiningPass());
Passes.add(createJumpThreadingPass()); // Thread jumps
Passes.add(createCorrelatedValuePropagationPass());
Passes.add(createDeadStoreEliminationPass()); // Delete dead stores
Passes.add(createAggressiveDCEPass()); // Delete dead instructions
Passes.add(createCFGSimplificationPass()); // Merge & remove BBs
Passes.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
// GlobalOpt already deletes dead functions and globals, at -O3 try a
// late pass of GlobalDCE. It is capable of deleting dead cycles.
if (optimizeLevel > 2)
Passes.add(createGlobalDCEPass()); // Remove dead fns and globals.
if (optimizeLevel > 1)
Passes.add(createConstantMergePass()); // Merge dup global constants
FPasses->run(*module);
Passes.run(*module);
}
void nativeCompile(llvm::Module *module,
const BuilderOptions *o,
const vector<string> &sharedLibs,
const vector<string> &libPaths) {
BuilderOptions::StringMap::const_iterator i = o->optionMap.find("out");
assert(i != o->optionMap.end() && "no out");
sys::Path oFile(i->second);
sys::Path binFile(i->second);
// see if we should output an object file/native binary,
// native assembly, or llvm bitcode
TargetMachine::CodeGenFileType cgt = TargetMachine::CGFT_ObjectFile;
bool doBitcode(false);
oFile.appendSuffix("o");
i = o->optionMap.find("codeGen");
if (i != o->optionMap.end()) {
if (i->second == "llvm") {
// llvm bitcode
oFile.eraseSuffix();
oFile.appendSuffix("bc");
doBitcode = true;
}
else if (i->second == "asm") {
// native assembly
oFile.eraseSuffix();
oFile.appendSuffix("s");
cgt = TargetMachine::CGFT_AssemblyFile;
}
}
InitializeNativeTarget();
InitializeNativeTargetAsmPrinter();
Triple TheTriple(module->getTargetTriple());
if (TheTriple.getTriple().empty())
TheTriple.setTriple(sys::getHostTriple());
const Target *TheTarget = 0;
std::string Err;
TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
assert(TheTarget && "unable to select target machine");
// XXX insufficient
bool is64Bit(TheTriple.getArch() == Triple::x86_64);
string FeaturesStr;
string CPU;
std::auto_ptr<TargetMachine>
target(TheTarget->createTargetMachine(TheTriple.getTriple(),
CPU,
FeaturesStr));
assert(target.get() && "Could not allocate target machine!");
TargetMachine &Target = *target.get();
// Build up all of the passes that we want to do to the module.
PassManager PM;
// Add the target data from the target machine or the module.
if (const TargetData *TD = Target.getTargetData())
PM.add(new TargetData(*TD));
else
PM.add(new TargetData(module));
// Override default to generate verbose assembly.
Target.setAsmVerbosityDefault(true);
std::string error;
unsigned OpenFlags = 0;
OpenFlags |= raw_fd_ostream::F_Binary;
tool_output_file *FDOut = new tool_output_file(oFile.str().c_str(),
Err,
OpenFlags);
if (!Err.empty()) {
cerr << error << '\n';
delete FDOut;
return;
}
{
formatted_raw_ostream FOS(FDOut->os());
// note, we expect optimizations to be done by now, so we don't do
// any here
if (o->verbosity)
cerr << "Generating file:\n" << oFile.str() << "\n";
if (doBitcode) {
// llvm bitcode
WriteBitcodeToFile(module, FOS);
}
else {
// native
if (Target.addPassesToEmitFile(PM,
FOS,
cgt,
CodeGenOpt::None,
o->debugMode // do verify
)) {
cerr << "target does not support generation of this"
<< " file type!\n";
return;
}
PM.run(*module);
}
}
// note FOS needs to destruct before we can keep
FDOut->keep();
delete FDOut;
// if we created llvm or native assembly file we're done
if (doBitcode ||
cgt == TargetMachine::CGFT_AssemblyFile)
return;
// if we reach here, we finish generating a native binary with gcc
sys::Path gcc = sys::Program::FindProgramByName("gcc");
assert(!gcc.isEmpty() && "Failed to find gcc");
vector<string> LibPaths(libPaths);
// if CRACK_LIB_PATH is set, add that
char *elp = getenv("CRACK_LIB_PATH");
if (elp) {
// XXX split on :
LibPaths.push_back(elp);
}
Linker::ItemList NativeLinkItems;
for (vector<string>::const_iterator i = sharedLibs.begin();
i != sharedLibs.end();
++i) {
if (path::has_parent_path(*i)) {
LibPaths.push_back(path::parent_path(*i));
}
#if __GNUC__ > 4 && __GNUC_MINOR__ > 2
NativeLinkItems.push_back(pair<string,bool>(":"+
string(path::stem(*i))+
string(path::extension(*i)),
true // .so
));
#else
string rtp = string(path::stem(*i)) + string(path::extension(*i));
Path sPath;
bool foundModule = false;
// We have to manually search for the linkitem
for (unsigned index = 0; index < LibPaths.size(); index++) {
sPath = Path(LibPaths[index]);
sPath.appendComponent(rtp);
if (o->verbosity > 2)
cerr << "search: " << sPath.str() << endl;
char *rp = realpath(sPath.c_str(), NULL);
if (!rp) {
switch (errno) {
case EACCES:
case ELOOP:
case ENAMETOOLONG:
case ENOENT:
case ENOTDIR:
break;
default:
perror("realpath");
}
continue;
} else {
free(rp);
foundModule = true;
break;
}
}
NativeLinkItems.push_back(pair<string,bool>(foundModule ? sPath.str() : rtp,
false // .so
));
#endif
}
// native runtime lib is required
NativeLinkItems.push_back(pair<string,bool>("CrackNativeRuntime",true));
string ErrMsg;
char **envp = ::environ;
GenerateNative(binFile.str(),
oFile.str(),
LibPaths,
NativeLinkItems,
gcc,
envp,
ErrMsg,
is64Bit,
o->verbosity
);
}
} }
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#include "FunctionTypeDef.h"
#include "model/NullConst.h"
#include "Ops.h"
#include "Utils.h"
#include <iostream>
#include <sstream>
#include <spug/StringFmt.h>
#include <llvm/DerivedTypes.h>
using namespace llvm;
using namespace model;
using namespace builder::mvll;
FunctionTypeDef::FunctionTypeDef(TypeDef *metaType, const std::string &name,
Type *rep
) :
BTypeDef(metaType, name, rep) {
defaultInitializer = new NullConst(this);
generic = new SpecializationCache();
}
// specializations of function types actually create a new type
// object, like array
TypeDef * FunctionTypeDef::getSpecialization(Context &context,
TypeVecObj *types
) {
// see if it already exists
TypeDef *spec = findSpecialization(types);
if (spec)
return spec;
// need at least one, the return type
assert(types->size() >= 1);
int arity(types->size() - 1);
// return type is always 0
BTypeDef *returnCType = BTypeDefPtr::rcast((*types)[0]);
// remaining types are function arguments
std::vector<Type *> fun_args;
if (arity) {
for (int i = 1; i < arity+1; ++i) {
BTypeDef *argCType = BTypeDefPtr::rcast((*types)[i]);
if (argCType == context.construct->voidType) {
context.error(context.getLocation(),
"Cannot specialize function type with void argument");
}
fun_args.push_back(argCType->rep);
}
}
Type *llvmFunType = FunctionType::get(returnCType->rep,
fun_args,
false // XXX isVarArg
);
Type *llvmFunPtrType = PointerType::get(llvmFunType, 0);
BTypeDefPtr tempSpec =
new BTypeDef(type.get(),
getSpecializedName(types, true),
llvmFunPtrType
);
tempSpec->setOwner(this);
tempSpec->defaultInitializer = new NullConst(tempSpec.get());
// create the implementation (this can be called before the meta-class is
// initialized, so check for it and defer if it is)
if (context.construct->classType->complete) {
createClassImpl(context, tempSpec.get());
} else {
LLVMBuilder &b = dynamic_cast<LLVMBuilder &>(context.builder);
b.deferMetaClass.push_back(tempSpec);
}
// Give it an "oper to .builtin.voidptr" method.
context.addDef(
new VoidPtrOpDef(context.construct->voidptrType.get()),
tempSpec.get()
);
// Give it a specialized "oper call" method, which wraps the
// call to the function pointer
FuncDefPtr fptrCall = new FunctionPtrOpDef(returnCType, arity);
std::ostringstream argName;
argName << "arg";
for (int i = 0; i < arity; ++i) {
argName << i+1;
fptrCall->args[i] = new ArgDef((*types)[i+1].get(), argName.str());
argName.rdbuf()->pubseekpos(3);
}
context.addDef(fptrCall.get(), tempSpec.get());
// cache and return
(*generic)[types] = tempSpec;
return tempSpec.get();
}
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_llvm_BTypeDef_h_
#define _builder_llvm_BTypeDef_h_
#include "model/TypeDef.h"
#include <llvm/Type.h>
#include <map>
#include <string>
#include <vector>
namespace llvm {
class Type;
class Constant;
class ExecutionEngine;
class GlobalVariable;
}
namespace builder {
namespace mvll {
class PlaceholderInstruction;
class VTableBuilder;
SPUG_RCPTR(BTypeDef);
// (RCPTR defined above)
class BTypeDef : public model::TypeDef {
public:
unsigned fieldCount;
llvm::GlobalVariable *classInst;
llvm::Type *rep;
unsigned nextVTableSlot;
std::vector<PlaceholderInstruction *> placeholders;
typedef std::vector< std::pair<BTypeDefPtr, model::ContextPtr> >
IncompleteChildVec;
IncompleteChildVec incompleteChildren;
// mapping from base types to their vtables.
std::map<BTypeDef *, llvm::Constant *> vtables;
llvm::Type *firstVTableType;
BTypeDef(TypeDef *metaType, const std::string &name,
llvm::Type *rep,
bool pointer = false,
unsigned nextVTableSlot = 0
) :
model::TypeDef(metaType, name, pointer),
fieldCount(0),
classInst(0),
rep(rep),
nextVTableSlot(nextVTableSlot),
firstVTableType(0) {
}
virtual void getDependents(std::vector<model::TypeDefPtr> &deps);
// add all of my virtual functions to 'vtb'
void extendVTables(VTableBuilder &vtb);
/**
* Create all of the vtables for 'type'.
*
* @param vtb the vtable builder
* @param name the name stem for the VTable global variables.
* @param firstVTable if true, we have not yet discovered the first
* vtable in the class schema.
*/
void createAllVTables(VTableBuilder &vtb, const std::string &name,
bool firstVTable = true
);
/**
* Add a base class to the type.
*/
void addBaseClass(BTypeDef *base);
/**
* register a placeholder instruction to be replaced when the class is
* completed.
*/
void addPlaceholder(PlaceholderInstruction *inst);
/**
* Find the ancestor with our first vtable.
*/
BTypeDef *findFirstVTable(BTypeDef *vtableBaseType);
/**
* Get the global variable, creating an extern instance in the module if
* it lives in another module.
* @param execEng the execution engine (may be null if this is unknown or
* there is no execution engine)
*/
llvm::GlobalVariable *getClassInstRep(llvm::Module *module,
llvm::ExecutionEngine *execEng
);
/**
* Add a dependent type - this is a nested type that is derived from an
* incomplete enclosing type. fixIncompletes() will be called on all of
* the dependents during the completion of the receiver.
*/
void addDependent(BTypeDef *type, model::Context *context);
/**
* Fix all incomplete instructions and incomplete children and set the
* "complete" flag.
*/
void fixIncompletes(model::Context &context);
};
} // end namespace builder::vmll
} // end namespace builder
#endif
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#include "VarDefs.h"
#include "BResultExpr.h"
#include "BTypeDef.h"
#include "model/AssignExpr.h"
#include <llvm/GlobalVariable.h>
using namespace llvm;
using namespace model;
using namespace builder::mvll;
// BArgVarDefImpl
VarDefImplPtr BArgVarDefImpl::promote(LLVMBuilder &builder, ArgDef *arg) {
Value *var;
BHeapVarDefImplPtr localVar =
builder.createLocalVar(BTypeDefPtr::arcast(arg->type), var, rep);
return localVar;
}
ResultExprPtr BArgVarDefImpl::emitRef(Context &context,
VarRef *var
) {
LLVMBuilder &b =
dynamic_cast<LLVMBuilder &>(context.builder);
b.emitArgVarRef(context, rep);
return new BResultExpr((Expr*)var, b.lastValue);
}
ResultExprPtr BArgVarDefImpl::emitAssignment(Context &context,
AssignExpr *assign
) {
// This should never happen - arguments except for "this" all get promoted
// to local variables at the start of the function.
assert(0 && "attempting to emit an argument assignment");
}
bool BArgVarDefImpl::hasInstSlot() const { return false; }
// BMemVarDefImpl
ResultExprPtr BMemVarDefImpl::emitRef(Context &context, VarRef *var) {
LLVMBuilder &b =
dynamic_cast<LLVMBuilder &>(context.builder);
b.emitMemVarRef(context, getRep(b));
return new BResultExpr((Expr*)var, b.lastValue);
}
ResultExprPtr BMemVarDefImpl::emitAssignment(Context &context, AssignExpr *assign) {
LLVMBuilder &b =
dynamic_cast<LLVMBuilder &>(context.builder);
ResultExprPtr result = assign->value->emit(context);
Value *exprVal = b.lastValue;
b.narrow(assign->value->type.get(), assign->var->type.get());
b.builder.CreateStore(b.lastValue, getRep(b));
result->handleAssignment(context);
b.lastValue = exprVal;
return new BResultExpr(assign, exprVal);
}
bool BMemVarDefImpl::hasInstSlot() const { return false; }
// BGlobalVarDefImpl
Value * BGlobalVarDefImpl::getRep(LLVMBuilder &builder) {
if (rep->getParent() != builder.module)
rep = builder.getModVar(this, this->rep);
return rep;
}
// BConstDefImpl
ResultExprPtr BConstDefImpl::emitRef(Context &context, VarRef *var) {
LLVMBuilder &b =
dynamic_cast<LLVMBuilder &>(context.builder);
b.lastValue = rep;
return new BResultExpr((Expr*)var, b.lastValue);
}
bool BConstDefImpl::hasInstSlot() const { return false; }
// BInstVarDefImpl
void BInstVarDefImpl::emitFieldAssign(IRBuilder<> &builder, Value *aggregate,
Value *value
) {
Value *fieldPtr = builder.CreateStructGEP(aggregate, index);
builder.CreateStore(value, fieldPtr);
}
Value *BInstVarDefImpl::emitFieldRef(IRBuilder<> &builder,
Type *fieldType,
Value *aggregate
) {
Value *fieldPtr = builder.CreateStructGEP(aggregate, index);
return builder.CreateLoad(fieldPtr);
}
bool BInstVarDefImpl::hasInstSlot() const { return true; }
// BOffsetFieldDefImpl
void BOffsetFieldDefImpl::emitFieldAssign(IRBuilder<> &builder,
Value *aggregate,
Value *value
) {
// cast to a byte pointer, GEP to the offset
Value *fieldPtr = builder.CreateBitCast(aggregate,
builder.getInt8Ty()->getPointerTo()
);
fieldPtr = builder.CreateConstGEP1_32(fieldPtr, offset);
Type *fieldPtrType = value->getType()->getPointerTo();
builder.CreateStore(value, builder.CreateBitCast(fieldPtr, fieldPtrType));
}
Value *BOffsetFieldDefImpl::emitFieldRef(IRBuilder<> &builder,
Type *fieldType,
Value *aggregate
) {
// cast to a byte pointer, GEP to the offset
Value *fieldPtr = builder.CreateBitCast(aggregate,
builder.getInt8Ty()->getPointerTo()
);
fieldPtr = builder.CreateConstGEP1_32(fieldPtr, offset);
Type *fieldPtrType = fieldType->getPointerTo();
return builder.CreateLoad(builder.CreateBitCast(fieldPtr, fieldPtrType));
}
bool BOffsetFieldDefImpl::hasInstSlot() const { return false; }
| C++ |
// Copyright 2009 Google Inc., Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_LLVMJitBuilder_h_
#define _builder_LLVMJitBuilder_h_
#include "LLVMBuilder.h"
namespace llvm {
class ExecutionEngine;
}
namespace builder {
namespace mvll {
class BModuleDef;
SPUG_RCPTR(LLVMJitBuilder);
class LLVMJitBuilder : public LLVMBuilder {
private:
llvm::ExecutionEngine *execEng;
llvm::ExecutionEngine *bindJitModule(llvm::Module *mp);
std::vector< std::pair<llvm::Function *, llvm::Function *> > externals;
typedef std::map<std::string, llvm::GlobalValue *> CacheMapType;
CacheMapType *cacheMap;
virtual void run();
virtual void dump();
void doRunOrDump(model::Context &context);
void ensureCacheMap();
void setupCleanup(BModuleDef *moduleDef);
void cacheModule(model::Context &context, model::ModuleDef *moduleDef);
protected:
virtual void addGlobalFuncMapping(llvm::Function*,
llvm::Function*);
virtual void addGlobalFuncMapping(llvm::Function*,
void*);
virtual void engineBindModule(BModuleDef *moduleDef);
virtual void engineFinishModule(BModuleDef *moduleDef);
virtual void fixClassInstRep(BTypeDef *type);
virtual BModuleDef *instantiateModule(model::Context &context,
const std::string &name,
llvm::Module *owner
);
public:
virtual void addGlobalVarMapping(llvm::GlobalValue *decl,
llvm::GlobalValue *externalDef
);
LLVMJitBuilder(void) : execEng(0), cacheMap(0) { }
virtual void *getFuncAddr(llvm::Function *func);
virtual BuilderPtr createChildBuilder();
virtual model::ModuleDefPtr createModule(model::Context &context,
const std::string &name,
const std::string &path,
model::ModuleDef *module
);
void innerCloseModule(model::Context &context,
model::ModuleDef *module
);
virtual void closeModule(model::Context &context,
model::ModuleDef *module
);
virtual bool isExec() { return true; }
virtual void finishBuild(model::Context &context) {
if (cacheMap)
delete cacheMap;
}
virtual void initializeImport(model::ModuleDef* m,
const model::ImportedDefVec &symbols,
bool annotation) {
initializeImportCommon(m, symbols);
}
virtual void registerDef(model::Context &context,
model::VarDef *varDef
);
virtual model::ModuleDefPtr materializeModule(
model::Context &context,
const std::string &canonicalName,
model::ModuleDef *owner
);
virtual model::ModuleDefPtr registerPrimFuncs(model::Context &context);
};
} } // namespace
#endif
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#include "Utils.h"
#include "BTypeDef.h"
#include "Ops.h"
#include "LLVMBuilder.h"
#include "BCleanupFrame.h"
#include <llvm/Module.h>
#include <llvm/LLVMContext.h>
#include <llvm/GlobalValue.h>
#include <llvm/GlobalVariable.h>
#include <spug/StringFmt.h>
using namespace llvm;
using namespace model;
using namespace std;
namespace builder { namespace mvll {
void closeAllCleanupsStatic(Context &context) {
BCleanupFrame* frame = BCleanupFramePtr::rcast(context.cleanupFrame);
while (frame) {
frame->close();
frame = BCleanupFramePtr::rcast(frame->parent);
}
}
void addArrayMethods(Context &context, TypeDef *arrayType,
BTypeDef *elemType
) {
Construct *gd = context.construct;
FuncDefPtr arrayGetItem =
new GeneralOpDef<ArrayGetItemCall>(elemType, FuncDef::method,
"oper []",
1
);
arrayGetItem->args[0] = new ArgDef(gd->uintType.get(), "index");
context.addDef(arrayGetItem.get(), arrayType);
arrayGetItem =
new GeneralOpDef<ArrayGetItemCall>(elemType, FuncDef::method,
"oper []",
1
);
arrayGetItem->args[0] = new ArgDef(gd->intType.get(), "index");
context.addDef(arrayGetItem.get(), arrayType);
FuncDefPtr arraySetItem =
new GeneralOpDef<ArraySetItemCall>(elemType, FuncDef::method,
"oper []=",
2
);
arraySetItem->args[0] = new ArgDef(gd->uintType.get(), "index");
arraySetItem->args[1] = new ArgDef(elemType, "value");
context.addDef(arraySetItem.get(), arrayType);
arraySetItem =
new GeneralOpDef<ArraySetItemCall>(elemType, FuncDef::method,
"oper []=",
2
);
arraySetItem->args[0] = new ArgDef(gd->intType.get(), "index");
arraySetItem->args[1] = new ArgDef(elemType, "value");
context.addDef(arraySetItem.get(), arrayType);
FuncDefPtr arrayOffset =
new GeneralOpDef<ArrayOffsetCall>(arrayType, FuncDef::method,
"oper +",
1
);
arrayOffset->args[0] = new ArgDef(gd->uintType.get(), "offset");
context.addDef(arrayOffset.get(), arrayType);
arrayOffset =
new GeneralOpDef<ArrayOffsetCall>(arrayType, FuncDef::method,
"oper +",
1
);
arrayOffset->args[0] = new ArgDef(gd->intType.get(), "offset");
context.addDef(arrayOffset.get(), arrayType);
FuncDefPtr arrayAlloc =
new GeneralOpDef<ArrayAllocCall>(arrayType, FuncDef::noFlags,
"oper new",
1
);
arrayAlloc->args[0] = new ArgDef(gd->uintType.get(), "size");
context.addDef(arrayAlloc.get(), arrayType);
}
namespace {
string earlyCanonicalize(Context &context, const string &name) {
string canonicalName(context.parent->ns->getNamespaceName());
if (canonicalName.empty())
canonicalName = ".builtin";
canonicalName.append("."+name);
return canonicalName;
}
}
void createClassImpl(Context &context, BTypeDef *type) {
LLVMContext &lctx = getGlobalContext();
LLVMBuilder &llvmBuilder = dynamic_cast<LLVMBuilder &>(context.builder);
// get the LLVM class structure type from out of the meta class rep.
BTypeDef *classType = BTypeDefPtr::arcast(context.construct->classType);
PointerType *classPtrType = cast<PointerType>(classType->rep);
StructType *classStructType =
cast<StructType>(classPtrType->getElementType());
// create a global variable holding the class object.
vector<Constant *> classStructVals(3);
Constant *zero = ConstantInt::get(Type::getInt32Ty(lctx), 0);
Constant *index00[] = { zero, zero };
// build the unique canonical name we need to ensure unique symbols
// normally type->getFullName() would do this, but at this stage
// the type itself doesn't have an owner yet, so we build it from
// context
string canonicalName(earlyCanonicalize(context, type->name));
// name
Constant *nameInit = ConstantArray::get(lctx, type->name, true);
GlobalVariable *nameGVar =
new GlobalVariable(*llvmBuilder.module,
nameInit->getType(),
true, // is constant
GlobalValue::ExternalLinkage,
nameInit,
canonicalName + ":name"
);
classStructVals[0] =
ConstantExpr::getGetElementPtr(nameGVar, index00, 2);
// numBases
Type *uintType = BTypeDefPtr::arcast(context.construct->uintType)->rep;
classStructVals[1] = ConstantInt::get(uintType, type->parents.size());
// bases
vector<Constant *> basesVal(type->parents.size());
for (int i = 0; i < type->parents.size(); ++i) {
// get the pointer to the inner "Class" object of "Class[BaseName]"
BTypeDefPtr base = BTypeDefPtr::arcast(type->parents[i]);
// get the class body global variable
Constant *baseClassPtr = base->classInst;
// make sure that this is in the module
if (cast<GlobalValue>(baseClassPtr)->getParent() != llvmBuilder.module) {
const string &name = baseClassPtr->getName();
Type *classInstType =
cast<PointerType>(baseClassPtr->getType())->getElementType();
// see if we've already got a copy in this module
baseClassPtr =
llvmBuilder.module->getGlobalVariable(baseClassPtr->getName());
// if not, create a new global variable for us
if (!baseClassPtr) {
GlobalVariable *gvar;
baseClassPtr = gvar =
new GlobalVariable(*llvmBuilder.module,
classInstType,
true,
GlobalValue::ExternalLinkage,
0, // initializer: null for externs
name
);
llvmBuilder.addGlobalVarMapping(gvar, base->classInst);
}
}
// 1) if the base class is Class, just use the pointer
// 2) if it's Class[BaseName], GEP our way into the base class
// (Class) instance.
if (base->type.get() == base.get())
basesVal[i] = baseClassPtr;
else
basesVal[i] =
ConstantExpr::getGetElementPtr(baseClassPtr, index00, 2);
}
ArrayType *baseArrayType =
ArrayType::get(classType->rep, type->parents.size());
Constant *baseArrayInit = ConstantArray::get(baseArrayType, basesVal);
GlobalVariable *basesGVar =
new GlobalVariable(*llvmBuilder.module,
baseArrayType,
true, // is constant
GlobalValue::ExternalLinkage,
baseArrayInit,
canonicalName + ":bases"
);
classStructVals[2] =
ConstantExpr::getGetElementPtr(basesGVar, index00, 2);
// build the instance of Class
Constant *classStruct =
ConstantStruct::get(classStructType, classStructVals);
// extract the meta class structure types from our meta-class
PointerType *metaClassPtrType =
cast<PointerType>(BTypeDefPtr::arcast(type->type)->rep);
StructType *metaClassStructType =
cast<StructType>(metaClassPtrType->getElementType());
// initialize the structure based on whether we're implementing an
// instance of Class or an instance of a meta-class derived from Class.
Constant *classObjVal;
if (type->type.get() != context.construct->classType.get()) {
// this is an instance of a normal meta-class, wrap the Class
// implementation in another structure.
vector<Constant *> metaClassStructVals(1);
metaClassStructVals[0] = classStruct;
classObjVal =
ConstantStruct::get(metaClassStructType, metaClassStructVals);
} else {
// this is an instance of Class - just use the Class implementation as
// is.
metaClassPtrType = classPtrType;
metaClassStructType = classStructType;
classObjVal = classStruct;
}
// Create the class global variable
type->classInst =
new GlobalVariable(*llvmBuilder.module, metaClassStructType,
true, // is constant
GlobalValue::ExternalLinkage,
classObjVal,
canonicalName + ":body"
);
// create the pointer to the class instance
GlobalVariable *classInstPtr =
new GlobalVariable(*llvmBuilder.module, metaClassPtrType,
true, // is constant
GlobalVariable::ExternalLinkage,
type->classInst,
canonicalName
);
// store the impl object in the class
type->impl = new BGlobalVarDefImpl(classInstPtr);
}
// Create a new meta-class.
// context: enclosing context.
// name: the original non-canonical class name.
BTypeDefPtr createMetaClass(Context &context, const string &name) {
LLVMBuilder &llvmBuilder =
dynamic_cast<LLVMBuilder &>(context.builder);
LLVMContext &lctx = getGlobalContext();
// we canonicalize locally here with context because a canonical
// name for the type is not always available yet
string canonicalName(earlyCanonicalize(context, name));
BTypeDefPtr metaType =
new BTypeDef(context.construct->classType.get(),
SPUG_FSTR(canonicalName << ":meta"),
0,
true,
0
);
BTypeDef *classType = BTypeDefPtr::arcast(context.construct->classType);
metaType->addBaseClass(classType);
PointerType *classPtrType = cast<PointerType>(classType->rep);
StructType *classStructType =
cast<StructType>(classPtrType->getElementType());
// Create a struct representation of the meta class. This just has the
// Class class as its only field.
vector<Type *> fields(1);
fields[0] = classStructType;
StructType *metaClassStructType =
StructType::create(lctx, fields);
Type *metaClassPtrType = PointerType::getUnqual(metaClassStructType);
metaType->rep = metaClassPtrType;
metaType->complete = true;
// make the owner the builtin module if it is available, if it is not we
// are presumably registering primitives, so just use the module namespace.
if (context.construct->builtinMod)
context.construct->builtinMod->addDef(metaType.get());
else
context.getDefContext()->addDef(metaType.get());
createClassImpl(context, metaType.get());
metaClassStructType->setName(metaType->getFullName());
return metaType;
}
}} // namespace builder::mvll
| C++ |
// Copyright 2009-2011 Google Inc., Shannon Weyrick <weyrick@mozek.us>
#include "LLVMBuilder.h"
#include "ArrayTypeDef.h"
#include "BBuilderContextData.h"
#include "BBranchPoint.h"
#include "BCleanupFrame.h"
#include "BFieldRef.h"
#include "BFuncDef.h"
#include "BFuncPtr.h"
#include "BModuleDef.h"
#include "BResultExpr.h"
#include "BTypeDef.h"
#include "Consts.h"
#include "ExceptionCleanupExpr.h"
#include "FuncBuilder.h"
#include "FunctionTypeDef.h"
#include "Incompletes.h"
#include "LLVMValueExpr.h"
#include "Ops.h"
#include "PlaceholderInstruction.h"
#include "Utils.h"
#include "VarDefs.h"
#include "VTableBuilder.h"
#include "DebugInfo.h"
#include "parser/Parser.h"
#include "parser/ParseError.h"
#include <dlfcn.h>
#include <stddef.h>
#include <stdlib.h>
#include <errno.h>
#include <llvm/Module.h>
#include <llvm/LLVMContext.h>
#include <llvm/PassManager.h>
#include <llvm/CallingConv.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Intrinsics.h>
#include <spug/Exception.h>
#include <spug/StringFmt.h>
#include <model/AllocExpr.h>
#include <model/AssignExpr.h>
#include <model/CompositeNamespace.h>
#include <model/Construct.h>
#include <model/InstVarDef.h>
#include <model/LocalNamespace.h>
#include <model/NullConst.h>
#include <model/OverloadDef.h>
#include <model/StubDef.h>
#include <model/TernaryExpr.h>
using namespace std;
using namespace llvm;
using namespace model;
using namespace builder;
using namespace builder::mvll;
typedef model::FuncCall::ExprVec ExprVec;
// XXX find a way to remove this? see Incompletes.cc
Type *llvmIntType = 0;
int LLVMBuilder::argc = 1;
namespace {
char *tempArgv[] = {const_cast<char *>("undefined")};
}
char **LLVMBuilder::argv = tempArgv;
extern "C" {
char **__getArgv() {
return LLVMBuilder::argv;
}
int __getArgc() {
return LLVMBuilder::argc;
}
}
namespace {
// emit all cleanups from this context to outerContext (non-inclusive)
void emitCleanupsTo(Context &context, Context &outerContext) {
// unless we've reached our stop, emit for all parent contexts
if (&outerContext != &context) {
// close all cleanups in thie context
closeAllCleanupsStatic(context);
emitCleanupsTo(*context.parent, outerContext);
}
}
BasicBlock *emitUnwindFrameCleanups(BCleanupFrame *frame,
BasicBlock *next
) {
if (frame->parent)
next = emitUnwindFrameCleanups(
BCleanupFramePtr::rcast(frame->parent),
next
);
return frame->emitUnwindCleanups(next);
}
Value *getExceptionObjectField(Context &context, IRBuilder<> &builder,
int index
) {
VarDefPtr exStr = context.ns->lookUp(":exStruct");
BHeapVarDefImplPtr exStrImpl = BHeapVarDefImplPtr::arcast(exStr->impl);
return builder.CreateLoad(
builder.CreateConstGEP2_32(exStrImpl->rep, 0, index)
);
}
Value *getExceptionObjectValue(Context &context, IRBuilder<> &builder) {
return getExceptionObjectField(context, builder, 0);
}
Value *getExceptionSelectorValue(Context &context, IRBuilder<> &builder) {
return getExceptionObjectField(context, builder, 1);
}
BasicBlock *emitUnwindCleanups(Context &context, Context &outerContext,
BasicBlock *finalBlock
) {
// unless we've reached our stop, emit for all parent contexts
if (&outerContext != &context) {
// emit the cleanups in the parent block
BasicBlock *next =
emitUnwindCleanups(*context.parent, outerContext, finalBlock);
// close all cleanups in thie context
BCleanupFrame *frame =
BCleanupFramePtr::rcast(context.cleanupFrame);
return emitUnwindFrameCleanups(frame, next);
} else {
return finalBlock;
}
}
// Prepares a function "func" to act as an override for "override"
unsigned wrapOverride(TypeDef *classType, BFuncDef *overriden,
FuncBuilder &funcBuilder
) {
// find the path to the overriden's class
BTypeDef *overridenClass = BTypeDefPtr::acast(overriden->getOwner());
classType->getPathToAncestor(
*overridenClass,
funcBuilder.funcDef->pathToFirstDeclaration
);
// augment it with the path from the overriden to its first
// declaration.
funcBuilder.funcDef->pathToFirstDeclaration.insert(
funcBuilder.funcDef->pathToFirstDeclaration.end(),
overriden->pathToFirstDeclaration.begin(),
overriden->pathToFirstDeclaration.end()
);
// the type of the receiver is that of its first declaration
BTypeDef *receiverClass =
BTypeDefPtr::acast(overriden->getReceiverType());
funcBuilder.setReceiverType(receiverClass);
funcBuilder.funcDef->vtableSlot = overriden->vtableSlot;
return overriden->vtableSlot;
}
void finishClassType(Context &context, BTypeDef *classType) {
// for the kinds of things we're about to do, we need a global block
// for functions to restore to, and for that we need a function and
// module.
LLVMContext &lctx = getGlobalContext();
LLVMBuilder &builder = dynamic_cast<LLVMBuilder &>(context.builder);
// builder.module should already exist from .builtin module
assert(builder.module);
vector<Type *> argTypes;
FunctionType *voidFuncNoArgs =
FunctionType::get(Type::getVoidTy(lctx), argTypes, false);
Function *func = Function::Create(voidFuncNoArgs,
Function::ExternalLinkage,
"__builtin_init__",
builder.module
);
func->setCallingConv(llvm::CallingConv::C);
builder.builder.SetInsertPoint(BasicBlock::Create(lctx,
"__builtin_init__",
builder.func
)
);
// add "Class"
int lineNum = __LINE__ + 1;
string temp(" byteptr name;\n"
" uint numBases;\n"
" array[Class] bases;\n"
" bool isSubclass(Class other) {\n"
" if (this is other)\n"
" return (1==1);\n"
" uint i;\n"
" while (i < numBases) {\n"
" if (bases[i].isSubclass(other))\n"
" return (1==1);\n"
" i = i + uint(1);\n"
" }\n"
" return (1==0);\n"
" }\n"
"}\n"
);
// create the class context
ContextPtr classCtx =
context.createSubContext(Context::instance, classType);
CompositeNamespacePtr ns = new CompositeNamespace(classType,
context.ns.get()
);
ContextPtr lexicalContext =
classCtx->createSubContext(Context::composite, ns.get());
BBuilderContextData *bdata =
BBuilderContextData::get(lexicalContext.get());
istringstream src(temp);
try {
parser::Toker toker(src, "<builtin>", lineNum);
parser::Parser p(toker, lexicalContext.get());
p.parseClassBody();
} catch (parser::ParseError &ex) {
std::cerr << ex << endl;
assert(false);
}
// let the "end class" emitter handle the rest of this.
context.builder.emitEndClass(*classCtx);
// close off the block.
builder.builder.CreateRetVoid();
}
void fixMeta(Context &context, TypeDef *type) {
BTypeDefPtr metaType;
BGlobalVarDefImplPtr classImpl;
type->type = metaType = createMetaClass(context, type->name);
context.construct->registerDef(metaType.get());
metaType->meta = type;
createClassImpl(context, BTypeDefPtr::acast(type));
}
void addExplicitTruncate(Context &context, BTypeDef *sourceType,
BTypeDef *targetType
) {
FuncDefPtr func =
new GeneralOpDef<TruncOpCall>(targetType, FuncDef::noFlags,
"oper new",
1
);
func->args[0] = new ArgDef(sourceType, "val");
context.addDef(func.get(), targetType);
}
void addNopNew(Context &context, BTypeDef *type) {
FuncDefPtr func =
new GeneralOpDef<NoOpCall>(type, FuncDef::noFlags,
"oper new",
1
);
func->args[0] = new ArgDef(type, "val");
context.addDef(func.get(), type);
}
template <typename opType>
void addExplicitFPTruncate(Context &context, BTypeDef *sourceType,
BTypeDef *targetType
) {
FuncDefPtr func =
new GeneralOpDef<opType>(targetType, FuncDef::noFlags,
"oper new",
1
);
func->args[0] = new ArgDef(sourceType, "val");
context.addDef(func.get(), targetType);
}
BTypeDef *createIntPrimType(Context &context, Type *llvmType,
const char *name
) {
BTypeDefPtr btype = new BTypeDef(context.construct->classType.get(),
name,
llvmType
);
btype->defaultInitializer =
context.builder.createIntConst(context, 0, btype.get());
context.addDef(new BoolOpDef(context.construct->boolType.get(),
"oper to .builtin.bool"
),
btype.get()
);
// if you remove this, for the love of god, change the return type so
// we don't leak the pointer.
context.addDef(btype.get());
return btype.get();
}
BTypeDef *createFloatPrimType(Context &context, Type *llvmType,
const char *name
) {
BTypeDefPtr btype = new BTypeDef(context.construct->classType.get(),
name,
llvmType
);
btype->defaultInitializer =
context.builder.createFloatConst(context, 0.0, btype.get());
context.addDef(new FBoolOpDef(context.construct->boolType.get(),
"oper to .builtin.bool"
),
btype.get()
);
// if you remove this, for the love of god, change the return type so
// we don't leak the pointer.
context.addDef(btype.get());
return btype.get();
}
BBuilderContextData::CatchDataPtr getContextCatchData(Context &context) {
ContextPtr catchContext = context.getCatch();
if (!catchContext->toplevel) {
BBuilderContextDataPtr bdata =
BBuilderContextDataPtr::rcast(catchContext->builderData);
return bdata->getCatchData();
} else {
return 0;
}
}
} // anon namespace
void LLVMBuilder::emitFunctionCleanups(Context &context) {
// close all cleanups in this context.
closeAllCleanupsStatic(context);
// recurse up through the parents.
if (!context.toplevel && context.parent->scope == Context::local)
emitFunctionCleanups(*context.parent);
}
void LLVMBuilder::createLLVMModule(const string &name) {
LLVMContext &lctx = getGlobalContext();
module = new llvm::Module(name, lctx);
getDeclaration(module, Intrinsic::eh_selector);
getDeclaration(module, Intrinsic::eh_exception);
// our exception personality function
vector<Type *> args(5);;
args[0] = Type::getInt32Ty(lctx);
args[1] = args[0];
args[2] = Type::getInt64Ty(lctx);
args[3] = Type::getInt8Ty(lctx)->getPointerTo();
args[4] = args[3];
FunctionType *epType = FunctionType::get(Type::getVoidTy(lctx), args,
false
);
Constant *ep =
module->getOrInsertFunction("__CrackExceptionPersonality", epType);
exceptionPersonalityFunc = cast<Function>(ep);
}
void LLVMBuilder::initializeMethodInfo(Context &context, FuncDef::Flags flags,
FuncDef *existing,
BTypeDef *&classType,
FuncBuilder &funcBuilder
) {
if (!classType) {
ContextPtr classCtx = context.getClassContext();
assert(classCtx && "method is not nested in a class context.");
classType = BTypeDefPtr::arcast(classCtx->ns);
}
// create the vtable slot for a virtual function
if (flags & FuncDef::virtualized) {
// use the original's slot if this is an override.
if (existing) {
funcBuilder.funcDef->vtableSlot =
wrapOverride(classType, BFuncDefPtr::acast(existing),
funcBuilder
);
} else {
funcBuilder.funcDef->vtableSlot = classType->nextVTableSlot++;
funcBuilder.setReceiverType(classType);
}
} else {
funcBuilder.setReceiverType(classType);
}
}
// this is confusingly named - it returns a block suitable for use in the
// "unwind" clause of an invoke, which is actually a landing pad (elsewhere
// we're using "unwind" to refer to the "resume" block)
BasicBlock *LLVMBuilder::getUnwindBlock(Context &context) {
// get the catch-level context and unwind block
ContextPtr outerContext = context.getCatch();
BBranchpointPtr bpos =
BBranchpointPtr::rcast(outerContext->getCatchBranchpoint());
BasicBlock *final;
BBuilderContextData::CatchDataPtr cdata;
if (bpos) {
final = bpos->block;
// get the "catch data" for the context so we can correctly store
// placeholders instructions for the selector calls.
BBuilderContextData *outerBData =
BBuilderContextData::get(outerContext.get());;
cdata = outerBData->getCatchData();
} else {
// no catch clause. Find or create the unwind clause for the function
// to continue the unwind.
ContextPtr funcCtx = context.getToplevel();
BBuilderContextData *bdata =
BBuilderContextDataPtr::arcast(funcCtx->builderData);
BasicBlock *unwindBlock = bdata->getUnwindBlock(func);
final = unwindBlock;
// move the outer context back one level so we get cleanups for the
// function scope.
outerContext = outerContext->getParent();
}
BasicBlock *cleanups = emitUnwindCleanups(context, *outerContext, final);
BCleanupFrame *firstCleanupFrame =
BCleanupFramePtr::rcast(context.cleanupFrame);
return firstCleanupFrame->getLandingPad(cleanups, cdata.get());
}
void LLVMBuilder::clearCachedCleanups(Context &context) {
BCleanupFrame *frame = BCleanupFramePtr::rcast(context.cleanupFrame);
if (frame)
frame->clearCachedCleanups();
BBuilderContextData *bdata = BBuilderContextData::get(&context);
bdata->unwindBlock = 0;
}
void LLVMBuilder::narrow(TypeDef *curType, TypeDef *ancestor) {
// quick short-circuit to deal with the trivial case
if (curType == ancestor)
return;
assert(curType->isDerivedFrom(ancestor));
BTypeDef *bcurType = BTypeDefPtr::acast(curType);
BTypeDef *bancestor = BTypeDefPtr::acast(ancestor);
if (curType->complete) {
lastValue = IncompleteNarrower::emitGEP(builder, bcurType, bancestor,
lastValue
);
} else {
// create a placeholder instruction
PlaceholderInstruction *placeholder =
new IncompleteNarrower(lastValue, bcurType, bancestor,
builder.GetInsertBlock()
);
lastValue = placeholder;
// store it
bcurType->addPlaceholder(placeholder);
}
}
Function *LLVMBuilder::getModFunc(FuncDef *funcDef, Function *funcRep) {
ModFuncMap::iterator iter = moduleFuncs.find(funcDef);
if (iter == moduleFuncs.end()) {
// not found, create a new one and map it to the existing function
// pointer. We use 'ExternalWeakLinkage' for these because it
// prevents an abort if we lookup a pointer to a function that hasn't
// been defined yet.
BFuncDef *bfuncDef = BFuncDefPtr::acast(funcDef);
Function *func = Function::Create(funcRep->getFunctionType(),
Function::ExternalWeakLinkage,
funcRep->getName(),
module
);
// possibly do a global mapping (delegated to specific builder impl.)
addGlobalFuncMapping(func, funcRep);
// low level symbol name
if (!bfuncDef->symbolName.empty())
func->setName(bfuncDef->symbolName);
// cache it in the map
moduleFuncs[bfuncDef] = func;
return func;
} else {
return iter->second;
}
}
GlobalVariable *LLVMBuilder::getModVar(VarDefImpl *varDefImpl,
GlobalVariable *gvar
) {
ModVarMap::iterator iter = moduleVars.find(varDefImpl);
if (iter == moduleVars.end()) {
// extract the raw type
Type *type = gvar->getType()->getElementType();
assert(!module->getGlobalVariable(gvar->getName()) &&
"global variable redefined"
);
GlobalVariable *global =
new GlobalVariable(*module, type, gvar->isConstant(),
GlobalValue::ExternalLinkage,
0, // initializer: null for externs
gvar->getName()
);
// possibly do a global mapping (delegated to specific builder impl.)
addGlobalVarMapping(global, gvar);
moduleVars[varDefImpl] = global;
return global;
} else {
return iter->second;
}
}
BTypeDefPtr LLVMBuilder::getFuncType(Context &context,
FuncDef *funcDef,
llvm::Type *llvmFuncType
) {
// create a new type object and store it
TypeDefPtr function = context.construct->functionType.get();
if (!function) {
// there is no function in this context XXX this should create a
// deferred entry.
BTypeDefPtr crkFuncType = new BTypeDef(context.construct->classType.get(),
"",
llvmFuncType
);
// Give it an "oper to .builtin.voidptr" method.
context.addDef(
new VoidPtrOpDef(context.construct->voidptrType.get()),
crkFuncType.get()
);
return crkFuncType.get();
}
// we have function, specialize based on return and argument types
TypeDef::TypeVecObjPtr args = new TypeDef::TypeVecObj();
// push return
args->push_back(funcDef->returnType);
// if there is a receiver, push that
TypeDefPtr rcvrType = funcDef->getReceiverType();
if (rcvrType)
args->push_back(rcvrType.get());
// now args
for (FuncDef::ArgVec::iterator arg = funcDef->args.begin();
arg != funcDef->args.end();
++arg
) {
args->push_back((*arg)->type.get());
}
BTypeDefPtr specFuncType =
BTypeDefPtr::acast(function->getSpecialization(context, args.get()));
specFuncType->defaultInitializer = new NullConst(specFuncType.get());
return specFuncType.get();
}
BHeapVarDefImplPtr LLVMBuilder::createLocalVar(BTypeDef *tp, Value *&var,
Value *initVal
) {
// insert an alloca into the first block of the function - we
// define all of our allocas up front because if we do them in
// loops they eat the stack.
// if the last instruction is terminal, we need to insert before it
BasicBlock::iterator i = funcBlock->end();
if (i != funcBlock->begin() && !(--i)->isTerminator())
// otherwise insert after it.
++i;
IRBuilder<> b(funcBlock, i);
var = b.CreateAlloca(tp->rep, 0);
if (initVal)
b.CreateStore(initVal, var);
return new BHeapVarDefImpl(var);
}
void LLVMBuilder::emitExceptionCleanup(Context &context) {
ExprPtr cleanup =
new ExceptionCleanupExpr(context.construct->voidType.get());
// we don't need to close this cleanup frame, these cleanups get generated
// at the close of the context.
context.createCleanupFrame();
context.cleanupFrame->addCleanup(cleanup.get());
}
LLVMBuilder::LLVMBuilder() :
debugInfo(0),
bModDef(0),
module(0),
builder(getGlobalContext()),
func(0),
lastValue(0) {
}
ResultExprPtr LLVMBuilder::emitFuncCall(Context &context, FuncCall *funcCall) {
// get the LLVM arg list from the receiver and the argument expressions
vector<Value*> valueArgs;
// either a normal function call or a function pointer call
BFuncDef *funcDef = BFuncDefPtr::rcast(funcCall->func);
BFuncPtr *funcPtr;
if (!funcDef) {
funcPtr = BFuncPtrPtr::rcast(funcCall->func);
assert(funcPtr && "no funcDef or funcPtr");
}
// if there's a receiver, use it as the first argument.
Value *receiver;
if (funcCall->receiver) {
assert(funcDef && "funcPtr instead of funcDef");
funcCall->receiver->emit(context)->handleTransient(context);
narrow(funcCall->receiver->type.get(), funcDef->getReceiverType());
receiver = lastValue;
valueArgs.push_back(receiver);
} else {
receiver = 0;
}
// emit the arguments
FuncCall::ExprVec &vals = funcCall->args;
FuncDef::ArgVec::iterator argIter = funcCall->func->args.begin();
for (ExprVec::const_iterator valIter = vals.begin(); valIter < vals.end();
++valIter, ++argIter
) {
(*valIter)->emit(context)->handleTransient(context);
narrow((*valIter)->type.get(), (*argIter)->type.get());
valueArgs.push_back(lastValue);
}
// if we're already emitting cleanups for an unwind, both the normal
// destination block and the cleanup block are the same.
BasicBlock *followingBlock = 0, *cleanupBlock;
getInvokeBlocks(context, followingBlock, cleanupBlock);
if (funcCall->virtualized) {
assert(funcDef && "funcPtr instead of funcDef");
lastValue = IncompleteVirtualFunc::emitCall(context, funcDef,
receiver,
valueArgs,
followingBlock,
cleanupBlock
);
}
else {
// for a normal funcdef, get the Function*
// for a function pointer, we invoke the pointer directly
Value *callee = (funcDef) ? funcDef->getRep(*this) : funcPtr->rep;
lastValue =
builder.CreateInvoke(callee, followingBlock,
cleanupBlock,
valueArgs
);
}
// continue emitting code into the new following block.
if (followingBlock != cleanupBlock)
builder.SetInsertPoint(followingBlock);
return new BResultExpr(funcCall, lastValue);
}
ResultExprPtr LLVMBuilder::emitStrConst(Context &context, StrConst *val) {
BStrConst *bval = BStrConstPtr::cast(val);
// if the global string hasn't been defined yet in this module, create it
if (!bval->rep || bval->module != module) {
// we have to do this the hard way because strings may contain
// embedded nulls (IRBuilder.CreateGlobalStringPtr expects a
// null-terminated string)
LLVMContext &llvmContext = getGlobalContext();
Constant *llvmVal =
ConstantArray::get(llvmContext, val->val, true);
GlobalVariable *gvar = new GlobalVariable(*module,
llvmVal->getType(),
true, // is constant
GlobalValue::InternalLinkage,
llvmVal,
"str:"+
module->getModuleIdentifier(),
0,
false);
Value *zero = ConstantInt::get(Type::getInt32Ty(llvmContext), 0);
Value *args[] = { zero, zero };
bval->rep = builder.CreateInBoundsGEP(gvar,
ArrayRef<Value *>(args, 2)
);
bval->module = module;
}
lastValue = bval->rep;
return new BResultExpr(val, lastValue);
}
ResultExprPtr LLVMBuilder::emitIntConst(Context &context, IntConst *val) {
lastValue = dynamic_cast<const BIntConst *>(val)->rep;
return new BResultExpr(val, lastValue);
}
ResultExprPtr LLVMBuilder::emitFloatConst(Context &context, FloatConst *val) {
lastValue = dynamic_cast<const BFloatConst *>(val)->rep;
return new BResultExpr(val, lastValue);
}
ResultExprPtr LLVMBuilder::emitNull(Context &context,
NullConst *nullExpr
) {
BTypeDef *btype = BTypeDefPtr::arcast(nullExpr->type);
lastValue = Constant::getNullValue(btype->rep);
return new BResultExpr(nullExpr, lastValue);
}
ResultExprPtr LLVMBuilder::emitAlloc(Context &context, AllocExpr *allocExpr,
Expr *countExpr
) {
// XXX need to be able to do this for an incomplete class when we
// allow user defined oper new.
BTypeDef *btype = BTypeDefPtr::arcast(allocExpr->type);
PointerType *tp = cast<PointerType>(btype->rep);
// XXX mega-hack, clear the contents of the allocated memory (this is to
// get around the temporary lack of automatic member initialization)
// calculate the size of instances of the type
assert(llvmIntType && "integer type has not been initialized");
Value *size = IncompleteSizeOf::emitSizeOf(context, btype, llvmIntType);
// if a count expression was supplied, emit it. Otherwise, count is a
// constant 1
Value *countVal;
if (countExpr) {
countExpr->emit(context)->handleTransient(context);
countVal = lastValue;
} else {
countVal = ConstantInt::get(llvmIntType, 1);
}
// construct a call to the "calloc" function
BTypeDef *voidptrType =
BTypeDefPtr::arcast(context.construct->voidptrType);
vector<Value *> callocArgs(2);
callocArgs[0] = countVal;
callocArgs[1] = size;
Value *result = builder.CreateCall(callocFunc, callocArgs);
lastValue = builder.CreateBitCast(result, tp);
return new BResultExpr(allocExpr, lastValue);
}
void LLVMBuilder::emitTest(Context &context, Expr *expr) {
expr->emit(context);
BTypeDef *exprType = BTypeDefPtr::arcast(expr->type);
lastValue =
builder.CreateICmpNE(lastValue,
Constant::getNullValue(exprType->rep)
);
}
BranchpointPtr LLVMBuilder::emitIf(Context &context, Expr *cond) {
return labeledIf(context, cond, "true", "false", true);
}
BranchpointPtr LLVMBuilder::labeledIf(Context &context, Expr *cond,
const char* tLabel,
const char* fLabel,
bool condInCleanupFrame
) {
// create blocks for the true and false conditions
LLVMContext &lctx = getGlobalContext();
BasicBlock *trueBlock = BasicBlock::Create(lctx, tLabel, func);
BBranchpointPtr result = new BBranchpoint(
BasicBlock::Create(lctx, fLabel, func)
);
if (condInCleanupFrame) context.createCleanupFrame();
cond->emitCond(context);
Value *condVal = lastValue; // condition value
if (condInCleanupFrame) context.closeCleanupFrame();
result->block2 = builder.GetInsertBlock(); // condition block
lastValue = condVal;
builder.CreateCondBr(lastValue, trueBlock, result->block);
// repoint to the new ("if true") block
builder.SetInsertPoint(trueBlock);
return result;
}
BranchpointPtr LLVMBuilder::emitElse(model::Context &context,
model::Branchpoint *pos,
bool terminal
) {
BBranchpoint *bpos = BBranchpointPtr::cast(pos);
// create a block to come after the else and jump to it from the current
// "if true" block.
BasicBlock *falseBlock = bpos->block;
bpos->block = 0;
if (!terminal) {
bpos->block = BasicBlock::Create(getGlobalContext(), "cond_end", func);
builder.CreateBr(bpos->block);
}
// new block is the "false" condition
builder.SetInsertPoint(falseBlock);
return pos;
}
void LLVMBuilder::emitEndIf(Context &context,
Branchpoint *pos,
bool terminal
) {
BBranchpoint *bpos = BBranchpointPtr::cast(pos);
// branch from the current block to the next block
if (!terminal) {
if (!bpos->block)
bpos->block =
BasicBlock::Create(getGlobalContext(), "cond_end", func);
builder.CreateBr(bpos->block);
}
// if we ended up with any non-terminal paths our of the if, the new
// block is the next block
if (bpos->block)
builder.SetInsertPoint(bpos->block);
}
TernaryExprPtr LLVMBuilder::createTernary(model::Context &context,
model::Expr *cond,
model::Expr *trueVal,
model::Expr *falseVal,
model::TypeDef *type
) {
return new TernaryExpr(cond, trueVal, falseVal, type);
}
ResultExprPtr LLVMBuilder::emitTernary(Context &context, TernaryExpr *expr) {
// condition on first arg
BranchpointPtr pos = labeledIf(context, expr->cond.get(), "tern_T",
"tern_F",
false
);
BBranchpoint *bpos = BBranchpointPtr::arcast(pos);
Value *condVal = lastValue; // arg[0] condition value
BasicBlock *falseBlock = expr->falseVal ? bpos->block : 0; // false block
BasicBlock *oBlock = bpos->block2; // condition block
// now pointing to true block, save it for phi
BasicBlock *trueBlock = builder.GetInsertBlock();
// create the block after the expression (use the "false" block if there
// is no false value)
LLVMContext &lctx = getGlobalContext();
BasicBlock *postBlock =
expr->falseVal ? BasicBlock::Create(lctx, "after_tern", func) :
bpos->block;
// emit the true expression in its own cleanup frame
context.createCleanupFrame();
ResultExprPtr tempResult = expr->trueVal->emit(context);
narrow(expr->trueVal->type.get(), expr->type.get());
Value *trueVal = lastValue;
// if the false expression is productive and this one isn't, make it
// productive
if (expr->falseVal && expr->falseVal->isProductive() &&
!expr->trueVal->isProductive()
)
tempResult->handleAssignment(context);
context.closeCleanupFrame();
// branch to the end
builder.CreateBr(postBlock);
// pick up changes to the block
trueBlock = builder.GetInsertBlock();
// emit the false expression
Value *falseVal;
if (expr->falseVal) {
builder.SetInsertPoint(falseBlock);
context.createCleanupFrame();
tempResult = expr->falseVal->emit(context);
narrow(expr->falseVal->type.get(), expr->type.get());
falseVal = lastValue;
// if the true expression was productive, and this one isn't, make it
// productive
if (expr->trueVal->isProductive() && !expr->falseVal->isProductive())
tempResult->handleAssignment(context);
context.closeCleanupFrame();
builder.CreateBr(postBlock);
falseBlock = builder.GetInsertBlock();
}
// emit the phi
builder.SetInsertPoint(postBlock);
if (expr->falseVal) {
PHINode *p = builder.CreatePHI(
BTypeDefPtr::arcast(expr->type)->rep, 2,
"tern_R"
);
p->addIncoming(trueVal, trueBlock);
p->addIncoming(falseVal, falseBlock);
lastValue = p;
}
return new BResultExpr(expr, lastValue);
}
BranchpointPtr LLVMBuilder::emitBeginWhile(Context &context,
Expr *cond,
bool gotPostBlock
) {
LLVMContext &lctx = getGlobalContext();
BBranchpointPtr bpos = new BBranchpoint(BasicBlock::Create(lctx,
"while_end",
func
)
);
bpos->context = &context;
BasicBlock *whileCond =
BasicBlock::Create(lctx, "while_cond", func);
// if there is a post-loop block, make it block2 (which gets branched to
// at the end of the body and from continue) and make the the condition
// block3.
if (gotPostBlock) {
bpos->block2 = BasicBlock::Create(lctx, "while_post", func);
bpos->block3 = whileCond;
} else {
// no post-loop: block2 is the condition
bpos->block2 = whileCond;
}
BasicBlock *whileBody = BasicBlock::Create(lctx, "while_body", func);
builder.CreateBr(whileCond);
builder.SetInsertPoint(whileCond);
// XXX see notes above on a conditional type.
context.createCleanupFrame();
cond->emitCond(context);
Value *condVal = lastValue;
context.closeCleanupFrame();
lastValue = condVal;
builder.CreateCondBr(lastValue, whileBody, bpos->block);
// begin generating code in the while body
builder.SetInsertPoint(whileBody);
return bpos;
}
void LLVMBuilder::emitEndWhile(Context &context, Branchpoint *pos,
bool isTerminal
) {
BBranchpoint *bpos = BBranchpointPtr::cast(pos);
// emit the branch back to the conditional
if (!isTerminal)
// if there's a post-block, jump to the conditional
if (bpos->block3)
builder.CreateBr(bpos->block3);
else
builder.CreateBr(bpos->block2);
// new code goes to the following block
builder.SetInsertPoint(bpos->block);
}
void LLVMBuilder::emitPostLoop(model::Context &context,
model::Branchpoint *pos,
bool isTerminal
) {
// block2 should be the post-loop code, block3 should be the condition
BBranchpoint *bpos = BBranchpointPtr::cast(pos);
assert(bpos->block3 && "attempted to emit undeclared post-loop");
if (!isTerminal)
// branch from the end of the body to the post-loop
builder.CreateBr(bpos->block2);
// set the new block to the post-loop
builder.SetInsertPoint(bpos->block2);
}
void LLVMBuilder::emitBreak(Context &context, Branchpoint *branch) {
BBranchpoint *bpos = BBranchpointPtr::acast(branch);
emitCleanupsTo(context, *bpos->context);
builder.CreateBr(bpos->block);
}
void LLVMBuilder::emitContinue(Context &context, Branchpoint *branch) {
BBranchpoint *bpos = BBranchpointPtr::acast(branch);
emitCleanupsTo(context, *bpos->context);
builder.CreateBr(bpos->block2);
}
void LLVMBuilder::createSpecialVar(Namespace *ns, TypeDef *type,
const string &name
) {
Value *ptr;
BTypeDef *tp = BTypeDefPtr::cast(type);
VarDefPtr varDef = new VarDef(tp, name);
varDef->impl = createLocalVar(tp, ptr);
ptr->setName(name);
ns->addDef(varDef.get());
}
void LLVMBuilder::createFuncStartBlocks(const std::string &name) {
// create the "function block" (the first block in the function, will be
// used to hold all local variable allocations)
funcBlock = BasicBlock::Create(getGlobalContext(), name, func);
builder.SetInsertPoint(funcBlock);
// since the function block can get appended to arbitrarily, create a
// first block where it is safe for us to emit terminating instructions
BasicBlock *firstBlock = BasicBlock::Create(getGlobalContext(), "l",
func
);
builder.CreateBr(firstBlock);
builder.SetInsertPoint(firstBlock);
}
void LLVMBuilder::getInvokeBlocks(Context &context,
BasicBlock *&followingBlock,
BasicBlock *&cleanupBlock
) {
followingBlock = 0;
BBuilderContextData *bdata;
if (context.emittingCleanups &&
(bdata = BBuilderContextDataPtr::rcast(context.builderData))
) {
followingBlock = bdata->nextCleanupBlock;
BBuilderContextData::CatchDataPtr cdata =
getContextCatchData(context);
if (followingBlock)
cleanupBlock = createLandingPad(context, followingBlock,
cdata.get()
);
}
// otherwise, create a new normal destinatation block and get the cleanup
// block.
if (!followingBlock) {
followingBlock = BasicBlock::Create(getGlobalContext(), "l",
this->func
);
cleanupBlock = getUnwindBlock(context);
}
}
BModuleDef *LLVMBuilder::instantiateModule(Context &context,
const string &name,
Module *module
) {
return new BModuleDef(name, context.ns.get(), module);
}
void LLVMBuilder::emitExceptionCleanupExpr(Context &context) {
Value *exObjVal = getExceptionObjectValue(context, builder);
Function *cleanupExceptionFunc =
module->getFunction("__CrackCleanupException");
BasicBlock *followingBlock, *cleanupBlock;
getInvokeBlocks(context, followingBlock, cleanupBlock);
builder.CreateInvoke(cleanupExceptionFunc, followingBlock, cleanupBlock,
exObjVal
);
if (followingBlock != cleanupBlock)
builder.SetInsertPoint(followingBlock);
}
BasicBlock *LLVMBuilder::createLandingPad(
Context &context,
BasicBlock *next,
BBuilderContextData::CatchData *cdata
) {
BasicBlock *lp;
// look up the exception structure variable and get its type
VarDefPtr exStructVar = context.ns->lookUp(":exStruct");
Type *exStructType = BTypeDefPtr::arcast(exStructVar->type)->rep;
lp = BasicBlock::Create(getGlobalContext(), "lp", func);
IRBuilder<> b(lp);
Type *i8PtrType = b.getInt8PtrTy();
// get the personality func
Value *personality = exceptionPersonalityFunc;
// create a catch selector or a cleanup selector
Value *exStruct;
if (cdata) {
// We're in a try/catch. create the incomplete selector function
// call (class impls will get filled in later)
IncompleteCatchSelector *sel =
new IncompleteCatchSelector(exStructType, personality,
b.GetInsertBlock()
);
cdata->selectors.push_back(sel);
exStruct = sel;
} else {
// cleanups only
LandingPadInst *lpi =
b.CreateLandingPad(exStructType, personality, 0);
lpi->setCleanup(true);
exStruct = lpi;
}
// get the function-wide exception structure and store the landingpad
// result in it.
BMemVarDefImpl *exStructImpl =
BMemVarDefImplPtr::rcast(exStructVar->impl);
b.CreateStore(exStruct, exStructImpl->getRep(*this));
b.CreateBr(next);
return lp;
}
bool LLVMBuilder::suppressCleanups() {
// only ever want to do this if the last instruction is unreachable.
BasicBlock *block = builder.GetInsertBlock();
BasicBlock::iterator i = block->end();
return i != block->begin() &&
(--i)->getOpcode() == Instruction::Unreachable;
}
BranchpointPtr LLVMBuilder::emitBeginTry(model::Context &context) {
BasicBlock *catchSwitch = BasicBlock::Create(getGlobalContext(),
"catch_switch",
func
);
BBranchpointPtr bpos = new BBranchpoint(catchSwitch);
return bpos;
}
ExprPtr LLVMBuilder::emitCatch(Context &context,
Branchpoint *branchpoint,
TypeDef *catchType,
bool terminal
) {
BBranchpoint *bpos = BBranchpointPtr::cast(branchpoint);
// get the catch data
BBuilderContextData *bdata =
BBuilderContextData::get(&context);
BBuilderContextData::CatchDataPtr cdata = bdata->getCatchData();
// if this is the first catch block (as indicated by the lack of a
// "post-try" block in block2), create the post-try and create a branch to
// it in the current block.
if (!bpos->block2) {
bpos->block2 = BasicBlock::Create(getGlobalContext(), "after_try",
func
);
if (!terminal)
builder.CreateBr(bpos->block2);
// get the cleanup blocks for the contexts in the function outside of
// the catch
ContextPtr outsideFunction = context.getToplevel()->getParent();
BasicBlock *funcUnwindBlock = bdata->getUnwindBlock(func);
BasicBlock *outerCleanups = emitUnwindCleanups(*context.getParent(),
*outsideFunction,
funcUnwindBlock
);
// generate a switch instruction based on the value of
// the selector in :exStruct, we'll fill it in with values later.
builder.SetInsertPoint(bpos->block);
Value *selVal = getExceptionSelectorValue(context, builder);
cdata->switchInst =
builder.CreateSwitch(selVal, outerCleanups, 3);
// if the last catch block was not terminal, branch to after_try
} else if (!terminal) {
builder.CreateBr(bpos->block2);
}
// create a catch block and make it the new insert point.
BasicBlock *catchBlock = BasicBlock::Create(getGlobalContext(), "catch",
func
);
builder.SetInsertPoint(catchBlock);
// store the type and the catch block for later fixup
BTypeDef *btype = BTypeDefPtr::cast(catchType);
fixClassInstRep(btype);
cdata->catches.push_back(
BBuilderContextData::CatchBranch(btype, catchBlock)
);
// record it if the last block was non-terminal
if (!terminal)
cdata->nonTerminal = true;
// emit an expression to get the exception object
Value *exObjVal = getExceptionObjectValue(context, builder);
Function *getExFunc = module->getFunction("__CrackGetException");
vector<Value *> parms(1);
parms[0] = exObjVal;
lastValue = builder.CreateCall(getExFunc, parms);
lastValue = builder.CreateBitCast(lastValue, btype->rep);
return new LLVMValueExpr(catchType, lastValue);
}
void LLVMBuilder::emitEndTry(model::Context &context,
Branchpoint *branchpoint,
bool terminal
) {
// get the catch-data
BBuilderContextData *bdata = BBuilderContextData::get(&context);
BBuilderContextData::CatchDataPtr cdata = bdata->getCatchData();
BasicBlock *nextBlock = BBranchpointPtr::cast(branchpoint)->block2;
if (!terminal) {
builder.CreateBr(nextBlock);
cdata->nonTerminal = true;
}
if (!cdata->nonTerminal) {
// all blocks are terminal - delete the after_try block
nextBlock->eraseFromParent();
} else {
// emit subsequent code into the new block
builder.SetInsertPoint(nextBlock);
}
// if this is a nested try/catch block, add it to the catch data for its
// parent.
ContextPtr outer = context.getParent()->getCatch();
if (!outer->toplevel) {
// this isn't a toplevel, therefore it is a try/catch statement
BBuilderContextData::CatchDataPtr enclosingCData =
BBuilderContextData::get(outer.get())->getCatchData();
enclosingCData->nested.push_back(cdata);
} else {
cdata->fixAllSelectors(module);
}
}
void LLVMBuilder::emitThrow(Context &context, Expr *expr) {
Function *throwFunc = module->getFunction("__CrackThrow");
context.createCleanupFrame();
expr->emit(context);
narrow(expr->type.get(), context.construct->vtableBaseType.get());
BasicBlock *unwindBlock = getUnwindBlock(context),
*unreachableBlock = BasicBlock::Create(getGlobalContext(),
"unreachable",
func
);
builder.CreateInvoke(throwFunc, unreachableBlock, unwindBlock, lastValue);
builder.SetInsertPoint(unreachableBlock);
builder.CreateUnreachable();
// XXX think I actually want to discard the cleanup frame
context.closeCleanupFrame();
}
FuncDefPtr LLVMBuilder::createFuncForward(Context &context,
FuncDef::Flags flags,
const string &name,
TypeDef *returnType,
const vector<ArgDefPtr> &args,
FuncDef *override
) {
assert(flags & FuncDef::forward || flags & FuncDef::abstract);
// create the function
FuncBuilder f(context, flags, BTypeDefPtr::cast(returnType), name,
args.size()
);
f.setArgs(args);
BTypeDef *classType = 0;
if (flags & FuncDef::method)
initializeMethodInfo(context, flags, override, classType, f);
f.finish(false);
return f.funcDef;
}
BTypeDefPtr LLVMBuilder::createClass(Context &context, const string &name,
unsigned int nextVTableSlot
) {
BTypeDefPtr type;
BTypeDefPtr metaType = createMetaClass(context, name);
string canonicalName = context.parent->ns->getNamespaceName() +
"." + name;
StructType *curType;
// we first check to see if a structure with this canonical name exists
// if it does, we use it. if it doesn't we create it, and the body and
// name get set in emitEndClass
BTypeDefPtr existing =
BTypeDefPtr::rcast(context.construct->getRegisteredDef(canonicalName));
if (existing)
curType = cast<StructType>(existing->rep);
else
curType = StructType::create(getGlobalContext());
type = new BTypeDef(metaType.get(), name,
PointerType::getUnqual(curType),
true,
nextVTableSlot
);
// tie the meta-class to the class
metaType->meta = type.get();
// create the unsafeCast() function.
context.addDef(new UnsafeCastDef(type.get()), metaType.get());
// create function to convert to voidptr
context.addDef(new VoidPtrOpDef(context.construct->voidptrType.get()),
type.get());
// make the class default to initializing to null
type->defaultInitializer = new NullConst(type.get());
return type;
}
TypeDefPtr LLVMBuilder::createClassForward(Context &context,
const string &name
) {
TypeDefPtr result = createClass(context, name, 0);
result->forward = true;
return result;
}
FuncDefPtr LLVMBuilder::emitBeginFunc(Context &context,
FuncDef::Flags flags,
const string &name,
TypeDef *returnType,
const vector<ArgDefPtr> &args,
FuncDef *existing
) {
// store the current function and block in the context
BBuilderContextData *contextData =
BBuilderContextData::get(&context);
contextData->func = func;
contextData->block = builder.GetInsertBlock();
// if we didn't get a forward declaration, create the function.
BFuncDefPtr funcDef;
BTypeDef *classType = 0;
const vector<ArgDefPtr> *realArgs;
if (!existing || !(existing->flags & FuncDef::forward)) {
// create the function
FuncBuilder f(context, flags, BTypeDefPtr::cast(returnType), name,
args.size()
);
f.setArgs(args);
// see if this is a method, if so store the class type as the receiver type
if (flags & FuncDef::method) {
initializeMethodInfo(context, flags, existing, classType, f);
if (debugInfo)
debugInfo->emitFunctionDef(SPUG_FSTR(classType->getFullName() <<
"::" <<
name
),
context.getLocation()
);
} else if (debugInfo) {
debugInfo->emitFunctionDef(name, context.getLocation());
debugInfo->emitLexicalBlock(context.getLocation());
}
f.finish(false);
funcDef = f.funcDef;
realArgs = &args;
} else {
// 'existing' is a forward definition, fill it in.
funcDef = BFuncDefPtr::acast(existing);
classType = BTypeDefPtr::cast(funcDef->getOwner());
funcDef->flags =
static_cast<FuncDef::Flags>(
funcDef->flags &
static_cast<FuncDef::Flags>(~FuncDef::forward)
);
if (debugInfo) {
debugInfo->emitFunctionDef(funcDef->getFullName(),
context.getLocation()
);
debugInfo->emitLexicalBlock(context.getLocation());
}
realArgs = &existing->args;
}
func = funcDef->getRep(*this);
createFuncStartBlocks(name);
if (flags & FuncDef::virtualized) {
// emit code to convert from the first declaration base class
// instance to the method's class instance.
ArgDefPtr thisVar = funcDef->thisArg;
BArgVarDefImpl *thisImpl = BArgVarDefImplPtr::arcast(thisVar->impl);
Value *inst = thisImpl->rep;
Context *classCtx = context.getClassContext().get();
Value *thisRep =
IncompleteSpecialize::emitSpecialize(context,
classType,
inst,
funcDef->pathToFirstDeclaration
);
// lookup the "this" variable, and replace its rep
// VarDefPtr thisVar = context.ns->lookUp("this");
// BArgVarDefImpl *thisImpl = BArgVarDefImplPtr::arcast(thisVar->impl);
thisImpl->rep = thisRep;
}
// promote all of the arguments to local variables.
const vector<ArgDefPtr> &a = *realArgs;
for (int i = 0; i < args.size(); ++i)
a[i]->impl =
BArgVarDefImplPtr::arcast(a[i]->impl)->promote(*this, a[i].get());
// create a variable to hold the exception info from the landing pad
createSpecialVar(context.ns.get(), getExStructType(), ":exStruct");
return funcDef;
}
void LLVMBuilder::emitEndFunc(model::Context &context,
FuncDef *funcDef) {
// in certain conditions, (multiple terminating branches) we can end up
// with an empty block. If so, remove.
BasicBlock *block = builder.GetInsertBlock();
if (block->begin() == block->end())
block->eraseFromParent();
// restore the block and function
BBuilderContextData *contextData =
BBuilderContextDataPtr::rcast(context.builderData);
func = contextData->func;
funcBlock = func ? &func->front() : 0;
builder.SetInsertPoint(contextData->block);
}
FuncDefPtr LLVMBuilder::createExternFunc(Context &context,
FuncDef::Flags flags,
const string &name,
TypeDef *returnType,
TypeDef *receiverType,
const vector<ArgDefPtr> &args,
void *cfunc,
const char *symbolName
) {
// XXX only needed for linker?
// if a symbol name wasn't given, we look it up from the dynamic library
string symName(symbolName?symbolName:"");
if (symName.empty()) {
Dl_info dinfo;
int rdl = dladdr(cfunc, &dinfo);
if (!rdl || !dinfo.dli_sname) {
throw spug::Exception(SPUG_FSTR("unable to locate symbol for "
"extern function: " << name));
}
symName = dinfo.dli_sname;
}
ContextPtr funcCtx =
context.createSubContext(Context::local, new
LocalNamespace(context.ns.get(), name)
);
FuncBuilder f(*funcCtx, flags, BTypeDefPtr::cast(returnType),
name,
args.size()
);
if (!symName.empty())
f.setSymbolName(symName);
// if we've got a receiver, add it to the func builder and store a "this"
// variable.
if (receiverType) {
// see if there is an existing method to override
FuncDefPtr existing;
TypeDef *existingOwner = 0;
OverloadDefPtr ovld = context.lookUp(name);
if (ovld) {
existing = ovld->getSigMatch(args);
if (existing) {
existingOwner = TypeDefPtr::cast(existing->getOwner());
// ignore it if it's not a method from a base class.
if (!existingOwner ||
!receiverType->isDerivedFrom(existingOwner) ||
!(existing->flags & FuncDef::method)
)
existing = 0;
}
}
// if we're overriding a virtual in a base class, change the receiver
// type to that of the virtual method
if (existing) {
assert(existing->flags & FuncDef::virtualized);
receiverType = existingOwner;
}
f.setReceiverType(BTypeDefPtr::acast(receiverType));
ArgDefPtr thisDef =
funcCtx->builder.createArgDef(receiverType, "this");
funcCtx->addDef(thisDef.get());
}
f.setArgs(args);
f.finish(false);
primFuncs[f.funcDef->getRep(*this)] = cfunc;
return f.funcDef;
}
namespace {
void createOperClassFunc(Context &context,
BTypeDef *objClass
) {
// build a local context to hold the "this"
Context localCtx(context.builder, Context::local, &context,
new LocalNamespace(objClass, objClass->name),
context.compileNS.get()
);
localCtx.addDef(new ArgDef(objClass, "this"));
BTypeDef *classType =
BTypeDefPtr::arcast(context.construct->classType);
FuncBuilder funcBuilder(localCtx,
FuncDef::method | FuncDef::virtualized,
classType,
"oper class",
0
);
// ensure canonicalized symbol names for link
if (context.parent->ns) {
funcBuilder.setSymbolName(context.parent->ns->getNamespaceName()+
":oper class");
}
// if this is an override, do the wrapping.
FuncDefPtr override = context.lookUpNoArgs("oper class", true,
objClass
);
if (override) {
wrapOverride(objClass, BFuncDefPtr::arcast(override), funcBuilder);
} else {
// everything must have an override except for VTableBase::oper
// class.
assert(objClass == context.construct->vtableBaseType);
funcBuilder.funcDef->vtableSlot = objClass->nextVTableSlot++;
funcBuilder.setReceiverType(objClass);
}
funcBuilder.finish(false);
context.addDef(funcBuilder.funcDef.get(), objClass);
LLVMBuilder &lb = dynamic_cast<LLVMBuilder &>(context.builder);
BasicBlock *block = BasicBlock::Create(getGlobalContext(),
"oper class",
funcBuilder.funcDef->getRep(lb)
);
// body of the function: load the class instance global variable
IRBuilder<> builder(block);
BGlobalVarDefImpl *impl =
BGlobalVarDefImplPtr::arcast(objClass->impl);
Value *val = builder.CreateLoad(impl->getRep(lb));
// extract the Class instance from it and return it.
val = builder.CreateConstGEP2_32(val, 0, 0);
builder.CreateRet(val);
}
}
TypeDefPtr LLVMBuilder::emitBeginClass(Context &context,
const string &name,
const vector<TypeDefPtr> &bases,
TypeDef *forwardDef
) {
assert(!context.builderData);
BBuilderContextData *bdata =
BBuilderContextData::get(&context);
// find the first base class with a vtable
BTypeDef *baseWithVTable = 0;
for (vector<TypeDefPtr>::const_iterator iter = bases.begin();
iter != bases.end();
++iter
) {
BTypeDef *base = BTypeDefPtr::rcast(*iter);
if (base->hasVTable) {
baseWithVTable = base;
break;
}
}
BTypeDefPtr type;
if (!forwardDef) {
type = createClass(context, name,
baseWithVTable ?
baseWithVTable->nextVTableSlot : 0
);
} else {
type = BTypeDefPtr::acast(forwardDef);
type->nextVTableSlot =
baseWithVTable ? baseWithVTable->nextVTableSlot : 0;
type->forward = false;
}
// add all of the base classes to the type
for (vector<TypeDefPtr>::const_iterator iter = bases.begin();
iter != bases.end();
++iter
) {
BTypeDef *base = BTypeDefPtr::rcast(*iter);
type->addBaseClass(base);
}
// create the class implementation.
createClassImpl(context, type.get());
// make the type the namespace of the context
context.ns = type;
// create the "oper class" function - currently returns voidptr, but
// that's good enough for now.
if (baseWithVTable)
createOperClassFunc(context, type.get());
return type.get();
}
void LLVMBuilder::emitEndClass(Context &context) {
// build a vector of the base classes and instance variables
vector<Type *> members;
// first the base classes
BTypeDef *type = BTypeDefPtr::arcast(context.ns);
for (TypeDef::TypeVec::iterator baseIter = type->parents.begin();
baseIter != type->parents.end();
++baseIter
) {
BTypeDef *typeDef = BTypeDefPtr::arcast(*baseIter);
members.push_back(cast<PointerType>(typeDef->rep)->getElementType());
}
for (TypeDef::VarDefMap::iterator iter = type->beginDefs();
iter != type->endDefs();
++iter
) {
BFuncDef *funcDef;
// see if the variable needs an instance slot
if (iter->second->hasInstSlot()) {
BInstVarDefImpl *impl =
BInstVarDefImplPtr::rcast(iter->second->impl);
// resize the set of members if the new guy doesn't fit
if (impl->index >= members.size())
members.resize(impl->index + 1, 0);
// get the underlying type object, add it to the vector
BTypeDef *typeDef = BTypeDefPtr::rcast(iter->second->type);
members[impl->index] = typeDef->rep;
}
}
// if instances of the type require padding, add a character array.
if (type->padding)
members.push_back(ArrayType::get(builder.getInt8Ty(), type->padding));
// verify that all of the members have been assigned
for (vector<Type *>::iterator iter = members.begin();
iter != members.end();
++iter
)
assert(*iter);
// refine the type to the actual type of the structure.
// we also check and reuse an existing type of the same canonical name
// if it exists in this llvm context. this happens in caching scenarios
string canonicalName = context.parent->ns->getNamespaceName() +
"." + type->name;
// extract the struct type out of the existing pointer type
const PointerType *ptrType =
cast<PointerType>(type->rep);
StructType *curType = cast<StructType>(ptrType->getElementType());
// a type may already have a name here if it existed in the llvm context
// when createClass was called. this happens in caching scenarios. only if
// it doesn't have a name do we proceed with the body and the name
if (!curType->hasName()) {
curType->setBody(members);
curType->setName(canonicalName);
}
// verify that all of the base classes are complete (because we can only
// inherit from an incomplete base class in the case of a nested derived
// class, there can be only one incomplete base class)
TypeDefPtr incompleteBase;
for (TypeDef::TypeVec::iterator iter = type->parents.begin();
iter != type->parents.end();
++iter
) {
if (!(*iter)->complete) {
assert(!incompleteBase);
incompleteBase = *iter;
}
}
// if we have an incomplete base, we have to defer placeholder instruction
// resolution to the incomplete base class
if (incompleteBase)
BTypeDefPtr::arcast(incompleteBase)->addDependent(type, &context);
else
type->fixIncompletes(context);
}
void LLVMBuilder::emitReturn(model::Context &context,
model::Expr *expr) {
if (expr) {
ResultExprPtr resultExpr = expr->emit(context);
narrow(expr->type.get(), context.returnType.get());
Value *retVal = lastValue;
// XXX there's an opportunity for an optimization here, if we return a
// local variable, we should omit the cleanup of that local variable
// and the bind of the assignment.
resultExpr->handleAssignment(context);
emitFunctionCleanups(context);
builder.CreateRet(retVal);
} else {
emitFunctionCleanups(context);
builder.CreateRetVoid();
}
}
VarDefPtr LLVMBuilder::emitVarDef(Context &context, TypeDef *type,
const string &name,
Expr *initializer,
bool staticScope
) {
// XXX use InternalLinkage for variables starting with _ (I think that
// might work)
// reveal our type object
BTypeDef *tp = BTypeDefPtr::cast(type);
// get the definition context
ContextPtr defCtx = context.getDefContext();
// do initialization (unless we're in instance scope - instance variables
// get initialized in the constructors)
if (defCtx->scope != Context::instance) {
ResultExprPtr result;
if (initializer) {
result = initializer->emit(context);
narrow(initializer->type.get(), type);
} else {
// assuming that we don't need to narrow a default initializer.
result = type->defaultInitializer->emit(context);
}
// handle the assignment, then restore the original last value (since
// assignment handling can modify that.
Value *tmp = lastValue;
result->handleAssignment(context);
lastValue = tmp;
}
Value *var = 0;
BMemVarDefImplPtr varDefImpl;
switch (defCtx->scope) {
case Context::instance:
// class statics share the same context as instance variables:
// they are distinguished from instance variables by their
// declaration and are equivalent to module scoped globals in the
// way they are emitted, so if the staticScope flag is set we want
// to fall through to module scope
if (!staticScope) {
// first, we need to determine the index of the new field.
BTypeDef *btype = BTypeDefPtr::arcast(defCtx->ns);
unsigned idx = btype->fieldCount++;
// instance variables are unlike the other stored types - we
// use the InstVarDef class to preserve the initializer and a
// different kind of implementation object.
VarDefPtr varDef =
new InstVarDef(type, name,
initializer ? initializer :
type->defaultInitializer.get()
);
varDef->impl = new BInstVarDefImpl(idx);
return varDef;
}
case Context::module: {
GlobalVariable *gvar;
var = gvar =
new GlobalVariable(*module, tp->rep, false, // isConstant
GlobalValue::ExternalLinkage,
// initializer - this needs to be
// provided or the global will be
// treated as an extern.
Constant::getNullValue(tp->rep),
module->getModuleIdentifier()+"."+name
);
varDefImpl = new BGlobalVarDefImpl(gvar);
moduleVars[varDefImpl.get()] = gvar;
break;
}
case Context::local: {
varDefImpl = createLocalVar(tp, var);
break;
}
default:
assert(false && "invalid context value!");
}
// allocate the variable and assign it
lastValue = builder.CreateStore(lastValue, var);
// create the definition object.
VarDefPtr varDef = new VarDef(type, name);
varDef->impl = varDefImpl;
return varDef;
}
VarDefPtr LLVMBuilder::createOffsetField(model::Context &context,
model::TypeDef *type,
const std::string &name,
size_t offset
) {
VarDefPtr varDef = new VarDef(type, name);
varDef->impl = new BOffsetFieldDefImpl(offset);
return varDef;
}
CleanupFramePtr LLVMBuilder::createCleanupFrame(Context &context) {
return new BCleanupFrame(&context);
}
void LLVMBuilder::closeAllCleanups(Context &context) {
closeAllCleanupsStatic(context);
}
model::StrConstPtr LLVMBuilder::createStrConst(model::Context &context,
const std::string &val) {
return new BStrConst(context.construct->byteptrType.get(), val);
}
IntConstPtr LLVMBuilder::createIntConst(model::Context &context, int64_t val,
TypeDef *typeDef
) {
// XXX probably need to consider the simplest type that the constant can
// fit into (compatibility rules will allow us to coerce it into another
// type)
return new BIntConst(typeDef ? BTypeDefPtr::acast(typeDef) :
BTypeDefPtr::acast(IntConst::selectType(context,
val
)
),
val
);
}
// in this case, we know we have a constant big enough to require an unsigned
// 64 bit int
IntConstPtr LLVMBuilder::createUIntConst(model::Context &context, uint64_t val,
TypeDef *typeDef
) {
return new BIntConst(typeDef ? BTypeDefPtr::acast(typeDef) :
BTypeDefPtr::acast(
context.construct->uint64Type.get()),
val
);
}
FloatConstPtr LLVMBuilder::createFloatConst(model::Context &context, double val,
TypeDef *typeDef
) {
// XXX probably need to consider the simplest type that the constant can
// fit into (compatibility rules will allow us to coerce it into another
// type)
return new BFloatConst(typeDef ? BTypeDefPtr::acast(typeDef) :
BTypeDefPtr::arcast(context.construct->floatType),
val
);
}
model::FuncCallPtr LLVMBuilder::createFuncCall(FuncDef *func,
bool squashVirtual
) {
// try to create a BinCmp
OpDef *specialOp = OpDefPtr::cast(func);
if (specialOp) {
// if this is a bin op, let it create the call
return specialOp->createFuncCall();
} else {
// normal function call
return new FuncCall(func, squashVirtual);
}
}
ArgDefPtr LLVMBuilder::createArgDef(TypeDef *type,
const string &name
) {
// we don't create BBuilderVarDefData for these yet - we will back-fill
// the builder data when we create the function object.
ArgDefPtr argDef = new ArgDef(type, name);
return argDef;
}
VarRefPtr LLVMBuilder::createVarRef(VarDef *varDef) {
return new VarRef(varDef);
}
VarRefPtr LLVMBuilder::createFieldRef(Expr *aggregate,
VarDef *varDef
) {
return new BFieldRef(aggregate, varDef);
}
ResultExprPtr LLVMBuilder::emitFieldAssign(Context &context,
Expr *aggregate,
AssignExpr *assign
) {
aggregate->emit(context);
// narrow to the type of the ancestor that owns the field.
BTypeDef *typeDef = BTypeDefPtr::acast(assign->var->getOwner());
narrow(aggregate->type.get(), typeDef);
Value *aggregateRep = lastValue;
// emit the value last, lastValue after this needs to be the expression so
// we can chain assignments.
ResultExprPtr resultExpr = assign->value->emit(context);
// record the result as being bound to a variable.
Value *temp = lastValue;
resultExpr->handleAssignment(context);
lastValue = temp;
// narrow the value to the type of the variable (we do some funky checking
// here because of constants, which can present a different type that they
// match)
if (assign->value->type != assign->var->type &&
assign->value->type->isDerivedFrom(assign->var->type.get()))
narrow(assign->value->type.get(), assign->var->type.get());
// emit the field assignment or a placeholder
BFieldDefImplPtr impl = BFieldDefImplPtr::rcast(assign->var->impl);
if (typeDef->complete) {
impl->emitFieldAssign(builder, aggregateRep, lastValue);
} else {
// create a placeholder instruction
PlaceholderInstruction *placeholder =
new IncompleteInstVarAssign(aggregateRep->getType(),
aggregateRep,
impl.get(),
lastValue,
builder.GetInsertBlock()
);
// store it
typeDef->addPlaceholder(placeholder);
}
lastValue = temp;
return new BResultExpr(assign, temp);
}
ModuleDefPtr LLVMBuilder::registerPrimFuncs(model::Context &context) {
assert(!context.getParent()->getParent() && "parent context must be root");
assert(!module);
ConstructStats::CompileState oldStatState;
if (options->statsMode) {
oldStatState = context.construct->stats->state;
context.construct->stats->switchState(ConstructStats::builtin);
}
createLLVMModule(".builtin");
BModuleDefPtr bMod = instantiateModule(context, ".builtin", module);
bModDef = bMod.get();
Construct *gd = context.construct;
LLVMContext &lctx = getGlobalContext();
// create the basic types
BTypeDef *classType;
Type *classTypeRep = StructType::create(lctx);
Type *classTypePtrRep = PointerType::getUnqual(classTypeRep);
gd->classType = classType = new BTypeDef(0, "Class", classTypePtrRep);
classType->type = classType;
classType->meta = classType;
classType->defaultInitializer = new NullConst(classType);
context.addDef(classType);
context.construct->registerDef(classType);
// some tools for creating meta-classes
BTypeDefPtr metaType; // storage for meta-types
BTypeDef *voidType;
gd->voidType = voidType = new BTypeDef(context.construct->classType.get(),
"void",
Type::getVoidTy(lctx)
);
context.addDef(voidType);
deferMetaClass.push_back(voidType);
BTypeDef *voidptrType;
llvmVoidPtrType = Type::getInt8Ty(lctx)->getPointerTo();
PointerType::getUnqual(StructType::create(getGlobalContext()));
gd->voidptrType = voidptrType = new BTypeDef(context.construct->classType.get(),
"voidptr",
llvmVoidPtrType
);
voidptrType->defaultInitializer = new NullConst(voidptrType);
context.addDef(voidptrType);
deferMetaClass.push_back(voidptrType);
// now that we've got a voidptr type, give the class object a cast to it.
context.addDef(new VoidPtrOpDef(voidptrType), classType);
llvm::Type *llvmBytePtrType =
PointerType::getUnqual(Type::getInt8Ty(lctx));
BTypeDef *byteptrType;
gd->byteptrType = byteptrType = new BTypeDef(context.construct->classType.get(),
"byteptr",
llvmBytePtrType
);
byteptrType->defaultInitializer = createStrConst(context, "");
byteptrType->complete = true;
context.addDef(
new VoidPtrOpDef(context.construct->voidptrType.get()),
byteptrType
);
deferMetaClass.push_back(byteptrType);
FuncDefPtr funcDef =
new GeneralOpDef<UnsafeCastCall>(byteptrType, FuncDef::noFlags,
"oper new",
1
);
funcDef->args[0] = new ArgDef(voidptrType, "val");
context.addDef(funcDef.get(), byteptrType);
context.addDef(byteptrType);
Type *llvmBoolType = IntegerType::getInt1Ty(lctx);
BTypeDef *boolType;
gd->boolType = boolType = new BTypeDef(context.construct->classType.get(),
"bool",
llvmBoolType
);
gd->boolType->defaultInitializer = new BIntConst(boolType, (int64_t)0);
context.addDef(boolType);
deferMetaClass.push_back(boolType);
BTypeDef *byteType = createIntPrimType(context, Type::getInt8Ty(lctx),
"byte"
);
gd->byteType = byteType;
deferMetaClass.push_back(byteType);
BTypeDef *int16Type = createIntPrimType(context, Type::getInt16Ty(lctx),
"int16"
);
gd->int16Type = int16Type;
deferMetaClass.push_back(int16Type);
BTypeDef *int32Type = createIntPrimType(context, Type::getInt32Ty(lctx),
"int32"
);
gd->int32Type = int32Type;
deferMetaClass.push_back(int32Type);
BTypeDef *int64Type = createIntPrimType(context, Type::getInt64Ty(lctx),
"int64"
);
gd->int64Type = int64Type;
deferMetaClass.push_back(int64Type);
BTypeDef *uint16Type = createIntPrimType(context, Type::getInt16Ty(lctx),
"uint16"
);
gd->uint16Type = uint16Type;
deferMetaClass.push_back(uint16Type);
BTypeDef *uint32Type = createIntPrimType(context, Type::getInt32Ty(lctx),
"uint32"
);
gd->uint32Type = uint32Type;
deferMetaClass.push_back(uint32Type);
BTypeDef *uint64Type = createIntPrimType(context, Type::getInt64Ty(lctx),
"uint64"
);
gd->uint64Type = uint64Type;
deferMetaClass.push_back(uint64Type);
BTypeDef *float32Type = createFloatPrimType(context, Type::getFloatTy(lctx),
"float32"
);
gd->float32Type = float32Type;
deferMetaClass.push_back(float32Type);
BTypeDef *float64Type = createFloatPrimType(context,
Type::getDoubleTy(lctx),
"float64"
);
gd->float64Type = float64Type;
deferMetaClass.push_back(float64Type);
// PDNTs
BTypeDef *intType, *uintType, *floatType, *intzType, *uintzType;
bool intIs32Bit, ptrIs32Bit, floatIs32Bit;
if (sizeof(int) == 4) {
intIs32Bit = true;
intType = createIntPrimType(context, Type::getInt32Ty(lctx), "int");
uintType = createIntPrimType(context, Type::getInt32Ty(lctx), "uint");
} else {
assert(sizeof(int) == 8);
intIs32Bit = false;
intType = createIntPrimType(context, Type::getInt64Ty(lctx), "int");
uintType = createIntPrimType(context, Type::getInt64Ty(lctx), "uint");
}
gd->intType = intType;
gd->uintType = uintType;
gd->intSize = intIs32Bit ? 32 : 64;
llvmIntType = intType->rep;
deferMetaClass.push_back(intType);
deferMetaClass.push_back(uintType);
if (sizeof(void *) == 4) {
ptrIs32Bit = true;
intzType = createIntPrimType(context, Type::getInt32Ty(lctx), "intz");
uintzType = createIntPrimType(context, Type::getInt32Ty(lctx), "uintz");
} else {
assert(sizeof(void *) == 8);
ptrIs32Bit = false;
intzType = createIntPrimType(context, Type::getInt64Ty(lctx), "intz");
uintzType =
createIntPrimType(context, Type::getInt64Ty(lctx), "uintz");
}
gd->intzType = intzType;
gd->uintzType = uintzType;
gd->intzSize = ptrIs32Bit ? 32 : 64;
deferMetaClass.push_back(intzType);
deferMetaClass.push_back(uintzType);
if (sizeof(float) == 4) {
floatIs32Bit = true;
floatType = createFloatPrimType(context, Type::getFloatTy(lctx),
"float"
);
} else {
floatIs32Bit = false;
assert(sizeof(float) == 8);
floatType = createFloatPrimType(context, Type::getDoubleTy(lctx),
"float"
);
}
gd->floatType = floatType;
deferMetaClass.push_back(floatType);
// conversion from voidptr to integer
funcDef =
new GeneralOpDef<PtrToIntOpCall>(uintzType, FuncDef::noFlags,
"oper new",
1
);
funcDef->args[0] = new ArgDef(voidptrType, "val");
context.addDef(funcDef.get(), uintzType);
// the definition order of global binary operations is significant, when
// there is no exact match and we need to attempt conversions, we want to
// check the higher precision types first.
// create integer operations
#define INTOPS(type, signed, shift, ns) \
context.addDef(new AddOpDef(type, 0, ns), ns); \
context.addDef(new SubOpDef(type, 0, ns), ns); \
context.addDef(new MulOpDef(type, 0, ns), ns); \
context.addDef(new signed##DivOpDef(type, 0, ns), ns); \
context.addDef(new signed##RemOpDef(type, 0, ns), ns); \
context.addDef(new ICmpEQOpDef(type, boolType, ns), ns); \
context.addDef(new ICmpNEOpDef(type, boolType, ns), ns); \
context.addDef(new ICmp##signed##GTOpDef(type, boolType, ns), ns); \
context.addDef(new ICmp##signed##LTOpDef(type, boolType, ns), ns); \
context.addDef(new ICmp##signed##GEOpDef(type, boolType, ns), ns); \
context.addDef(new ICmp##signed##LEOpDef(type, boolType, ns), ns); \
context.addDef(new NegOpDef(type, "oper -", ns), ns); \
context.addDef(new BitNotOpDef(type, "oper ~", ns), ns); \
context.addDef(new OrOpDef(type, 0, ns), ns); \
context.addDef(new AndOpDef(type, 0, ns), ns); \
context.addDef(new XorOpDef(type, 0, ns), ns); \
context.addDef(new ShlOpDef(type, 0, ns), ns); \
context.addDef(new shift##ShrOpDef(type, 0, ns), ns);
INTOPS(byteType, U, L, 0)
INTOPS(int16Type, S, A, 0)
INTOPS(uint16Type, U, L, 0)
INTOPS(int32Type, S, A, 0)
INTOPS(uint32Type, U, L, 0)
INTOPS(int64Type, S, A, 0)
INTOPS(uint64Type, U, L, 0)
// float operations
#define FLOPS(type, ns) \
context.addDef(new FAddOpDef(type, 0, ns), ns); \
context.addDef(new FSubOpDef(type, 0, ns), ns); \
context.addDef(new FMulOpDef(type, 0, ns), ns); \
context.addDef(new FDivOpDef(type, 0, ns), ns); \
context.addDef(new FRemOpDef(type, 0, ns), ns); \
context.addDef(new FCmpOEQOpDef(type, boolType, ns), ns); \
context.addDef(new FCmpONEOpDef(type, boolType, ns), ns); \
context.addDef(new FCmpOGTOpDef(type, boolType, ns), ns); \
context.addDef(new FCmpOLTOpDef(type, boolType, ns), ns); \
context.addDef(new FCmpOGEOpDef(type, boolType, ns), ns); \
context.addDef(new FCmpOLEOpDef(type, boolType, ns), ns); \
context.addDef(new FNegOpDef(type, "oper -", ns), ns);
FLOPS(float32Type, 0)
FLOPS(float64Type, 0)
// Reverse integer operations
#define REVINTOPS(type, signed, shift) \
context.addDef(new AddROpDef(type, 0, true, true), type); \
context.addDef(new SubROpDef(type, 0, true, true), type); \
context.addDef(new MulROpDef(type, 0, true, true), type); \
context.addDef(new signed##DivROpDef(type, 0, true, true), type); \
context.addDef(new signed##RemROpDef(type, 0, true, true), type); \
context.addDef(new ICmpEQROpDef(type, boolType, true, true), type); \
context.addDef(new ICmpNEROpDef(type, boolType, true, true), type); \
context.addDef(new ICmpSGTROpDef(type, boolType, true, true), type); \
context.addDef(new ICmpSLTROpDef(type, boolType, true, true), type); \
context.addDef(new ICmpSGEROpDef(type, boolType, true, true), type); \
context.addDef(new ICmpSLEROpDef(type, boolType, true, true), type); \
context.addDef(new OrROpDef(type, 0, true, true), type); \
context.addDef(new AndROpDef(type, 0, true, true), type); \
context.addDef(new XorROpDef(type, 0, true, true), type); \
context.addDef(new ShlROpDef(type, 0, true, true), type); \
context.addDef(new shift##ShrROpDef(type, 0, true, true), type);
// reverse floating point operations
#define REVFLOPS(type) \
context.addDef(new FAddROpDef(type, 0, true, true), type); \
context.addDef(new FSubROpDef(type, 0, true, true), type); \
context.addDef(new FMulROpDef(type, 0, true, true), type); \
context.addDef(new FDivROpDef(type, 0, true, true), type); \
context.addDef(new FRemROpDef(type, 0, true, true), type); \
context.addDef(new FCmpOEQROpDef(type, boolType, true, true), type); \
context.addDef(new FCmpONEROpDef(type, boolType, true, true), type); \
context.addDef(new FCmpOGTROpDef(type, boolType, true, true), type); \
context.addDef(new FCmpOLTROpDef(type, boolType, true, true), type); \
context.addDef(new FCmpOGEROpDef(type, boolType, true, true), type); \
context.addDef(new FCmpOLEROpDef(type, boolType, true, true), type);
// PDNT operations need to be methods so that we try to resolve them with
// type conversions prior to attempting the general methods and _only if_
// one of the arguments is a PDNT. We also define reverse operations for
// them for the same reason.
INTOPS(intType, S, A, intType)
REVINTOPS(intType, S, A)
INTOPS(uintType, U, L, uintType)
REVINTOPS(uintType, U, L)
INTOPS(intzType, S, A, intzType)
REVINTOPS(intzType, S, A)
INTOPS(uintzType, U, L, uintzType)
REVINTOPS(intType, U, L)
FLOPS(floatType, floatType)
REVFLOPS(floatType)
// boolean logic
context.addDef(new LogicAndOpDef(boolType, boolType));
context.addDef(new LogicOrOpDef(boolType, boolType));
// implicit conversions (no loss of precision)
context.addDef(new ZExtOpDef(int16Type, "oper to .builtin.int16"), byteType);
context.addDef(new ZExtOpDef(int32Type, "oper to .builtin.int32"), byteType);
context.addDef(new ZExtOpDef(int64Type, "oper to .builtin.int64"), byteType);
context.addDef(new ZExtOpDef(uint16Type, "oper to .builtin.uint16"), byteType);
context.addDef(new ZExtOpDef(uint32Type, "oper to .builtin.uint32"), byteType);
context.addDef(new ZExtOpDef(uint64Type, "oper to .builtin.uint64"), byteType);
context.addDef(new ZExtOpDef(int32Type, "oper to .builtin.int32"), int16Type);
context.addDef(new ZExtOpDef(int64Type, "oper to .builtin.int64"), int16Type);
context.addDef(new ZExtOpDef(int32Type, "oper to .builtin.int32"), uint16Type);
context.addDef(new ZExtOpDef(int64Type, "oper to .builtin.int64"), uint16Type);
context.addDef(new ZExtOpDef(uint32Type, "oper to .builtin.uint32"), uint16Type);
context.addDef(new ZExtOpDef(uint64Type, "oper to .builtin.uint64"), uint16Type);
context.addDef(new UIToFPOpDef(float32Type, "oper to .builtin.float32"), byteType);
context.addDef(new UIToFPOpDef(float64Type, "oper to .builtin.float64"), byteType);
context.addDef(new SIToFPOpDef(float32Type, "oper to .builtin.float32"), int16Type);
context.addDef(new SIToFPOpDef(float64Type, "oper to .builtin.float64"), int16Type);
context.addDef(new UIToFPOpDef(float32Type, "oper to .builtin.float32"), uint16Type);
context.addDef(new UIToFPOpDef(float64Type, "oper to .builtin.float64"), uint16Type);
context.addDef(new SExtOpDef(int64Type, "oper to .builtin.int64"), int32Type);
context.addDef(new SIToFPOpDef(float64Type, "oper to .builtin.float64"), int32Type);
context.addDef(new ZExtOpDef(uint64Type, "oper to .builtin.uint64"), uint32Type);
context.addDef(new ZExtOpDef(int64Type, "oper to .builtin.int64"), uint32Type);
context.addDef(new UIToFPOpDef(float64Type, "oper to .builtin.float64"), uint32Type);
context.addDef(new FPExtOpDef(float64Type, "oper to .builtin.float64"), float32Type);
// implicit conversions from UNTs to PDNTs
context.addDef(new ZExtOpDef(intType, "oper to .builtin.int"), byteType);
context.addDef(new ZExtOpDef(uintType, "oper to .builtin.uint"), byteType);
context.addDef(new ZExtOpDef(intzType, "oper to .builtin.intz"), byteType);
context.addDef(new ZExtOpDef(uintzType, "oper to .builtin.uintz"), byteType);
context.addDef(new UIToFPOpDef(floatType, "oper to .builtin.float"), byteType);
context.addDef(new ZExtOpDef(intType, "oper to .builtin.int"), uint16Type);
context.addDef(new ZExtOpDef(uintType, "oper to .builtin.uint"), uint16Type);
context.addDef(new ZExtOpDef(intzType, "oper to .builtin.intz"), uint16Type);
context.addDef(new ZExtOpDef(uintzType, "oper to .builtin.uintz"), uint16Type);
context.addDef(new UIToFPOpDef(floatType, "oper to .builtin.float"), uint16Type);
context.addDef(new ZExtOpDef(intType, "oper to .builtin.int"), int16Type);
context.addDef(new ZExtOpDef(uintType, "oper to .builtin.uint"), int16Type);
context.addDef(new ZExtOpDef(intzType, "oper to .builtin.intz"), int16Type);
context.addDef(new ZExtOpDef(uintzType, "oper to .builtin.uintz"), int16Type);
context.addDef(new SIToFPOpDef(floatType, "oper to .builtin.float"), int16Type);
if (intIs32Bit) {
context.addDef(new NoOpDef(intType, "oper to .builtin.int"), int32Type);
context.addDef(new NoOpDef(uintType, "oper to .builtin.uint"), int32Type);
context.addDef(new NoOpDef(intType, "oper to .builtin.int"), uint32Type);
context.addDef(new NoOpDef(uintType, "oper to .builtin.uint"), uint32Type);
context.addDef(new TruncOpDef(intType, "oper to .builtin.int"), int64Type);
context.addDef(new TruncOpDef(uintType, "oper to .builtin.uint"), int64Type);
context.addDef(new TruncOpDef(intType, "oper to .builtin.int"), uint64Type);
context.addDef(new TruncOpDef(uintType, "oper to .builtin.uint"), uint64Type);
} else {
context.addDef(new SExtOpDef(intType, "oper to .builtin.int"), int32Type);
context.addDef(new ZExtOpDef(uintType, "oper to .builtin.uint"), int32Type);
context.addDef(new ZExtOpDef(intType, "oper to .builtin.int"), uint32Type);
context.addDef(new ZExtOpDef(uintType, "oper to .builtin.uint"), uint32Type);
context.addDef(new NoOpDef(intType, "oper to .builtin.int"), int64Type);
context.addDef(new NoOpDef(uintType, "oper to .builtin.uint"), int64Type);
context.addDef(new NoOpDef(intType, "oper to .builtin.int"), uint64Type);
context.addDef(new NoOpDef(uintType, "oper to .builtin.uint"), uint64Type);
}
if (ptrIs32Bit) {
context.addDef(new NoOpDef(intzType, "oper to .builtin.intz"), int32Type);
context.addDef(new NoOpDef(uintzType, "oper to .builtin.uintz"), int32Type);
context.addDef(new NoOpDef(intzType, "oper to .builtin.intz"), uint32Type);
context.addDef(new NoOpDef(uintzType, "oper to .builtin.uintz"), uint32Type);
context.addDef(new TruncOpDef(intzType, "oper to .builtin.intz"), int64Type);
context.addDef(new TruncOpDef(uintzType, "oper to .builtin.uintz"), int64Type);
context.addDef(new TruncOpDef(intzType, "oper to .builtin.intz"), uint64Type);
context.addDef(new TruncOpDef(uintzType, "oper to .builtin.uintz"), uint64Type);
} else {
context.addDef(new SExtOpDef(intzType, "oper to .builtin.intz"), int32Type);
context.addDef(new ZExtOpDef(uintzType, "oper to .builtin.uintz"), int32Type);
context.addDef(new ZExtOpDef(intzType, "oper to .builtin.intz"), uint32Type);
context.addDef(new ZExtOpDef(uintzType, "oper to .builtin.uintz"), uint32Type);
context.addDef(new NoOpDef(intzType, "oper to .builtin.intz"), int64Type);
context.addDef(new NoOpDef(uintzType, "oper to .builtin.uintz"), int64Type);
context.addDef(new NoOpDef(intzType, "oper to .builtin.intz"), uint64Type);
context.addDef(new NoOpDef(uintzType, "oper to .builtin.uintz"), uint64Type);
}
if (floatIs32Bit) {
context.addDef(new NoOpDef(floatType, "oper to .builtin.float"), float32Type);
context.addDef(new FPTruncOpDef(floatType, "oper to .builtin.float"),
float64Type
);
context.addDef(new FPExtOpDef(float64Type, "oper to .builtin.float64"),
floatType
);
} else {
context.addDef(new FPExtOpDef(floatType, "oper to .builtin.float"),
float32Type
);
context.addDef(new NoOpDef(floatType, "oper to .builtin.float"), float64Type);
context.addDef(new NoOpDef(float64Type, "oper to .builtin.float64"), floatType);
}
context.addDef(new SIToFPOpDef(floatType, "oper to .builtin.float"), int16Type);
context.addDef(new UIToFPOpDef(floatType, "oper to .builtin.float"), uint16Type);
context.addDef(new SIToFPOpDef(floatType, "oper to .builtin.float"), int32Type);
context.addDef(new UIToFPOpDef(floatType, "oper to .builtin.float"), uint32Type);
context.addDef(new SIToFPOpDef(floatType, "oper to .builtin.float"), int64Type);
context.addDef(new ZExtOpDef(intzType, "oper to .builtin.intz"), uint64Type);
context.addDef(new ZExtOpDef(uintzType, "oper to .builtin.uintz"), uint64Type);
context.addDef(new UIToFPOpDef(floatType, "oper to .builtin.float"), uint64Type);
context.addDef(new FPToSIOpDef(intType, "oper to .builtin.int"), float32Type);
context.addDef(new FPToUIOpDef(uintType, "oper to .builtin.uint"), float32Type);
context.addDef(new FPToSIOpDef(intzType, "oper to .builtin.intz"), float32Type);
context.addDef(new FPToUIOpDef(uintzType, "oper to .builtin.uintz"), float32Type);
context.addDef(new FPToSIOpDef(intType, "oper to .builtin.int"), float64Type);
context.addDef(new FPToUIOpDef(uintType, "oper to .builtin.uint"), float64Type);
context.addDef(new FPToSIOpDef(intzType, "oper to .builtin.intz"), float64Type);
context.addDef(new FPToUIOpDef(uintzType, "oper to .builtin.uintz"), float64Type);
// implicit conversion from PDNTs to UNTs
if (intIs32Bit) {
context.addDef(new SExtOpDef(int64Type, "oper to .builtin.int64"), intType);
context.addDef(new ZExtOpDef(uint64Type, "oper to .builtin.uint64"), uintType);
} else {
context.addDef(new NoOpDef(int64Type, "oper to .builtin.int64"), intType);
context.addDef(new NoOpDef(uint64Type, "oper to .builtin.uint64"), uintType);
}
if (ptrIs32Bit) {
context.addDef(new SExtOpDef(int64Type, "oper to .builtin.int64"), intzType);
context.addDef(new ZExtOpDef(uint64Type, "oper to .builtin.uint64"), uintzType);
} else {
context.addDef(new NoOpDef(int64Type, "oper to .builtin.int64"), intzType);
context.addDef(new NoOpDef(uint64Type, "oper to .builtin.uint64"), uintzType);
}
if (floatIs32Bit)
context.addDef(new FPExtOpDef(float64Type, "oper to .builtin.float64"),
floatType
);
else
context.addDef(new NoOpDef(float64Type, "oper to .builtin.float64"), floatType);
context.addDef(new UIToFPOpDef(float32Type, "oper to .builtin.float32"), uintType);
context.addDef(new SIToFPOpDef(float32Type, "oper to .builtin.float32"), intType);
context.addDef(new UIToFPOpDef(float64Type, "oper to .builtin.float64"), uintType);
context.addDef(new SIToFPOpDef(float64Type, "oper to .builtin.float64"), intType);
context.addDef(new UIToFPOpDef(float32Type, "oper to .builtin.float32"), uintzType);
context.addDef(new SIToFPOpDef(float32Type, "oper to .builtin.float32"), intzType);
context.addDef(new UIToFPOpDef(float64Type, "oper to .builtin.float64"), uintzType);
context.addDef(new SIToFPOpDef(float64Type, "oper to .builtin.float64"), intzType);
// implicit conversion from PDNTs to other PDNTs
context.addDef(new NoOpDef(uintType, "oper to .builtin.uint"), intType);
context.addDef(new NoOpDef(intType, "oper to .builtin.int"), uintType);
context.addDef(new NoOpDef(uintzType, "oper to .builtin.uintz"), intzType);
context.addDef(new NoOpDef(intzType, "oper to .builtin.intz"), uintzType);
if (intIs32Bit == ptrIs32Bit) {
context.addDef(new NoOpDef(intzType, "oper to .builtin.intz"), intType);
context.addDef(new NoOpDef(uintzType, "oper to .builtin.uintz"), intType);
context.addDef(new NoOpDef(intzType, "oper to .builtin.intz"), uintType);
context.addDef(new NoOpDef(uintzType, "oper to .builtin.uintz"), uintType);
context.addDef(new NoOpDef(intType, "oper to .builtin.int"), intzType);
context.addDef(new NoOpDef(uintType, "oper to .builtin.uint"), intzType);
context.addDef(new NoOpDef(intType, "oper to .builtin.int"), uintzType);
context.addDef(new NoOpDef(uintType, "oper to .builtin.uint"), uintzType);
} else if (intIs32Bit) {
context.addDef(new SExtOpDef(intzType, "oper to .builtin.intz"), intType);
context.addDef(new ZExtOpDef(uintzType, "oper to .builtin.uintz"), intType);
context.addDef(new ZExtOpDef(intzType, "oper to .builtin.intz"), uintType);
context.addDef(new ZExtOpDef(uintzType, "oper to .builtin.uintz"), uintType);
context.addDef(new TruncOpDef(intType, "oper to .builtin.int"), intzType);
context.addDef(new TruncOpDef(uintType, "oper to .builtin.uint"), intzType);
context.addDef(new TruncOpDef(intType, "oper to .builtin.int"), uintzType);
context.addDef(new TruncOpDef(uintType, "oper to .builtin.uint"), uintzType);
} else if (ptrIs32Bit) {
// integer is wider than a pointer? Not very likely, but just in
// case...
context.addDef(new TruncOpDef(intzType, "oper to .builtin.intz"), intType);
context.addDef(new TruncOpDef(uintzType, "oper to .builtin.uintz"), intType);
context.addDef(new TruncOpDef(intzType, "oper to .builtin.intz"), uintType);
context.addDef(new TruncOpDef(uintzType, "oper to .builtin.uintz"), uintType);
context.addDef(new SExtOpDef(intType, "oper to .builtin.int"), intzType);
context.addDef(new ZExtOpDef(uintType, "oper to .builtin.uint"), intzType);
context.addDef(new ZExtOpDef(intType, "oper to .builtin.int"), uintzType);
context.addDef(new ZExtOpDef(uintType, "oper to .builtin.uint"), uintzType);
}
context.addDef(new SIToFPOpDef(floatType, "oper to .builtin.float"), intType);
context.addDef(new UIToFPOpDef(floatType, "oper to .builtin.float"), uintType);
context.addDef(new SIToFPOpDef(floatType, "oper to .builtin.float"), intzType);
context.addDef(new UIToFPOpDef(floatType, "oper to .builtin.float"), uintzType);
context.addDef(new FPToUIOpDef(intType, "oper to .builtin.int"), floatType);
context.addDef(new FPToUIOpDef(uintType, "oper to .builtin.uint"), floatType);
context.addDef(new FPToUIOpDef(intzType, "oper to .builtin.intz"), floatType);
context.addDef(new FPToUIOpDef(uintzType, "oper to .builtin.uintz"), floatType);
// add the increment and decrement operators
context.addDef(new PreIncrIntOpDef(byteType, "oper ++x"), byteType);
context.addDef(new PreIncrIntOpDef(int16Type, "oper ++x"), int16Type);
context.addDef(new PreIncrIntOpDef(uint16Type, "oper ++x"), uint16Type);
context.addDef(new PreIncrIntOpDef(int32Type, "oper ++x"), int32Type);
context.addDef(new PreIncrIntOpDef(uint32Type, "oper ++x"), uint32Type);
context.addDef(new PreIncrIntOpDef(int64Type, "oper ++x"), int64Type);
context.addDef(new PreIncrIntOpDef(uint64Type, "oper ++x"), uint64Type);
context.addDef(new PreIncrIntOpDef(intType, "oper ++x"), intType);
context.addDef(new PreIncrIntOpDef(uintType, "oper ++x"), uintType);
context.addDef(new PreIncrIntOpDef(intzType, "oper ++x"), intzType);
context.addDef(new PreIncrIntOpDef(uintzType, "oper ++x"), uintzType);
context.addDef(new PreDecrIntOpDef(byteType, "oper --x"), byteType);
context.addDef(new PreDecrIntOpDef(int16Type, "oper --x"), int16Type);
context.addDef(new PreDecrIntOpDef(uint16Type, "oper --x"), uint16Type);
context.addDef(new PreDecrIntOpDef(int32Type, "oper --x"), int32Type);
context.addDef(new PreDecrIntOpDef(uint32Type, "oper --x"), uint32Type);
context.addDef(new PreDecrIntOpDef(int64Type, "oper --x"), int64Type);
context.addDef(new PreDecrIntOpDef(uint64Type, "oper --x"), uint64Type);
context.addDef(new PreDecrIntOpDef(intType, "oper --x"), intType);
context.addDef(new PreDecrIntOpDef(uintType, "oper --x"), uintType);
context.addDef(new PreDecrIntOpDef(intzType, "oper --x"), intzType);
context.addDef(new PreDecrIntOpDef(uintzType, "oper --x"), uintzType);
context.addDef(new PostIncrIntOpDef(byteType, "oper x++"), byteType);
context.addDef(new PostIncrIntOpDef(int16Type, "oper x++"), int16Type);
context.addDef(new PostIncrIntOpDef(uint16Type, "oper x++"), uint16Type);
context.addDef(new PostIncrIntOpDef(int32Type, "oper x++"), int32Type);
context.addDef(new PostIncrIntOpDef(uint32Type, "oper x++"), uint32Type);
context.addDef(new PostIncrIntOpDef(int64Type, "oper x++"), int64Type);
context.addDef(new PostIncrIntOpDef(uint64Type, "oper x++"), uint64Type);
context.addDef(new PostIncrIntOpDef(intType, "oper x++"), intType);
context.addDef(new PostIncrIntOpDef(uintType, "oper x++"), uintType);
context.addDef(new PostIncrIntOpDef(intzType, "oper x++"), intzType);
context.addDef(new PostIncrIntOpDef(uintzType, "oper x++"), uintzType);
context.addDef(new PostDecrIntOpDef(byteType, "oper x--"), byteType);
context.addDef(new PostDecrIntOpDef(int16Type, "oper x--"), int16Type);
context.addDef(new PostDecrIntOpDef(uint16Type, "oper x--"), uint16Type);
context.addDef(new PostDecrIntOpDef(int32Type, "oper x--"), int32Type);
context.addDef(new PostDecrIntOpDef(uint32Type, "oper x--"), uint32Type);
context.addDef(new PostDecrIntOpDef(int64Type, "oper x--"), int64Type);
context.addDef(new PostDecrIntOpDef(uint64Type, "oper x--"), uint64Type);
context.addDef(new PostDecrIntOpDef(intType, "oper x--"), intType);
context.addDef(new PostDecrIntOpDef(uintType, "oper x--"), uintType);
context.addDef(new PostDecrIntOpDef(intzType, "oper x--"), intzType);
context.addDef(new PostDecrIntOpDef(uintzType, "oper x--"), uintzType);
// explicit no-op construction
addNopNew(context, int64Type);
addNopNew(context, uint64Type);
addNopNew(context, int32Type);
addNopNew(context, uint32Type);
addNopNew(context, int16Type);
addNopNew(context, uint16Type);
addNopNew(context, byteType);
addNopNew(context, float32Type);
addNopNew(context, float64Type);
addNopNew(context, intType);
addNopNew(context, uintType);
addNopNew(context, intzType);
addNopNew(context, uintzType);
addNopNew(context, floatType);
// explicit (loss of precision)
addExplicitTruncate(context, int64Type, uint64Type);
addExplicitTruncate(context, int64Type, int32Type);
addExplicitTruncate(context, int64Type, uint32Type);
addExplicitTruncate(context, int64Type, int16Type);
addExplicitTruncate(context, int64Type, uint16Type);
addExplicitTruncate(context, int64Type, byteType);
addExplicitTruncate(context, uint64Type, int64Type);
addExplicitTruncate(context, uint64Type, int32Type);
addExplicitTruncate(context, uint64Type, uint32Type);
addExplicitTruncate(context, uint64Type, int16Type);
addExplicitTruncate(context, uint64Type, uint16Type);
addExplicitTruncate(context, uint64Type, byteType);
addExplicitTruncate(context, int32Type, byteType);
addExplicitTruncate(context, int32Type, uint16Type);
addExplicitTruncate(context, int32Type, int16Type);
addExplicitTruncate(context, int32Type, uint32Type);
addExplicitTruncate(context, uint32Type, byteType);
addExplicitTruncate(context, uint32Type, int16Type);
addExplicitTruncate(context, uint32Type, uint16Type);
addExplicitTruncate(context, uint32Type, int32Type);
addExplicitTruncate(context, int16Type, byteType);
addExplicitTruncate(context, int16Type, uint16Type);
addExplicitTruncate(context, uint16Type, byteType);
addExplicitTruncate(context, uint16Type, int16Type);
addExplicitTruncate(context, intType, int16Type);
addExplicitTruncate(context, intType, uint16Type);
addExplicitTruncate(context, intType, int32Type);
addExplicitTruncate(context, intType, uint32Type);
addExplicitTruncate(context, intType, byteType);
addExplicitTruncate(context, uintType, int16Type);
addExplicitTruncate(context, uintType, uint16Type);
addExplicitTruncate(context, uintType, int32Type);
addExplicitTruncate(context, uintType, uint32Type);
addExplicitTruncate(context, uintType, byteType);
addExplicitFPTruncate<FPTruncOpCall>(context, float64Type, float32Type);
addExplicitFPTruncate<FPToUIOpCall>(context, float32Type, byteType);
addExplicitFPTruncate<FPToSIOpCall>(context, float32Type, int16Type);
addExplicitFPTruncate<FPToUIOpCall>(context, float32Type, uint16Type);
addExplicitFPTruncate<FPToSIOpCall>(context, float32Type, int32Type);
addExplicitFPTruncate<FPToUIOpCall>(context, float32Type, uint32Type);
addExplicitFPTruncate<FPToSIOpCall>(context, float32Type, int64Type);
addExplicitFPTruncate<FPToUIOpCall>(context, float32Type, uint64Type);
addExplicitFPTruncate<FPToUIOpCall>(context, float64Type, byteType);
addExplicitFPTruncate<FPToSIOpCall>(context, float64Type, int16Type);
addExplicitFPTruncate<FPToUIOpCall>(context, float64Type, uint16Type);
addExplicitFPTruncate<FPToSIOpCall>(context, float64Type, int32Type);
addExplicitFPTruncate<FPToUIOpCall>(context, float64Type, uint32Type);
addExplicitFPTruncate<FPToSIOpCall>(context, float64Type, int64Type);
addExplicitFPTruncate<FPToUIOpCall>(context, float64Type, uint64Type);
addExplicitFPTruncate<SIToFPOpCall>(context, int64Type, float32Type);
addExplicitFPTruncate<SIToFPOpCall>(context, uint64Type, float32Type);
addExplicitFPTruncate<SIToFPOpCall>(context, int64Type, float64Type);
addExplicitFPTruncate<SIToFPOpCall>(context, uint64Type, float64Type);
// create the array generic
TypeDefPtr arrayType = new ArrayTypeDef(context.construct->classType.get(),
"array",
0
);
context.addDef(arrayType.get());
deferMetaClass.push_back(arrayType);
// create the raw function type
// "oper call" methods are added as this type is specialized during parse
TypeDefPtr functionType = new FunctionTypeDef(
context.construct->classType.get(),
"function",
0
);
context.addDef(functionType.get());
gd->functionType = functionType;
deferMetaClass.push_back(functionType);
{
// add the exception structure type (this is required for creating any
// kind of function)
vector<Type *> elems(2);
elems[0] = builder.getInt8PtrTy();
elems[1] = builder.getInt32Ty();
exStructType = new BTypeDef(metaType.get(), ":ExStruct",
StructType::get(lctx, elems),
false
);
}
// now that we have byteptr and array and all of the integer types, we can
// initialize the body of Class (the meta-type) and create an
// implementation object for it.
context.addDef(new IsOpDef(classType, boolType));
finishClassType(context, classType);
createClassImpl(context, classType);
// back fill the meta-class for the types defined so far.
for (int i = 0; i < deferMetaClass.size(); ++i)
fixMeta(context, deferMetaClass[i].get());
deferMetaClass.clear();
// create OverloadDef's type
metaType = createMetaClass(context, "Overload");
BTypeDefPtr overloadDef = new BTypeDef(metaType.get(), "Overload", 0);
metaType->meta = overloadDef.get();
createClassImpl(context, overloadDef.get());
// Give it a context and an "oper to .builtin.voidptr" method.
context.addDef(
new VoidPtrOpDef(context.construct->voidptrType.get()),
overloadDef.get()
);
// create an empty structure type and its pointer for VTableBase
// Actual type is {}** (another layer of pointer indirection) because
// classes need to be pointer types.
vector<Type *> members;
Type *vtableType = StructType::create(getGlobalContext(), members,
".builtin.VTableBase"
);
Type *vtablePtrType = PointerType::getUnqual(vtableType);
metaType = createMetaClass(context, "VTableBase");
BTypeDef *vtableBaseType;
gd->vtableBaseType = vtableBaseType =
new BTypeDef(metaType.get(), "VTableBase",
PointerType::getUnqual(vtablePtrType),
true
);
vtableBaseType->hasVTable = true;
createClassImpl(context, vtableBaseType);
metaType->meta = vtableBaseType;
context.addDef(vtableBaseType);
context.construct->registerDef(vtableBaseType);
createOperClassFunc(context, vtableBaseType);
// build VTableBase's vtable
VTableBuilder vtableBuilder(this, vtableBaseType);
vtableBaseType->createAllVTables(vtableBuilder, ".vtable.VTableBase",
vtableBaseType
);
vtableBuilder.emit(vtableBaseType);
// finally, mark the class as complete
vtableBaseType->complete = true;
// pointer equality check (to allow checking for None)
context.addDef(new IsOpDef(voidptrType, boolType));
context.addDef(new IsOpDef(byteptrType, boolType));
// boolean not
context.addDef(new BitNotOpDef(boolType, "oper !"));
// byteptr array indexing
addArrayMethods(context, byteptrType, byteType);
// bind the module to the execution engine
engineBindModule(bMod.get());
engineFinishModule(bMod.get());
if (options->statsMode) {
context.construct->stats->switchState(oldStatState);
}
return bMod;
}
std::string LLVMBuilder::getSourcePath(const std::string &path) {
char *rp = realpath(path.c_str(), NULL);
string result;
if (!rp) {
result = path;
}
else {
result = rp;
free(rp);
}
return result;
}
void LLVMBuilder::initializeImportCommon(model::ModuleDef* m,
const ImportedDefVec &symbols) {
BModuleDef *importedMod = dynamic_cast<BModuleDef*>(m);
assert(bModDef && "no bModDef before initializeImportCommon");
assert(importedMod && "importedMod was not a BModuleDef");
assert(importedMod->getFullName().find('[') == -1);
bModDef->importList[importedMod] = symbols;
}
void LLVMBuilder::createModuleCommon(Context &context) {
ConstructStats::CompileState oldStatState;
if (options->statsMode) {
oldStatState = context.construct->stats->state;
context.construct->stats->switchState(ConstructStats::builtin);
}
// name some structs in this module
BTypeDef *classType = BTypeDefPtr::arcast(context.construct->classType);
BTypeDef *vtableBaseType = BTypeDefPtr::arcast(
context.construct->vtableBaseType);
// all of the "extern" primitive functions have to be created in each of
// the modules - we can not directly reference across modules.
//BTypeDef *int32Type = BTypeDefPtr::arcast(context.construct->int32Type);
//BTypeDef *int64Type = BTypeDefPtr::arcast(context.construct->int64Type);
//BTypeDef *uint64Type = BTypeDefPtr::arcast(context.construct->uint64Type);
BTypeDef *intType = BTypeDefPtr::arcast(context.construct->intType);
BTypeDef *voidType = BTypeDefPtr::arcast(context.construct->int32Type);
//BTypeDef *float32Type = BTypeDefPtr::arcast(context.construct->float32Type);
BTypeDef *byteptrType =
BTypeDefPtr::arcast(context.construct->byteptrType);
BTypeDef *voidptrType =
BTypeDefPtr::arcast(context.construct->voidptrType);
// create "void *calloc(uint size)"
{
FuncBuilder f(context, FuncDef::noFlags, voidptrType, "calloc", 2);
f.addArg("size", intType);
f.addArg("size", intType);
f.setSymbolName("calloc");
f.finish();
callocFunc = f.funcDef->getRep(*this);
}
// create "array[byteptr] __getArgv()"
{
TypeDefPtr array = context.ns->lookUp("array");
assert(array.get() && "array not defined in context");
TypeDef::TypeVecObjPtr types = new TypeDef::TypeVecObj();
types->push_back(byteptrType);
TypeDefPtr arrayOfByteptr =
array->getSpecialization(context, types.get());
FuncBuilder f(context, FuncDef::noFlags,
BTypeDefPtr::arcast(arrayOfByteptr),
"__getArgv",
0
);
f.setSymbolName("__getArgv");
f.finish();
}
// create "int __getArgc()"
{
FuncBuilder f(context, FuncDef::noFlags, intType, "__getArgc", 0);
f.setSymbolName("__getArgc");
f.finish();
}
// create "__CrackThrow(VTableBase)"
{
FuncBuilder f(context, FuncDef::noFlags, voidType, "__CrackThrow", 1);
f.addArg("exception", vtableBaseType);
f.setSymbolName("__CrackThrow");
f.finish();
}
// create "__CrackGetException(voidptr)"
{
FuncBuilder f(context, FuncDef::noFlags, voidptrType,
"__CrackGetException",
1
);
f.addArg("exceptionObject", byteptrType);
f.setSymbolName("__CrackGetException");
f.finish();
}
// create "__CrackBadCast(Class a, Class b)"
{
FuncBuilder f(context, FuncDef::noFlags, voidType,
"__CrackBadCast",
2
);
f.addArg("curType", classType);
f.addArg("newType", classType);
f.setSymbolName("__CrackBadCast");
f.finish();
}
// create "__CrackCleanupException(voidptr exceptionObject)"
{
FuncBuilder f(context, FuncDef::noFlags, voidType,
"__CrackCleanupException",
1
);
f.addArg("exceptionObject", voidptrType);
f.setSymbolName("__CrackCleanupException");
f.finish();
}
// create "__CrackExceptionFrame()"
{
FuncBuilder f(context, FuncDef::noFlags, voidType,
"__CrackExceptionFrame",
0
);
f.setSymbolName("__CrackExceptionFrame");
f.finish();
}
if (options->statsMode) {
context.construct->stats->switchState(oldStatState);
}
// create the exception structure for the module main function
createSpecialVar(context.ns.get(), getExStructType(), ":exStruct");
}
void *LLVMBuilder::loadSharedLibrary(const std::string &name) {
// leak the handle so the library stays mapped for the life of the process.
void *handle = dlopen(name.c_str(), RTLD_LAZY|RTLD_GLOBAL);
if (!handle)
throw spug::Exception(dlerror());
return handle;
}
void LLVMBuilder::importSharedLibrary(const string &name,
const ImportedDefVec &symbols,
Context &context,
Namespace *ns
) {
void *handle = loadSharedLibrary(name);
for (ImportedDefVec::const_iterator iter = symbols.begin();
iter != symbols.end();
++iter
) {
void *sym = dlsym(handle, iter->source.c_str());
if (!sym)
throw spug::Exception(dlerror());
// save for caching (when called from parser). when called from Cacher,
// we don't save (and don't need to since we're already cached)
if (bModDef)
bModDef->shlibImportList[name] = symbols;
// store a stub for the symbol
ns->addDef(new StubDef(context.construct->voidType.get(),
iter->local,
sym
)
);
}
}
void LLVMBuilder::registerImportedDef(Context &context, VarDef *varDef) {
// no-op for LLVM builder.
}
void LLVMBuilder::setArgv(int newArgc, char **newArgv) {
argc = newArgc;
argv = newArgv;
}
void LLVMBuilder::emitMemVarRef(Context &context, Value *val) {
lastValue = builder.CreateLoad(val);
}
void LLVMBuilder::emitArgVarRef(Context &context, Value *val) {
lastValue = val;
}
void LLVMBuilder::emitVTableInit(Context &context, TypeDef *typeDef) {
BTypeDef *btype = BTypeDefPtr::cast(typeDef);
BTypeDef *vtableBaseType =
BTypeDefPtr::arcast(context.construct->vtableBaseType);
PlaceholderInstruction *vtableInit =
new IncompleteVTableInit(btype, lastValue, vtableBaseType,
builder.GetInsertBlock()
);
// store it
btype->addPlaceholder(vtableInit);
}
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_llvm_VTableBuilder_h_
#define _builder_llvm_VTableBuilder_h_
#include <spug/RCPtr.h>
#include <spug/RCBase.h>
#include <map>
#include <string>
#include <vector>
#include "LLVMBuilder.h" // need this because we are accessing its methods
namespace llvm {
class Constant;
class Module;
}
namespace builder {
namespace mvll {
class BTypeDef;
class BFuncDef;
SPUG_RCPTR(VTableInfo);
// stores information on a single VTable
class VTableInfo : public spug::RCBase {
private:
// give an error if we try to copy this
VTableInfo(const VTableInfo &other);
public:
// the vtable variable name
std::string name;
// the vtable entries
std::vector<llvm::Constant *> entries;
VTableInfo(const std::string &name) : name(name) {}
void dump();
};
// encapsulates all of the vtables for a new type
class VTableBuilder {
private:
typedef std::map<BTypeDef *, VTableInfoPtr> VTableMap;
VTableMap vtables;
// keep track of the first VTable in the type
VTableInfo *firstVTable;
// used for emmission, but also IR type naming
llvm::Module *module;
// used to get correct Function* for the builder's Module*
LLVMBuilder *builder;
public:
BTypeDef *vtableBaseType;
VTableBuilder(LLVMBuilder *b,
BTypeDef *vtableBaseType) :
firstVTable(0),
vtableBaseType(vtableBaseType),
module(b->module),
builder(b) {
}
void dump();
void addToAncestor(BTypeDef *ancestor, BFuncDef *func);
// add the function to all vtables.
void addToAll(BFuncDef *func);
// add a new function entry to the appropriate VTable
void add(BFuncDef *func);
// create a new VTable
void createVTable(BTypeDef *type, const std::string &name,
bool first);
// emit all of the VTable globals
void emit(BTypeDef *type);
};
} // end namespace builder::mvll
} // end namespace builder
#endif
| C++ |
// Copyright 2011 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_llvm_BModuleDef_h_
#define _builder_llvm_BModuleDef_h_
#include "builder/util/SourceDigest.h"
#include "model/ModuleDef.h"
#include "model/ImportedDef.h"
#include <spug/RCPtr.h>
#include <string>
#include <vector>
#include <map>
namespace model {
class Context;
}
namespace llvm {
class Module;
}
namespace builder {
namespace mvll {
SPUG_RCPTR(BModuleDef);
class BModuleDef : public model::ModuleDef {
public:
// primitive cleanup function
void (*cleanup)();
llvm::Module *rep;
// source text hash code, used for caching
SourceDigest digest;
// list of modules imported by this one, along with its imported symbols
typedef std::map<BModuleDef*, model::ImportedDefVec > ImportListType;
ImportListType importList;
// list of shared libraries imported, along with imported symbols
typedef std::map<std::string, model::ImportedDefVec > ShlibImportListType;
ShlibImportListType shlibImportList;
BModuleDef(const std::string &canonicalName,
model::Namespace *parent,
llvm::Module *rep0
) :
ModuleDef(canonicalName, parent),
cleanup(0),
rep(rep0),
digest(),
importList()
{
}
void callDestructor() {
if (cleanup)
cleanup();
}
void recordDependency(ModuleDef *other);
virtual bool matchesSource(const std::string &source) {
return digest == SourceDigest::fromFile(source);
}
};
} // end namespace builder::vmll
} // end namespace builder
#endif
| C++ |
// Copyright 2012 Shannon Weyrick <weyrick@mozek.us>
#include "StructResolver.h"
#include <assert.h>
#include <ctype.h>
#include <vector>
#include <iostream>
#include <llvm/ADT/StringMap.h>
#include <llvm/Module.h>
#include <llvm/LLVMContext.h>
#include <llvm/DerivedTypes.h>
#include <llvm/User.h>
#include <llvm/Constants.h>
using namespace llvm;
using namespace std;
#define SR_DEBUG if (0)
namespace {
const char *tName(int t) {
if (t == 11)
return "Structure";
else if (t == 12)
return "Array";
else if (t == 13)
return "Pointer";
else
return "-Other-";
}
}
StructResolver::StructListType StructResolver::getDisjointStructs() {
string sName;
StructListType result;
vector<StructType*> usedTypes;
module->findUsedStructTypes(usedTypes);
// NOTE this gets a list by struct name only: no isomorphism checks
for (int i=0; i < usedTypes.size(); ++i) {
// does it have a name?
if (!usedTypes[i]->hasName())
continue;
sName = usedTypes[i]->getName().str();
// does it have a numeric suffix?
int pos = sName.rfind(".");
if (pos != string::npos && sName.size() > pos) {
string suffix = sName.substr(pos+1);
bool isNumeric = false;
for (string::const_iterator si = suffix.begin();
si != suffix.end();
++si) {
isNumeric = isdigit(*si);
if (!isNumeric)
break;
}
if (isNumeric)
result[sName] = usedTypes[i];
}
}
return result;
}
void StructResolver::run(StructMapType *m) {
if (m->empty())
return;
module->MaterializeAll();
typeMap = m;
mapGlobals();
mapFunctions();
mapMetadata();
SR_DEBUG module->dump();
}
Type *StructResolver::maybeGetMappedType(Type *t) {
if (typeMap->find(t) != typeMap->end()) {
SR_DEBUG cout << "\t\t## --- MAPPING --- ##\n";
SR_DEBUG cout << "was:\n";
SR_DEBUG t->dump();
SR_DEBUG cout << "\nnow:\n";
SR_DEBUG (*typeMap)[t]->dump();
SR_DEBUG cout << "\n";
return (*typeMap)[t];
}
// short cut if not composite
if (!isa<CompositeType>(t))
return t;
if (isa<PointerType>(t)) {
PointerType *a = dyn_cast<PointerType>(t);
SR_DEBUG cout << "\t\t## pointer, points to type: " << tName(a->getElementType()->getTypeID()) << "\n";
Type *p = maybeGetMappedType(a->getElementType());
// p will be the end of a pointer chain
if (p != a->getElementType()) {
// it's one we are mapping, so map and recurse back up
Type *m = PointerType::get(p, a->getAddressSpace());
(*typeMap)[t] = m;
//return m;
return maybeGetMappedType(t);
}
}
else if (isa<ArrayType>(t)) {
ArrayType *a = dyn_cast<ArrayType>(t);
SR_DEBUG cout << "\t\t## array of type: " << tName(a->getElementType()->getTypeID()) << "\n";
Type *p = maybeGetMappedType(a->getElementType());
if (p != a->getElementType()) {
// it's one we are mapping, so map and recurse back up
Type *m = ArrayType::get(p, a->getNumElements());
(*typeMap)[t] = m;
//return m;
return maybeGetMappedType(t);
}
}
else if (isa<StructType>(t)) {
StructType *a = dyn_cast<StructType>(t);
SR_DEBUG cout << "\t\t## struct\n";
if (a->hasName()) {
SR_DEBUG cout << "\t\t## has name: " << a->getName().str() << "\n";
}
// element iterate on types
vector<Type*> sVec;
Type *p;
bool modified = false;
for (StructType::element_iterator e = a->element_begin();
e != a->element_end();
++e) {
//cout << "\t\t\t---> type: [[[[[\n";
//(*e)->dump();
//cout << "]]]]]\n";
// accumulate the types. if we find one we have to map, we'll use
// the accumlated types to create a new structure with the mapped
// type. if it doesn't contain one, we discard it
p = maybeGetMappedType(*e);
if (p != *e) {
modified = true;
sVec.push_back(p);
}
else {
sVec.push_back(*e);
}
}
if (modified) {
StructType *m;
StructType *origS = cast<StructType>(t);
if (origS->isLiteral()) {
m = StructType::get(getGlobalContext(), sVec);
}
else {
// take over the name
origS->setName("");
m = StructType::create(sVec, origS->getName().str());
}
(*typeMap)[t] = m;
//return m;
return maybeGetMappedType(t);
}
}
// unchanged
return t;
}
void StructResolver::mapValue(Value &val) {
// we only care about compsite types
/*
if (!isa<CompositeType>(val.getType())) {
cout << "\t@@ skipping non composite type\n";
return;
}*/
SR_DEBUG cout << "@@ mapValue ["<<&val<<"], before\n";
SR_DEBUG val.dump();
if (visited.find(&val) != visited.end()) {
SR_DEBUG cout << "\t@@ already seen\n";
return;
}
if (isa<Function>(val)) {
SR_DEBUG cout << "\t@@ skipping function\n";
return;
}
Type *t = maybeGetMappedType(val.getType());
if (t != val.getType()) {
val.mutateType(t);
}
visited[&val] = true;
SR_DEBUG cout << "@@ mapValue ["<<&val<<"], after\n";
SR_DEBUG val.dump();
}
// User is a Value and may have a list of Value operands
void StructResolver::mapUser(User &val) {
SR_DEBUG cout << "#mapUser, before\n";
//val.dump();
if (visited.find(&val) != visited.end()) {
SR_DEBUG cout << "\t@@ already seen\n";
return;
}
SR_DEBUG cout << "#value itself:\n";
mapValue(val);
if (val.getNumOperands()) {
int opNum = 1;
for (User::op_iterator o = val.op_begin();
o != val.op_end();
++o) {
// o iterates through Use, which is essentially a wrapper for Value
Value *op = *o;
if (isa<CompositeType>(op->getType())) {
/*if ((*o)->hasName())
cout << "#op named: " << (*o)->getValueName()->getKey().str() << "\n";
else
cout << "#op #" << opNum++ << "\n";*/
if (isa<User>(op))
mapUser(cast<User>(*op));
else
mapValue(*op);
}
}
}
SR_DEBUG cout << "#mapUser, after\n";
//val.dump();
}
void StructResolver::mapGlobals() {
for (Module::global_iterator i = module->global_begin();
i != module->global_end();
++i) {
SR_DEBUG cout << "---------------------------------------] looking at global: " << i->getName().str() << "----------------------------------\n";
mapUser(*i);
}
//module->dump();
}
void StructResolver::mapFunction(Function &fun) {
// get a FunctionType based on running the existing one through
// our mapper. since llvm uniques them, if it's unchanged, we should have
// the same FunctionType back
vector<Type*> ftArgs;
for (Function::arg_iterator a = fun.arg_begin();
a != fun.arg_end();
++a) {
ftArgs.push_back(maybeGetMappedType(a->getType()));
}
FunctionType *ft = FunctionType::get(maybeGetMappedType(fun.getReturnType()),
ftArgs,
fun.isVarArg());
if (ft != fun.getFunctionType()) {
SR_DEBUG cout << "mapping function type\n";
fun.mutateType(PointerType::getUnqual(ft));
}
}
void StructResolver::mapFunctions() {
for (Module::iterator i = module->begin();
i != module->end();
++i) {
SR_DEBUG cout << "---------------------------------------] looking at function: " << i->getName().str() << "----------------------------------\n";
Function &f = (*i);
SR_DEBUG f.dump();
// mutate FunctionType if necessary
mapFunction(f);
// Body
for (Function::iterator b = f.begin();
b != f.end();
++b) {
for (BasicBlock::iterator inst = (*b).begin();
inst != (*b).end();
++inst) {
mapUser(*inst);
}
}
SR_DEBUG f.dump();
}
//module->dump();
}
void StructResolver::mapMetadata() {
for (Module::named_metadata_iterator i = module->named_metadata_begin();
i != module->named_metadata_end();
++i) {
SR_DEBUG cout << "---------------------------------------] looking at metadata: " << i->getName().str() << "----------------------------------\n";
NamedMDNode &m = (*i);
// MD nodes in named node
for (int o = 0;
o < m.getNumOperands();
++o) {
// operands of nodes
MDNode *node = m.getOperand(o);
for (int n = 0;
n < node->getNumOperands();
++n) {
Value *v = node->getOperand(n);
if (v)
mapValue(*v);
}
}
}
//module->dump();
}
| C++ |
// Copyright 2011 Google Inc
#ifndef _builder_llvm_ExceptionCleanupExpr_h_
#define _builder_llvm_ExceptionCleanupExpr_h_
#include "model/Expr.h"
namespace builder { namespace mvll {
/**
* Expression class for wrapping LLVMValues.
*/
class ExceptionCleanupExpr : public model::Expr {
public:
ExceptionCleanupExpr(model::TypeDef *type) : Expr(type) {}
virtual model::ResultExprPtr emit(model::Context &context);
virtual void writeTo(std::ostream &out) const;
/** Override isProductive(), always false. */
virtual bool isProductive() const;
};
}} // namespace builder::llvm
#endif
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_llvm_ArrayTypeDef_h_
#define _builder_llvm_ArrayTypeDef_h_
#include "model/Context.h"
#include "BTypeDef.h"
#include "Utils.h"
#include <string>
namespace llvm {
class Type;
}
namespace builder {
namespace mvll {
class ArrayTypeDef : public BTypeDef {
public:
ArrayTypeDef(model::TypeDef *metaType,
const std::string &name,
llvm::Type *rep
);
// specializations of array types actually create a new type
// object.
virtual model::TypeDef *getSpecialization(model::Context &context,
TypeVecObj *types
);
};
} // end namespace builder::vmll
} // end namespace builder
#endif
| C++ |
// Copyright 2010 Shannon Weyrick <weyrick@mozek.us>
// a class for maintaining debug information. in llvm, this consists
// of metadeta that is emitted into the ir
#ifndef _builder_llvm_DebugInfo_h_
#define _builder_llvm_DebufInfo_h_
#include "parser/Location.h"
#include <string>
#include <llvm/Analysis/DebugInfo.h>
#include <llvm/Analysis/DIBuilder.h>
namespace llvm {
class Module;
}
namespace builder {
namespace mvll {
class DebugInfo {
private:
llvm::Module *module;
llvm::DIBuilder builder;
llvm::DIFile currentFile;
llvm::DIDescriptor currentScope;
public:
static const unsigned CRACK_LANG_ID = llvm::dwarf::DW_LANG_lo_user + 50;
DebugInfo(llvm::Module *m, const std::string &file);
void emitFunctionDef(const std::string &name,
const parser::Location &loc);
llvm::MDNode* emitLexicalBlock(const parser::Location &loc);
};
} // end namespace builder::vmll
} // end namespace builder
#endif
| C++ |
// Copyright 2011 Google Inc.
#include "BCleanupFrame.h"
#include <llvm/Intrinsics.h>
#include <llvm/LLVMContext.h>
#include <llvm/Module.h>
#include "model/ResultExpr.h"
#include "model/VarDef.h"
#include "BBuilderContextData.h"
#include "BTypeDef.h"
#include "VarDefs.h"
#include "Incompletes.h"
#include "LLVMBuilder.h"
using namespace std;
using namespace llvm;
using namespace model;
using namespace builder::mvll;
void BCleanupFrame::close() {
if (dynamic_cast<LLVMBuilder &>(context->builder).suppressCleanups())
return;
context->emittingCleanups = true;
for (CleanupList::iterator iter = cleanups.begin();
iter != cleanups.end();
++iter
) {
iter->emittingCleanups = true;
iter->action->emit(*context);
iter->emittingCleanups = false;
}
context->emittingCleanups = false;
}
BasicBlock *BCleanupFrame::emitUnwindCleanups(BasicBlock *next) {
context->emittingCleanups = true;
BBuilderContextData *bdata = BBuilderContextData::get(context);
bdata->nextCleanupBlock = next;
// store the current block and get a reference to the builder so we
// can set the current block
LLVMBuilder &llvmBuilder = dynamic_cast<LLVMBuilder &>(context->builder);
IRBuilder<> &builder =
llvmBuilder.builder;
BasicBlock *savedBlock = builder.GetInsertBlock();
// emit these cleanups from back to front
for (CleanupList::reverse_iterator iter = cleanups.rbegin();
iter != cleanups.rend();
++iter
) {
// if we're already emitting this cleanup in a normal context, stop
// here
if (iter->emittingCleanups)
break;
if (!iter->unwindBlock) {
iter->unwindBlock = BasicBlock::Create(getGlobalContext(),
"cleanup",
llvmBuilder.func
);
builder.SetInsertPoint(iter->unwindBlock);
// emit the cleanup, which should end on an invoke that takes us to
// the next block, so a branch should never be needed.
iter->action->emit(*context);
}
bdata->nextCleanupBlock = next = iter->unwindBlock;
}
bdata->nextCleanupBlock = 0;
context->emittingCleanups = false;
builder.SetInsertPoint(savedBlock);
return next;
}
BasicBlock *BCleanupFrame::getLandingPad(
BasicBlock *next,
BBuilderContextData::CatchData *cdata
) {
// if this is an empty frame, associate the landing pad with the frame.
// Otherwise, associate it with the first cleanup
BasicBlock *&lp =
(cleanups.size()) ? cleanups.front().landingPad : landingPad;
if (!lp) {
// get the builder
LLVMBuilder &llvmBuilder =
dynamic_cast<LLVMBuilder &>(context->builder);
lp = llvmBuilder.createLandingPad(*context, next, cdata);
}
return lp;
}
void BCleanupFrame::clearCachedCleanups() {
for (CleanupList::iterator iter = cleanups.begin(); iter != cleanups.end();
++iter
)
iter->unwindBlock = iter->landingPad = 0;
landingPad = 0;
if (parent)
BCleanupFramePtr::rcast(parent)->clearCachedCleanups();
}
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_llvm_BArgVarDefImpl_h_
#define _builder_llvm_BArgVarDefImpl_h_
#include "model/VarDef.h"
#include "model/VarDefImpl.h"
#include "model/Context.h"
#include "model/ResultExpr.h"
#include "LLVMBuilder.h"
namespace llvm {
class Value;
class GlobalVariable;
}
namespace model {
class AssignExpr;
class VarRef;
}
namespace builder {
namespace mvll {
SPUG_RCPTR(BArgVarDefImpl);
class BArgVarDefImpl : public model::VarDefImpl {
public:
llvm::Value *rep;
BArgVarDefImpl(llvm::Value *rep) : rep(rep) {}
virtual model::ResultExprPtr emitRef(model::Context &context,
model::VarRef *var
);
virtual model::ResultExprPtr
emitAssignment(model::Context &context,
model::AssignExpr *assign);
model::VarDefImplPtr promote(LLVMBuilder &builder, model::ArgDef *arg);
virtual bool hasInstSlot() const;
};
// generates references for memory variables (globals and instance vars)
SPUG_RCPTR(BMemVarDefImpl);
class BMemVarDefImpl : public model::VarDefImpl {
public:
virtual model::ResultExprPtr emitRef(model::Context &context,
model::VarRef *var);
virtual model::ResultExprPtr
emitAssignment(model::Context &context,
model::AssignExpr *assign);
virtual llvm::Value *getRep(LLVMBuilder &builder) = 0;
virtual bool hasInstSlot() const;
};
SPUG_RCPTR(BHeapVarDefImpl)
class BHeapVarDefImpl : public BMemVarDefImpl {
public:
llvm::Value *rep;
BHeapVarDefImpl(llvm::Value *rep) : rep(rep) {}
virtual llvm::Value *getRep(LLVMBuilder &builder) {
return rep;
}
};
SPUG_RCPTR(BGlobalVarDefImpl);
class BGlobalVarDefImpl : public BMemVarDefImpl {
private:
// global var rep's are module specific, this variable points to the
// value for the module most recently evaluated by getRep().
llvm::GlobalVariable *rep;
public:
BGlobalVarDefImpl(llvm::GlobalVariable *rep) : rep(rep) {}
virtual llvm::Value *getRep(LLVMBuilder &builder);
};
class BConstDefImpl : public model::VarDefImpl {
public:
llvm::Constant *rep;
BConstDefImpl(llvm::Constant *rep) : rep(rep) {}
virtual model::ResultExprPtr emitRef(model::Context &context,
model::VarRef *var);
virtual model::ResultExprPtr
emitAssignment(model::Context &context,
model::AssignExpr *assign) {
assert(false && "assignment to a constant");
return 0;
}
virtual bool hasInstSlot() const;
};
SPUG_RCPTR(BFieldDefImpl);
// Base class for variable implementations that are offsets from a base
// pointer.
class BFieldDefImpl : public model::VarDefImpl {
public:
virtual model::ResultExprPtr emitRef(model::Context &context,
model::VarRef *var
) {
assert(false &&
"attempting to emit a direct reference to a instance "
"variable."
);
}
virtual model::ResultExprPtr emitAssignment(model::Context &context,
model::AssignExpr *assign
) {
assert(false &&
"attempting to assign a direct reference to a instance "
"variable."
);
}
// emit assignment of the field in the aggregate from the value.
virtual void emitFieldAssign(llvm::IRBuilder<> &builder,
llvm::Value *aggregate,
llvm::Value *value
) = 0;
// emit a field reference.
virtual llvm::Value *emitFieldRef(llvm::IRBuilder<> &builder,
llvm::Type *fieldType,
llvm::Value *aggregate
) = 0;
};
SPUG_RCPTR(BInstVarDefImpl);
// Impl object for instance variables. These should never be used to emit
// instance variables, so when used they just raise an assertion error.
class BInstVarDefImpl : public BFieldDefImpl {
public:
unsigned index;
BInstVarDefImpl(unsigned index) : index(index) {}
virtual void emitFieldAssign(llvm::IRBuilder<> &builder,
llvm::Value *aggregate,
llvm::Value *value
);
virtual llvm::Value *emitFieldRef(llvm::IRBuilder<> &builder,
llvm::Type *fieldType,
llvm::Value *aggregate
);
virtual bool hasInstSlot() const;
};
// Implementation for "offset fields." These are used to access structure
// fields in extension objects, where we need fine grain control over where
// the field is located.
class BOffsetFieldDefImpl : public BFieldDefImpl {
public:
size_t offset;
BOffsetFieldDefImpl(size_t offset) : offset(offset) {}
virtual void emitFieldAssign(llvm::IRBuilder<> &builder,
llvm::Value *aggregate,
llvm::Value *value
);
virtual llvm::Value *emitFieldRef(llvm::IRBuilder<> &builder,
llvm::Type *fieldType,
llvm::Value *aggregate
);
virtual bool hasInstSlot() const;
};
} // end namespace builder::vmll
} // end namespace builder
#endif
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#include "Consts.h"
#include "BTypeDef.h"
#include <llvm/Constants.h>
using namespace llvm;
using namespace model;
using namespace builder::mvll;
BStrConst::BStrConst(TypeDef *type, const std::string &val) :
StrConst(type, val),
rep(0),
module(0) {
}
BIntConst::BIntConst(BTypeDef *type, int64_t val) :
IntConst(type, val),
rep(ConstantInt::get(type->rep, val)) {
}
IntConstPtr BIntConst::create(int64_t val) {
return new BIntConst(BTypeDefPtr::arcast(type), val);
}
IntConstPtr BIntConst::create(uint64_t val) {
return new BIntConst(BTypeDefPtr::arcast(type), val);
}
BIntConst::BIntConst(BTypeDef *type, uint64_t val) :
IntConst(type, val),
rep(ConstantInt::get(type->rep, val)) {
}
BFloatConst::BFloatConst(BTypeDef *type, double val) :
FloatConst(type, val),
rep(ConstantFP::get(type->rep, val)) {
}
FloatConstPtr BFloatConst::create(double val) const {
return new BFloatConst(BTypeDefPtr::arcast(type), val);
}
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_llvm_FuncBuilder_h_
#define _builder_llvm_FuncBuilder_h_
#include "BTypeDef.h"
#include "BFuncDef.h"
#include "model/Context.h"
#include "model/FuncDef.h"
#include "model/ArgDef.h"
#include <vector>
#include <string>
#include <llvm/Function.h>
namespace model {
class TypeDef;
}
namespace builder {
namespace mvll {
class FuncBuilder {
public:
model::Context &context;
BTypeDefPtr returnType;
BTypeDefPtr receiverType;
BFuncDefPtr funcDef;
int argIndex;
llvm::Function::LinkageTypes linkage;
// the receiver variable
model::VarDefPtr receiver;
// This is lame: if there is a receiver, "context"
// should be the function context (and include a definition for
// the receiver) and the finish() method should be called with a
// "false" value - indicating that the definition should not be
// stored in the context.
// If there is no receiver, it's safe to call this with the
// context in which the definition should be stored.
FuncBuilder(model::Context &context, model::FuncDef::Flags flags,
BTypeDef *returnType,
const std::string &name,
size_t argCount,
llvm::Function::LinkageTypes linkage =
llvm::Function::ExternalLinkage
);
void finish(bool storeDef = true);
void setSymbolName(const std::string &sname) {
assert(funcDef);
funcDef->symbolName = sname;
}
void addArg(const char *name, model::TypeDef *type);
void setArgs(const std::vector<model::ArgDefPtr> &args);
void setReceiverType(BTypeDef *type) {
receiverType = type;
}
};
} // end namespace builder::vmll
} // end namespace builder
#endif
| C++ |
// Copyright 2012 Shannon Weyrick <weyrick@mozek.us>
#ifndef StructRewrite_h_
#define StructRewrite_h_
#include <map>
#include <string>
namespace llvm {
class Module;
class Type;
class User;
class Value;
class Function;
}
class StructResolver {
public:
typedef std::map<llvm::Type*, llvm::Type*> StructMapType;
typedef std::map<std::string, llvm::Type*> StructListType;
protected:
llvm::Module *module;
StructMapType *typeMap;
std::map<llvm::Value*, bool> visited;
llvm::Type *maybeGetMappedType(llvm::Type *t);
void mapValue(llvm::Value &val);
void mapUser(llvm::User &val);
void mapFunction(llvm::Function &fun);
void mapGlobals();
void mapFunctions();
void mapMetadata();
public:
StructResolver(llvm::Module *mod0): module(mod0), typeMap(0) { }
// return the list of structs which conflict (by name only) with existing
// definitions in the current llvm context. these are recognized by
// their numeric suffix, e.g. foo.0, bar.1, etc.
StructListType getDisjointStructs();
void run(StructMapType *m);
};
#endif
| C++ |
// Copyright 2011 Google Inc., Shannon Weyrick <weyrick@mozek.us>
#include "LLVMLinkerBuilder.h"
#include "BModuleDef.h"
#include "DebugInfo.h"
#include "model/Context.h"
#include "BTypeDef.h"
#include "FuncBuilder.h"
#include "Utils.h"
#include "BBuilderContextData.h"
#include "Native.h"
#include "Cacher.h"
#include <llvm/LLVMContext.h>
#include <llvm/PassManager.h>
#include <llvm/LinkAllPasses.h>
#include <llvm/Module.h>
#include <llvm/Linker.h>
#include <llvm/Analysis/Verifier.h>
using namespace std;
using namespace llvm;
using namespace model;
using namespace builder;
using namespace builder::mvll;
// emit the final cleanup function, a collection of calls
// to the cleanup functions for the individual modules we have
// included in this build
// by convention, the name is "main:cleanup". this is used by Native.cc
Function *LLVMLinkerBuilder::emitAggregateCleanup(Module *module) {
assert(!rootBuilder && "emitAggregateCleanup must be called from "
"root builder");
LLVMContext &lctx = getGlobalContext();
llvm::Constant *c =
module->getOrInsertFunction("main:cleanup",
Type::getVoidTy(lctx), NULL);
Function *func = llvm::cast<llvm::Function>(c);
func->setCallingConv(llvm::CallingConv::C);
BasicBlock *block = BasicBlock::Create(lctx, "", func);
for (ModuleListType::reverse_iterator i =
moduleList->rbegin();
i != moduleList->rend();
++i) {
Function *dfunc = module->getFunction((*i)->name+":cleanup");
// missing a cleanup function isn't an error, because the moduleDef
// list currently includes modules that don't have any associated
// codegen, like "crack"
if (!dfunc)
continue;
CallInst::Create(dfunc, "", block);
}
ReturnInst::Create(lctx, block);
return func;
}
// maintain a single list of modules throughout the compile in the root builder
LLVMLinkerBuilder::ModuleListType
*LLVMLinkerBuilder::addModule(BModuleDef *mod) {
if (moduleList) {
moduleList->push_back(mod);
} else {
if (rootBuilder)
moduleList = LLVMLinkerBuilderPtr::cast(
rootBuilder.get())->addModule(mod);
else {
moduleList = new ModuleListType();
moduleList->push_back(mod);
}
}
return moduleList;
}
void *LLVMLinkerBuilder::getFuncAddr(llvm::Function *func) {
assert(false && "LLVMLinkerBuilder::getFuncAddr called");
}
void LLVMLinkerBuilder::finishBuild(Context &context) {
assert(!rootBuilder && "run must be called from root builder");
// if optimizing, do module level unit at a time
if (options->optimizeLevel) {
for (ModuleListType::iterator i = moduleList->begin();
i != moduleList->end();
++i) {
if (options->verbosity > 2)
std::cerr << "optimizing " << (*i)->rep->getModuleIdentifier() <<
std::endl;
optimizeUnit((*i)->rep, options->optimizeLevel);
}
}
// now link all moduloes
linker = new Linker("crack",
"main-module",
getGlobalContext(),
(options->verbosity > 2) ?
Linker::Verbose :
0
);
assert(linker && "unable to create Linker");
string errMsg;
string mainModuleName;
for (ModuleListType::iterator i = moduleList->begin();
i != moduleList->end();
++i) {
if (options->verbosity > 2)
std::cerr << "linking " << (*i)->rep->getModuleIdentifier() <<
std::endl;
linker->LinkInModule((*i)->rep, &errMsg);
if (errMsg.length()) {
std::cerr << "error linking " << (*i)->rep->getModuleIdentifier() <<
" [" + errMsg + "]\n";
(*i)->rep->dump();
}
// if this is the main module, store its name.
string moduleName = (*i)->getNamespaceName();
if (!moduleName.compare(0, 6, ".main."))
mainModuleName = moduleName;
}
// final linked IR
Module *finalir = linker->getModule();
// final IR generation: cleanup and main
emitAggregateCleanup(finalir);
BTypeDef *vtableType =
BTypeDefPtr::rcast(context.construct->vtableBaseType);
Value *vtableTypeBody = vtableType->getClassInstRep(finalir, 0);
createMain(finalir, options.get(), vtableTypeBody, mainModuleName);
// possible LTO optimizations
if (options->optimizeLevel) {
if (options->verbosity > 2)
std::cerr << "link time optimize final IR" << std::endl;
optimizeLink(finalir, options->debugMode);
}
// if we're not optimizing but we're doing debug, verify now
// if we are optimizing and we're doing debug, verify is done in the
// optimization passes instead
if (!options->optimizeLevel && options->debugMode)
verifyModule(*module, llvm::PrintMessageAction);
// if we're dumping, return now that we've added main and finalized ir
if (options->dumpMode) {
PassManager passMan;
passMan.add(llvm::createPrintModulePass(&llvm::outs()));
passMan.run(*finalir);
return;
}
// finish native compile and link
nativeCompile(finalir,
options.get(),
sharedLibs,
context.construct->sourceLibPath
);
}
BuilderPtr LLVMLinkerBuilder::createChildBuilder() {
LLVMLinkerBuilder *result = new LLVMLinkerBuilder();
result->rootBuilder = rootBuilder ? rootBuilder : this;
result->llvmVoidPtrType = llvmVoidPtrType;
result->options = options;
return result;
}
ModuleDefPtr LLVMLinkerBuilder::createModule(Context &context,
const string &name,
const string &path,
ModuleDef *owner
) {
assert(!module);
LLVMContext &lctx = getGlobalContext();
createLLVMModule(name);
if (options->debugMode) {
debugInfo = new DebugInfo(module, name);
}
BBuilderContextData::get(&context);
string funcName = name + ":main";
llvm::Constant *c =
module->getOrInsertFunction(funcName, Type::getVoidTy(lctx), NULL);
func = llvm::cast<llvm::Function>(c);
func->setCallingConv(llvm::CallingConv::C);
createFuncStartBlocks(funcName);
// insert point is now at the begining of the :main function for
// this module. this will run the top level code for the module
// however, we consult a module level global to ensure that we only
// run the top level code once, since this module may be imported from
// more than one place
GlobalVariable *moduleInit =
new GlobalVariable(*module,
Type::getInt1Ty(lctx),
false, // constant
GlobalValue::InternalLinkage,
Constant::getIntegerValue(
Type::getInt1Ty(lctx),APInt(1,0,false)),
name+":initialized"
);
// emit code that checks the global and returns immediately if it
// has been set to 1
BasicBlock *alreadyInitBlock = BasicBlock::Create(lctx, "alreadyInit", func);
assert(!mainInsert);
mainInsert = BasicBlock::Create(lctx, "topLevel", func);
Value* currentInitVal = builder.CreateLoad(moduleInit);
builder.CreateCondBr(currentInitVal, alreadyInitBlock, mainInsert);
// already init, return
builder.SetInsertPoint(alreadyInitBlock);
builder.CreateRetVoid();
// branch to the actual first block of the function
builder.SetInsertPoint(mainInsert);
BasicBlock *temp = BasicBlock::Create(lctx, "moduleBody", func);
builder.CreateBr(temp);
builder.SetInsertPoint(temp);
createModuleCommon(context);
bModDef = new BModuleDef(name, context.ns.get(), module);
bModDef->sourcePath = getSourcePath(path);
return bModDef;
}
void LLVMLinkerBuilder::closeModule(Context &context, ModuleDef *moduleDef) {
assert(module);
LLVMContext &lctx = getGlobalContext();
// add the module to the list
addModule(BModuleDefPtr::cast(moduleDef));
// get the "initialized" flag
GlobalVariable *moduleInit = module->getNamedGlobal(moduleDef->name +
":initialized"
);
// if there was a top-level throw, we could already have a terminator.
// Generate the code to set the init flag and a return instruction if not.
if (!builder.GetInsertBlock()->getTerminator()) {
if (moduleDef->fromExtension) {
// if this is an extension, we create a runtime initialize call
// this allows the extension to initialize, but also ensures the
// extension will be linked since ld requires at least one call into it
// XXX real mangle? see Construct::loadSharedLib
string name = moduleDef->getFullName();
for (int i=0; i < name.size(); ++i) {
if (name[i] == '.')
name[i] = '_';
}
Constant *initFunc =
module->getOrInsertFunction(name + "_rinit",
Type::getVoidTy(getGlobalContext()),
NULL
);
Function *f = llvm::cast<llvm::Function>(initFunc);
builder.CreateCall(f);
}
// at the end of the code for the module, set the "initialized" flag.
builder.CreateStore(Constant::getIntegerValue(
Type::getInt1Ty(lctx),APInt(1,1,false)
),
moduleInit
);
builder.CreateRetVoid();
}
// since the cleanups have to be emitted against the module context, clear
// the unwind blocks so we generate them for the del function.
clearCachedCleanups(context);
// emit the cleanup function for this module
// we will emit calls to these (for all modules) during run() in the finalir
string cleanupFuncName = moduleDef->name + ":cleanup";
llvm::Constant *c =
module->getOrInsertFunction(cleanupFuncName,
Type::getVoidTy(lctx), NULL);
Function *initFunc = func;
func = llvm::cast<llvm::Function>(c);
func->setCallingConv(llvm::CallingConv::C);
// create a new exStruct variable for this context in the standard start
// block.
createFuncStartBlocks(cleanupFuncName);
createSpecialVar(context.ns.get(), getExStructType(), ":exStruct");
// if the initialization flag is not set, branch to return
BasicBlock *cleanupBlock = BasicBlock::Create(lctx, ":cleanup", func),
*retBlock = BasicBlock::Create(lctx, "done", func);
Value *initVal = builder.CreateLoad(moduleInit);
builder.CreateCondBr(initVal, cleanupBlock, retBlock);
builder.SetInsertPoint(cleanupBlock);
closeAllCleanupsStatic(context);
builder.CreateBr(retBlock);
builder.SetInsertPoint(retBlock);
builder.CreateRetVoid();
// emit a table of address/function for the module
vector<Constant *> funcVals;
Type *byteType = builder.getInt8Ty();
Type *bytePtrType = byteType->getPointerTo();
Constant *zero = ConstantInt::get(Type::getInt32Ty(lctx), 0);
Constant *index00[] = { zero, zero };
Module::FunctionListType &funcList = module->getFunctionList();
for (Module::FunctionListType::iterator funcIter = funcList.begin();
funcIter != funcList.end();
++funcIter
) {
string name = funcIter->getName();
if (!funcIter->isDeclaration()) {
funcVals.push_back(ConstantExpr::getBitCast(funcIter,
bytePtrType
)
);
ArrayType *byteArrType =
ArrayType::get(byteType, name.size() + 1);
Constant *funcName = ConstantArray::get(lctx, name, true);
GlobalVariable *nameGVar =
new GlobalVariable(*module, byteArrType, true, // is constant
GlobalValue::InternalLinkage,
funcName,
moduleDef->name +
":debug_func_name",
0,
false
);
Constant *namePtr =
ConstantExpr::getGetElementPtr(nameGVar, index00, 2);
funcVals.push_back(namePtr);
}
}
funcVals.push_back(Constant::getNullValue(bytePtrType));
ArrayType *bytePtrArrType =
ArrayType::get(bytePtrType, funcVals.size());
GlobalVariable *funcTable = new GlobalVariable(
*module, bytePtrArrType,
true,
GlobalValue::InternalLinkage,
ConstantArray::get(bytePtrArrType,
funcVals
),
moduleDef->name + ":debug_func_table",
0,
false
);
// call the function to populate debug info.
vector<Type *> argTypes(1);
argTypes[0] = bytePtrType->getPointerTo();
FunctionType *funcType = FunctionType::get(builder.getVoidTy(), argTypes,
false
);
Function *registerFunc =
cast<Function>(module->getOrInsertFunction("__CrackRegisterFuncTable",
funcType
)
);
vector<Value *> args(1);
args[0] = ConstantExpr::getGetElementPtr(funcTable, index00, 2);
BasicBlock &entryBlock = initFunc->getEntryBlock();
builder.SetInsertPoint(&entryBlock, entryBlock.begin());
builder.CreateCall(registerFunc, args);
if (rootBuilder->options->cacheMode) {
Cacher c(context, options.get(), BModuleDefPtr::acast(moduleDef));
c.saveToCache();
}
if (debugInfo)
delete debugInfo;
}
void *LLVMLinkerBuilder::loadSharedLibrary(const string &name) {
if (rootBuilder) {
rootBuilder->loadSharedLibrary(name);
} else {
sharedLibs.push_back(name);
LLVMBuilder::loadSharedLibrary(name);
}
}
void LLVMLinkerBuilder::initializeImport(model::ModuleDef* m,
const ImportedDefVec &symbols,
bool annotation) {
assert(!annotation && "annotation given to linker builder");
initializeImportCommon(m, symbols);
// we add a call into our module's :main function
// to run the top level function of the imported module
// each :main is only run once, however, so that a module imported
// from two different modules will have its top level code only
// run once. this is handled in the :main function itself.
BasicBlock *orig = builder.GetInsertBlock();
assert(mainInsert && "no main insert block");
// if the last instruction is terminal, we need to insert before it
// TODO: reuse createFuncStartBlock for this
BasicBlock::iterator i = mainInsert->end();
if (i != mainInsert->begin() && !(--i)->isTerminator())
// otherwise insert after it.
++i;
IRBuilder<> b(mainInsert, i);
Constant *fc =
module->getOrInsertFunction(m->name+":main",
Type::getVoidTy(getGlobalContext()),
NULL
);
Function *f = llvm::cast<llvm::Function>(fc);
b.CreateCall(f);
}
void LLVMLinkerBuilder::engineFinishModule(BModuleDef *moduleDef) {
// only called from registerPrimFuncs in base LLVMBuilder
addModule(moduleDef);
}
void LLVMLinkerBuilder::fixClassInstRep(BTypeDef *type) {
type->getClassInstRep(module, 0);
}
model::ModuleDefPtr LLVMLinkerBuilder::materializeModule(
model::Context &context,
const std::string &canonicalName,
model::ModuleDef *owner
) {
Cacher c(context, options.get());
return c.maybeLoadFromCache(canonicalName);
}
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#include "ArrayTypeDef.h"
#include "model/NullConst.h"
#include "Ops.h"
#include <spug/StringFmt.h>
#include <llvm/DerivedTypes.h>
using namespace llvm;
using namespace model;
using namespace builder::mvll;
ArrayTypeDef::ArrayTypeDef(TypeDef *metaType, const std::string &name,
Type *rep
) : BTypeDef(metaType, name, rep) {
defaultInitializer = new NullConst(this);
generic = new SpecializationCache();
}
// specializations of array types actually create a new type
// object.
TypeDef * ArrayTypeDef::getSpecialization(Context &context,
TypeVecObj *types
) {
// see if it already exists
TypeDef *spec = findSpecialization(types);
if (spec)
return spec;
// create it.
assert(types->size() == 1);
BTypeDef *parmType = BTypeDefPtr::rcast((*types)[0]);
Type *llvmType = PointerType::getUnqual(parmType->rep);
BTypeDefPtr tempSpec =
new BTypeDef(type.get(),
SPUG_FSTR(name << "[" << parmType->getFullName() <<
"]"
),
llvmType
);
tempSpec->setOwner(this);
context.addDef(new VoidPtrOpDef(context.construct->voidptrType.get()),
tempSpec.get()
);
tempSpec->defaultInitializer = new NullConst(tempSpec.get());
// create the implementation (this can be called before the meta-class is
// initialized, so check for it and defer if it is)
if (context.construct->classType->complete) {
createClassImpl(context, tempSpec.get());
} else {
LLVMBuilder &b = dynamic_cast<LLVMBuilder &>(context.builder);
b.deferMetaClass.push_back(tempSpec);
}
// add all of the methods and finish up.
addArrayMethods(context, tempSpec.get(), parmType);
tempSpec->complete = true;
(*generic)[types] = tempSpec;
return tempSpec.get();
}
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_llvm_Utils_h_
#define _builder_llvm_Utils_h_
#include "model/Context.h"
#include "BTypeDef.h"
#include "VarDefs.h"
#include <string>
#include <vector>
namespace builder {
namespace mvll {
void addArrayMethods(model::Context &context,
model::TypeDef *arrayType,
BTypeDef *elemType
);
void closeAllCleanupsStatic(model::Context &context);
/**
* Create the implementation object for a class.
*/
void createClassImpl(model::Context &context, BTypeDef *type);
BTypeDefPtr createMetaClass(model::Context &context,
const std::string &name
);
llvm::Value *createInvoke(llvm::IRBuilder<> &builder, model::Context &context,
llvm::Value *func,
std::vector<llvm::Value *> &valueArgs
);
} // end namespace builder::vmll
} // end namespace builder
#endif
| C++ |
// Copyright 2011 Google Inc
#include "ExceptionCleanupExpr.h"
#include "model/Context.h"
#include "model/ResultExpr.h"
#include "LLVMBuilder.h"
using namespace model;
using namespace builder::mvll;
ResultExprPtr ExceptionCleanupExpr::emit(model::Context &context) {
LLVMBuilder &b = dynamic_cast<LLVMBuilder &>(context.builder);
b.emitExceptionCleanupExpr(context);
// we can get away with this because the results of cleanup expressions
// are ignored.
return 0;
}
void ExceptionCleanupExpr::writeTo(std::ostream &out) const {
out << "LLVMExceptionCleanupExpr";
}
bool ExceptionCleanupExpr::isProductive() const { return false; }
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#include "Ops.h"
#include "LLVMBuilder.h"
#include "BBranchPoint.h"
#include "BFieldRef.h"
#include "BResultExpr.h"
#include "BTypeDef.h"
#include "BFuncDef.h"
#include "BFuncPtr.h"
#include "model/AllocExpr.h"
#include "model/AssignExpr.h"
#include "model/CleanupFrame.h"
#include "model/IntConst.h"
#include "model/FloatConst.h"
#include "model/VarRef.h"
using namespace std;
using namespace llvm;
using namespace model;
using namespace builder::mvll;
typedef spug::RCPtr<builder::mvll::BFieldRef> BFieldRefPtr;
#define UNOP(opCode) \
model::ResultExprPtr opCode##OpCall::emit(model::Context &context) { \
if (receiver) \
receiver->emit(context)->handleTransient(context); \
else \
args[0]->emit(context)->handleTransient(context); \
LLVMBuilder &builder = \
dynamic_cast<LLVMBuilder &>(context.builder); \
builder.lastValue = \
builder.builder.Create##opCode( \
builder.lastValue, \
BTypeDefPtr::arcast(func->returnType)->rep \
); \
\
return new BResultExpr(this, builder.lastValue); \
}
#define QUAL_BINOP(prefix, opCode, op) \
ResultExprPtr prefix##OpCall::emit(Context &context) { \
LLVMBuilder &builder = \
dynamic_cast<LLVMBuilder &>(context.builder); \
int arg = 0; \
\
TypeDef *ltype, *funcLType; \
if (receiver) { \
ltype = receiver->type.get(); \
funcLType = func->getReceiverType(); \
receiver->emit(context)->handleTransient(context); \
} else { \
ltype = args[arg]->type.get(); \
funcLType = func->args[arg]->type.get(); \
args[arg++]->emit(context)->handleTransient(context); \
} \
builder.narrow(ltype, func->args[arg]->type.get()); \
Value *lhs = builder.lastValue; \
args[arg]->emit(context)->handleTransient(context); \
builder.narrow(args[arg]->type.get(), func->args[arg]->type.get()); \
builder.lastValue = \
builder.builder.Create##opCode(lhs, \
builder.lastValue \
); \
\
return new BResultExpr(this, builder.lastValue); \
}
// reverse binary operators, must be run as methods.
#define REV_BINOP(opCode) \
ResultExprPtr opCode##ROpCall::emit(Context &context) { \
LLVMBuilder &builder = \
dynamic_cast<LLVMBuilder &>(context.builder); \
receiver->emit(context)->handleTransient(context); \
Value *rhs = builder.lastValue; \
args[0]->emit(context)->handleTransient(context); \
builder.lastValue = \
builder.builder.Create##opCode(builder.lastValue, \
rhs \
); \
\
return new BResultExpr(this, builder.lastValue); \
} \
#define REV_BINOPF(opCode, cls) \
REV_BINOP(opCode) \
ExprPtr opCode##ROpCall::foldConstants() { \
ExprPtr rval = receiver.get(); \
ExprPtr lval = args[0].get(); \
cls##ConstPtr ci = cls##ConstPtr::rcast(lval); \
ExprPtr result; \
if (ci) \
result = ci->fold##opCode(rval.get()); \
return result ? result : this; \
}
#define BINOP(opCode, op) QUAL_BINOP(opCode, opCode, op)
// binary operation with folding
#define BINOPF(prefix, op, cls) \
BINOP(prefix, op) \
ExprPtr prefix##OpCall::foldConstants() { \
ExprPtr lval = receiver ? receiver.get() : args[0].get(); \
ExprPtr rval = receiver ? args[0].get() : args[1].get(); \
cls##ConstPtr ci = cls##ConstPtr::rcast(lval); \
ExprPtr result; \
if (ci) \
result = ci->fold##prefix(rval.get()); \
return result ? result : this; \
}
#define BINOPIF(prefix, op) BINOPF(prefix, op, Int)
#define REV_BINOPIF(prefix) REV_BINOPF(prefix, Int)
#define BINOPFF(prefix, op) BINOPF(prefix, op, Float)
#define REV_BINOPFF(prefix) REV_BINOPF(prefix, Float)
// Binary Ops
BINOPIF(Add, "+");
BINOPIF(Sub, "-");
BINOPIF(Mul, "*");
BINOPIF(SDiv, "/");
BINOPIF(UDiv, "/");
BINOPIF(SRem, "%"); // Note: C'99 defines '%' as the remainder, not modulo
BINOPIF(URem, "%"); // the sign is that of the dividend, not divisor.
BINOPIF(Or, "|");
BINOPIF(And, "&");
BINOPIF(Xor, "^");
BINOPIF(Shl, "<<");
BINOPIF(LShr, ">>");
BINOPIF(AShr, ">>");
REV_BINOPIF(Add)
REV_BINOPIF(Sub)
REV_BINOPIF(Mul)
REV_BINOPIF(SDiv)
REV_BINOPIF(UDiv)
REV_BINOPIF(SRem)
REV_BINOPIF(URem)
REV_BINOPIF(Or)
REV_BINOPIF(And)
REV_BINOPIF(Xor)
REV_BINOPIF(Shl)
REV_BINOPIF(LShr)
REV_BINOPIF(AShr)
BINOP(ICmpEQ, "==");
BINOP(ICmpNE, "!=");
BINOP(ICmpSGT, ">");
BINOP(ICmpSLT, "<");
BINOP(ICmpSGE, ">=");
BINOP(ICmpSLE, "<=");
BINOP(ICmpUGT, ">");
BINOP(ICmpULT, "<");
BINOP(ICmpUGE, ">=");
BINOP(ICmpULE, "<=");
REV_BINOP(ICmpEQ)
REV_BINOP(ICmpNE)
REV_BINOP(ICmpSGT)
REV_BINOP(ICmpSLT)
REV_BINOP(ICmpSGE)
REV_BINOP(ICmpSLE)
REV_BINOP(ICmpUGT)
REV_BINOP(ICmpULT)
REV_BINOP(ICmpUGE)
REV_BINOP(ICmpULE)
BINOPFF(FAdd, "+");
BINOPFF(FSub, "-");
BINOPFF(FMul, "*");
BINOPFF(FDiv, "/");
BINOPFF(FRem, "%");
REV_BINOPFF(FAdd)
REV_BINOPFF(FSub)
REV_BINOPFF(FMul)
REV_BINOPFF(FDiv)
REV_BINOPFF(FRem)
BINOP(FCmpOEQ, "==");
BINOP(FCmpONE, "!=");
BINOP(FCmpOGT, ">");
BINOP(FCmpOLT, "<");
BINOP(FCmpOGE, ">=");
BINOP(FCmpOLE, "<=");
REV_BINOP(FCmpOEQ)
REV_BINOP(FCmpONE)
REV_BINOP(FCmpOGT)
REV_BINOP(FCmpOLT)
REV_BINOP(FCmpOGE)
REV_BINOP(FCmpOLE)
QUAL_BINOP(Is, ICmpEQ, "is");
// Type Conversion Ops
UNOP(SExt);
UNOP(ZExt);
UNOP(FPExt);
UNOP(SIToFP);
UNOP(UIToFP);
#define FPTRUNCOP(opCode) \
ResultExprPtr opCode##OpCall::emit(Context &context) { \
if (receiver) \
receiver->emit(context)->handleTransient(context); \
else \
args[0]->emit(context)->handleTransient(context); \
\
LLVMBuilder &builder = \
dynamic_cast<LLVMBuilder &>(context.builder); \
builder.lastValue = \
builder.builder.Create##opCode( \
builder.lastValue, \
BTypeDefPtr::arcast(func->returnType)->rep \
); \
\
return new BResultExpr(this, builder.lastValue); \
} \
// Floating Point Truncating Ops
FPTRUNCOP(FPTrunc);
FPTRUNCOP(FPToSI);
FPTRUNCOP(FPToUI);
// BinOpDef
BinOpDef::BinOpDef(TypeDef *argType,
TypeDef *resultType,
const string &name,
bool isMethod,
bool reversed
) :
OpDef(resultType,
(isMethod ? FuncDef::method : FuncDef::noFlags) |
(reversed ? FuncDef::reverse : FuncDef::noFlags),
name,
isMethod ? 1 : 2
) {
int arg = 0;
if (!isMethod)
args[arg++] = new ArgDef(argType, "lhs");
args[arg] = new ArgDef(argType, "rhs");
}
// TruncOpCall
ResultExprPtr TruncOpCall::emit(Context &context) {
if (receiver)
receiver->emit(context)->handleTransient(context);
else
args[0]->emit(context)->handleTransient(context);
LLVMBuilder &builder =
dynamic_cast<LLVMBuilder &>(context.builder);
builder.lastValue =
builder.builder.CreateTrunc(
builder.lastValue,
BTypeDefPtr::arcast(func->returnType)->rep
);
return new BResultExpr(this, builder.lastValue);
}
// NoOpCall
ResultExprPtr NoOpCall::emit(Context &context) {
if (receiver)
return receiver->emit(context);
else
return args[0]->emit(context);
}
// BitNotOpCall
ResultExprPtr BitNotOpCall::emit(Context &context) {
if (receiver)
receiver->emit(context)->handleTransient(context);
else
args[0]->emit(context)->handleTransient(context);
LLVMBuilder &builder =
dynamic_cast<LLVMBuilder &>(context.builder);
builder.lastValue =
builder.builder.CreateXor(
builder.lastValue,
ConstantInt::get(
BTypeDefPtr::arcast(func->returnType)->rep,
-1
)
);
return new BResultExpr(this, builder.lastValue);
}
ExprPtr BitNotOpCall::foldConstants() {
ExprPtr val;
if (receiver)
val = receiver;
else
val = args[0];
IntConstPtr v = IntConstPtr::rcast(val);
if (v)
return v->foldBitNot();
else
return this;
}
// BitNotOpDef
BitNotOpDef::BitNotOpDef(BTypeDef *resultType, const std::string &name,
bool isMethod
) :
OpDef(resultType, isMethod ? FuncDef::method :FuncDef::noFlags, name,
isMethod ? 0 : 1
) {
if (!isMethod)
args[0] = new ArgDef(resultType, "operand");
}
// LogicAndOpCall
ResultExprPtr LogicAndOpCall::emit(Context &context) {
LLVMBuilder &builder =
dynamic_cast<LLVMBuilder &>(context.builder);
// condition on lhs
BranchpointPtr pos = builder.labeledIf(context,
args[0].get(),
"and_T",
"and_F");
BBranchpoint *bpos = BBranchpointPtr::arcast(pos);
Value* oVal = builder.lastValue; // arg[0] condition value
BasicBlock* oBlock = bpos->block2; // value block
// now pointing to true block, emit condition of rhs in its
// own cleanup frame (only want to do cleanups if we evaluated
// this expression)
context.createCleanupFrame();
args[1].get()->emitCond(context);
Value* tVal = builder.lastValue; // arg[1] condition value
context.closeCleanupFrame();
BasicBlock* tBlock = builder.builder.GetInsertBlock(); // arg[1] val block
// this branches us to end
builder.emitEndIf(context, pos.get(), false);
// now we phi for result
PHINode* p = builder.builder.CreatePHI(
BTypeDefPtr::arcast(context.construct->boolType)->rep,
2,
"and_R");
p->addIncoming(oVal, oBlock);
p->addIncoming(tVal, tBlock);
builder.lastValue = p;
return new BResultExpr(this, builder.lastValue);
}
// LogicOrOpCall
ResultExprPtr LogicOrOpCall::emit(Context &context) {
LLVMBuilder &builder =
dynamic_cast<LLVMBuilder &>(context.builder);
// condition on lhs
BranchpointPtr pos = builder.labeledIf(context,
args[0].get(),
"or_T",
"or_F"
);
BBranchpoint *bpos = BBranchpointPtr::arcast(pos);
Value *oVal = builder.lastValue; // arg[0] condition value
BasicBlock *fBlock = bpos->block; // false block
BasicBlock *oBlock = bpos->block2; // condition block
// now pointing to true block, save it for phi
BasicBlock *tBlock = builder.builder.GetInsertBlock();
// repoint to false block, emit condition of rhs (in its own
// cleanup frame, we only want to cleanup if we evaluated this
// expression)
builder.builder.SetInsertPoint(fBlock);
context.createCleanupFrame();
args[1]->emitCond(context);
Value *fVal = builder.lastValue; // arg[1] condition value
context.closeCleanupFrame();
// branch to true for phi
builder.builder.CreateBr(tBlock);
// pick up any changes to the fBlock
fBlock = builder.builder.GetInsertBlock();
// now jump back to true and phi for result
builder.builder.SetInsertPoint(tBlock);
PHINode *p = builder.builder.CreatePHI(
BTypeDefPtr::arcast(context.construct->boolType)->rep,
2,
"or_R"
);
p->addIncoming(oVal, oBlock);
p->addIncoming(fVal, fBlock);
builder.lastValue = p;
return new BResultExpr(this, builder.lastValue);
}
// NegOpCall
ResultExprPtr NegOpCall::emit(Context &context) {
if (receiver)
receiver->emit(context)->handleTransient(context);
else
args[0]->emit(context)->handleTransient(context);
LLVMBuilder &builder =
dynamic_cast<LLVMBuilder &>(context.builder);
builder.lastValue =
builder.builder.CreateSub(
ConstantInt::get(
BTypeDefPtr::arcast(func->returnType)->rep,
0
),
builder.lastValue
);
return new BResultExpr(this, builder.lastValue);
}
ExprPtr NegOpCall::foldConstants() {
ExprPtr val;
if (receiver)
val = receiver;
else
val = args[0];
IntConstPtr v = IntConstPtr::rcast(val);
if (v)
return v->foldNeg();
else
return this;
}
// NegOpDef
NegOpDef::NegOpDef(BTypeDef *resultType, const std::string &name,
bool isMethod
) :
OpDef(resultType, isMethod ? FuncDef::method : FuncDef::noFlags, name,
isMethod ? 0 : 1
) {
if (!isMethod)
args[0] = new ArgDef(resultType, "operand");
}
// FNegOpCall
ResultExprPtr FNegOpCall::emit(Context &context) {
if (receiver)
receiver->emit(context)->handleTransient(context);
else
args[0]->emit(context)->handleTransient(context);
LLVMBuilder &builder =
dynamic_cast<LLVMBuilder &>(context.builder);
builder.lastValue =
builder.builder.CreateFSub(
ConstantFP::get(BTypeDefPtr::arcast(func->returnType)->rep,
0
),
builder.lastValue
);
return new BResultExpr(this, builder.lastValue);
}
ExprPtr FNegOpCall::foldConstants() {
FloatConstPtr fc = FloatConstPtr::rcast(receiver ? receiver : args[0]);
if (fc)
return fc->foldNeg();
else
return this;
}
// FNegOpDef
FNegOpDef::FNegOpDef(BTypeDef *resultType, const std::string &name,
bool isMethod
) :
OpDef(resultType, isMethod ? FuncDef::method : FuncDef::noFlags, name,
isMethod ? 0 : 1
) {
if (!isMethod)
args[0] = new ArgDef(resultType, "operand");
}
// FunctionPtrCall
ResultExprPtr FunctionPtrCall::emit(Context &context) {
LLVMBuilder &builder =
dynamic_cast<LLVMBuilder &>(context.builder);
receiver->emit(context)->handleTransient(context);
Value *fptr = builder.lastValue;
// generate a function pointer call by passing on arguments
// from oper call to llvm function pointer
BFuncPtrPtr bfp = new BFuncPtr(fptr, args.size());
bfp->returnType = func->returnType;
bfp->args.assign(func->args.begin(), func->args.end());
FuncCallPtr fc = new FuncCall(bfp.get());
fc->args.assign(args.begin(), args.end());
builder.emitFuncCall(context, fc.get());
return new BResultExpr(this, builder.lastValue);
}
// FunctionPtrOpDef
model::FuncCallPtr FunctionPtrOpDef::createFuncCall() {
return new FunctionPtrCall(this);
}
// ArrayGetItemCall
ResultExprPtr ArrayGetItemCall::emit(Context &context) {
receiver->emit(context)->handleTransient(context);
LLVMBuilder &builder =
dynamic_cast<LLVMBuilder &>(context.builder);
Value *r = builder.lastValue;
args[0]->emit(context)->handleTransient(context);
Value *addr = builder.builder.CreateGEP(r, builder.lastValue);
builder.lastValue = builder.builder.CreateLoad(addr);
return new BResultExpr(this, builder.lastValue);
}
// ArraySetItemCall
ResultExprPtr ArraySetItemCall::emit(Context &context) {
LLVMBuilder &builder =
dynamic_cast<LLVMBuilder &>(context.builder);
// emit the receiver
receiver->emit(context)->handleTransient(context);
Value *r = builder.lastValue;
// emit the index
args[0]->emit(context)->handleTransient(context);
Value *i = builder.lastValue;
// emit the rhs value
args[1]->emit(context)->handleTransient(context);
builder.narrow(args[1]->type.get(), func->args[1]->type.get());
Value *v = builder.lastValue;
// get the address of the index, store the value in it.
Value *addr = builder.builder.CreateGEP(r, i);
builder.builder.CreateStore(v, addr);
return new BResultExpr(this, v);
}
// ArrayAllocCall
ResultExprPtr ArrayAllocCall::emit(Context &context) {
LLVMBuilder &builder =
dynamic_cast<LLVMBuilder &>(context.builder);
// get the BTypeDef from the return type, then get the pointer
// type out of that
BTypeDef *retType = BTypeDefPtr::rcast(func->returnType);
const PointerType *ptrType =
cast<const PointerType>(retType->rep);
// malloc based on the element type
builder.emitAlloc(context, new
AllocExpr(func->returnType.get()),
args[0].get()
);
return new BResultExpr(this, builder.lastValue);
}
// ArrayOffsetCall
ResultExprPtr ArrayOffsetCall::emit(Context &context) {
LLVMBuilder &builder =
dynamic_cast<LLVMBuilder &>(context.builder);
receiver->emit(context)->handleTransient(context);
Value *base = builder.lastValue;
args[0]->emit(context)->handleTransient(context);
builder.lastValue =
builder.builder.CreateGEP(base, builder.lastValue);
return new BResultExpr(this, builder.lastValue);
}
// BoolOpCall
ResultExprPtr BoolOpCall::emit(Context &context) {
// emit the receiver
receiver->emit(context)->handleTransient(context);
LLVMBuilder &builder =
dynamic_cast<LLVMBuilder &>(context.builder);
builder.lastValue =
builder.builder.CreateICmpNE(
builder.lastValue,
Constant::getNullValue(builder.lastValue->getType())
);
return new BResultExpr(this, builder.lastValue);
}
// FBoolOpCall
ResultExprPtr FBoolOpCall::emit(Context &context) {
// emit the receiver
receiver->emit(context)->handleTransient(context);
LLVMBuilder &builder =
dynamic_cast<LLVMBuilder &>(context.builder);
builder.lastValue =
builder.builder.CreateFCmpONE(
builder.lastValue,
Constant::getNullValue(builder.lastValue->getType())
);
return new BResultExpr(this, builder.lastValue);
}
// VoidPtrOpCall
ResultExprPtr VoidPtrOpCall::emit(Context &context) {
// emit the receiver
receiver->emit(context)->handleTransient(context);
LLVMBuilder &builder =
dynamic_cast<LLVMBuilder &>(context.builder);
builder.lastValue = builder.builder.CreateBitCast(builder.lastValue,
builder.llvmVoidPtrType
);
return new BResultExpr(this, builder.lastValue);
}
// PtrToIntOpCall
ResultExprPtr PtrToIntOpCall::emit(Context &context) {
args[0]->emit(context)->handleTransient(context);
LLVMBuilder &builder =
dynamic_cast<LLVMBuilder &>(context.builder);
BTypeDef *type = BTypeDefPtr::arcast(func->returnType);
builder.lastValue = builder.builder.CreatePtrToInt(builder.lastValue,
type->rep
);
return new BResultExpr(this, builder.lastValue);
}
// UnsafeCastCall
ResultExprPtr UnsafeCastCall::emit(Context &context) {
// emit the argument
args[0]->emit(context)->handleTransient(context);
LLVMBuilder &builder =
dynamic_cast<LLVMBuilder &>(context.builder);
BTypeDef *type = BTypeDefPtr::arcast(func->returnType);
builder.lastValue =
builder.builder.CreateBitCast(builder.lastValue,
type->rep
);
return new BResultExpr(this, builder.lastValue);
}
// UnsafeCastDef
UnsafeCastDef::UnsafeCastDef(TypeDef *resultType) :
OpDef(resultType, model::FuncDef::noFlags, "unsafeCast", 1) {
args[0] = new ArgDef(resultType, "val");
}
namespace {
LLVMBuilder &beginIncrDecr(Expr *receiver, Context &context,
VarRef *&ref,
TypeDef *type,
BTypeDef *&t,
ResultExprPtr &receiverResult,
Value *&receiverVal
) {
// the receiver needs to be a variable
ref = VarRefPtr::cast(receiver);
if (!ref)
context.error("Integer ++ operators can only be used on variables.");
receiverResult = receiver->emit(context);
LLVMBuilder &builder = dynamic_cast<LLVMBuilder &>(context.builder);
receiverVal = builder.lastValue;
t = BTypeDefPtr::acast(type);
return builder;
}
ResultExprPtr emitAssign(Context &context, VarRef *ref,
ResultExpr *mutated
) {
// create a field assignment or variable assignment expression, as
// appropriate.
AssignExprPtr assign;
BFieldRef *fieldRef;
if (fieldRef = BFieldRefPtr::cast(ref))
assign = new AssignExpr(fieldRef->aggregate.get(),
fieldRef->def.get(),
mutated
);
else
assign = new AssignExpr(0, ref->def.get(), mutated);
return assign->emit(context);
}
inline ResultExprPtr endPreIncrDecr(Context &context,
LLVMBuilder &builder,
VarRef *ref,
Expr *mutatedResult,
Value *mutatedVal
) {
ResultExprPtr mutated = new BResultExpr(mutatedResult, mutatedVal);
mutated->handleTransient(context);
return emitAssign(context, ref, mutated.get());
}
} // anon namespace
// PreIncrIntOpCall
ResultExprPtr PreIncrIntOpCall::emit(Context &context) {
VarRef *ref;
BTypeDef *t;
ResultExprPtr receiverResult;
Value *receiverVal;
LLVMBuilder &builder = beginIncrDecr(receiver.get(), context, ref,
type.get(),
t,
receiverResult,
receiverVal
);
receiverResult->handleTransient(context);
builder.lastValue = builder.builder.CreateAdd(builder.lastValue,
ConstantInt::get(t->rep, 1)
);
return endPreIncrDecr(context, builder, ref, this, builder.lastValue);
}
// PreDecrIntOpCall
ResultExprPtr PreDecrIntOpCall::emit(Context &context) {
VarRef *ref;
BTypeDef *t;
ResultExprPtr receiverResult;
Value *receiverVal;
LLVMBuilder &builder = beginIncrDecr(receiver.get(), context, ref,
type.get(),
t,
receiverResult,
receiverVal
);
receiverResult->handleTransient(context);
builder.lastValue = builder.builder.CreateSub(builder.lastValue,
ConstantInt::get(t->rep, 1)
);
return endPreIncrDecr(context, builder, ref, this, builder.lastValue);
}
// PostIncrIntOpCall
ResultExprPtr PostIncrIntOpCall::emit(Context &context) {
VarRef *ref;
BTypeDef *t;
ResultExprPtr receiverResult;
Value *receiverVal;
LLVMBuilder &builder = beginIncrDecr(receiver.get(), context, ref,
type.get(),
t,
receiverResult,
receiverVal
);
Value *mutatedVal = builder.builder.CreateAdd(builder.lastValue,
ConstantInt::get(t->rep, 1)
);
ResultExprPtr assign = endPreIncrDecr(context, builder, ref, this,
mutatedVal
);
assign->handleTransient(context);
builder.lastValue = receiverVal;
return receiverResult;
}
// PostDecrIntOpCall
ResultExprPtr PostDecrIntOpCall::emit(Context &context) {
VarRef *ref;
BTypeDef *t;
ResultExprPtr receiverResult;
Value *receiverVal;
LLVMBuilder &builder = beginIncrDecr(receiver.get(), context, ref,
type.get(),
t,
receiverResult,
receiverVal
);
Value *mutatedVal = builder.builder.CreateSub(builder.lastValue,
ConstantInt::get(t->rep, 1)
);
ResultExprPtr assign = endPreIncrDecr(context, builder, ref, this,
mutatedVal
);
assign->handleTransient(context);
builder.lastValue = receiverVal;
return receiverResult;
}
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_llvm_BCleanupFrame_h_
#define _builder_llvm_BCleanupFrame_h_
#include "model/CleanupFrame.h"
#include "model/Expr.h"
#include "model/Context.h"
#include <spug/RCPtr.h>
#include <llvm/Support/IRBuilder.h>
#include <list>
#include "BBuilderContextData.h"
namespace builder {
namespace mvll {
SPUG_RCPTR(BCleanupFrame)
class BCleanupFrame : public model::CleanupFrame {
private:
struct Cleanup {
bool emittingCleanups;
model::ExprPtr action;
llvm::BasicBlock *unwindBlock, *landingPad;
Cleanup(model::ExprPtr action) :
emittingCleanups(false),
action(action),
unwindBlock(0),
landingPad(0) {
}
};
llvm::BasicBlock *landingPad;
public:
typedef std::list<Cleanup> CleanupList;
CleanupList cleanups;
BCleanupFrame(model::Context *context) :
CleanupFrame(context),
landingPad(0) {
}
virtual void addCleanup(model::Expr *cleanup) {
cleanups.push_front(Cleanup(cleanup));
}
virtual void close();
llvm::BasicBlock *emitUnwindCleanups(llvm::BasicBlock *next);
/**
* Returns a cached landing pad for the cleanup. LLVM requires a call to
* the selector to be in the unwind block for an invoke, so we have to
* keep one of these for every cleanup block that needs one.
*/
llvm::BasicBlock *getLandingPad(llvm::BasicBlock *block,
BBuilderContextData::CatchData *cdata
);
void clearCachedCleanups();
};
} // end namespace builder::vmll
} // end namespace builder
#endif
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#include "VTableBuilder.h"
#include "BTypeDef.h"
#include "BFuncDef.h"
#include "model/Context.h"
#include <llvm/Module.h>
#include <llvm/LLVMContext.h>
#include <llvm/GlobalVariable.h>
#include <vector>
using namespace std;
using namespace llvm;
using namespace model;
using namespace builder::mvll;
namespace {
// utility function to resize a vector to accomodate a new element, but
// only if necessary.
template<typename T>
void accomodate(vector<T *> &vec, size_t index) {
if (vec.size() < index + 1)
vec.resize(index + 1, 0);
}
}
void VTableInfo::dump() {
std::cerr << name << ":\n";
for (int i = 0; i < entries.size(); ++i) {
if (entries[i])
entries[i]->dump();
else
std::cerr << "null entry" << std::endl;
}
}
void VTableBuilder::dump() {
for (VTableMap::iterator iter = vtables.begin();
iter != vtables.end();
++iter)
iter->second->dump();
}
void VTableBuilder::addToAncestor(BTypeDef *ancestor, BFuncDef *func) {
// lookup the vtable
VTableMap::iterator iter = vtables.find(ancestor);
// if we didn't find a vtable in the ancestors, append the
// function to the first vtable (I don't think this can ever happen)
VTableInfo *targetVTable;
if (iter == vtables.end()) {
assert(firstVTable && "no first vtable");
targetVTable = firstVTable;
} else {
targetVTable = iter->second.get();
}
// insert the function
vector<Constant *> &entries = targetVTable->entries;
accomodate(entries, func->vtableSlot);
Function *funcRep = func->getRep(*builder);
entries[func->vtableSlot] =
(func->flags & FuncDef::abstract) ?
Constant::getNullValue(funcRep->getType()) :
(Constant*)funcRep;
}
// add the function to all vtables.
void VTableBuilder::addToAll(BFuncDef *func) {
for (VTableMap::iterator iter = vtables.begin();
iter != vtables.end();
++iter
) {
vector<Constant *> &entries = iter->second->entries;
accomodate(entries, func->vtableSlot);
Function *funcRep = func->getRep(*builder);
entries[func->vtableSlot] =
(func->flags & FuncDef::abstract) ?
Constant::getNullValue(funcRep->getType()) :
(Constant*)funcRep;
}
}
// add a new function entry to the appropriate VTable
void VTableBuilder::add(BFuncDef *func) {
// find the ancestor whose vtable this function needs to go
// into
BTypeDef *ancestor;
TypeDef::AncestorPath &path = func->pathToFirstDeclaration;
if (path.size())
ancestor = BTypeDefPtr::arcast(path.back().ancestor);
else
ancestor = BTypeDefPtr::acast(func->getOwner());
// now find the ancestor of "ancestor" with the first vtable
ancestor = ancestor->findFirstVTable(vtableBaseType);
// if the function comes from VTableBase, we have to insert
// the function into _all_ of the vtables - this is because
// all of them are derived from vtable base. (the only such
// function is "oper class")
if (ancestor == vtableBaseType)
addToAll(func);
else
addToAncestor(ancestor, func);
}
// create a new VTable
void VTableBuilder::createVTable(BTypeDef *type, const std::string &name,
bool first
) {
assert(vtables.find(type) == vtables.end());
VTableInfo *info;
vtables[type] = info = new VTableInfo(name);
if (first)
firstVTable = info;
}
void VTableBuilder::emit(BTypeDef *type) {
for (VTableMap::iterator iter = vtables.begin();
iter != vtables.end();
++iter
) {
// populate the types array
vector<Constant *> &entries = iter->second->entries;
vector<Type *> vtableTypes(entries.size());
int i = 0;
for (vector<Constant *>::iterator entryIter =
entries.begin();
entryIter != entries.end();
++entryIter, ++i
) {
assert(*entryIter && "Null vtable entry.");
vtableTypes[i] = (*entryIter)->getType();
}
// create a constant structure that actually is the vtable
StructType *vtableStructType =
StructType::create(getGlobalContext(), vtableTypes,
iter->second->name
);
type->vtables[iter->first] =
new GlobalVariable(*module, vtableStructType,
true, // isConstant
GlobalValue::ExternalLinkage,
// initializer - this needs to be
// provided or the global will be
// treated as an extern.
ConstantStruct::get(
vtableStructType,
iter->second->entries
),
iter->second->name
);
// store the first VTable pointer (a pointer-to-pointer to the
// struct type, actually, because that is what we need to cast our
// VTableBase instances to)
if (iter->second == firstVTable)
type->firstVTableType =
PointerType::getUnqual(
PointerType::getUnqual(vtableStructType)
);
}
assert(type->firstVTableType);
}
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#include "BFieldRef.h"
#include "model/VarDef.h"
#include "BTypeDef.h"
#include "VarDefs.h"
#include "BResultExpr.h"
#include "Incompletes.h"
#include "LLVMBuilder.h"
#include "VarDefs.h"
using namespace llvm;
using namespace model;
using namespace builder::mvll;
ResultExprPtr BFieldRef::emit(Context &context) {
ResultExprPtr aggregateResult = aggregate->emit(context);
LLVMBuilder &bb = dynamic_cast<LLVMBuilder &>(context.builder);
// narrow to the ancestor type where the variable is defined.
bb.narrow(aggregate->type.get(), BTypeDefPtr::acast(def->getOwner()));
// cast the implementation and type to their local types.
BFieldDefImplPtr impl = BFieldDefImplPtr::arcast(def->impl);
BTypeDef *typeDef = BTypeDefPtr::arcast(def->type);
// if the variable is from a complete type, we can emit it.
// Otherwise, we need to store a placeholder.
BTypeDef *owner = BTypeDefPtr::acast(def->getOwner());
if (owner->complete) {
bb.lastValue = impl->emitFieldRef(bb.builder, typeDef->rep,
bb.lastValue
);
} else {
// stash the aggregate, emit a placeholder for the
// reference
Value *aggregate = bb.lastValue;
PlaceholderInstruction *placeholder =
new IncompleteInstVarRef(typeDef->rep, aggregate,
impl.get(),
bb.builder.GetInsertBlock()
);
bb.lastValue = placeholder;
// store the placeholder
owner->addPlaceholder(placeholder);
}
// release the aggregate
aggregateResult->handleTransient(context);
return new BResultExpr(this, bb.lastValue);
}
| C++ |
// Copyright 2010-2011 Shannon Weyrick <weyrick@mozek.us>
#include "DebugInfo.h"
#include <llvm/Module.h>
using namespace llvm;
using namespace std;
using namespace builder::mvll;
DebugInfo::DebugInfo(Module *m,
const string &file
): module(m),
builder(*m)
{
// XXX
string dir("./");
builder.createCompileUnit(
DebugInfo::CRACK_LANG_ID,
file,
dir,
"crack", // needs real version string
false, // isOptimized
"", // flags
0 // runtime version for objc?
);
currentFile = builder.createFile(file, dir);
currentScope = currentFile;
}
void DebugInfo::emitFunctionDef(const std::string &name,
const parser::Location &loc) {
currentScope = builder.createFunction(
currentScope,
name,
name,
currentFile,
loc.getLineNumber(),
llvm::DIType(),
false, // local to unit (i.e. like C static)
true // is definition
);
}
MDNode* DebugInfo::emitLexicalBlock(const parser::Location &loc) {
currentScope = builder.createLexicalBlock(currentScope,
currentFile,
loc.getLineNumber(),
0 // col
);
}
| C++ |
// Copyright 2011 Google Inc
#ifndef _builder_llvm_LLVMValueExpr_h_
#define _builder_llvm_LLVMValueExpr_h_
#include "model/Expr.h"
namespace llvm {
class Value;
}
namespace builder { namespace mvll {
/**
* Expression class for wrapping LLVMValues.
*/
class LLVMValueExpr : public model::Expr {
private:
llvm::Value *value;
public:
LLVMValueExpr(model::TypeDef *type, llvm::Value *value) :
Expr(type),
value(value) {
}
virtual model::ResultExprPtr emit(model::Context &context);
virtual void writeTo(std::ostream &out) const;
/** Override isProductive(), LLVM values are not. */
virtual bool isProductive() const;
};
}} // namespace builder::llvm
#endif
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#include "Incompletes.h"
#include <llvm/LLVMContext.h>
#include "BTypeDef.h"
#include "BFuncDef.h"
#include "LLVMBuilder.h"
#include "Utils.h"
#include <map>
#include "llvm/GlobalValue.h" // XXX for getting a module
#include "llvm/Module.h" // XXX for getting a module
using namespace llvm;
using namespace model;
using namespace std;
using namespace builder::mvll;
// XXX defined in LLVMBuilder.cc
extern Type * llvmIntType;
namespace {
// utility
Value *narrowToAncestor(IRBuilder<> &builder,
Value *receiver,
const TypeDef::AncestorPath &path
) {
for (TypeDef::AncestorPath::const_iterator iter = path.begin();
iter != path.end();
++iter
)
receiver =
builder.CreateStructGEP(receiver, iter->index);
return receiver;
}
} // namespace
// IncompleteInstVarRef
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IncompleteInstVarRef, Value);
void * IncompleteInstVarRef::operator new(size_t s) {
return User::operator new(s, 1);
}
IncompleteInstVarRef::IncompleteInstVarRef(Type *type,
Value *aggregate,
BFieldDefImpl *fieldImpl,
BasicBlock *parent
) :
PlaceholderInstruction(
type,
parent,
OperandTraits<IncompleteInstVarRef>::op_begin(this),
OperandTraits<IncompleteInstVarRef>::operands(this)
),
fieldImpl(fieldImpl) {
Op<0>() = aggregate;
}
IncompleteInstVarRef::IncompleteInstVarRef(Type *type,
Value *aggregate,
BFieldDefImpl *fieldImpl,
Instruction *insertBefore
) :
PlaceholderInstruction(
type,
insertBefore,
OperandTraits<IncompleteInstVarRef>::op_begin(this),
OperandTraits<IncompleteInstVarRef>::operands(this)
),
fieldImpl(fieldImpl) {
Op<0>() = aggregate;
}
Instruction * IncompleteInstVarRef::clone_impl() const {
return new IncompleteInstVarRef(getType(), Op<0>(), fieldImpl.get());
}
void IncompleteInstVarRef::insertInstructions(IRBuilder<> &builder) {
replaceAllUsesWith(fieldImpl->emitFieldRef(builder, getType(), Op<0>()));
}
// IncompleteInstVarAssign
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IncompleteInstVarAssign, Value);
void * IncompleteInstVarAssign::operator new(size_t s) {
return User::operator new(s, 2);
}
IncompleteInstVarAssign::IncompleteInstVarAssign(Type *type,
Value *aggregate,
BFieldDefImpl *fieldDefImpl,
Value *rval,
BasicBlock *parent
) :
PlaceholderInstruction(
type,
parent,
OperandTraits<IncompleteInstVarAssign>::op_begin(this),
OperandTraits<IncompleteInstVarAssign>::operands(this)
),
fieldDefImpl(fieldDefImpl) {
Op<0>() = aggregate;
Op<1>() = rval;
}
IncompleteInstVarAssign::IncompleteInstVarAssign(Type *type,
Value *aggregate,
BFieldDefImpl *fieldDefImpl,
Value *rval,
Instruction *insertBefore
) :
PlaceholderInstruction(
type,
insertBefore,
OperandTraits<IncompleteInstVarAssign>::op_begin(this),
OperandTraits<IncompleteInstVarAssign>::operands(this)
),
fieldDefImpl(fieldDefImpl) {
Op<0>() = aggregate;
Op<1>() = rval;
}
Instruction *IncompleteInstVarAssign::clone_impl() const {
return new IncompleteInstVarAssign(getType(), Op<0>(), fieldDefImpl.get(),
Op<1>()
);
}
void IncompleteInstVarAssign::insertInstructions(IRBuilder<> &builder) {
fieldDefImpl->emitFieldAssign(builder, Op<0>(), Op<1>());
}
// IncompleteCatchSelector
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IncompleteCatchSelector, Value);
void *IncompleteCatchSelector::operator new(size_t s) {
return User::operator new(s, 0);
}
IncompleteCatchSelector::IncompleteCatchSelector(Type *type,
Value *personalityFunc,
BasicBlock *parent
) :
PlaceholderInstruction(
type,
parent,
OperandTraits<IncompleteCatchSelector>::op_begin(this),
OperandTraits<IncompleteCatchSelector>::operands(this)
),
personalityFunc(personalityFunc),
typeImpls(0) {
}
IncompleteCatchSelector::IncompleteCatchSelector(Type *type,
Value *personalityFunc,
Instruction *insertBefore
) :
PlaceholderInstruction(
type,
insertBefore,
OperandTraits<IncompleteCatchSelector>::op_begin(this),
OperandTraits<IncompleteCatchSelector>::operands(this)
),
personalityFunc(personalityFunc),
typeImpls(0) {
}
IncompleteCatchSelector::~IncompleteCatchSelector() {
}
Instruction *IncompleteCatchSelector::clone_impl() const {
return new IncompleteCatchSelector(getType(), personalityFunc);
}
void IncompleteCatchSelector::insertInstructions(IRBuilder<> &builder) {
LandingPadInst *lp = builder.CreateLandingPad(getType(),
personalityFunc,
typeImpls->size()
);
vector<Value *> args(3 + typeImpls->size());
for (int i = 0; i < typeImpls->size(); ++i)
lp->addClause((*typeImpls)[i]);
replaceAllUsesWith(lp);
}
// IncompleteNarrower
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IncompleteNarrower, Value);
void * IncompleteNarrower::operator new(size_t s) {
return User::operator new(s, 1);
}
IncompleteNarrower::IncompleteNarrower(Value *aggregate,
BTypeDef *startType,
BTypeDef *ancestor,
BasicBlock *parent
) :
PlaceholderInstruction(
ancestor->rep,
parent,
OperandTraits<IncompleteNarrower>::op_begin(this),
OperandTraits<IncompleteNarrower>::operands(this)
),
startType(startType),
ancestor(ancestor) {
Op<0>() = aggregate;
}
IncompleteNarrower::IncompleteNarrower(Value *aggregate,
BTypeDef *startType,
BTypeDef *ancestor,
Instruction *insertBefore
) :
PlaceholderInstruction(
ancestor->rep,
insertBefore,
OperandTraits<IncompleteNarrower>::op_begin(this),
OperandTraits<IncompleteNarrower>::operands(this)
),
startType(startType),
ancestor(ancestor) {
Op<0>() = aggregate;
}
Instruction * IncompleteNarrower::clone_impl() const {
return new IncompleteNarrower(Op<0>(), startType, ancestor);
}
Value * IncompleteNarrower::emitGEP(IRBuilder<> &builder,
BTypeDef *type,
BTypeDef *ancestor,
Value *inst
) {
if (type == ancestor)
return inst;
int i = 0;
for (TypeDef::TypeVec::iterator iter = type->parents.begin();
iter != type->parents.end();
++iter, ++i
)
if ((*iter)->isDerivedFrom(ancestor)) {
inst = builder.CreateStructGEP(inst, i);
BTypeDef *base =
BTypeDefPtr::arcast(*iter);
return emitGEP(builder, base, ancestor, inst);
}
assert(false && "narrowing to non-ancestor!");
}
void IncompleteNarrower::insertInstructions(IRBuilder<> &builder) {
replaceAllUsesWith(emitGEP(builder, startType, ancestor, Op<0>()));
}
// IncompleteVTableInit
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IncompleteVTableInit, Value);
void * IncompleteVTableInit::operator new(size_t s) {
return User::operator new(s, 1);
}
IncompleteVTableInit::IncompleteVTableInit(BTypeDef *aggregateType,
Value *aggregate,
BTypeDef *vtableBaseType,
BasicBlock *parent
) :
PlaceholderInstruction(
aggregateType->rep,
parent,
OperandTraits<IncompleteVTableInit>::op_begin(this),
OperandTraits<IncompleteVTableInit>::operands(this)
),
aggregateType(aggregateType),
vtableBaseType(vtableBaseType) {
Op<0>() = aggregate;
}
IncompleteVTableInit::IncompleteVTableInit(BTypeDef *aggregateType, Value *aggregate,
BTypeDef *vtableBaseType,
Instruction *insertBefore
) :
PlaceholderInstruction(
aggregateType->rep,
insertBefore,
OperandTraits<IncompleteVTableInit>::op_begin(this),
OperandTraits<IncompleteVTableInit>::operands(this)
),
aggregateType(aggregateType),
vtableBaseType(vtableBaseType) {
Op<0>() = aggregate;
}
Instruction * IncompleteVTableInit::clone_impl() const {
return new IncompleteVTableInit(aggregateType, Op<0>(),
vtableBaseType
);
}
void IncompleteVTableInit::emitInitOfFirstVTable(IRBuilder<> &builder,
BTypeDef *btype,
Value *inst,
Constant *vtable
) {
TypeDef::TypeVec &parents = btype->parents;
int i = 0;
for (TypeDef::TypeVec::iterator ctxIter =
parents.begin();
ctxIter != parents.end();
++ctxIter, ++i
) {
BTypeDef *base = BTypeDefPtr::arcast(*ctxIter);
if (base == vtableBaseType) {
inst = builder.CreateStructGEP(inst, i);
// convert the vtable to {}*
const PointerType *emptyStructPtrType =
cast<PointerType>(vtableBaseType->rep);
Type *emptyStructType =
emptyStructPtrType->getElementType();
Value *castVTable =
builder.CreateBitCast(vtable, emptyStructType);
// store the vtable pointer in the field.
builder.CreateStore(castVTable, inst);
return;
}
}
assert(false && "no vtable base class");
}
// emit the code to initialize all vtables in an object.
void IncompleteVTableInit::emitVTableInit(IRBuilder<> &builder, BTypeDef *btype,
Value *inst
) {
// if btype has a registered vtable, startClass gets
// incremented so that we don't emit a parent vtable that
// overwrites it.
int startClass = 0;
// check for the vtable of the current class
map<BTypeDef *, Constant *>::iterator firstVTableIter =
aggregateType->vtables.find(btype);
if (firstVTableIter != aggregateType->vtables.end()) {
emitInitOfFirstVTable(builder, btype, inst,
firstVTableIter->second
);
startClass = 1;
}
// recurse through all other parents with vtables
TypeDef::TypeVec &parents = btype->parents;
int i = 0;
for (TypeDef::TypeVec::iterator ctxIter =
parents.begin() + startClass;
ctxIter != parents.end();
++ctxIter, ++i
) {
BTypeDef *base =
BTypeDefPtr::arcast(*ctxIter);
// see if this class has a vtable in the aggregate type
map<BTypeDef *, Constant *>::iterator vtableIter =
aggregateType->vtables.find(base);
if (vtableIter != aggregateType->vtables.end()) {
Value *baseInst =
builder.CreateStructGEP(inst, i);
emitInitOfFirstVTable(builder, base, baseInst,
vtableIter->second
);
} else if (base->hasVTable) {
Value *baseInst =
builder.CreateStructGEP(inst, i);
emitVTableInit(builder, base, baseInst);
}
}
}
void IncompleteVTableInit::insertInstructions(IRBuilder<> &builder) {
emitVTableInit(builder, aggregateType, Op<0>());
}
// IncompleteVirtualFunc
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IncompleteVirtualFunc, Value);
Value * IncompleteVirtualFunc::getVTableReference(IRBuilder<> &builder,
BTypeDef *vtableBaseType,
Type *finalVTableType,
BTypeDef *curType,
Value *inst
) {
// (the logic here looks painfully like that of
// emitVTableInit(), but IMO converting this to an internal
// iterator would just make the code harder to grok)
if (curType == vtableBaseType) {
// XXX this is fucked
// convert the instance pointer to the address of a
// vtable pointer.
return builder.CreateBitCast(inst, finalVTableType);
} else {
// recurse through all parents with vtables
TypeDef::TypeVec &parents = curType->parents;
int i = 0;
for (TypeDef::TypeVec::iterator baseIter = parents.begin();
baseIter != parents.end();
++baseIter, ++i
) {
BTypeDef *base = BTypeDefPtr::arcast(*baseIter);
if (base->hasVTable) {
Value *baseInst = builder.CreateStructGEP(inst, i);
Value *vtable =
getVTableReference(builder, vtableBaseType,
finalVTableType,
base,
baseInst
);
if (vtable)
return vtable;
}
}
return 0;
}
}
Value *IncompleteVirtualFunc::innerEmitCall(IRBuilder<> &builder,
BTypeDef *vtableBaseType,
BFuncDef *funcDef,
Value *receiver,
const vector<Value *> &args,
BasicBlock *normalDest,
BasicBlock *unwindDest
) {
BTypeDef *receiverType =
BTypeDefPtr::acast(funcDef->getReceiverType());
assert(receiver->getType() == receiverType->rep);
// get the underlying vtable
Value *vtable =
getVTableReference(builder, vtableBaseType,
receiverType->firstVTableType,
receiverType,
receiver
);
assert(vtable && "virtual function receiver has no vtable");
vtable = builder.CreateLoad(vtable);
Value *funcFieldRef =
builder.CreateStructGEP(vtable, funcDef->vtableSlot);
Value *funcPtr = builder.CreateLoad(funcFieldRef);
Value *result = builder.CreateInvoke(funcPtr, normalDest, unwindDest,
args
);
return result;
}
void IncompleteVirtualFunc::init(Value *receiver, const vector<Value *> &args) {
// fill in all of the operands
assert(NumOperands == args.size() + 1);
OperandList[0] = receiver;
for (int i = 0; i < args.size(); ++i)
OperandList[i + 1] = args[i];
}
IncompleteVirtualFunc::IncompleteVirtualFunc(
BTypeDef *vtableBaseType,
BFuncDef *funcDef,
Value *receiver,
const vector<Value *> &args,
BasicBlock *parent,
BasicBlock *normalDest,
BasicBlock *unwindDest
) :
PlaceholderInstruction(
BTypeDefPtr::arcast(funcDef->returnType)->rep,
parent,
OperandTraits<IncompleteVirtualFunc>::op_end(this) -
(args.size() + 1),
args.size() + 1
),
vtableBaseType(vtableBaseType),
funcDef(funcDef),
normalDest(normalDest),
unwindDest(unwindDest) {
init(receiver, args);
}
IncompleteVirtualFunc::IncompleteVirtualFunc(
BTypeDef *vtableBaseType,
BFuncDef *funcDef,
Value *receiver,
const vector<Value *> &args,
BasicBlock *normalDest,
BasicBlock *unwindDest,
Instruction *insertBefore
) :
PlaceholderInstruction(
BTypeDefPtr::arcast(funcDef->returnType)->rep,
insertBefore,
OperandTraits<IncompleteVirtualFunc>::op_end(this) -
(args.size() + 1),
args.size() + 1
),
vtableBaseType(vtableBaseType),
funcDef(funcDef),
normalDest(normalDest),
unwindDest(unwindDest) {
init(receiver, args);
}
IncompleteVirtualFunc::IncompleteVirtualFunc(
BTypeDef *vtableBaseType,
BFuncDef *funcDef,
Use *operands,
unsigned numOperands,
BasicBlock *normalDest,
BasicBlock *unwindDest
) :
PlaceholderInstruction(
BTypeDefPtr::arcast(funcDef->returnType)->rep,
static_cast<Instruction *>(0),
operands,
numOperands
),
vtableBaseType(vtableBaseType),
funcDef(funcDef),
normalDest(normalDest),
unwindDest(unwindDest) {
for (int i = 0; i < numOperands; ++i)
OperandList[i] = operands[i];
}
Instruction * IncompleteVirtualFunc::clone_impl() const {
return new(NumOperands) IncompleteVirtualFunc(vtableBaseType,
funcDef,
OperandList,
NumOperands,
normalDest,
unwindDest
);
}
void IncompleteVirtualFunc::insertInstructions(IRBuilder<> &builder) {
vector<Value *> args(NumOperands - 1);
for (int i = 1; i < NumOperands; ++i)
args[i - 1] = OperandList[i];
Value *callInst =
innerEmitCall(builder, vtableBaseType, funcDef,
OperandList[0],
args,
normalDest,
unwindDest
);
replaceAllUsesWith(callInst);
}
Value * IncompleteVirtualFunc::emitCall(Context &context,
BFuncDef *funcDef,
Value *receiver,
const vector<Value *> &args,
BasicBlock *normalDest,
BasicBlock *unwindDest
) {
// do some conversions that we need to do either way.
LLVMBuilder &llvmBuilder =
dynamic_cast<LLVMBuilder &>(context.builder);
BTypeDef *vtableBaseType =
BTypeDefPtr::arcast(context.construct->vtableBaseType);
BTypeDef *type = BTypeDefPtr::acast(funcDef->getOwner());
// if this is for a complete class, go ahead and emit the code.
// Otherwise just emit a placeholder.
if (type->complete) {
Value *val = innerEmitCall(llvmBuilder.builder,
vtableBaseType,
funcDef,
receiver,
args,
normalDest,
unwindDest
);
return val;
} else {
PlaceholderInstruction *placeholder =
new(args.size() + 1) IncompleteVirtualFunc(
vtableBaseType,
funcDef,
receiver,
args,
llvmBuilder.builder.GetInsertBlock(),
normalDest,
unwindDest
);
type->addPlaceholder(placeholder);
return placeholder;
}
}
// IncompleteSpecialize
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IncompleteSpecialize, Value);
void * IncompleteSpecialize::operator new(size_t s) {
return User::operator new(s, 1);
}
Instruction * IncompleteSpecialize::clone_impl() const {
return new IncompleteSpecialize(getType(), value,
ancestorPath
);
}
IncompleteSpecialize::IncompleteSpecialize(
Type *type,
Value *value,
const TypeDef::AncestorPath &ancestorPath,
Instruction *insertBefore
) : PlaceholderInstruction(
type,
insertBefore,
OperandTraits<IncompleteSpecialize>::op_begin(this),
OperandTraits<IncompleteSpecialize>::operands(this)
),
value(value),
ancestorPath(ancestorPath) {
Op<0>() = value;
}
IncompleteSpecialize::IncompleteSpecialize(
Type *type,
Value *value,
const TypeDef::AncestorPath &ancestorPath,
BasicBlock *parent
) : PlaceholderInstruction(
type,
parent,
OperandTraits<IncompleteSpecialize>::op_begin(this),
OperandTraits<IncompleteSpecialize>::operands(this)
),
value(value),
ancestorPath(ancestorPath) {
Op<0>() = value;
}
Value * IncompleteSpecialize::emitSpecializeInner(
IRBuilder<> &builder,
Type *type,
Value *value,
const TypeDef::AncestorPath &ancestorPath
) {
// XXX won't work for virtual base classes
// create a constant offset from the start of the derived
// class to the start of the base class
Value *offset =
narrowToAncestor(builder,
Constant::getNullValue(type),
ancestorPath
);
// convert to an integer and subtract from the pointer to the
// base class.
assert(llvmIntType && "integer type has not been initialized");
offset = builder.CreatePtrToInt(offset, llvmIntType);
value = builder.CreatePtrToInt(value, llvmIntType);
Value *derived = builder.CreateSub(value, offset);
Value *specialized =
builder.CreateIntToPtr(derived, type);
return specialized;
}
void IncompleteSpecialize::insertInstructions(IRBuilder<> &builder) {
replaceAllUsesWith(emitSpecializeInner(builder,
getType(),
value,
ancestorPath
)
);
}
// Utility function - emits the specialize instructions if the
// target class is defined, emits a placeholder instruction if it
// is not.
Value *IncompleteSpecialize::emitSpecialize(
Context &context,
BTypeDef *type,
Value *value,
const TypeDef::AncestorPath &ancestorPath
) {
LLVMBuilder &llvmBuilder =
dynamic_cast<LLVMBuilder &>(context.builder);
if (type->complete) {
return emitSpecializeInner(llvmBuilder.builder, type->rep,
value,
ancestorPath
);
} else {
PlaceholderInstruction *placeholder =
new IncompleteSpecialize(type->rep, value,
ancestorPath,
llvmBuilder.builder.GetInsertBlock()
);
type->addPlaceholder(placeholder);
return placeholder;
}
}
// IncompleteSizeOf
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IncompleteSizeOf, Value);
void * IncompleteSizeOf::operator new(size_t s) {
return User::operator new(s, 0);
}
Instruction *IncompleteSizeOf::clone_impl() const {
return new IncompleteSizeOf(type, intType);
}
IncompleteSizeOf::IncompleteSizeOf(Type *type,
Type *intType,
Instruction *insertBefore
) :
type(type),
intType(intType),
PlaceholderInstruction(
IntegerType::get(type->getContext(), 32),
insertBefore,
OperandTraits<IncompleteSizeOf>::op_begin(this),
OperandTraits<IncompleteSizeOf>::operands(this)
) {
}
IncompleteSizeOf::IncompleteSizeOf(Type *type,
Type *intType,
BasicBlock *parent
) :
type(type),
intType(intType),
PlaceholderInstruction(
IntegerType::get(type->getContext(), 32),
parent,
OperandTraits<IncompleteSizeOf>::op_begin(this),
OperandTraits<IncompleteSizeOf>::operands(this)
) {
}
Value *IncompleteSizeOf::emitInner(Type *type, Type *intType,
IRBuilder<> &builder
) {
Value *null = Constant::getNullValue(type);
Value *offset = builder.CreateConstGEP1_32(null, 1);
return builder.CreatePtrToInt(offset, intType);
}
void IncompleteSizeOf::insertInstructions(IRBuilder<> &builder) {
replaceAllUsesWith(emitInner(type, intType, builder));
}
Value *IncompleteSizeOf::emitSizeOf(Context &context,
BTypeDef *type,
Type *intType
) {
LLVMBuilder &b = dynamic_cast<LLVMBuilder &>(context.builder);
if (type->complete) {
return emitInner(type->rep, intType, b.builder);
} else {
IncompleteSizeOf *placeholder =
new IncompleteSizeOf(type->rep, intType,
b.builder.GetInsertBlock()
);
type->addPlaceholder(placeholder);
return placeholder;
}
}
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_llvm_BBuilderContextData_h_
#define _builder_llvm_BBuilderContextData_h_
#include <vector>
#include "model/BuilderContextData.h"
#include "model/Context.h"
#include <spug/RCPtr.h>
#include <llvm/Support/IRBuilder.h>
namespace llvm {
class Function;
class BasicBlock;
class Module;
class SwitchInst;
class Value;
}
namespace builder { namespace mvll {
class IncompleteCatchSelector;
SPUG_RCPTR(BBuilderContextData);
SPUG_RCPTR(BTypeDef);
class BBuilderContextData : public model::BuilderContextData {
public:
// stores the type to catch and the block to branch to if the type is
// caught.
struct CatchBranch {
BTypeDefPtr type;
llvm::BasicBlock *block;
CatchBranch(BTypeDef *type, llvm::BasicBlock *block) :
type(type),
block(block) {
}
};
// state information on the current try/catch block.
SPUG_RCPTR(CatchData);
struct CatchData : spug::RCBase {
// all of the type/branch combinations in the catch clauses (this will
// be augmented with all of the combos for statements that this is
// nested in)
std::vector<CatchBranch> catches;
// list of the incomplete catch selectors for the block.
std::vector<IncompleteCatchSelector *> selectors;
// the switch instruction for the catch blocks
llvm::SwitchInst *switchInst;
// catch data for nested catches.
std::vector<CatchDataPtr> nested;
// true if some of the blocks in the try statement are non-terminal
bool nonTerminal;
CatchData() : nonTerminal(false) {}
/**
* Populate the 'values' array with the implementations of the types
* in 'types'.
*/
void populateClassImpls(std::vector<llvm::Value *> &values,
llvm::Module *module
);
/**
* Fix all of the selectors in the context by filling in the class
* implementation objects and calling Incomplete::fix() on them to
* convert them to calls to llvm.eh.selector().
*/
void fixAllSelectors(llvm::Module *module);
};
model::Context *context;
llvm::Function *func;
llvm::BasicBlock *block,
*unwindBlock, // the unwind block for the catch/function
*nextCleanupBlock; // the current next cleanup block
BBuilderContextData(model::Context *context) :
context(context),
func(0),
block(0),
unwindBlock(0),
nextCleanupBlock(0) {
}
static BBuilderContextData *get(model::Context *context) {
if (!context->builderData)
context->builderData = new BBuilderContextData(context);
return BBuilderContextDataPtr::rcast(context->builderData);
}
CatchDataPtr getCatchData() {
if (!catchData)
catchData = new CatchData();
return catchData;
}
void deleteCatchData() {
assert(catchData);
catchData = 0;
}
llvm::Value *getExceptionLandingPadResult(llvm::IRBuilder<> &builder);
llvm::BasicBlock *getUnwindBlock(llvm::Function *func);
private:
CatchDataPtr catchData;
BBuilderContextData(const BBuilderContextData &);
};
}} // end namespace builder::vmll
#endif
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_llvm_BBranchPoint_h_
#define _builder_llvm_BBranchPoint_h_
#include "spug/RCPtr.h"
#include "model/Branchpoint.h"
namespace llvm {
class BasicBlock;
}
namespace builder {
namespace mvll {
SPUG_RCPTR(BBranchpoint);
class BBranchpoint : public model::Branchpoint {
public:
llvm::BasicBlock *block, *block2, *block3;
BBranchpoint(llvm::BasicBlock *block) :
block(block),
block2(0),
block3(0) {
}
};
} // end namespace builder::vmll
} // end namespace builder
#endif
| C++ |
// Copyright 2010 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_llvm_BResultExpr_h_
#define _builder_llvm_BResultExpr_h_
#include "LLVMBuilder.h"
#include "model/Context.h"
#include "model/ResultExpr.h"
namespace llvm {
class Value;
}
namespace builder {
namespace mvll {
class BResultExpr : public model::ResultExpr {
public:
llvm::Value *value;
BResultExpr(model::Expr *sourceExpr, llvm::Value *value) :
ResultExpr(sourceExpr),
value(value) {
}
model::ResultExprPtr emit(model::Context &context) {
dynamic_cast<LLVMBuilder &>(context.builder).lastValue =
value;
return new BResultExpr(this, value);
}
};
} // end namespace builder::vmll
} // end namespace builder
#endif
| C++ |
// Copyright 2009-2011 Google Inc., Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_BuilderOptions_h_
#define _builder_BuilderOptions_h_
#include <spug/RCPtr.h>
#include <spug/RCBase.h>
#include <string>
#include <map>
namespace builder {
SPUG_RCPTR(BuilderOptions);
class BuilderOptions : public spug::RCBase {
public:
typedef std::map<std::string, std::string> StringMap;
// Builder specific optimization aggresiveness
int optimizeLevel;
// Builder specific verbosity
int verbosity;
// Dump IR rather than execute/compile code
bool dumpMode;
// Generate debug information
bool debugMode;
// Keep compile time statistics
bool statsMode;
// Enable builder module caching
bool cacheMode;
// builder specific option strings
StringMap optionMap;
BuilderOptions(void): optimizeLevel(0),
verbosity(0),
dumpMode(false),
debugMode(false),
statsMode(false),
cacheMode(false),
optionMap() { }
};
} // namespace builder
#endif
| C++ |
// Copyright 2011 Shannon Weyrick <weyrick@mozek.us>
#ifndef _builder_llvm_CacheFiles_h_
#define _builder_llvm_CacheFiles_h_
#include "model/Context.h"
#include <string>
namespace builder {
class BuilderOptions;
std::string getCacheFilePath(BuilderOptions* o,
const std::string &path,
const std::string &destExt
);
bool initCacheDirectory(BuilderOptions *o);
} // end namespace builder
#endif
| C++ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.