Skip to content

Tweaks to reduce sketch size - #28

Closed
evq wants to merge 1 commit into
rogerclarkmelbourne:masterfrom
evq:master
Closed

evq wants to merge 1 commit into
rogerclarkmelbourne:masterfrom
evq:master

Conversation

@evq

@evq evq commented Feb 18, 2015

Copy link
Copy Markdown

Spent some time trying to get the code size down, ended up getting a sketch that was 72k down to 18k.

I see that the compile options already include "-fno-exceptions", but I was having issues with them getting pulled in anyway.

I redefined "__verbose_terminate_handler" as is mentioned in a few places online. I also removed "-Wl,--whole-archive" in the linker options which bought another few k, I think "-Wl,--no-whole-archive" can also be removed but I'm no expert :)

@rogerclarkmelbourne

Copy link
Copy Markdown
Owner

Hi evq

I'm not sure how safe your changes ae.
I recall -whole-archive was added for some reason by BobC via a pull request

There is a way to use newlibnano rather than newlib which greatly reduces the size.

However as there aren't any test units for this code, its impossible to determine the ramifications of making changes to the build options

So I'm afraid at the moment, I can't action this pull request.

What I plan to do is to add a wiki page with suggestions for people who run out of space including the options to use newlibnano etc

So I think this is the best place for your changes.

Or I guess I could branch. But I'd then need to to keep merging core changes from the Master branch back into the "size reduction" branch

@evq

evq commented Feb 18, 2015

Copy link
Copy Markdown
Author

Hey Roger,

Thanks for the quick reply.

I saw in the topic on the Arduino forums that bobcousins (bobc?) said "I have no hard evidence that whole-archive flag is needed with our current build setup, so we can probably revert commit fd450f2 and we will be back where we before. Sorry about that!"

http://forum.arduino.cc/index.php?topic=265904.msg2022377#msg2022377

Was there a follow up post by him on that?

@evq

evq commented Feb 18, 2015

Copy link
Copy Markdown
Author

Also, as an alternative I can prepare a pull request that only has the change to not pull in exception handling code. This makes the largest difference (~40k) and is in line with the current intent of the compilation options.

@rogerclarkmelbourne

Copy link
Copy Markdown
Owner

Hi Evq

I can't remember exactly why the whole archive was added or removed or added again.

I'll need to check.

I agree its quite possible that its not needed.

Actually, I will PM Bob. But I'm not sure if he will reply, because he was not happy with some responses to his suggestions from other forum members, and has said that he is not willing to participate on this project any more. (which is very unfortunate as he is extremely talented)

@rogerclarkmelbourne

Copy link
Copy Markdown
Owner

I've reviewed what BobC wrote on the forum, and I agree it looks like the whole archive flag is not needed.

So I've removed it and committed the change to platform.txt

Can you let me know what other changes you propose ?

Sorry to be so cautious, but I've had multiple instances where I have actioned pull requests or patched after people sent me .diff files, only to find that they'd overlooked something or that their change only worked for one board variant.

Thanks

Roger

@evq

evq commented Feb 18, 2015

Copy link
Copy Markdown
Author

Hey Roger,

No worries, I'm all for being cautious and testing.

The other change that I made was to override "__verbose_terminate_handler", which seems to be the code that is run when an uncaught exception is encountered.The default implementation prints the name of the uncaught exception, but it must first unmangle the name. By default it never returns, which is what the overridden version does by going into an infinite loop :)

There is some mention on it here - http://www.webalice.it/fede.tft/cpp_on_microcontrollers_tricks/cpp_on_microcontrollers_tricks.html

Truthfully I am not a C++ person or much of an Arduino person, I generally write pure C when doing embedded stuff. So it might be be me pulling my assumptions in here but I can't really see why one would need exceptions here. The compiler options also include "-fno-exceptions" so I'm thinking that this was the original intent. It's interesting to me that one can pass that no exceptions flag and still have such a large uncaught exception handler be dragged in.

@rogerclarkmelbourne

Copy link
Copy Markdown
Owner

Hi @evq

I'm not a hard core C++ or C person myself either ;-)

I agree, its pointless having an exception handler that does nothing. I guess if it worked it would be quite beneficial, but as it doesn't appear to work, we may as well remove it.

There is one other piece of code that seems similar but also doesn't do anything usefull

