Friday, June 05, 2009

IAR, STL and the MSP430

Apparently, the IAR MSP430 compiler supports C++'s STL.  My jaw drops.

In my previous post, I alluded to the desire to try generic programming on a Cortex M3.  Out of curiosity, I wondered whether or not it would be possible/practical to do C++ on an MSP430.

Well,  after some deep digging I've found that IAR has "some" C++ support that includes the STL!

How efficient can it be? Well, I don't like resorting to dynamic memory allocation when I don't have to (and certainly not on an MSP430) but I decided to give some basic STL algorithms a try.  I am less concerned about performance than about code size. STL is (undeservedly, IMHO) notorious about being a source of bloat.

Here is the sample code:

#include  <msp430x54x.h>
#include <numeric>
#include <functional>

static volatile int res;

int main( void )
  int a[] = { 9, 1, 5, 6, 7, 8};
  // Stop watchdog timer to prevent time out reset
  res = accumulate(a,a+sizeof(a)/sizeof(int),0);
  res = accumulate(a, a+sizeof(a)/sizeof(int), 1, multiplies<int>());

  return 0;

This compiles to 250 bytes of CODE, 162 bytes of DATA and 12 bytes of CONST  with default compile settings. (Some of the DATA is pre-sized stack and heap.)

With the highest optimization settings this compiles to 180 bytes of CODE, 162 bytes of DATA and 12 bytes of CONST.

I am impressed.

Sure this was a contrived test, but I am amazed that I could even do this.

Is this more efficient than a hand written accumulator? No. There are function calls here that wouldn't exist if I were to do it by hand. However, this may scale better than I could muster by hand:  By cherry picking STL algorithms I am choosing to be more type "aware".  I am also avoiding writing stuff like:
  for (int i=0; i < sizeof(a)/sizeof(int); i++)
    res += a[i];
Simple, right? But do you see the two potential problems? First, I never initialized "res". Second, I introduced another variable "i".  While the STL code has the overhead of function calls, it uses the more space efficient technique of incrementing through "a" rather than indexing.

I'm not planning on using the STL for any real MSP430 work. That would be overkill.  But the Cortex M3 is a different issue...

No comments:

Post a Comment