Bug 51971 - unclear/unverified restrictions on attribute((const|pure))
Summary: unclear/unverified restrictions on attribute((const|pure))
Status: UNCONFIRMED
Alias: None
Product: gcc
Classification: Unclassified
Component: c (show other bugs)
Version: 4.6.2
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords: documentation
: 97364 (view as bug list)
Depends on:
Blocks:
 
Reported: 2012-01-23 17:26 UTC by Akim Demaille
Modified: 2021-04-20 02:04 UTC (History)
5 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed:


Attachments
Declare pure functions which obviously do not return (110 bytes, application/octet-stream)
2012-01-23 17:26 UTC, Akim Demaille
Details

Note You need to log in before you can comment on or make changes to this bug.
Description Akim Demaille 2012-01-23 17:26:28 UTC
Created attachment 26434 [details]
Declare pure functions which obviously do not return

Hi,

The documentation for const and pure is not clear about the fact that functions should "return normally":

  Interesting non-pure functions are functions with infinite loops or those depending on volatile memory or other system resource, that may change between two consecutive calls (such as feof in a multithreading environment).

In particular, at that point nothing is said about abort().

This is something which does appear in the documentation of -Wsuggest-attribute, yet at that point it is still unclear (to me?):

  The compiler only warns for functions
  visible in other compilation units or (in the case of pure and
  const) if it cannot prove that the function returns normally.

It does not say "do not flag as pure if the function does not return normally".  It does not tell either how to silence the suggestion if the function is not pure.

The warning itself is clearer though:

  akim@boss ~/src/gcc $ g++-mp-4.6 -O2 -Wsuggest-attribute=pure -c gcc/testsuite/gcc.dg/pure-2.c
  gcc/testsuite/gcc.dg/pure-2.c: In function 'int foo3(int)':
  gcc/testsuite/gcc.dg/pure-2.c:38:1: warning: function might be candidate for attribute 'pure' if it is known to return normally [-Wsuggest-attribute=pure]

I think that the documentation should also unveil why there is this restriction.  The documentation for "pure" mentions:

  Such a function can be subject to common subexpression elimination and loop optimization just as an arithmetic operator would be.

It also rules out every use of assert, which is a serious limitation, even for pure functions.

Does that mean that the function might be called _because_ of the optimization?  In which case, yes, indeed, looping or aborting becomes a problem :)  Can CSE really introduce extraneous calls?  The doc does not say so (it says "fewer", not "more"):

  For example,
         int square (int) __attribute__ ((pure));
  says that the hypothetical function square is safe to call fewer times than the program says.

Finally, if really "non-normally returning functions" are ruled out, then GCC should diagnose misuses, such as the attached one.

akim@padam /tmp $ gcc-mp-4.6 -O2 -Wall -Wextra -Wsuggest-attribute=pure -Wsuggest-attribute=const -c /tmp/pure.c
akim@padam /tmp $ echo $?
0

akim@padam /tmp $ gcc-mp-4.6 --version
gcc-mp-4.6 (GCC) 4.6.2
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Comment 1 Richard Biener 2012-01-24 13:01:03 UTC
GCC explicitely allows you to use const/pure to enable CSE even if it would
not consider the function const/pure itself (thus, if you are happy to
loose a second assert (), or a debug printf).

About returning normally it wants to exclude side-effects that happen
via the return, such as if the function calls longjmp/fork (return twice).
It also wants to exclude functions that do not return because they loop
infinitely.  For example

int foo (int b)
{
  if (b) while (1);
  return b;
}

is not const, as GCC would, if you declare it so, happily remove

  foo (1);

as dead code (GCC will do so for all pure/const functions if the result
is not needed).
Comment 2 Eric Gallager 2017-07-26 16:15:40 UTC
Related: bug 18487. They seem different enough to leave as separate bugs though.
Comment 3 Eric Gallager 2020-10-10 17:18:53 UTC
*** Bug 97364 has been marked as a duplicate of this bug. ***
Comment 4 David Stone 2021-04-17 18:20:40 UTC
Here are more examples that are currently unclear:

```
struct a {
	[[gnu::const]] a(): m(1) {}
	int m;
};
```

If you think of a constructor as a function (that is named after the type) that returns a value of that type, then the default constructor of `a` can safely be marked `gnu::const`. If you think of a constructor as a member function that gets a hidden `this` pointer passed in and then writes into that memory, then the default constructor of `a` cannot even be marked `gnu::pure`.

```
struct b {
	b(): m(1) {}
	~b() {}
	int m;
};

[[gnu::const]] b make_b() {
	return b();
}
```

Because `b` is not trivially destructible, the Itanium ABI requires that the return value passed by invisible reference. Here, whether it follows the requirements of the attribute depend on the calling convention of your platform if you take the "writing to memory in the return address is a side effect" view.

The following function is not even `gnu::pure`, but it is not immediately obvious why and the documentation should probably mention exception handling:

```
int c() {
	try {
		throw 1;
	} catch(int) {
		return 1;
	}
}
```

The issue here is that `c()` could be called in a destructor, and that destructor could be called during stack unwinding while handling another exception (in which case `std::terminate()` is called rather than this function returning 1).

Finally, the documentation is also not clear on what happens if you violate the requirements. Richard Biener's comment suggests that you get some somewhat unspecified result (some unspecified number of your calls might be replaced by the result of another call), and what you are communicating to the compiler is statements about whether side effects matter to you. Another possible interpretation is that the behavior of the program is undefined on violation. These are two very different models for what the attributes mean, but I suspect only the "undefined behavior" model ends up actually being workable in the long run. Consider the following code:

```
int d() {
	int x;
	std::vector<int> temporary_buffer;
	// do some work
	return x;
}
```

From the perspective of the world, this is logically `gnu::const`, assuming we don't run out of memory. From the "You might get fewer calls and some of your side effects might get discarded" model, I'm perfectly happy if the compiler remembers this result of calling the function and doesn't allocate and deallocate memory multiple times. My code doesn't handle `std::bad_alloc` so I'm fine with it calling `std::terminate` in that rare case, but I'm also fine with it not calling `std::terminate` in cases where I didn't have enough memory, but the result was effectively cached by the compiler. I suspect this will cause strange bugs in the optimizer if users adopt this model:

```
int e() {
	// After some inlining
	std::allocator<int>::__some_internal_call();
	d();
	std::allocator<int>::__some_other_internal_call();
}
```

These internal calls might expect consistent state of the allocator that can be violated if `d` calls `allocate()`. It seems like a safer model to just come right out and say that the behavior of your program is undefined if you violate these requirements.
Comment 5 David Stone 2021-04-20 02:04:32 UTC
After compiling this code

```
struct s {
	s();
};

s::s() {}

s g() {
	return s();
}
```

with `-O3 -Wsuggest-attribute=pure -Wsuggest-attribute=const`

I get the output

```
<source>: In function 's g()':
<source>:7:3: warning: function might be candidate for attribute 'const' [-Wsuggest-attribute=const]
    7 | s g() {
      |   ^
Compiler returned: 0
```