volatile

Mike Mahar mahar at weitek.UUCP
Wed May 18 03:06:12 AEST 1988


Consider the following C program.  Remember this is All the information you
get.  The actual addresses of variables are unknown. Any other modules 
are compiled separately.  What you see is all you get.

char fifo;
buf_fill(buffer,cnt)
    char *buffer;
    int cnt;
    {
    int i;
    for( i = 0; i < cnt; i++)
	{
	buffer++ = fifo;
	}
    }

Question: Is it safe to compile the preceding routine like this:

_buf_fill:
	movl	(a7),d1		#get count
	movl	4(a7),a1	#getbuffer address
	clrl	d0		#clear i
	movb	_fifo,d2	#pre-load fifo
L1:
	movb	d2,(a1)+	#store into buffer
	addq	#1,d0
	cmpl	d1,d0
	jlt	L1
	rts

If the variable "fifo" was physicaly mapped to a hardware FIFO, 
this optimization will give unexpected results.  Given all the information
above, the compiler must assume that the variable "fifo" is volatile and the
code given is incorrect.  Without some form of volatile declaration, the
compiler must assume that all global variables are volatile.  This disables
a whole class of optimizations.  The information is just not available.
If there is a class of optimiziations that are impossible, it makes the
compiler writters job a lot easier.  The question, "Can I do this"? is
always answered "Nope, Gee that was easy".
-- 
	Mike Mahar
	UUCP: {turtlevax, cae780}!weitek!mahar



More information about the Comp.lang.c mailing list