[llvm-dev] Adding [[nodiscard]] to Compiler.h

Justin Bogner via llvm-dev llvm-dev at lists.llvm.org
Fri Sep 2 14:20:51 PDT 2016


I started to try to use llvm::Error recently. This has nice runtime
checks for if you didn't check the result, but I thought it would be
really nice to get a compiler warning for the obvious cases of this
rather than having to wait for a runtime check.

This, of course, is exactly what the C++17 [[nodiscard]] attribute is
for - with new enough compilers in C++17 mode we can just declare the
class like so:

  class [[nodiscard]] Error { ... };

So, I'd like to add an LLVM_NODISCARD macro to Compiler.h, and this is
where it gets interesting. Pre-C++17, clang already allows
__attribute__((warn_unused_result)) and [[clang::warn_unused_result]] to
be used on a class this way, with equivalent affects, so it'd be nice to
use that if we aren't building in C++17 mode.

We already have a LLVM_UNUSED_RESULT defined to this, but AFAICT gcc
only allows it on function declarations, and the MSVC equivalent
(_Check_return_) seems like it's not allowed on types either. I guess we
want a new macro LLVM_NODISCARD, that's [[nodiscard]] if available, else
[[clang::warn_unused_result]] if we're clang (maybe even clang 3.6 and
up, I'm not sure if it works before that), else empty.

Thoughts?


More information about the llvm-dev mailing list