Skip to content

Commit

Permalink
fix Issue 7625 - inlining only works with explicit else branch
Browse files Browse the repository at this point in the history
  • Loading branch information
WalterBright committed Sep 20, 2015
1 parent 2c94b22 commit f5261a2
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 3 deletions.
69 changes: 66 additions & 3 deletions src/inline.d
Expand Up @@ -103,7 +103,33 @@ public:
Statement s2 = (*s.statements)[i];
if (s2)
{
s2.accept(icv);
/* Specifically allow:
* if (condition)
* return exp1;
* return exp2;
*/
IfStatement ifs;
Statement s3;
if ((ifs = s2.isIfStatement()) !is null &&
ifs.ifbody &&
ifs.ifbody.isReturnStatement() &&
!ifs.elsebody &&
i + 1 < s.statements.dim &&
(s3 = (*s.statements)[i + 1]) !is null &&
s3.isReturnStatement()
)
{
if (ifs.prm) // if variables are declared
{
cost = COST_MAX;
return;
}
expressionInlineCost(ifs.condition);
ifs.ifbody.accept(this);
s3.accept(this);
}
else
s2.accept(icv);
if (tooCostly(icv.cost))
break;
}
Expand Down Expand Up @@ -564,8 +590,45 @@ extern (C++) Expression doInline(Statement s, InlineDoState* ids)
Statement sx = (*s.statements)[i];
if (sx)
{
Expression e = doInline(sx, ids);
result = Expression.combine(result, e);
/* Specifically allow:
* if (condition)
* return exp1;
* return exp2;
*/
IfStatement ifs;
Statement s3;
if ((ifs = sx.isIfStatement()) !is null &&
ifs.ifbody &&
ifs.ifbody.isReturnStatement() &&
!ifs.elsebody &&
i + 1 < s.statements.dim &&
(s3 = (*s.statements)[i + 1]) !is null &&
s3.isReturnStatement()
)
{
/* Rewrite as ?:
*/
Expression econd = doInline(ifs.condition, ids);
assert(econd);
Expression e1 = doInline(ifs.ifbody, ids);
assert(ids.foundReturn);
Expression e2 = doInline(s3, ids);

Expression e = new CondExp(econd.loc, econd, e1, e2);
e.type = e1.type;
if (e.type.ty == Ttuple)
{
e1.type = Type.tvoid;
e2.type = Type.tvoid;
e.type = Type.tvoid;
}
result = Expression.combine(result, e);
}
else
{
Expression e = doInline(sx, ids);
result = Expression.combine(result, e);
}
if (ids.foundReturn)
break;
}
Expand Down
30 changes: 30 additions & 0 deletions test/runnable/inline.d
Expand Up @@ -752,6 +752,35 @@ void test14975() {

/**********************************/

int foo7625(int v)
{
return bar7625(2 * v);
}

int bar7625(int a)
{
++a;
if (a > 0)
return 1;
return baz(a);
}

int baz(int a)
{
if (a > 0)
throw new Exception("a > 0");
return a - 1;
}

void test7625()
{
int x = foo7625(1);
if (x != 1)
assert(0);
}

/**********************************/

int main()
{
test1();
Expand All @@ -777,6 +806,7 @@ int main()
test14754();
test14606();
test14975();
test7625();

printf("Success\n");
return 0;
Expand Down

0 comments on commit f5261a2

Please sign in to comment.