There is an ASSERT handler, but all it ends up doing is flashing the Maple mini LED (well it PWM's its brilliance ) , which may as not be included either.

The code may as well just halt, or perhaps ignore the ASSERT and crash elsewhere, as this feature isn't documented and doesnt provide anything useful. (although I believe the original intent was to output an ASSERT message via serial - but this doesn't seem to work in the current code base)

I don't have time to look at this until later, as I need to get back to work, but I will take a look at the pull request in detail this evening (my time)

Thanks again

Roger

@rogerclarkmelbourne

Copy link
Copy Markdown
Owner

Hi @evq

I've done a local pull on your change, but its not making any difference to the file size reported by the IDE.

I've tried both a bare minimum sketch and also a more complex one (the BMP085 barometer example from Adafruit)

I've checked the size of the bin file, and not just relied on the size reported by the IDE.

Did you make any other changes in order to reduce the file size? e.g. changes to the build options in platform.txt ?

@rogerclarkmelbourne

Copy link
Copy Markdown
Owner

Hi @evq
I've just had to revert the change for the whole-archive flag, because it caused an issue with the Hardware timers.

Basically it crashed the code, as it looks like something required for the timer interrupts was not being linked in

This code won't run on the Maple mini etc with the whole-archive flag removed :-(

There may be a way to make sure it compiles, but at the moment its safer to just leave the whole-archive flag as it was before.

#define LED_RATE 50000    // in microseconds; should give 0.5Hz toggles

// We'll use timer 2
HardwareTimer timer(1);

void setup() {
    // Set up the LED to blink
    pinMode(BOARD_LED_PIN, OUTPUT);

    // Pause the timer while we're configuring it
    timer.pause();

    // Set up period
    timer.setPeriod(LED_RATE); // in microseconds

    // Set up an interrupt on channel 1
    timer.setChannel1Mode(TIMER_OUTPUT_COMPARE);
    timer.setCompare(TIMER_CH1, 1);  // Interrupt 1 count after each update
    timer.attachCompare1Interrupt(handler_led);

    // Refresh the timer's count, prescale, and overflow
    timer.refresh();

    // Start the timer counting
    timer.resume();

  //  Serial.begin(115200);

}

void loop() {
    // Nothing! It's all in the handler_led() interrupt:
    //Serial.println("HERE");
   // digitalWrite(BOARD_LED_PIN,!digitalRead(BOARD_LED_PIN));
   // delay(100);
}

void handler_led(void) {
   digitalWrite(BOARD_LED_PIN,!digitalRead(BOARD_LED_PIN));
}

@evq

evq commented Feb 24, 2015

Copy link
Copy Markdown
Author

@rogerclarkmelbourne That's rather unfortunate :(

Going back to the exception handler change. I noticed the large difference when using the FastLED library. I didn't see any obvious references to exceptions in a brief grep of that codebase, but something must be pulling the uncaught handler in anyway. I suspect other libraries might also cause this, but my use cases aren't really broad enough to say with any certainty. I'm going to close this PR, but will continue to maintain a size optimized fork. I can't use the FastLED library on the smaller (64k) STM32 clones without the handler change.

@evq evq closed this Feb 24, 2015
@rogerclarkmelbourne

Copy link
Copy Markdown
Owner

@evq

Ok. Thanks.

Its good to document this stuff even if its not currently used.

Cheers

Roger

evq referenced this pull request in evq/Arduino_STM32 Jan 20, 2018
@ajkeeton

Copy link
Copy Markdown

Just throwing it out there that I ran in to an almost identical problem as @evq ... I'm also using FastLED and my binary comes out around 90k. With the diff applied, it drops to 47k with no apparent issues on my blue pill.

@rogerclarkmelbourne

Copy link
Copy Markdown
Owner

Looking at this change, it seems to have evolved / changed from its original version.

The comments seem to suggest the original fix was to change the "wholearchive" flag in the build process, but now it seems to do something different

Its not my area of expertise, so I'll need to ask someone more experienced in the depths of the compiler

e..g perhaps @RickKimball may now what this PR is doing, by adding a function
perhaps its overriding a larger exception handler in one of the c libraries

@stevstrong

Copy link
Copy Markdown
Collaborator

