Re: Asserts & optimisation (repost from comp.lang.c++) (Michael Tiomkin)
8 Dec 2003 00:23:26 -0500

          From comp.compilers

Related articles
Asserts & optimisation (repost from com.lang.c++) nospam@nospam.nospam.nospam (David Fisher) (2003-12-03)
Re: Asserts & optimisation (repost from comp.lang.c++) (2003-12-08)
| List of all articles for this month |

From: (Michael Tiomkin)
Newsgroups: comp.compilers
Date: 8 Dec 2003 00:23:26 -0500
References: 03-12-034
Keywords: C++, optimize
Posted-Date: 08 Dec 2003 00:23:26 EST

"David Fisher" <nospam@nospam.nospam.nospam> wrote in message news:03-12-034...
> Error checking (and recovery) in itself isn't a bad thing in a release
> build - it's the cost that people object to. A really clever compiler
> could potentially take care of this problem - for example:
> T& Array::operator [] (int index)
> {
> assert(index >= 0 && index < arrayLength);
> return arrayVal[index];
> }
> void incrementValues(Array &a)
> {
> for (int n = 0;n < a.length();++n)
> {
> ++a[n];
> }
> }
> An intelligent compiler could recognise that in this particular loop,
> the assert condition is always false, and so the check is not
> necessary at run time.
> Has anyone ever seen an optimising compiler that actually does
> this ?

    You can add "inline" before the operator and put it in the class
declaration. If the assert() and length() are also defined as
inlined, many optimizers would do it. This is frequently done in C++
to ease optimization and make less call/return statements.
    Recall that for large functions you wouldn't want several copies
of the same function anyway. A better design can have a small
inlined "decision" function that will call the needed functions depending
on the values of its arguments.

> This would require:
> - data flow analysis across function boundaries
> - some way of preventing execution of the "assert" code:
> - multiple entry points to functions with preconditions ?
> - multiple versions of functions, with and without checks ?
> (similar to the code generation done by templates)
> (but avoid having 2^N versions of a function with N asserts !)
> - possibly embedding this information in object modules / libraries
> so separate compilation is handled, too
> This applies to "optimising out" any block of code the compiler
> knows will never be entered, not just asserts like this one.

    This is called "inter-procedure optimization". This usually needs
compiling to an intermediate language representation and doing
optimization and linking together. This can be done by compiler only
for static functions in C, and for some templates in C++.
    External functions/classes can be replaced later with a different version,
and they can be used in interprocedure optimization only immediately
before the link stage, and only for executables that wouldn't be
relinked again.

Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.