Skip to content
Snippets Groups Projects

Add preprocessor macro DUNE_ASSUME

Merged Simon Praetorius requested to merge feature/assume into master

Summary

Introduce a new dune macro DUNE_ASSUME to provide optimization information about invariants to the compiler. It is a compiler portable implementation of the C++23 [[assume(invariant)]] attribute, see https://wg21.link/p1774r8.

The implementation provided in this MR adds fallback implementation, that might actually evaluate the invariant expression at runtime.

Where to use this macro

Is can be used whereever we know an invariant holds true. It should not be used as a replacement for an assert. First of all, the DUNE_ASSUME macro is always active, also in release mode. Especially there, we can benefit from the extra information. It should not introduce extra overhead since a violation of the assumption is undefined behavior and the compiler is allowed to even eliminate the test completely. But still the compiler can use the tested expression in its optimizer.

Examples where it could be useful:

  • Internal function in the Dune::ReferenceElementImplementation, where we know the indices and codimensions that are passed to the function. These might even be checked using an assert() macro before.
  • Inside of loops where the loop index is tight to the allowed index range in a container.
  • After a debug check of the same condition was made.

Example

The following example is artificial and should not be used that way. IT just demonstrates that the compiler can generate better Code.

int abs (int x)
{
    DUNE_ASSUME(!(x < 0));
    return x < 0 ? -x : x;
}

Produces with clang++ -O1 the following assembler output

abs(int):
        mov     eax, edi
        ret

Without the DUNE_ASSUME call, it produces

abs(int):
        mov     eax, edi
        neg     eax
        cmovs   eax, edi
        ret
Edited by Simon Praetorius

Merge request reports

Loading
Loading

Activity

Filter activity
  • Approvals
  • Assignees & reviewers
  • Comments (from bots)
  • Comments (from users)
  • Commits & branches
  • Edits
  • Labels
  • Lock status
  • Mentions
  • Merge request status
  • Tracking
  • Loading
  • Loading
  • Loading
  • Loading
  • Loading
  • Loading
  • Loading
  • Loading
  • Loading
  • Loading
Please register or sign in to reply
Loading