[cfe-dev] Patch for review: enhancement to __builtin_strlen
Andy Gibbs
andyg1001 at hotmail.co.uk
Thu Jun 21 09:58:40 PDT 2012
Hi,
I would like to offer a patch for review that extends the use of the
compile-time evaluation of __builtin_strlen to include immutable
null-terminated const char arrays, i.e. beyond just standard string
literals. (It will still fall back to runtime use of library strlen, if
compile-time evaluation is not possible/required -- this side of the
functionality is not changed).
This is not a bug fix but a feature enhancement, which I believe may have
broader appeal to those developing with C++11 and, in particular, with
user-defined literals.
The target use for this would be in generating transparent wrapper classes
for user-defined literals, so that these may be used in situations wherever
normal strings may be used.
Let's say we have the following simplified setup:
template <char... String>
struct Literal {
private:
typedef const char type[sizeof...(String)+1];
static constexpr type string = { String..., 0 };
public:
constexpr operator const type&() const { return string; }
// room for more implementation, such as operator[] and
// also string manipulation, such as operator+, and so on.
}
};
template <char... String> constexpr char Literal<String...>::string[];
template <char... String>
constexpr Literal<String...> operator"" _str() {
return Literal<String...>();
}
With the attached patch, __builtin_strlen(12345_str) will now return 5,
rather than throw a compiler error, and so opens up the use of such a
wrapper class to macros which make use of __builtin_strlen.
The patch is intended to be very conservative in terms of what it will
accept, and so the extension only allows constant sized arrays of const char
(__builtin_strlen limits this to char, although wchar_t, etc. would work
otherwise) and where the compiler can evaluate the expression as a constant
array (i.e. not a pointer or an lvalue of an array that can be modified at
runtime, for example). I believe there are adequate checks to stop
incorrect compilation, for example, incorrectly doing a compile-time
evaluation of __builtin_strlen on a variable which is not immutable, but
please can this be particularly verified by someone.
I have included a test-case in the patch.
Please let me know if this interests anyone.
Thanks
Andy
-------------- next part --------------
A non-text attachment was scrubbed...
Name: strlen.diff
Type: application/octet-stream
Size: 4933 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20120621/cc6d6f86/attachment.obj>
More information about the cfe-dev
mailing list