[cfe-dev] Ho to instruct the optimizer to not throw out certain constructs

Compiler Dragon via cfe-dev cfe-dev at lists.llvm.org
Wed Nov 23 02:44:26 PST 2016


Hi Mats,

thanks for your reply. Basically I want to implement some defensive actions against unauthorized code changes. The artifical introduced variables are used in a specifc manner and should be left untouched
by the optimizer.

One very basic and simplistic example:

Original code:

res = foo(a);
---
int foo(int a) {
  int b;
  ...
  b = a + 1;
  ...
  return(b);
}

Transformed code:

foo(a0, a1, &res0, &res1);
...
void foo(int a0, int a1, int *res0, int *res1) {
  int a0, a1;
  ...
  b0 = a0 + 1;
  b1 = a1 + 1;
  if ( b0 != b1 )
     throw_error();
  ...
  *b0 = 1;
  *b1 = 1;
  return;

Thanks

Marcel

> If they are not used, why do you want them to remain? `volatile` can be
> used to ensure that the compiler doesn't optimise something away, or
> "explicit use in a way that is never true - but compiler doesn't know it is
> so" (e.g. `if (sin(x) > 1.0) { do stuff that actually never happens }` ) -
> calling `sin` is probably not the best choice, but there may be other ways
> to achieve something similar that is less intrusive but still "unknown to
> the compiler".
> 
> 
> Can you give an example piece of code?
> 
> --
> Mats
> 
> On 22 November 2016 at 10:37, Compiler Dragon via cfe-dev <
> cfe-dev at lists.llvm.org> wrote:
> 
> > Hi *,
> >
> > I am currently writing a clang plugin, which add to specific functions for
> > e.g. additional arguments.
> >
> > How can I instruct the optimizer not to throw out these arguments, because
> > they are not used in the function body?
> >
> > With (optnone) we can instruct the optimizer to not optimize the whole
> > function. But this ist not what I want. The function body should be
> > optimized like before.
> >
> > Any idea or hints where to look?
> >
> > Thanks
> >
> > Marcel



More information about the cfe-dev mailing list