Optimized Out variables

Tip / Sign in to post questions, reply, level up, and achieve exciting badges. Know more

cross mob
DaHu_285096
Level 5
Level 5
10 likes received 250 replies posted 100 replies posted

 I have been having trouble with this optimizing out of variables in several projects and it seems I do not understand when this happens.

   

In the last case I had a variable defined within scope of a procedure (method) that retrieved info from a serial port buffer and used the value to store a record in SPI flash IC. I thought the variable would only be optimized out if I did not use it.

   

This is what I am doing:

   

uint16 level;

   

level = buf[3]*256 + buf[4];

   

StoreRecord(.....,level);  //I though variable would be retained because I am using it in another function

   

 

   

In this case I had to set up "level" as volatile. 

   

I thought it would only be optimized out if not used, like this...

   

uint8 level;

   

Level = buf[3]*256 + buf[4];

   

//then do nothing else with it

0 Likes
1 Solution
ScottA_91
Employee
Employee
10 solutions authored 100 replies posted 50 replies posted

Well, so based on your code, level is not considered volatile.  You'd need something like:

   

volatile uint16 level;
level = buf[3]*256 + buf[4];
StoreRecord(.....,level);

   

for it to be marked as volatile.  See http://www.keil.com/support/man/docs/c51/c51_le_volatile.htm.The reason Keil is optimizing out your variable is it looks at the assignment and the singular use case and it can either replace the usage with the assignment value, or keep the assignment in a CPU register instead of commiting it back.  If you mark the variable volatile as the link above specfies, does it work as expected?

View solution in original post

0 Likes
3 Replies
ETRO_SSN583
Level 9
Level 9
250 likes received 100 sign-ins 5 likes given

Are you using Keil or GNU ?

   

 

   

For Keil - www.cypress.com/

   

 

   

Regards, Dana.

0 Likes
DaHu_285096
Level 5
Level 5
10 likes received 250 replies posted 100 replies posted

 Keil

0 Likes
ScottA_91
Employee
Employee
10 solutions authored 100 replies posted 50 replies posted

Well, so based on your code, level is not considered volatile.  You'd need something like:

   

volatile uint16 level;
level = buf[3]*256 + buf[4];
StoreRecord(.....,level);

   

for it to be marked as volatile.  See http://www.keil.com/support/man/docs/c51/c51_le_volatile.htm.The reason Keil is optimizing out your variable is it looks at the assignment and the singular use case and it can either replace the usage with the assignment value, or keep the assignment in a CPU register instead of commiting it back.  If you mark the variable volatile as the link above specfies, does it work as expected?

0 Likes