Re: [PATCH] C undefined behavior fix

Peter Barada (pbarada@mail.wm.sps.mot.com)
Wed, 9 Jan 2002 19:19:24 -0500


>Even
>
>int b;
>volatile const int a = 5;
>b = a - a;
>
>can not be optimized to
>
>b = 0;

Until you define the scope of the variables, you can't make that
assertion. If the code is:

int b;
volatile const a=5;
void stuff()
{
b = a - a;
}

I can see how a can change in the midst of the execution since
some other code has access to a since its global scope.

If the code is:

int b;
void stuff()
{
volatile const a=5;

b = a - a;
}

Then the code can be optimized to 'b = 0;' since nowhere in the scope
of 'a' does anyone take its address(which would allow it to be changed).
Of course if 'a' is external then another function can access its
address.

>And a CAN change between the two pushes. It is not resposibility of the
>compiler to try to be clever than the programmer, if the volatile is there
>is for a reason (it can be a hardware mapped register like a DAC,
>or who knows).
>In the (in)famous example above the compiler should not convert to a += 13.
>If it is expected to do it, then the (in)famous is the programmer who
>put a volatile in a local variable. Usually a mapped register would
>be a 'volatile extern int my_reg'.

I don't think that anyone is arguing about that case *if so stated*.
What they are arguing about is the following code(and literally!):

void foo()
{
int a=3;
{
volatile int b=10;

a += b;
}
bar(a);
}

can *by inspection* be modified into:

void foo()
{
bar(13);
}

Since:
1) a and b's scope are limited to the function, so they will reside on
the stack.
2) No one takes the address of b, so there is no way for any external
hardware/thread to modify b.

For the above code, I see no reason for not optimizing out 'b'(and for
that case 'a'). If others want to argue about volatile variables,
generate a *realistic* testcase where the possibility for modification
can be inferred, and then pitch your case.

-- 
Peter Barada                                   Peter.Barada@motorola.com
Wizard                                         781-852-2768 (direct)
WaveMark Solutions(wholly owned by Motorola)   781-270-0193 (fax)
-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@vger.kernel.org
More majordomo info at  http://vger.kernel.org/majordomo-info.html
Please read the FAQ at  http://www.tux.org/lkml/