Skip to content
Closed
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
4 changes: 4 additions & 0 deletions src/dmd/dinterpret.d
Original file line number Diff line number Diff line change
Expand Up @@ -5035,6 +5035,10 @@ public:
result = interpret(ae, istate);
return;
}
else if (fd.ident == Id._d_arrayappendT)
assert(0, "CTFE cannot interpret _d_arrayappendT!");
else if (fd.ident == Id._d_arrayappendcTX)
assert(0, "CTFE cannot interpret _d_arrayappendcTX!");
}
else if (auto soe = ecall.isSymOffExp())
{
Expand Down
73 changes: 16 additions & 57 deletions src/dmd/e2ir.d
Original file line number Diff line number Diff line change
Expand Up @@ -3289,66 +3289,12 @@ elem *toElem(Expression e, IRState *irs)

case TOK.concatenateAssign:
{
// Append array
assert(tb2.ty == Tarray || tb2.ty == Tsarray);

assert(tb1n.equals(tb2.nextOf().toBasetype()));

e1 = el_una(OPaddr, TYnptr, e1);
if (config.exe == EX_WIN64)
e2 = addressElem(e2, tb2, true);
else
e2 = useOPstrpar(e2);
elem *ep = el_params(e2, e1, getTypeInfo(ce.e1.loc, ce.e1.type, irs), null);
e = el_bin(OPcall, TYdarray, el_var(getRtlsym(RTLSYM_ARRAYAPPENDT)), ep);
toTraceGC(irs, e, ce.loc);
break;
assert(0, "This case should have been rewritten to `_d_arrayappendT` in the semantic phase");
}

case TOK.concatenateElemAssign:
{
// Append element
assert(tb1n.equals(tb2));

elem *e2x = null;

if (e2.Eoper != OPvar && e2.Eoper != OPconst)
{
// Evaluate e2 and assign result to temporary s2.
// Do this because of:
// a ~= a[$-1]
// because $ changes its value
type* tx = Type_toCtype(tb2);
Symbol *s2 = symbol_genauto(tx);
e2x = elAssign(el_var(s2), e2, tb1n, tx);

e2 = el_var(s2);
}

// Extend array with _d_arrayappendcTX(TypeInfo ti, e1, 1)
e1 = el_una(OPaddr, TYnptr, e1);
elem *ep = el_param(e1, getTypeInfo(ce.e1.loc, ce.e1.type, irs));
ep = el_param(el_long(TYsize_t, 1), ep);
e = el_bin(OPcall, TYdarray, el_var(getRtlsym(RTLSYM_ARRAYAPPENDCTX)), ep);
toTraceGC(irs, e, ce.loc);
Symbol *stmp = symbol_genauto(Type_toCtype(tb1));
e = el_bin(OPeq, TYdarray, el_var(stmp), e);

// Assign e2 to last element in stmp[]
// *(stmp.ptr + (stmp.length - 1) * szelem) = e2

elem *eptr = array_toPtr(tb1, el_var(stmp));
elem *elength = el_una(irs.params.is64bit ? OP128_64 : OP64_32, TYsize_t, el_var(stmp));
elength = el_bin(OPmin, TYsize_t, elength, el_long(TYsize_t, 1));
elength = el_bin(OPmul, TYsize_t, elength, el_long(TYsize_t, ce.e2.type.size()));
eptr = el_bin(OPadd, TYnptr, eptr, elength);
elem *ederef = el_una(OPind, e2.Ety, eptr);

elem *eeq = elAssign(ederef, e2, tb1n, null);
e = el_combine(e2x, e);
e = el_combine(e, eeq);
e = el_combine(e, el_var(stmp));
break;
assert(0, "This case should have been rewritten to `_d_arrayappendcTX` in the semantic phase");
}

default:
Expand Down Expand Up @@ -3529,6 +3475,18 @@ elem *toElem(Expression e, IRState *irs)

override void visit(CondExp ce)
{
if (auto ve = ce.econd.isVarExp)
if (ve.var.ident == Id.ctfe)
{
elem *e = toElem(ce.e2, irs);
if (irs.params.cov && ce.e2.loc.linnum)
e = el_combine(incUsageElem(irs, ce.e2.loc), e);
if (tybasic(e.Ety) == TYstruct)
e.ET = Type_toCtype(ce.e2.type);
elem_setLoc(e, ce.loc);
result = e;
return;
}

@jpf91 jpf91 Aug 3, 2019 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like a good idea to me. Needs to be in its own PR though and I guess there's already a bug report for this somewhere.

Ideally, this should not hard-detect the ctfe variable though. You code will fail on constructs such as these:

void foo(bool dummy)
{
    if (__ctfe && dummy)
    {
        // CTFE-only Code goes here
    }
}

What should be done instead is this: Set __ctfe (somehow) to false, then constant fold / interpret the condition. If the result is a constant false, the if part of the condition is a ctfe only part. If it is constant true, the else branch is a ctfe only branch. If it is not const, both branches may be used at runtime.

Maybe that's out of scope for GSoC though, but it would be very useful for betterC.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder how all that stuff integrates with SCOPEctfe though, maybe what should really happen is that the if block content should be set to SCOPEctfe instead and the toElem / nogc visitors should skip these scopes.

OTOH there's no scope introduced when using CondExp, so for CondExp your code here seems to be corret.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ping @JinShil as IIRC your working on SCOPEctfe issues, so you may be interested in this.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is this code doing and why?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It detects an __ctfe ? e1 : e2 expression, then ignores e1 and only sends e2 to the code generation stage. I guess without this, dropping e1 code occurs later in the backend. @Vild can you elaborate why exactly this is necessary?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without this change the codegen would generate code for both e1 and e2, and while generating code for e1 it would trigger this assert(0) https://github.com/dlang/dmd/pull/9982/files#diff-7a340f667e49df4f91bcab621efa8521R3294

It will also only trigger on code that looks like __ctfe ? e1 : e2, as this is the only form I'm outputting inside expressionsem.d. But I probably need to extend this to atleast support if statements as the inline can rewrite CondExp to IfStatement.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without this change the codegen would generate code for both e1 and e2, and while generating code for e1 it would trigger this assert(0).

OK. But somehow the backend currently also drops the e1 branch, the code is not in the generated object file. Does this happen only as dead-code-elimination after the initial codegen stage?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this happen only as dead-code-elimination after the initial codegen stage?

I have been unable to find where in the backend were it gets removed, all I know is that it is removed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It detects an __ctfe ? e1 : e2 expression, then ignores e1 and only sends e2 to the code generation stage.

So, this is basically a workaround because we don't have version(CTFE)?

Without this change the codegen would generate code for both e1 and e2, and while generating code for e1 it would trigger this assert(0).

Why wasn't e1 lowered in the semantic phase?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So, this is basically a workaround because we don't have version(CTFE)?
ya

Why wasn't e1 lowered in the semantic phase?
Because e1 is the __ctfe code-path, which is the original expression.

elem *ec = toElem(ce.econd, irs);

elem *eleft = toElem(ce.e1, irs);
Expand Down Expand Up @@ -5314,7 +5272,8 @@ elem *toElem(Expression e, IRState *irs)
else
{
Symbol *sp = toSymbol(s);
symbol_add(sp);
if (sp.Ssymnum == -1)
symbol_add(sp);
//printf("\tadding symbol '%s'\n", sp.Sident);
if (vd._init)
{
Expand Down
4 changes: 3 additions & 1 deletion src/dmd/expression.d
Original file line number Diff line number Diff line change
Expand Up @@ -1286,7 +1286,8 @@ extern (C++) abstract class Expression : ASTNode

// Lowered non-@nogc'd hooks will print their own error message inside of nogc.d (NOGCVisitor.visit(CallExp e)),
// so don't print anything to avoid double error messages.
if (!(f.ident == Id._d_HookTraceImpl || f.ident == Id._d_arraysetlengthT))
if (!(f.ident == Id._d_HookTraceImpl || f.ident == Id._d_arraysetlengthT
|| f.ident == Id._d_arrayappendT || f.ident == Id._d_arrayappendcTX))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this list grows much longer, we should probably use a switch statement instead? But I guess with 4 entries this is still ok.

error("`@nogc` %s `%s` cannot call non-@nogc %s `%s`",
sc.func.kind(), sc.func.toPrettyChars(), f.kind(), f.toPrettyChars());
return true;
Expand Down Expand Up @@ -5976,6 +5977,7 @@ extern (C++) final class UshrAssignExp : BinAssignExp
*/
extern (C++) class CatAssignExp : BinAssignExp
{
bool isCTFEHookPart;
extern (D) this(const ref Loc loc, Expression e1, Expression e2)
{
super(loc, TOK.concatenateAssign, __traits(classInstanceSize, CatAssignExp), e1, e2);
Expand Down
122 changes: 122 additions & 0 deletions src/dmd/expressionsem.d
Original file line number Diff line number Diff line change
Expand Up @@ -9331,6 +9331,128 @@ private extern (C++) final class ExpressionSemanticVisitor : Visitor
if ((exp.op == TOK.concatenateElemAssign || exp.op == TOK.concatenateDcharAssign) && global.params.vsafe)
checkAssignEscape(sc, res, false);
result = res;

if (!exp.isCTFEHookPart &&
(exp.op == TOK.concatenateAssign || exp.op == TOK.concatenateElemAssign) &&
!(sc.flags & (SCOPE.ctfe | SCOPE.compile)))
{
// if aa ordering is triggered, `res` will be a CommaExp
// and `.e2` will be the rewritten original expression.

// `output` will point to the expression that the lowering will overwrite
Expression* output;
if (auto comma = res.isCommaExp())
{
output = &comma.e2;
// manual cast because it could be either CatAssignExp or CatElemAssignExp
exp = cast(CatAssignExp)comma.e2;
}
else
{
output = &result;
exp = cast(CatAssignExp)result;
}

if (exp.op == TOK.concatenateAssign)
{
Identifier hook = global.params.tracegc ? Id._d_arrayappendTTrace : Id._d_arrayappendT;

if (!verifyHookExist(exp.loc, *sc, Id._d_arrayappendTImpl, "appending array to arrays", Id.object))
return setError();

// Lower to object._d_arrayappendTImpl!(typeof(e1))._d_arrayappendT{,Trace}(e1, e2)
Expression id = new IdentifierExp(exp.loc, Id.empty);
id = new DotIdExp(exp.loc, id, Id.object);
auto tiargs = new Objects();
tiargs.push(exp.e1.type);
id = new DotTemplateInstanceExp(exp.loc, id, Id._d_arrayappendTImpl, tiargs);
id = new DotIdExp(exp.loc, id, hook);
id = id.expressionSemantic(sc);

auto arguments = new Expressions();
arguments.reserve(5);
if (global.params.tracegc)
{
auto funcname = (sc.callsc && sc.callsc.func) ? sc.callsc.func.toPrettyChars() : sc.func.toPrettyChars();
arguments.push(new StringExp(exp.loc, cast(char*)exp.loc.filename));
arguments.push(new IntegerExp(exp.loc, exp.loc.linnum, Type.tint32));
arguments.push(new StringExp(exp.loc, cast(char*)funcname));
}
arguments.push(exp.e1);
arguments.push(exp.e2);

exp.isCTFEHookPart = true;
Expression ce = new CallExp(exp.loc, id, arguments).expressionSemantic(sc);
auto cond = new IdentifierExp(exp.loc, Id.ctfe).expressionSemantic(sc);
ce = new CondExp(exp.loc, cond, exp, ce);

*output = ce.expressionSemantic(sc);
}
else if (exp.op == TOK.concatenateElemAssign)
{
if (auto ve = exp.e1.isVarExp)
{
import core.stdc.ctype : isdigit;
// The name of the indices array that static foreach loops uses.
// See dmd.cond.lowerNonArrayAggregate
enum varName = "__res";
const(char)[] id = ve.var.ident.toString;
if (id.length > varName.length && id[0 .. varName.length] == varName && id[varName.length].isdigit)
return;
}

Identifier hook = global.params.tracegc ? Id._d_arrayappendcTXTrace : Id._d_arrayappendcTX;
if (!verifyHookExist(exp.loc, *sc, Id._d_arrayappendcTXImpl, "appending element to arrays", Id.object))
return setError();

// Lower to object._d_arrayappendcTXImpl!(typeof(e1))._d_arrayappendcTX{,Trace}(e1, 1), e1[$-1]=e2
Expression id = new IdentifierExp(exp.loc, Id.empty);
id = new DotIdExp(exp.loc, id, Id.object);
auto tiargs = new Objects();
tiargs.push(exp.e1.type);
id = new DotTemplateInstanceExp(exp.loc, id, Id._d_arrayappendcTXImpl, tiargs);
id = new DotIdExp(exp.loc, id, hook);
id = id.expressionSemantic(sc);

auto arguments = new Expressions();
arguments.reserve(5);
if (global.params.tracegc)
{
auto funcname = (sc.callsc && sc.callsc.func) ? sc.callsc.func.toPrettyChars() : sc.func.toPrettyChars();
arguments.push(new StringExp(exp.loc, cast(char*)exp.loc.filename));
arguments.push(new IntegerExp(exp.loc, exp.loc.linnum, Type.tint32));
arguments.push(new StringExp(exp.loc, cast(char*)funcname));
}
arguments.push(exp.e1);
arguments.push(new IntegerExp(exp.loc, 1, Type.tsize_t));

Expression ce = new CallExp(exp.loc, id, arguments);
ce = ce.expressionSemantic(sc);

Expression eValue;
Expression value = exp.e2;
if (!value.isVarExp && !value.isIntegerExp && !value.isStructLiteralExp && !value.isArrayLiteralExp && !value.isAssocArrayLiteralExp)
{
value = extractSideEffect(sc, "__appendtmp", eValue, value, true);
exp.e2 = value;
}

exp.isCTFEHookPart = true;
auto elem = new IndexExp(exp.loc, exp.e1, new MinExp(exp.loc, new DollarExp(exp.loc), IntegerExp.literal!1));
auto ae = new ConstructExp(exp.loc, elem, value);
ae = cast(ConstructExp)ae.expressionSemantic(sc);

auto e0 = Expression.combine(ce, ae).expressionSemantic(sc);
e0 = Expression.combine(e0, exp.e1).expressionSemantic(sc);

auto cond = new IdentifierExp(exp.loc, Id.ctfe).expressionSemantic(sc);
e0 = new CondExp(exp.loc, cond, exp, e0.expressionSemantic(sc));
e0 = Expression.combine(eValue, e0);

*output = e0.expressionSemantic(sc);
}
}

}

override void visit(AddExp exp)
Expand Down
6 changes: 6 additions & 0 deletions src/dmd/id.d
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,12 @@ immutable Msgtable[] msgtable =
{ "_d_arraysetlengthTImpl"},
{ "_d_arraysetlengthT"},
{ "_d_arraysetlengthTTrace"},
{ "_d_arrayappendTImpl" },
{ "_d_arrayappendT" },
{ "_d_arrayappendTTrace" },
{ "_d_arrayappendcTXImpl" },
{ "_d_arrayappendcTX" },
{ "_d_arrayappendcTXTrace" },

// varargs implementation
{ "va_start" },
Expand Down
18 changes: 15 additions & 3 deletions src/dmd/nogc.d
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,17 @@ public:
}
f.printGCUsage(e.loc, "setting `length` may cause a GC allocation");
}
else if (fd.ident == Id._d_arrayappendT || fd.ident == Id._d_arrayappendcTX)
{
if (f.setGC())
{
e.error("cannot use operator `~=` in `@nogc` %s `%s`",
f.kind(), f.toPrettyChars());
err = true;
return;
}
f.printGCUsage(e.loc, "operator `~=` may cause a GC allocation");
}

@JinShil JinShil Aug 4, 2019 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't quite understand the need for these error messages. If the runtime hook causes a GC allocation, then the error message will already be emitted there. However, the error message will be in terms of the lowered code, and not the user's code.

If the purpose of this code is to make the error message more relevant to user code, then that is the case that I mentioned earlier on slack. What we could do instead is pass the file, line number, and even the user's code to the runtime hook and have the runtime hook emit a more meaningful error message, perhaps with a static assert.

Regardless, I'm ok with keeping this as is to maintain the status quo.

@jpf91 jpf91 Aug 4, 2019 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, long-term moving error generation into the hooks would be nicer*. For now I think this is fine to keep compatibility for the error messages.

EDIT: Actually, thinking about this some more, the problem below should be unrelated. I'll keep it here though, as I think it's an interesting, although unrelated, thought.
(*) Right now, main1 and main2 won't compile:

string aCTFEOnlyHelper()(string a)
{
    return "Hello" ~ a;
}

void nogcAppend(ref string r, string val) @nogc
{
}

void main1() @nogc
{
    string result;
    __ctfe ? result ~= "foo" : nogcAppend(result, "foo");
}

void main2() @nogc
{
    enum val = aCTFEOnlyHelper("foo");
}

With the changes suggested here, main1 will actually compile.

For main2, you have the problem that as soon as you instantiate aCTFEOnlyHelper, even if it's in a CTFE-only context, the code for aCTFEOnlyHelper will also be emitted to the object file, so you need the GC there. This is probably harder to fix than the main1 problem, I've filed an issue here: https://issues.dlang.org/show_bug.cgi?id=20101

(Actually, we writing the issue I had epiphany: What we want there is actually already largely available in speculative template instantiation. So it might actually not be too difficult to get the main2 case working).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code was moved from visit(CatAssignExp) as a call to _d_arrayappend{T,cTX} is now what symbolizes array appending, and the message will be printed when compiling with -vgc.

}

override void visit(ArrayLiteralExp e)
Expand Down Expand Up @@ -206,14 +217,15 @@ public:

override void visit(CatAssignExp e)
{
/* CatAssignExp will exist in `__traits(compiles, ...)` and in the `.e1` branch of a `__ctfe ? :` CondExp.
* The other branch will be `_d_arrayappendcTX(e1, 1), e1[$-1]=e2` which will generate the warning about
* GC usage. See visit(CallExp).
*/

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, could we change visit(ConExp) instead to not visit __ctfe only code? I guess that right now we probably do not differentiate, but in the long run it should be possible to ignore everything in __ctfe only blocks for nogc/codegen. As you already have the patch for codegen, why not do the same for nogc checks?

And then add a Test + Changelog entry for this. Some people might be quite happy about this change: https://run.dlang.io/is/G6fv55 ;-)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sadly I cannot change so it doesn't visit this function because of two reasons.

  1. nogc.d is using dmd.apply.walkPostorder which walks it in this order: walk(econd), walk(e1), walk(e2), and lastly visit(CondExp). https://github.com/dlang/dmd/blob/master/src/dmd/apply.d#L144. As this walker is used all over the codebase I don't think it is a good idea to introduce changes to it.

  2. It still needs to set err = true to mark the appending as non-@nogc because the lowering code will not lower code that is in a __traits(compiles, ...). Printing error here is not needed because the error will always be gagged for SCOPE.compile, and if errors were printed they would print the exact same message as the one in visit(CallExp).

So this visit function will now just silently error.

if (f.setGC())
{
e.error("cannot use operator `~=` in `@nogc` %s `%s`",
f.kind(), f.toPrettyChars());
err = true;
return;
}
f.printGCUsage(e.loc, "operator `~=` may cause a GC allocation");
}

override void visit(CatExp e)
Expand Down