Friday, August 29, 2014

volatile qualifier and storage location

purpose of volatile qualifier:

  • Tells the compiler that dont apply your optimization techniques on me(variable which decleared as volatie) !


Where volatile qualifier used:

  • The first case involves memory-mapped hardware (a device such as a graphics adaptor that appears to the computer's hardware as if it were part of the computer's memory),
  • the second involves shared memory (memory used by two or more programs running simultaneously).



time_t time_addition(volatile const struct timer *t, int a)
{
        int     n;
        int     x;
        time_t  then;
        x = 0;
        then = t->value;
        for (n = 0; n < 1000; n++)
        {
                x = x + a;
        }
       return t->value - then;
}


  • If a variable is a pointer to something other than normal memory, such as memory-mapped ports on a peripheral, redundant load and store optimizations might be detrimental.
  • In this code, the variable t->value is actually a hardware counter that is being incremented as time passes. The function adds the value of a to x 1000 times, and it returns the amount the timer was incremented by while the 1000 additions were being performed.
  • Without the volatile modifier, a clever optimizer might assume that the value of t  does not change during the execution of the function, because there is no statement that explicitly changes it. In that case, there's no need to read it from memory a second time and subtract it, because the answer will always be 0. The compiler might therefore "optimize" the function by making it always return 0.






When we compile code with “–save-temps” option of gcc it generates 3 output files
1) preprocessed code (having .i extention)
2) assembly code (having .s extention) and
3) object code (having .o option).

We compile code without optimization, that’s why the size of assembly code will be larger (which is highlighted in red color below).


Storage of volatiler qualifer


  • volatile just tells the compiler it can't cache the value of the variable in a register—it doesn't change where it gets allocated. if local volatile variable then on stack or otherwise on bss/initialized variable section

  1. Local variables and function frame - stack
  2. Global and static variables if uninitialized - .bss block start by symbol
  3. Global and static variables if initialized - data segment
  4. Environment variables and arguments - on top of the stack
  5. Dynamic data allocation - heap
  6. Const - ROM
  7. Volatile - no storage
  8. Register - cpu register
  9. Const volatile - in the same place as const storage

Reference:



No comments:

Post a Comment