Path: utzoo!dciem!nrcaer!scs!spl1!laidbak!att!ihnp4!amdcad!tim From: tim@amdcad.AMD.COM (Tim Olson) Newsgroups: comp.lang.c Subject: Re: why do you need volatile? Message-ID: <21888@amdcad.AMD.COM> Date: 3 Jun 88 03:25:26 GMT Article-I.D.: amdcad.21888 References: <15735@brl-adm.ARPA> <3754@pasteur.Berkeley.Edu> Reply-To: tim@delirun.amd.com (Tim Olson) Organization: Advanced Micro Devices Lines: 109 In article <3754@pasteur.Berkeley.Edu> faustus@ic.Berkeley.EDU (Wayne A. Christopher) writes: | In article <15735@brl-adm.ARPA>, reg%lti.UUCP@bu-it.bu.edu (Rick Genter x18) writes: | > for (A = 1.0, i = 0 ; i < iCalcRep ; i++) { | > if (! bContinueCalc) | > break; | > A = Savage (A); | > } | > ... should be declared | > | > volatile BOOL bContinueCalc = FALSE; | > | > otherwise the C compiler is perfectly justified taking the test of | > bContinueCalc out of the for loop, thus invalidating the whole use | > of the variable. Actually, because there is a function call in the loop, the test cannot typically be removed, unless the compiler can trace the program flow and ensure that bContinueCalc is not modified elsewhere. However, if there were no function call in the loop, then the compiler *is* justified in moving the test out of the loop, since it is invariant. Here is an example, from the MetaWare 29000 C compiler: === non-volatile, function call in loop === ;int bool; ; ;int f() ;{ ; int i = 0; ; ; for (;;) { ; if (bool) ; break; ; i = A(i); ; } ; return i; ;} const gr96,0 ; (0x0) const lr4,_bool consth lr4,_bool L00012: load 0,0,gr121,lr4 <-- note that load of "bool", cpeq gr121,gr121,0 <-- and comparison are in the loop jmpt gr121,L00014 nop . . === non-volatile, no function call in loop === ;int bool; ; ;int f() ;{ ; int i = 0; ; ; for (;;) { ; if (bool) ; break; ; ++i; ; } ; return i; ;} const gr121,_bool consth gr121,_bool load 0,0,gr121,gr121 <-- "bool" is loop-invariant, so it const gr96,0 ; (0x0) <-- is moved out, along with the cpeq gr121,gr121,0 <-- comparison to zero! L00012: jmpt gr121,L00014 nop jmpi lr0 nop L00014: jmp L00012 add gr96,gr96,1 === volatile, no function call in loop === ;volatile int bool; ; ;int f() ;{ ; int i = 0; ; ; for (;;) { ; if (bool) ; break; ; ++i; ; } ; return i; ;} const gr96,0 ; (0x0) const gr120,_bool consth gr120,_bool L00012: load 0,0,gr121,gr120 <-- load is not hoisted because cpeq gr121,gr121,0 <-- of volatile declaration. jmpt gr121,L00014 nop jmpi lr0 nop L00014: jmp L00012 add gr96,gr96,1 -- Tim Olson Advanced Micro Devices (tim@delirun.amd.com)