@ajkeeton
If you are talking about FastLed being bloated there could be one other reason found not so long ago in another lib (I don't remember which).
It is about using static variables within functions.
I see FastLed also uses two of them here: https://github.com/FastLED/FastLED/blob/master/FastLED.cpp#L207
Try to remove the "static" property and check it again.

@rogerclarkmelbourne

rogerclarkmelbourne commented Jan 27, 2018 •

Copy link
Copy Markdown
Owner

I don't use FastLED, but but changing static to non static would effect the operation of the function

AFIK, static vars are special as they are initialised only once, (I cant remember if the compiler does this when it does the globals or when the function is first called.)
The variable is retained even when the function is complete.

Looking at the code in the code you linked to, the code would not make any sense unless br was static, otherwise the code may as well check for

(1 >= nFrames)

@stevstrong

Copy link
Copy Markdown
Collaborator

OK, in this case place the static declaration outside the function.

@kolyshkin

Copy link
Copy Markdown
Contributor

The commit looks good to me; this is a standard GCC trick to disable some exception debugging (unfortunately enabled by default). I have also tested it on my blue pill board with FastLED library; sketch size decrease is impressive!

@RickKimball

RickKimball commented Feb 15, 2018 •

Copy link
Copy Markdown
Contributor

That changes seems like it would only affect stuff in the libc++. @evq are you using the Arduino IDE or are you using another ide that is adding the libstdc++ to the link? Maybe platform.io ?

@kolyshkin

Copy link
Copy Markdown
Contributor

That changes seems like it would only affect stuff in the libc++ stuff.

I am using Arduino IDE 1.8.5 and recent Arduino_STM32 (2018.2.2 I believe), with the FastLED package. I took a quick look at FastLED code and haven't found it using any of the libstdc++ (grep for std:: and namespace std found nothing in the code).

@RickKimball

RickKimball commented Feb 15, 2018 •

Copy link
Copy Markdown
Contributor

Where did you get the FastLED (url please) where did you get the libmaple version of Arduino_STM32 (url please) ? Please provide a link to your code. There is no recent 2018.2.2 release of Arduino_STM32

@evq

evq commented Feb 15, 2018

Copy link
Copy Markdown
Author

I was also using the Arduino IDE. The result was similarly confusing to me, it did not seem like libstdc++ should have been included

@kolyshkin

kolyshkin commented Feb 15, 2018 •

Copy link
Copy Markdown
Contributor

Where did you get the FastLED (url please)

I am using the current HEAD of https://github.com/FastLED/FastLED/ plus a patch to enable stm32 support (FastLED/FastLED#568). As this PR is not yet merged, you can use the following commands to get the source tree:

git clone https://github.com/kolyshkin/FastLED.git
cd FastLED
git checkout stm32

where did you get the libmaple version of Arduino_STM32 (url please)?

The additional board manager URL configured in Arduino IDE is:

(I guess I took the URL from http://wiki.stm32duino.com/index.php?title=Boards_Manager_package)

I believe the URL to the exact platform package installed is:

(please let me know if you want me to re-check that -- I can compare the files from the above .zip and the ones that Arduino IDE has installed to ~/.arduino15/packages/stm32duino/).

There is no recent 2018.2.2 release of Arduino_STM32

Here's the screenshot from Arduino's boards manager:

stm32

Please provide a link to your code.

If you mean the code I was compiling (i.e. Arduino sketch), I was just using an example from FastLED: https://github.com/FastLED/FastLED/tree/master/examples/DemoReel100/

The only change I made is to change the data pin:

-#define DATA_PIN    3
+#define DATA_PIN    PB9

@RickKimball please let me know if you need any other information.

@kolyshkin

Copy link
Copy Markdown
Contributor

For the record, here's Arduino IDE output after compiling the https://github.com/FastLED/FastLED/tree/master/examples/DemoReel100/ example:

with this PR applied

Sketch uses 28064 bytes (42%) of program storage space. Maximum is 65536 bytes.
Global variables use 6216 bytes (30%) of dynamic memory, leaving 14264 bytes for local variables. Maximum is 20480 bytes.

without

Sketch uses 75104 bytes (114%) of program storage space. Maximum is 65536 bytes.
Global variables use 6272 bytes (30%) of dynamic memory, leaving 14208 bytes for local variables. Maximum is 20480 bytes.

@stevstrong

Copy link
Copy Markdown
Collaborator

It seems that you are not using this Arduino_STM32 core but the STM32DUINO core so you should post there the PR.

@fpistm

fpistm commented Feb 15, 2018

Copy link
Copy Markdown
Contributor

@stevstrong,
@kolyshkin uses the Arduino_STM32 packaged by Dan Drown ;)

@kolyshkin

Copy link
Copy Markdown
Contributor

@kolyshkin

Copy link
Copy Markdown
Contributor

I have re-tested with the version from this very repository (recent git commit f928acf). Got very similar results:

without this PR

Sketch uses 75088 bytes (114%) of program storage space. Maximum is 65536 bytes.
Global variables use 6272 bytes (30%) of dynamic memory, leaving 14208 bytes for local variables. Maximum is 20480 bytes.

with

Sketch uses 28128 bytes (42%) of program storage space. Maximum is 65536 bytes.
Global variables use 6216 bytes (30%) of dynamic memory, leaving 14264 bytes for local variables. Maximum is 20480 bytes.

@kolyshkin

Copy link
Copy Markdown
Contributor

OK, I found why libstdc++ is included, and a way to fix it in a nicer way. Will send a separate PR shortly.

@kolyshkin

kolyshkin commented Feb 16, 2018 •

Copy link
Copy Markdown
Contributor

BTW the code size (with the same sketch) is now down to:

Sketch uses 16428 bytes (25%) of program storage space. Maximum is 65536 bytes.
Global variables use 3136 bytes (15%) of dynamic memory, leaving 17344 bytes for local variables. Maximum is 20480 bytes.

I declare a win!

kolyshkin added a commit to kolyshkin/Arduino_STM32 that referenced this pull request Feb 16, 2018
In case static local variables are used anywhere in the C++ code of
the sketch or the libraries, gcc kicks in to protect initializing
those from any potential threads being run in parallel.

The implementation of the above is to emit calls to __cxa_guard_acquire()
and __cxa_guard_release(). These functions are part of libstdc++ [1],
and so, once a local static variable appears, the whole libstdc++ is
linked into the binary with all its bells and whistles, greatly
increasing the binary size as a result.

One possible solution to that was proposed in [2], but it dealt with
a single consequence of linking in libstdc++ (adding the
__verbose_terminate_handler()).

This commits deals with the reason of libstdc++ linking. A gcc option
-fno-threadsafe-statics is disabling the above local statics protection
mechanism, as a result libstdc++ is not linked in.

Resulting binary size comparison using a sketch from FastLED examples
(as reported by Arduino IDE, in bytes; the first number is "program
storage space", the second is "dynamic memory"):

Before: 75160 / 6392
After:  14964 / 3152

For comparison, here are the numbers after applying the commit from [2]:

PR#28:	29592 / 6328

Finally, the resulting sketch is working just fine.

[1] https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/libsupc%2B%2B/guard.cc
[2] rogerclarkmelbourne#28

Signed-off-by: Kir Kolyshkin <[email protected]>
kolyshkin added a commit to kolyshkin/Arduino_STM32 that referenced this pull request Feb 20, 2019
In case static local variables are used anywhere in the C++ code of
the sketch or the libraries, gcc kicks in to protect initializing
those from any potential threads being run in parallel.

The implementation of the above is to emit calls to __cxa_guard_acquire()
and __cxa_guard_release(). These functions are part of libstdc++ [1],
and so, once a local static variable appears, the whole libstdc++ is
linked into the binary with all its bells and whistles, greatly
increasing the binary size as a result.

One possible solution to that was proposed in [2], but it dealt with
a single consequence of linking in libstdc++ (adding the
__verbose_terminate_handler()).

This commits deals with the reason of libstdc++ linking. A gcc option
-fno-threadsafe-statics is disabling the above local statics protection
mechanism, as a result libstdc++ is not linked in.

Resulting binary size comparison using a sketch from FastLED examples
(as reported by Arduino IDE, in bytes; the first number is "program
storage space", the second is "dynamic memory"):

Before: 75160 / 6392
After:  14964 / 3152

For comparison, here are the numbers after applying the commit from [2]:

PR#28:	29592 / 6328

Finally, the resulting sketch is working just fine.

[1] https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/libsupc%2B%2B/guard.cc
[2] rogerclarkmelbourne#28

Signed-off-by: Kir Kolyshkin <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants