Skip to content

Commit 79db6ad

Browse files
cmd/gc: error on constant shift overflows.
Fixes golang#3019. R=golang-dev, rsc CC=golang-dev, remy https://golang.org/cl/5674044
1 parent 88f8af1 commit 79db6ad

2 files changed

Lines changed: 20 additions & 10 deletions

File tree

src/cmd/gc/mparith2.c

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,10 @@ mplen(Mpint *a)
2727

2828
//
2929
// left shift mpint by one
30-
// ignores sign and overflow
30+
// ignores sign
3131
//
3232
static void
33-
mplsh(Mpint *a)
33+
mplsh(Mpint *a, int quiet)
3434
{
3535
long *a1, x;
3636
int i, c;
@@ -46,19 +46,27 @@ mplsh(Mpint *a)
4646
}
4747
*a1++ = x;
4848
}
49+
a->ovf = c;
50+
if(a->ovf && !quiet)
51+
yyerror("constant shift overflow");
4952
}
5053

5154
//
5255
// left shift mpint by Mpscale
53-
// ignores sign and overflow
56+
// ignores sign
5457
//
5558
static void
56-
mplshw(Mpint *a)
59+
mplshw(Mpint *a, int quiet)
5760
{
5861
long *a1;
5962
int i;
6063

6164
a1 = &a->a[Mpprec-1];
65+
if(*a1) {
66+
a->ovf = 1;
67+
if(!quiet)
68+
yyerror("constant shift overflow");
69+
}
6270
for(i=1; i<Mpprec; i++) {
6371
a1[0] = a1[-1];
6472
a1--;
@@ -168,11 +176,11 @@ mpshiftfix(Mpint *a, int s)
168176
{
169177
if(s >= 0) {
170178
while(s >= Mpscale) {
171-
mplshw(a);
179+
mplshw(a, 0);
172180
s -= Mpscale;
173181
}
174182
while(s > 0) {
175-
mplsh(a);
183+
mplsh(a, 0);
176184
s--;
177185
}
178186
} else {
@@ -294,7 +302,7 @@ mpmulfixfix(Mpint *a, Mpint *b)
294302
for(j=0; j<Mpscale; j++) {
295303
if(x & 1)
296304
mpaddfixfix(&q, &s, 1);
297-
mplsh(&s);
305+
mplsh(&s, 1);
298306
x >>= 1;
299307
}
300308
}
@@ -606,7 +614,7 @@ mpdivmodfixfix(Mpint *q, Mpint *r, Mpint *n, Mpint *d)
606614
for(i=0; i<Mpprec*Mpscale; i++) {
607615
if(mpcmp(d, r) > 0)
608616
break;
609-
mplsh(d);
617+
mplsh(d, 1);
610618
}
611619

612620
// if it never happens
@@ -625,7 +633,7 @@ mpdivmodfixfix(Mpint *q, Mpint *r, Mpint *n, Mpint *d)
625633
// when done the remaining numerator
626634
// will be the remainder
627635
for(; i>0; i--) {
628-
mplsh(q);
636+
mplsh(q, 1);
629637
mprsh(d);
630638
if(mpcmp(d, r) <= 0) {
631639
mpaddcfix(q, 1);

test/const2.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,6 @@ const (
1313

1414
const LargeA = 1000000000000000000
1515
const LargeB = LargeA * LargeA * LargeA
16-
const LargeC = LargeB * LargeB * LargeB // ERROR "constant multiplication overflow"
16+
const LargeC = LargeB * LargeB * LargeB // ERROR "constant multiplication overflow"
17+
18+
const AlsoLargeA = LargeA << 400 << 400 >> 400 >> 400 // ERROR "constant shift overflow"

0 commit comments

Comments
 (0)