title: Accessing ARM peripheral registers through structures
body: <p>I want to make my own library for ARM Cortex-M3 enabled devices. Currently writing to a register looks like this:</p>
  <pre><code>(*((unsigned int volatile * const)(0x400E0410))) = (1 &lt;&lt; 11) | (1 &lt;&lt; 12);
  </code></pre>
  <p>Where <code>0x400E0410</code> is the address of a 32-bit peripheral register (in this case the address of Power Management Controller's 'Peripheral Clock Enable Register').</p>
  <p>So I wish to abstract peripherals into <code>struct</code> so it's a lot more user-friendly, readable, and allows for autocompletion inside the IDE. The previous example would then look like so:</p>
  <pre><code>PMC.PCER = PORTB.ID | PORTC.ID;
  </code></pre>
  <p>I can't use <code>volatile</code> on <code>struct</code> or on its members, otherwise (to my knowledge) that'd always include the struct in the final code even if its not actually being used for anything in the code. I also noticed that even if the struct is <code>name-less</code> and all its members have been initialised as const values, the compiler makes a constructor for it and stores it in RAM instead of the FLASH which is really suboptimal.</p>
  <p>Optimally I'd also want the <code>struct</code> approach to generate assembly code like this (disassembly of first example):</p>
  <p><a href="https://i.stack.imgur.com/zq7NZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zq7NZ.png" alt="first example disassembly" /></a></p>
  <p>Instead of code like this that's reading struct variables from RAM (my approach using volatile members inside a struct):</p>
  <p><a href="https://i.stack.imgur.com/xrSzm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xrSzm.png" alt="second example disassembly" /></a></p>
  <p>How could I implement this while not compromising for program size or performance?</p>
  <p><strong>EDIT: C++ code for my approach, u32v is an unsigned volatile 32bit integer, u32c is an unsigned const 32bit integer</strong>
  <a href="https://i.stack.imgur.com/2HXSb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2HXSb.png" alt="my code" /></a></p>