Borland Online And The Cobb Group Present:


February, 1994 - Vol. 1 No. 2

A closer look at subexpressions

In the accompanying article, Optimizing your code - Eliminating common subexpressions we show you how to tell the Borland C++ compiler to eliminate common subexpressions globally or locally. However, it's not always clear which form of subexpression elimination is better. Let's look at each method individually.

Global subexpression Elimination

When you tell the compiler to eliminate common subexpressions globally, it will look for more than one occurrence of any given computational fragment, or subexpression, in the whole function. If the compiler finds a common subexpression, it will analyze the function's scope to determine if it would be more efficient to store the result of the computation either in a register or at a RAM address than to recompute the value. If it will be more efficient, the compiler will store the value as necessary.

In some cases, this optimization may reduce the size of your code. However, most of the time, it will slightly increase your code size.

If your code contains many subexpressions that repeat only once or twice, the increase in code size from this optimization may negate the improvement in speed. In this case, you may want to use a more modest form of subexpression elimination in your projects.

Local subexpression Elimination

When you tell the compiler to eliminate common subexpressions locally, it will look for them only within basic blocks of code. The compiler creates a basic block of code when it compiles a series of statements that don't branch to another location.

Using the code in Figure A as an example, when the same expression appears before an if statement as well as inside the body of the if statement, the compiler will consider the body of the statement a basic block. The compiler sees the same expression prior to the if statement as part of a different basic block. Therefore, local subexpression elimination will not eliminate the second expression.


Figure A In local subexpression elimination, the compiler treats NewVal * 3 as part of two different basic blocks.

void foo(int NewVal)
{
  int Val1 = NewVal * 3;
  if(Val1 > 12)
  {
   GlobalVal = NewVal * 3;
  }
}

Conclusion

In a complex function, eliminating subexpressions globally may create a large number of temporary variables and thus increase your code size. By eliminating subexpressions locally, you can achieve some of the speed benefits with a smaller size penalty.

Return to the Borland C++ Developer's Journal index

Subscribe to the Borland C++ Developer's Journal


Copyright (c) 1996 The Cobb Group, a division of Ziff-Davis Publishing Company. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of Ziff-Davis Publishing Company is prohibited. The Cobb Group and The Cobb Group logo are trademarks of Ziff-Davis Publishing Company.