Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!iuvax!rutgers!cmcl2!adm!smoke!gwyn From: gwyn@smoke.BRL.MIL (Doug Gwyn) Newsgroups: comp.lang.c Subject: Re: Ambiguous C? Message-ID: <10136@smoke.BRL.MIL> Date: 27 Apr 89 04:01:39 GMT References: <111@ssp1.idca.tds.philips.nl> <17133@mimsy.UUCP> Reply-To: gwyn@brl.arpa (Doug Gwyn) Organization: Ballistic Research Lab (BRL), APG, MD. Lines: 32 In article <17133@mimsy.UUCP> chris@mimsy.UUCP (Chris Torek) writes: >If your compiler does not understand `volatile', and has no way to >disable optimisation, you are out of luck. (You can resort to assembly >language subroutines.) Back, back! (Making the sign of the cross.) No need to resort to assembly language for something so simple. What is the real problem here? It's that the compiler knows that we only need to inspect one byte in order to determine the state of the bit. So how do we outwit the compiler? We have to make it unsure of whether or not the other bytes are also needed. One simple way to do that is to resolve the bit test into two phases, the first of which performs the proper access, after which the second determines what the state of the bit is. To force a longword access, it suffices to copy the addressed object into an external longword, because the compiler cannot know what other use might be made of its contents (by other independently-compiled modules) and must therefore pick up the whole object. Having gotten the object into an ordinary storage cell, it can then be inspected to our heart's content. The one thing you can't really accomplish via such a trick is an atomic read-modify-write operation, such as ORing a bit into a memory- mapped device register. I can't recall ever needing to ensure that, but it is theoretically possible that one might. In such a case we might be inspired by the trick and code the operation something like: if ( (*(long *)DEVADDR |= BIT) == BIT ) something_innocuous(); which will also force the compiler to examine the whole longword. Odds are good that it will generate the desired code for the OR operation. (If not, additional effort along these general lines should eventually outwit the compiler's optimization.)