Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix potentially wrong context pointers when calling delegate literals #3554

Merged
merged 1 commit into from
Sep 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 1 addition & 24 deletions gen/toir.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2165,35 +2165,12 @@ class ToElemVisitor : public Visitor {
if (fd->isNested()) {
LLType *dgty = DtoType(e->type);

LLValue *cval;
auto &funcGen = p->funcGen();
auto &irfn = funcGen.irFunc;
if (funcGen.nestedVar && fd->toParent2() == irfn.decl) {
// We check fd->toParent2() because a frame allocated in one
// function cannot be used for a delegate created in another
// function. Happens with anonymous functions.
cval = funcGen.nestedVar;
} else if (irfn.nestArg) {
cval = irfn.nestArg;
} else if (irfn.thisArg) {
AggregateDeclaration *ad = irfn.decl->isMember2();
if (!ad || !ad->vthis) {
cval = getNullPtr(getVoidPtrType());
} else {
cval =
ad->isClassDeclaration() ? DtoLoad(irfn.thisArg) : irfn.thisArg;
cval = DtoLoad(
DtoGEP(cval, 0, getFieldGEPIndex(ad, ad->vthis), ".vthis"));
}
} else {
cval = getNullPtr(getVoidPtrType());
}
LLValue *cval = DtoNestedContext(e->loc, fd);
cval = DtoBitCast(cval, dgty->getContainedType(0));

LLValue *castfptr = DtoBitCast(callee, dgty->getContainedType(1));

result = new DImValue(e->type, DtoAggrPair(cval, castfptr, ".func"));

} else {
result = new DFuncValue(e->type, fd, callee);
}
Expand Down
16 changes: 16 additions & 0 deletions tests/codegen/gh3553.d
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// https://github.com/ldc-developers/ldc/issues/3553
// RUN: %ldc -run %s

auto makeDelegate(alias fn)(long l) {
auto callIt() {
return fn() * l;
}
return &callIt;
}

void main()
{
int i = 7;
auto dg = makeDelegate!(() => i)(3);
assert(dg() == 21);
}