Readable Code – August 03, 2005

I think this is the worst code I have ever seen, except where people were trying to make code hard to read. This code is in a video driver, written by Silicon Motion.This is the function at the top level, supposedly easy to read, since it is using these lovely macros.
POKE_32(DE_WINDOW_SOURCE_BASE,
     FIELD_VALUE(0, DE_WINDOW_SOURCE_BASE, EXT, m_SMISettings.m_bUMA) |
     FIELD_VALUE(0, DE_WINDOW_SOURCE_BASE, ADDRESS,
     VgxSurfAddr(((SMISurf*)
     (pBltParms->pSrc))->OffsetInVideoMemory())) |
     0);
Now, to investigate what this does, here are the subsequent macros. My hat is off to you, if you can figure out how this works prior to reading the last group of defines.
#define POKE_32(address, value)   *(volatile ULONG *)
                (VGX_MMIO_ARENA + (address)) = (value)
Not bad so far, don't be too confident yet...
#define FIELD_VALUE(x, reg, field, value)    ((x & 
     ~_F_MASK(reg ## _ ## field)) | _F_DENORMALIZE(value, reg ## _ ## field) )
Swell, using that substitution stuff, don't worry, it gets better.
#define _F_MASK(f)              (((1 < < _F_SIZE(f)) - 1) << _F_START(f))
#define _F_DENORMALIZE(v, f)    (((v) << _F_START(f)) & _F_MASK(f))
#define _F_SIZE(f)              (1 + _F_END(f) - _F_START(f))
#define _F_START(f)             (0 ? f)
#define _F_END(f)               (1 ? f)
Perfectly obvious, no? What is that question mark doing without a colon? Perhaps it is an overridden operator, this is C++ after all. Ok, here is the final bit, and then it will all be clear.
#define DE_WINDOW_SOURCE_BASE                           0x100040
#define DE_WINDOW_SOURCE_BASE_EXT                       27:27
#define DE_WINDOW_SOURCE_BASE_EXT_LOCAL                 0
#define DE_WINDOW_SOURCE_BASE_EXT_EXTERNAL              1
#define DE_WINDOW_SOURCE_BASE_CS                        26:26
#define DE_WINDOW_SOURCE_BASE_CS_0                      0
#define DE_WINDOW_SOURCE_BASE_CS_1                      1
#define DE_WINDOW_SOURCE_BASE_ADDRESS                   25:0
Now you have all the code, still stuck?