sparse: add support for __VA_OPT__
PATCH 1/1 sparse: add support for __VA_OPT__
In reply to a message not in the archiveThe linux kernel has started using __VA_OPT__ so lets add support for it.
What it does is it adds an optional thing, normally a comma, if the __VA_ARGS__ parameter is not empty. So if you have at least one argument but possibly more then you could create a macro like:
#define test_args(a, ...) printf(a __VA_OPT__(,) __VA_ARGS__)
If you call test_args("foo\n") it expands to:
printf("foo\n");
but if you pass two arguments test_args("foo %d\n", 2) it expands to:
printf("foo\n" , 2);
I guess if you wanted instead of a comma then you could have an empty __VA_OPT__() or you could pass random things like __VA_OPT__(a b c). I don't know why you would do that. In this case, "a" is a macro argument so that has to be expanded out.
--- ident-list.h | 1 + pre-process.c | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+)
ident-list.h +1 -0
@@ -66,6 +66,7 @@ IDENT(c_static_assert);__IDENT (pragma_ident,"__pragma__" ,0 );__IDENT (_Pragma_ident,"_Pragma" ,0 );__IDENT (__VA_ARGS___ident,"__VA_ARGS__" ,0 ); +__IDENT (__VA_OPT___ident,"__VA_OPT__" ,0 );__IDENT (__func___ident,"__func__" ,0 );__IDENT (__FUNCTION___ident,"__FUNCTION__" ,0 );__IDENT (__PRETTY_FUNCTION___ident,"__PRETTY_FUNCTION__" ,0 );
pre-process.c +52 -0
87 lines not on this page · raw message
Signature · 1 line
2.51.0
Quoted 14 lines · Dan Carpenter
The linux kernel has started using
__VA_OPT__so lets add support for it.What it does is it adds an optional thing, normally a comma, if the
__VA_ARGS__parameter is not empty. So if you have at least one argument but possibly more then you could create a macro like:#define
test_args(a, ...)printf(a __VA_OPT__(,) __VA_ARGS__)If you call
test_args("foo\n")it expands to:
printf("foo\n");but if you pass two arguments
test_args("foo %d\n", 2)it expands to:
Quoted 9 lines
printf("foo\n" , 2);I guess if you wanted instead of a comma then you could have an empty
__VA_OPT__()or you could pass random things like__VA_OPT__(a b c). I don't know why you would do that. In this case, "a" is a macro argument so that has to be expanded out.Signed-off-by Dan Carpenter <[email protected]>
This wouldn't apply to the current tree using git-am. Current head for me is 37156835e3d725b6d750f000be33ba3814bb2310
$ git am < \[PATCH\]\ sparse\:\ add\ support\ for\ __VA_OPT__\ -\ Dan\ Carpenter\ \<[email protected]\>\ -\ 2026-02-24\ 1107.eml Applying: sparse: add support for __VA_OPT__ error: patch failed: ident-list.h:66 error: ident-list.h: patch does not apply error: patch failed: pre-process.c:643 error: pre-process.c: patch does not apply Patch failed at 0001 sparse: add support for __VA_OPT__
Signature · 4 lines
Ben Dooks http://www.codethink.co.uk/ Senior Engineer Codethink - Providing Genius https://www.codethink.co.uk/privacy.html
Oh, sorry, Al's branch changed that code more than I imagined. I would resend the patch, but I need to figure out this GCC warning...
CC pre-process.opre-process.c: In function ‘substitute’:
pre-process.c:785:16: warning: function may return address of local variable [-Wreturn-local-addr]
785 | return list;
| ^~~~
pre-process.c:687:31: note: declared here
687 | struct token *added, *arg;
| ^~~~~
Anyway, here is what I've forward ported.
regards,
dan carpenter
--- ident-list.h | 1 + pre-process.c | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+)
ident-list.h +1 -0
@@ -65,6 +65,7 @@ IDENT(c_generic_selections);IDENT (c_static_assert);__IDENT (pragma_ident,"__pragma__" ,0 );__IDENT (__VA_ARGS___ident,"__VA_ARGS__" ,0 ); +__IDENT (__VA_OPT___ident,"__VA_OPT__" ,0 );__IDENT (__func___ident,"__func__" ,0 );__IDENT (__FUNCTION___ident,"__FUNCTION__" ,0 );__IDENT (__PRETTY_FUNCTION___ident,"__PRETTY_FUNCTION__" ,0 );
pre-process.c +53 -0
88 lines not on this page · raw message
Signature · 1 line
2.51.0
Richard Fitzgerald
Tested-byQuoted 12 lines · Dan Carpenter
Oh, sorry, Al's branch changed that code more than I imagined. I would resend the patch, but I need to figure out this GCC warning...
CC pre-process.o
pre-process.c: In function ‘substitute’:
pre-process.c:785:16: warning: function may return address of local variable [-Wreturn-local-addr]
785 | return list;
| ^~~~
pre-process.c:687:31: note: declared here
687 | struct token *added, *arg;
| ^~~~~
Quoted 5 lines
Anyway, here is what I've forward ported.
regards,
dan carpenter
Ben Dooks
Tested-byQuoted 13 lines · Richard Fitzgerald
Quoted 12 lines · Dan Carpenter
Oh, sorry, Al's branch changed that code more than I imagined. I would resend the patch, but I need to figure out this GCC warning...
CC pre-process.o
pre-process.c: In function ‘substitute’:
pre-process.c:785:16: warning: function may return address of local variable [-Wreturn-local-addr] 785 | return list;
| ^~~~
pre-process.c:687:31: note: declared here
687 | struct token *added, *arg;
| ^~~~~
Quoted 7 lines
Quoted 5 lines
Anyway, here is what I've forward ported.
regards,
dan carpenterTested-by Richard Fitzgerald <[email protected]>
Signature · 4 lines
Ben Dooks http://www.codethink.co.uk/ Senior Engineer Codethink - Providing Genius https://www.codethink.co.uk/privacy.html
Chris Li
maintainerHi Dan,
Thanks for the patch.
BTW, can you CC my personal email next time? Thanks.
Quoted 58 lines · Dan Carpenter
The linux kernel has started using
__VA_OPT__so lets add support for it.What it does is it adds an optional thing, normally a comma, if the
__VA_ARGS__parameter is not empty. So if you have at least one argument but possibly more then you could create a macro like:#define
test_args(a, ...)printf(a __VA_OPT__(,) __VA_ARGS__)If you call
test_args("foo\n")it expands to:
printf("foo\n");but if you pass two arguments
test_args("foo %d\n", 2)it expands to:
printf("foo\n" , 2);I guess if you wanted instead of a comma then you could have an empty
__VA_OPT__()or you could pass random things like__VA_OPT__(a b c). I don't know why you would do that. In this case, "a" is a macro argument so that has to be expanded out.Signed-off-by Dan Carpenter <[email protected]>--- ident-list.h | 1 + pre-process.c | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+)ident-list.h +1
-0@@ -66,6 +66,7 @@ IDENT(c_static_assert);__IDENT (pragma_ident,"__pragma__" ,0 );__IDENT (_Pragma_ident,"_Pragma" ,0 );__IDENT (__VA_ARGS___ident,"__VA_ARGS__" ,0 ); +__IDENT (__VA_OPT___ident,"__VA_OPT__" ,0 );__IDENT (__func___ident,"__func__" ,0 );__IDENT (__FUNCTION___ident,"__FUNCTION__" ,0 );__IDENT (__PRETTY_FUNCTION___ident,"__PRETTY_FUNCTION__" ,0 );pre-process.c +10
-0@@ -643,11 +643,49 @@ static int handle_kludge(struct token **p, struct arg *args) } } +static struct token *get_VA_OPT (struct token **p,struct arg *args) +{ +struct token *t = (*p)->next; +const char *expected; +struct token *ret =NULL ; +struct token *dup, *tail; + +if (token_type (t) !=TOKEN_SPECIAL || t->special !='(' ) { + expected ="(" ; + goto error;
pre-process.c static int handle_kludge(struct token **p, struct arg *args) · line 665
Quoted 10 lines
pre-process.c +10
-0+ } +while (true) { + t = t->next; +if (eof_token (t)) { + expected =")" ; + goto error; + } +if (token_type (t) ==TOKEN_SPECIAL && + t->special ==')' ) +break ;
I think this approach has some limitations. You can use the collect_arguments() to collect and expand the arguments for __VA_OPT__().
I did a small test case to show that gcc actually expand the arguments inside the __VA_OPT__().
============ terminal ===============
$ cat ~/tmp/va_opt.c #define A(B) , #define foo(fmt, ...) printk(fmt __VA_OPT__(A(x)) __VA_ARGS__)
foo("\n");foo("\n", "a");
$ gcc -E ~/tmp/va_opt.c # 0 "/home/chrisl/tmp/va_opt.c" # 0 "<built-in>" # 0 "<command-line>" # 1 "/usr/include/stdc-predef.h" 1 3 4 # 0 "<command-line>" 2 # 1 "/home/chrisl/tmp/va_opt.c"
printk("\n" );printk("\n" , "a");
========== terminal =============
That shows that gcc correctly expand the A() macro inside __VA_OPT__(A(x)).
I have not test it on your program yet, reading your patch I assume it will not expand the A() here.
One idea is to add an expand function expand___VA_OPT__, similar to expand_has_feature(). Register it in the dynamic expand macro array. That way you get the collect_arguments() for free and it behaves just like a builtin macro expansion. Just duplicate the collected arg list to the current token, if there are extra arguments.
If you go that route, likely don't need the manual __VA_OPT__ident parsing.
I haven't had time to code it myself yet; it's just an idea.
Chris
Quoted 72 lines
pre-process.c +32
-1+ dup =dup_token (t, &(*p)->pos); +if (!ret) + ret = dup; +else + tail->next = dup; + tail = dup; + } + +if (tail) + tail->next = &eof_token_entry; + *p = t; +return ret; +error: +sparse_error (t->pos,"__VA_OPT__ error: expected '%s'" , expected); +return NULL ; +} +static struct token **substitute (struct token **list,struct token *body,struct arg *args) {struct position *base_pos = &(*list)->pos;int *count;enum {Normal, Placeholder, Concat} state = Normal; +struct token *va_opt =NULL ;for (; !eof_token (body); body = body->next) {struct token *added, *arg;@@ -697,6 +735,10 @@ static struct token **substitute(struct token **list, struct token *body, structcase TOKEN_MACRO_ARGUMENT : arg = args[body->argnum].expanded; +if (va_opt && !eof_token (arg)) { + list =substitute (list, va_opt, args); + va_opt =NULL ; + } count = &args[body->argnum].n_normal;if (eof_token (arg)) { state = Normal;@@ -716,6 +758,11 @@ static struct token **substitute(struct token **list, struct token *body, structcontinue ;case TOKEN_IDENT : +if (body->ident == &__VA_OPT___ident) { + va_opt =get_VA_OPT (&body, args); +continue ; + } + added =dup_token (body, base_pos);if (added->ident->tainted) added->pos.noexpand =1 ;@@ -1234,6 +1281,8 @@ static struct token *parse_arguments(struct token *list)while (token_type (arg) ==TOKEN_IDENT ) {if (arg->ident == &__VA_ARGS___ident) goto Eva_args; +if (arg->ident == &__VA_OPT___ident) + goto Eva_opt;if (!++count->normal) goto Eargs; next = arg->next;@@ -1312,6 +1361,9 @@ Enotclosed: Eva_args:sparse_error (arg->pos,"__VA_ARGS__ can only appear in the expansion of a C99 variadic macro" );return NULL ; +Eva_opt: +sparse_error (arg->pos,"__VA_OPT__ can only appear in the expansion of a C99 variadic macro" ); +return NULL ; Eargs:sparse_error (arg->pos,"too many arguments in macro definition" );return NULL ; --2.51.0
Quoted 4 lines · Chris Li
Quoted 4 lines
I guess if you wanted instead of a comma then you could have an empty
__VA_OPT__()or you could pass random things like__VA_OPT__(a b c). I don't know why you would do that. In this case, "a" is a macro argument so that has to be expanded out.
<sarcasm>
Then perhaps reading the standard might prove enlightening - possibly due to examples that might be in there, or seeing the actual description of semantics? https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf
is there and searching for __VA_OPT__ would immediately get you this:
#define SDEF(sname, ...) S sname __VA_OPT__(= { __VA_ARGS__ }) SDEF(foo); // replaced by S foo;SDEF(bar, 1, 2); // replaced by S bar = { 1, 2 };
Would that answer your question?
</sarcasm>
Quoted 5 lines
One idea is to add an expand function
expand___VA_OPT__, similar toexpand_has_feature(). Register it in the dynamic expand macro array. That way you get thecollect_arguments()for free and it behaves just like a builtin macro expansion. Just duplicate the collected arg list to the current token, if there are extra arguments.
Sorry, no go; for one thing, #__VA_OPT__() won't be dealt with that way, for another there's fun with foo ## __VA_OPT__(arg) (argument is expanded *and* subjected to ## - yes, it's possible now).
I have something resembling a workable approach, but there's nasty corner case when you mix it with the side effects; that's impossible in standard C, but gcc has the sodding __COUNTER__ thing and _that_ makes life really interesting.
If there's __VA_OPT__ in the body, we want to expand vararg whether it occurs in the body or not.
We want to expand each argument that is present in the body.
Question: should we expand an argument that occurs *only* under __VA_OPT__? Note that "expand and discard" is *not* a no-op - expansion of __COUNTER__ will have visible side effects. What's more, gcc and clang diverge there.
Another kind of side effect is possible in standard C: argument substitution might fail when attempted. And gcc is arguably broken there - see
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=123325 for fun details. clang handles that one sanely...
I got stalled waiting for gcc folks to respond, then sidetracked to other stuff. I'll resurrect that stuff later this week.
RFC PATCH 1/1 pre-process: add __VA_OPT__ support
Add __VA_OPT__ support (C23 6.10.5) including some tests.
At expansion time, substitute() checks whether the variadic argument is empty: if so, skip the region between the markers; otherwise, process the enclosed tokens normally.
---
Discussed this with Chris during lunch yesterday and got curious about the problem, so made a few attempts. Introducing TOKEN_VA_OPT_START/END feels a bit like an anti-pattern, but I couldn't find a cleaner way to handle it without new token types. Happy to hear suggestions.
Note: this does not handle the __COUNTER__ side-effect issue (arguments under __VA_OPT__ are expanded even when discarded).
ident-list.h | 1 + pre-process.c | 132 ++++++++++++++++++++++++ token.h | 2 + tokenize.c | 6 ++ validation/preprocessor/va-opt-errors.c | 38 +++++++ validation/preprocessor/va-opt.c | 66 ++++++++++++ 6 files changed, 245 insertions(+) create mode 100644 validation/preprocessor/va-opt-errors.c create mode 100644 validation/preprocessor/va-opt.c
ident-list.h +1 -0
@@ -65,6 +65,7 @@ IDENT(c_generic_selections);IDENT (c_static_assert);__IDENT (pragma_ident,"__pragma__" ,0 );__IDENT (__VA_ARGS___ident,"__VA_ARGS__" ,0 ); +__IDENT (__VA_OPT___ident,"__VA_OPT__" ,0 );__IDENT (__func___ident,"__func__" ,0 );__IDENT (__FUNCTION___ident,"__FUNCTION__" ,0 );__IDENT (__PRETTY_FUNCTION___ident,"__PRETTY_FUNCTION__" ,0 );
pre-process.c +132 -0
211 lines not on this page · raw message
token.h +2 -0
@@ -104,6 +104,8 @@ enum token_type {TOKEN_QUOTED_ARGUMENT ,TOKEN_CONCAT ,TOKEN_GNU_KLUDGE , +TOKEN_VA_OPT_START , +TOKEN_VA_OPT_END ,TOKEN_UNTAINT ,TOKEN_ARG_COUNT , TOKEN_IF,
tokenize.c +6 -0
@@ -237,6 +237,12 @@ const char *show_token(const struct token *token)sprintf (buffer,"<end of '%s'>" ,stream_name (token->pos.stream));return buffer; +case TOKEN_VA_OPT_START : +return "__VA_OPT__(" ; + +case TOKEN_VA_OPT_END : +return ")" ; +case TOKEN_UNTAINT :sprintf (buffer,"<untaint>" );return buffer;
validation/preprocessor/va-opt-errors.c new file +38 -0
@@ -0,0 +1,38 @@ +/* +* __VA_OPT__ error cases (C23 6.10.5) +* +* Constraints from C23 (N3220 6.10.5): +* - __VA_OPT__ shall only occur in the replacement-list of a +* function-like macro that uses the ellipsis notation. +* - __VA_OPT__ shall not appear within its own replacement tokens. +* - ## shall not appear at either end of __VA_OPT__(). +*/ + +/* non-variadic macro */ +#define NONVAR (x) __VA_OPT__(,) + +/* nested __VA_OPT__ */ +#define NESTED (...) __VA_OPT__(__VA_OPT__(x)) + +/* not followed by ( */ +#define NOPAREN (...) __VA_OPT__ x + +/* ## at start */ +#define HASH_START (...) __VA_OPT__(## x) + +/* ## at end */ +#define HASH_END (...) __VA_OPT__(x ##) + +/* +* check-name: __VA_OPT__ errors (C23) +* check-command: sparse -E $file +* check-output-ignore +* +* check-error-start +preprocessor/va-opt-errors.c:12:19: error: __VA_OPT__ can only appear in the expansion of a variadic macro +preprocessor/va-opt-errors.c:15:32: error: __VA_OPT__ may not be nested +preprocessor/va-opt-errors.c:18:22: error: __VA_OPT__ must be followed by '(' +preprocessor/va-opt-errors.c:21:25: error: '##' cannot appear at either end of __VA_OPT__ +preprocessor/va-opt-errors.c:24:34: error: '##' cannot appear at either end of __VA_OPT__ +* check-error-end +*/
validation/preprocessor/va-opt.c new file +66 -0
66 lines not on this page · raw message
Signature · 1 line
2.43.0
Re: [RFC PATCH] pre-process: add __VA_OPT__ support
Quoted 6 lines · Eric Zhang
Add
__VA_OPT__support (C23 6.10.5) including some tests.At expansion time,
substitute()checks whether the variadic argument is empty: if so, skip the region between the markers; otherwise, process the enclosed tokens normally.
Quoted 7 lines
Signed-off-by Eric Zhang <[email protected]>---
Discussed this with Chris during lunch yesterday and got curious about the problem, so made a few attempts. Introducing TOKEN_VA_OPT_START/END feels a bit like an anti-pattern, but I couldn't find a cleaner way to handle it without new token types. Happy to hear suggestions.
Your variant will break with __VA_OPT__ following #. It won't do the right thing with ## either, AFAICS, in case when __VA_OPT__ token list is empty.
Chris Li
maintainer"
Quoted 21 lines · Al Viro
Quoted 4 lines · Chris Li
Quoted 4 lines
I guess if you wanted instead of a comma then you could have an empty
__VA_OPT__()or you could pass random things like__VA_OPT__(a b c). I don't know why you would do that. In this case, "a" is a macro argument so that has to be expanded out.<sarcasm>
Then perhaps reading the standard might prove enlightening - possibly due to examples that might be in there, or seeing the actual description of semantics? https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf
is there and searching for__VA_OPT__would immediately get you this:#define
SDEF(sname, ...)S sname__VA_OPT__(= { __VA_ARGS__ })SDEF(foo); // replaced by S foo;SDEF(bar, 1, 2); // replaced by S bar = { 1, 2 };Would that answer your question?
</sarcasm>
Quoted 7 lines
Quoted 5 lines
One idea is to add an expand function
expand___VA_OPT__, similar toexpand_has_feature(). Register it in the dynamic expand macro array. That way you get thecollect_arguments()for free and it behaves just like a builtin macro expansion. Just duplicate the collected arg list to the current token, if there are extra arguments.Sorry, no go; for one thing, #__VA_OPT__() won't be dealt with that way,
Ah, thanks for the great insight. I did not read the spec and trusted the gcc behavior instead. I just learn from you that that gcc is buggy in this regard.
Never mind my bad idea.
Quoted 2 lines
for another there's fun with foo ##
__VA_OPT__(arg)(argument is expanded *and* subjected to ## - yes, it's possible now).
That is very tricky. I just took a look at the "6.10.5.1" regarding __VA_OPT__(). I don't have a good solution yet.
Quoted 14 lines
I have something resembling a workable approach, but there's nasty corner case when you mix it with the side effects; that's impossible in standard C, but gcc has the sodding
__COUNTER__thing and _that_ makes life really interesting.If there's
__VA_OPT__in the body, we want to expand vararg whether it occurs in the body or not.We want to expand each argument that is present in the body.
Question: should we expand an argument that occurs *only* under
__VA_OPT__? Note that "expand and discard" is *not* a no-op - expansion of__COUNTER__will have visible side effects. What's more, gcc and clang diverge there.
Quoted 7 lines
Another kind of side effect is possible in standard C: argument substitution might fail when attempted. And gcc is arguably broken there - see
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=123325 for fun details. clang handles that one sanely...I got stalled waiting for gcc folks to respond, then sidetracked to other stuff. I'll resurrect that stuff later this week.
Lookin forward to your solutions.
Chris
Re: [RFC PATCH] pre-process: add __VA_OPT__ support
In reply to Al ViroQuoted 15 lines · Al Viro
Quoted 6 lines · Eric Zhang
Add
__VA_OPT__support (C23 6.10.5) including some tests.At expansion time,
substitute()checks whether the variadic argument is empty: if so, skip the region between the markers; otherwise, process the enclosed tokens normally.Quoted 7 lines
Signed-off-by Eric Zhang <[email protected]>---
Discussed this with Chris during lunch yesterday and got curious about the problem, so made a few attempts. Introducing TOKEN_VA_OPT_START/END feels a bit like an anti-pattern, but I couldn't find a cleaner way to handle it without new token types. Happy to hear suggestions.
Quoted 3 lines
Your variant will break with
__VA_OPT__following #. It won't do the right thing with ## either, AFAICS, in case when__VA_OPT__token list is empty.
Another problem is that having no __VA_ARGS__ in the body should *not* be treated as "vararg is empty" - if there's a __VA_OPT__ in the body, you must expand the vararg, no matter what.
Re: [RFC PATCH] pre-process: add __VA_OPT__ support
Quoted 3 lines · Al Viro
Your variant will break with
__VA_OPT__following #. It won't do the right thing with ## either, AFAICS, in case when__VA_OPT__token list is empty.
Thanks for the review Al! Wow|Hummm, supprised now they support case like foo ## __VA_OPT__(arg), and I just noticed you've pointed it out in the previous reply.
Maybe split parse_expansion() into two passes could fix it, smth like
1. Convert __VA_OPT__(...) → TOKEN_VA_OPT_START...TOKEN_VA_OPT_END
2. Run the existing #/## handling, with handle_hash() and handle_hashhash() taught to recognize the new markers
For # __VA_OPT__(), a stringify flag on TOKEN_VA_OPT_START could signal substitute() to stringify or produce "" depending on whether varargs are empty.
For ## adjacent to __VA_OPT__, the existing Concat/Placeholder state machine in substitute() should handle the empty case naturally once the ## is properly converted to TOKEN_CONCAT in pass 2.
Quoted 2 lines
Another problem is that having no
__VA_ARGS__in the body should *not* be treated as "vararg is empty"
Missed in the test case, but it seems like it can work in the current version.
Quoted 2 lines
I got stalled waiting for gcc folks to respond, then sidetracked to other stuff. I'll resurrect that stuff later this week.
Then I will look forward to your approach :)
Eric
Re: [RFC PATCH] pre-process: add __VA_OPT__ support
Quoted 3 lines · Eric Zhang
For #
__VA_OPT__(), a stringify flag onTOKEN_VA_OPT_STARTcould signalsubstitute()to stringify or produce "" depending on whether varargs are empty.
IMO it's better to turn that into
TOKEN_VA_OPT[<token-list>]
and
TOKEN_QUOTED_VA_OPT[<token-list>]
with list hanging off the cannibalized token. Interpreter (substitute()) can easily keep track of where it is.
FWIW, the way they patched __VA_OPT__ into 10.5.1 is unfortunate - I can understand wanting to keep the changes localized, but it ends up very convoluted ;-/ In part it's due to the way ## and # evaluation order is left unspecified, but... ouch.
Basically, #__VA_OPT__(<token-list>) is treated the following way:
it's "" if va-opt is suppressed, otherwise we
* do argument substitution in <token-list>
* [unspecified, but everyone does that] process # and ##
in the token-list.
* do *NOT* remove placemaker tokens
* do *NOT* rescan
* stringify the resulting token list, same way we would if
that token list had been passed as an argument and we were processing #<that argument> (as per 6.10.5.2[3]).
## vs. __VA_OPT__ is similar; the tricky part is placemaker treatment. For normal arguments it's either a non-empty list or a solitary placemaker; here we might have placemakers with non-empty list.
#define F1(X, Y, ...) Y ## __VA_OPT__(X X) ## Y
#define F2(X, Y, ...) Y ## __VA_OPT__(X) ## YF1(,a,_)F2(,a,_)
We get a ## placemaker placemaker ## a (i.e. a a) or a ## placemaker ## a (i.e. aa) respectively. Approach without explicit ## tokens at expansion time is easy to adapt to that - we just interpret the translated token-list hanging off __VA_OPT__, then return to the rest of the body; state is updated as usual. Quoted __VA_OPT__ == run the interpreter (starting from Normal) on the token-list, then feed that to stringify() and use the result as if it came from quoted argument (note that concatenation with previous token *is* possible - L ## #__VA_OPT__(something) is not invalid).
Since __VA_OPT__ can't nest, it's easy to save the body->next into a local variable, set body to body->va_opt_list and, after the main loop check if that local variable is non-NULL. In that case we just set body to that, clear that variable and go back to the beginning of the loop. Quoted ones get a recursive call...
NOTE: substitute() is the second hottest loop in the entire thing; only tokenizer is hotter. And gcc is too enthusiastic about the inlining around that function, ending up with bad register spills, along with a bunch of stalls. Worse, decisions are sensitive to minor changes in places textually far away, making it a real bitch to deal with. Makes for fun reordering the commits in local queue... ;-/
Quoted 5 lines
Quoted 2 lines
Another problem is that having no
__VA_ARGS__in the body should *not* be treated as "vararg is empty"Missed in the test case, but it seems like it can work in the current version.
AFAICS you won't even try to expand it at expand_arguments(), so the reference will remain NULL.
Re: [RFC PATCH] pre-process: add __VA_OPT__ support
Quoted 6 lines · Al Viro
NOTE:
substitute()is the second hottest loop in the entire thing; only tokenizer is hotter. And gcc is too enthusiastic about the inlining around that function, ending up with bad register spills, along with a bunch of stalls. Worse, decisions are sensitive to minor changes in places textually far away, making it a real bitch to deal with. Makes for fun reordering the commits in local queue... ;-/
FWIW, looking at that thing again, I wonder if we would be better off with doing argument expansion on demand rather than doing it in expand_arguments(). Should be doable with a bit of care - we'd need to mark the TOKEN_..._ARG with several bits to decide whether we want to duplicate or not, etc., but that's worth doing anyway - better than playing with the counters.
Note, BTW, that collapsing TOKEN_..._ARG together, with "kind of argument" moved into bits stolen from ->argnum improves code generation - that switch by token type is _hot_ and it reducing the number of cases gives a measurable speedup. Sure, we don't want heavy work at #define time - most of the macros are never expanded at all, but AFAICS this kind of processing can be dealt with while parsing the body, with no extra passes needed, etc.
I'm going down right now, will look into that tomorrow morning...
Re: [RFC PATCH] pre-process: add __VA_OPT__ support
Quoted 24 lines · Al Viro
Quoted 6 lines · Al Viro
NOTE:
substitute()is the second hottest loop in the entire thing; only tokenizer is hotter. And gcc is too enthusiastic about the inlining around that function, ending up with bad register spills, along with a bunch of stalls. Worse, decisions are sensitive to minor changes in places textually far away, making it a real bitch to deal with. Makes for fun reordering the commits in local queue... ;-/FWIW, looking at that thing again, I wonder if we would be better off with doing argument expansion on demand rather than doing it in
expand_arguments(). Should be doable with a bit of care - we'd need to mark the TOKEN_..._ARG with several bits to decide whether we want to duplicate or not, etc., but that's worth doing anyway - better than playing with the counters.Note, BTW, that collapsing TOKEN_..._ARG together, with "kind of argument" moved into bits stolen from ->argnum improves code generation - that switch by token type is _hot_ and it reducing the number of cases gives a measurable speedup. Sure, we don't want heavy work at #define time - most of the macros are never expanded at all, but AFAICS this kind of processing can be dealt with while parsing the body, with no extra passes needed, etc.
Quoted 1 line
I'm going down right now, will look into that tomorrow morning...
That turned out to be trickier than I hoped, but I've got something that works.
See git://git.kernel.org/pub/scm/linux/kernel/git/viro/sparse.git #va_opt (or individual patches in followups)
__VA_OPT__ supported, AFAICS behaviour matches C23.
* expansion and stringifying of arguments is full-lazy now -
done on demand and at most once.
* va-opt-replacement parsed at #define time, handled correctly
by dump_macro() (i.e. -dM), comparisons when redefining and at expansion time.
* arglist mangling is gone, so's the argcount kludge.
* it's no slower than it used to be prior to that series.
I have local followups (tentative fixes for whitespace handling in preprocessor and optimizations in tokenizer), but let's deal with that one first.
Shortlog:
Al Viro (21):
split copy() into "need to copy" and "can move in place" cases expand and simplify the call of dup_token() in copy()
more dup_token() optimizations
parsing #define: saner handling of argument count, part 1 simplify collect_arguments() and fix error handling there try_arg(): don't use arglist for argument name lookups
make expand_has_...() responsible for expanding its argument preparing to change argument number encoding for TOKEN_..._ARGUMENT steal 2 bits from argnum for argument kind
on-demand argument expansion
kill create_arglist()
stop mangling arglist, get rid of TOKEN_ARG_COUNT
deal with ## on arguments separately
preparations for __VA_OPT__ support: reshuffle argument slot assignments pre-process.c: split try_arg()
__VA_OPT__: parsing
expansion-time va_opt handling
merge(): saner handling of ->noexpand
simplify the calling conventions of collect_arguments() make expand_one_symbol() inline
substitute(): convert switch() into cascade of ifs
Diffstat:
ident-list.h | 1 + pre-process.c | 929 +++++++++++++++++----------- symbol.h | 1 + token.h | 32 +- tokenize.c | 4 - validation/preprocessor/bad-args.c | 18 + validation/preprocessor/dump-macro.c | 13 + validation/preprocessor/has-attribute.c | 3 + validation/preprocessor/has-builtin.c | 3 + validation/preprocessor/va_opt.c | 54 ++ validation/preprocessor/va_opt2.c | 34 + validation/preprocessor/va_opt_compare.c | 28 + validation/preprocessor/va_opt_parse.c | 37 ++ validation/preprocessor/va_opt_whitespace.c | 14 + 14 files changed, 797 insertions(+), 374 deletions(-) create mode 100644 validation/preprocessor/bad-args.c create mode 100644 validation/preprocessor/dump-macro.c create mode 100644 validation/preprocessor/va_opt.c create mode 100644 validation/preprocessor/va_opt2.c create mode 100644 validation/preprocessor/va_opt_compare.c create mode 100644 validation/preprocessor/va_opt_parse.c create mode 100644 validation/preprocessor/va_opt_whitespace.c
PS: as for the interesting uses of __VA_OPT__, consider this:
; cat >test.c <<'EOF'
// based on a fun trick from David Mazières
// see https://www.scs.stanford.edu/~dm/blog/va-opt.html for the entire story // No, it's not unbounded recursion - up to 256 (4^4) elements in __VA_ARGS__; // more with trivial modifications, just add more levels to EXPAND... #define PARENS ()
#define EXPAND(...) EXPAND4(EXPAND4(EXPAND4(EXPAND4(__VA_ARGS__)))) #define EXPAND4(...) EXPAND3(EXPAND3(EXPAND3(EXPAND3(__VA_ARGS__)))) #define EXPAND3(...) EXPAND2(EXPAND2(EXPAND2(EXPAND2(__VA_ARGS__)))) #define EXPAND2(...) EXPAND1(EXPAND1(EXPAND1(EXPAND1(__VA_ARGS__)))) #define EXPAND1(...) __VA_ARGS__
#define FOR_EACH_PAIR(macro, ...) \
__VA_OPT__(EXPAND(FOR_EACH_PAIR_HELPER(macro, __VA_ARGS__)))
#define FOR_EACH_PAIR_HELPER(macro, a1, a2, ...) \
macro(a1, a2) \
__VA_OPT__(FOR_EACH_PAIR_AGAIN PARENS (macro, __VA_ARGS__))
#define FOR_EACH_PAIR_AGAIN() FOR_EACH_PAIR_HELPER
FOR_EACH_PAIR(F, t1, id1, t2, id2, t3, id3, t4, id4, t5, id5, t6, id6) EOF
; cpp -E test.c
# 0 "test.c"
# 0 "<built-in>"
# 0 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 0 "<command-line>" 2
# 1 "test.c"
# 18 "test.c"F(t1, id1) F(t2, id2) F(t3, id3) F(t4, id4) F(t5, id5) F(t6, id6) ;
and the same output from sparse, modulo the # ... lines - sparse -E doesn't produce those. Our (fairly brittle) analogue is __MAP in linux/syscalls.h and if nothing else, unlike __MAP() this thing does not need the number of pairs passed as explicit argument. Would be interesting to try unifying SYSCALL0..SYSCALL6 into a single macro that would bloody well _count_ the arguments...
PATCH 1/21 split copy() into "need to copy" and "can move in place" cases
For one thing, rechecking the flag on each iteration of a loop is rather silly, especially when there's very little in common between the "copy" and "move" cases and the loop is pretty hot.
For another, it's better to have the counter-related logics lifted into substitute().
--- pre-process.c | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-)
pre-process.c +18 -7
@@ -598,15 +598,23 @@ static struct token *dup_token(const struct token *token, struct position *streareturn alloc; } -static struct token **copy (struct token **where,struct token *list,int *count) +static struct token **move_into (struct token **where,struct token *list) +{ + *where = list; +while (!eof_token (list)) { +if (token_type (list) ==TOKEN_IDENT && list->ident->tainted) + list->pos.noexpand =1 ; + where = &list->next; + list = *where; + } +return where; +} + +static struct token **copy (struct token **where,struct token *list) { -int need_copy = --*count;while (!eof_token (list)) {struct token *token; -if (need_copy) - token =dup_token (list, &list->pos); -else - token = list; + token =dup_token (list, &list->pos);if (token_type (token) ==TOKEN_IDENT && token->ident->tainted) token->pos.noexpand =1 ; *where = token;
@@ -698,7 +706,10 @@ static struct token **substitute(struct token **list, const struct token *body,continue ; } copy_arg: - tail =copy (&added, arg, count); +if (!--*count) + tail =move_into (&added, arg); +else + tail =copy (&added, arg); added->pos.newline = body->pos.newline; added->pos.whitespace = body->pos.whitespace;break ;
Signature · 1 line
2.47.3
PATCH 2/21 expand and simplify the call of dup_token() in copy()
reducing ->pos handling helps there
--- pre-process.c | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-)
pre-process.c +9 -4
@@ -613,10 +613,15 @@ static struct token **move_into(struct token **where, struct token *list)static struct token **copy (struct token **where,struct token *list) {while (!eof_token (list)) { -struct token *token; - token =dup_token (list, &list->pos); -if (token_type (token) ==TOKEN_IDENT && token->ident->tainted) - token->pos.noexpand =1 ; +struct position pos = list->pos; +struct token *token =__alloc_token (0 ); + + token->ident = list->ident; +if (pos.type ==TOKEN_STRING || pos.type ==TOKEN_WIDE_STRING ) + list->string->immutable =1 ; +if (pos.type ==TOKEN_IDENT && list->ident->tainted) + pos.noexpand =1 ; + token->pos = pos; *where = token; where = &token->next; list = list->next;
Signature · 1 line
2.47.3
PATCH 3/21 more dup_token() optimizations
In reply to Al Viropull handling to tainted identifiers into dup_token(), eliminating reread and resulting stall in there.
--- pre-process.c | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-)
pre-process.c +10 -10
@@ -583,18 +583,21 @@ static int merge(struct token *left, struct token *right)return 0 ; } -static struct token *dup_token (const struct token *token,struct position *streampos) +static inline struct token *dup_token (const struct token *token,struct position *streampos) {struct position pos = *streampos;struct token *alloc =__alloc_token (0 ); +struct position pos2 = token->pos; - alloc->pos = token->pos; - alloc->number = token->number; - alloc->pos.stream = pos.stream; - alloc->pos.line = pos.line; - alloc->pos.pos = pos.pos; -if (token_type (alloc) ==TOKEN_STRING ||token_type (alloc) ==TOKEN_WIDE_STRING ) + alloc->ident = token->ident; + pos2.stream = pos.stream; + pos2.line = pos.line; + pos2.pos = pos.pos; +if (pos2.type ==TOKEN_STRING || pos2.type ==TOKEN_WIDE_STRING ) token->string->immutable =1 ; +if (pos2.type ==TOKEN_IDENT && token->ident->tainted) + pos2.noexpand =1 ; + alloc->pos = pos2;return alloc; }
@@ -728,9 +731,6 @@ static struct token **substitute(struct token **list, const struct token *body,default : added =dup_token (body, base_pos); -if (token_type (body) ==TOKEN_IDENT && - added->ident->tainted) - added->pos.noexpand =1 ; tail = &added->next;break ; }
Signature · 1 line
2.47.3
PATCH 4/21 parsing #define: saner handling of argument count, part 1
In reply to Al ViroMangling arglist the way we do is a bad kludge and it limits what we can do both at parsing a macro definition and at expansion time.
We use it to
* store the number of arguments (gets stashed in the cannibalized
token of opening parenthesis)
* store the number of times each argument is used expanded,
unexpanded and stringified (stashed in cannibalized token of comma or closing parenthesis that follows an argument)
* mark the vararg argument (ditto)
Total number of arguments would be better off in struct symbol, next to arglist. As the matter of fact, we'd be better off with number of non-vararg arguments and "is there a vararg" stored separately.
Number of times each argument occurs expanded, etc. is used to find if given occurrence of argument in the body is the last one of given sort
- by counting down as we process the body during expansion, no less. Each counter runs down at the same token of the body every time we expand the macro, and we can just as easily mark those tokens when we parse the definition. It is also used to tell whether we need to expand and/or stringify the argument in the first place. Again, easily expressed as marking the tokens and we can easily steal bits for TOKEN_..._ARG payload - we have a 32bit value that represents the argument's number.
"Is it a vararg argument" flag is used both at definition parsing time (when we would be better off with "the index of vararg argument or -1 if there's none") and at expansion time, when we collect the arguments. There we pass those values to collect_argument(), telling it whether it should stop on (unprotected) commas. The current logics is seriously convoluted, especially around the error recovery. Untangling that ends up with a variant that wants to know the number of non-vararg arguments along with "do we have a vararg at all" flag, upfront and not scattered through the arglist.
As the first step, introduce sym->fixed_args and sym->vararg and have them calculated when we parse a macro definition; stop storing the number of arguments in the first token of arglist.
--- pre-process.c | 64 +++++++++++++++++++++++++++++++++++---------------- symbol.h | 1 + 2 files changed, 45 insertions(+), 20 deletions(-)
pre-process.c +44 -20
@@ -312,9 +312,10 @@ struct arg {int n_str; }; -static int collect_arguments (struct token *start,struct token *arglist,struct arg *args,struct token *what) +static int collect_arguments (struct token *start,struct symbol *sym,struct arg *args,struct token *what) { -int wanted = arglist->count.normal; +struct token *arglist = sym->arglist; +int wanted = sym->fixed_args + sym->vararg;struct token *next =NULL ;int count =0 ;
@@ -760,7 +761,7 @@ static int expand(struct token **list, struct symbol *sym)struct ident *expanding = token->ident;struct token **tail;struct token *expansion = sym->expansion; -int nargs = sym->arglist ? sym->arglist->count.normal :0 ; +int nargs = sym->fixed_args + sym->vararg;struct arg args[nargs];if (expanding->tainted) {
@@ -771,7 +772,7 @@ static int expand(struct token **list, struct symbol *sym)if (sym->arglist) {if (!match_op (scan_next (&token->next),'(' ))return 1 ; -if (!collect_arguments (token->next, sym->arglist, args, token)) +if (!collect_arguments (token->next, sym, args, token))return 1 ;expand_arguments (nargs, args); }
@@ -1087,6 +1088,21 @@ static int token_list_different(struct token *list1, struct token *list2) } } +static int macro_nargs =0 ; +static int macro_vararg =-1 ; +static bool macro_funclike = false; + +static bool macro_add_arg (struct position pos,struct ident *ident) +{ +if (macro_nargs ==1024 ) + goto Eargs; + macro_nargs++; +return true; +Eargs: +sparse_error (pos,"too many arguments in macro definition" ); +return false; +} +static inline void set_arg_count (struct token *token) {token_type (token) =TOKEN_ARG_COUNT ;
@@ -1097,7 +1113,6 @@ static inline void set_arg_count(struct token *token)static struct token *parse_arguments (struct token *list) {struct token *arg = list->next, *next = list; -struct argcount *count = &list->count;set_arg_count (list);
@@ -1110,10 +1125,10 @@ static struct token *parse_arguments(struct token *list)while (token_type (arg) ==TOKEN_IDENT ) {if (arg->ident == &__VA_ARGS___ident) goto Eva_args; -if (!++count->normal) - goto Eargs; - next = arg->next; +if (!macro_add_arg (arg->pos, arg->ident)) +return NULL ; + next = arg->next;if (match_op (next,',' )) {set_arg_count (next); arg = next->next;
@@ -1132,6 +1147,7 @@ static struct token *parse_arguments(struct token *list)if (match_op (next,SPECIAL_ELLIPSIS )) {if (match_op (next->next,')' )) {set_arg_count (next); + macro_vararg = macro_nargs -1 ; next->count.vararg =1 ; next = next->next; arg->next->next = &eof_token_entry;
@@ -1156,9 +1172,10 @@ static struct token *parse_arguments(struct token *list) arg->ident = &__VA_ARGS___ident;if (!match_op (next,')' )) goto Enotclosed; -if (!++count->normal) - goto Eargs; +if (!macro_add_arg (arg->pos, &__VA_ARGS___ident)) +return NULL ;set_arg_count (next); + macro_vararg = macro_nargs -1 ; next->count.vararg =1 ; next = next->next; arg->next->next = &eof_token_entry;
@@ -1188,9 +1205,6 @@ Enotclosed: Eva_args:sparse_error (arg->pos,"__VA_ARGS__ can only appear in the expansion of a C99 variadic macro" );return NULL ; -Eargs: -sparse_error (arg->pos,"too many arguments in macro definition" ); -return NULL ; }static int try_arg (struct token *token,enum token_type type,struct token *arglist)
@@ -1198,7 +1212,7 @@ static int try_arg(struct token *token, enum token_type type, struct token *arglstruct ident *ident = token->ident;int nr; -if (!arglist ||token_type (token) !=TOKEN_IDENT ) +if (!macro_funclike ||token_type (token) !=TOKEN_IDENT )return 0 ; arglist = arglist->next;
@@ -1221,7 +1235,7 @@ static int try_arg(struct token *token, enum token_type type, struct token *argl n = ++count->str; }if (n) -return count->vararg ?2 :1 ; +return nr == macro_vararg ?2 :1 ;/* * XXX - need saner handling of that * (>= 1024 instances of argument)
@@ -1236,7 +1250,7 @@ static int try_arg(struct token *token, enum token_type type, struct token *arglstatic struct token *handle_hash (struct token **p,struct token *arglist) {struct token *token = *p; -if (arglist) { +if (macro_funclike) {struct token *next = token->next;if (!try_arg (next,TOKEN_STR_ARGUMENT , arglist)) goto Equote;
@@ -1354,7 +1368,7 @@ static int do_define(struct position pos, struct token *token, struct ident *nam expansion =parse_expansion (expansion, arglist, name);if (!expansion) -return 1 ; + goto out; sym =lookup_symbol (name,NS_MACRO |NS_UNDEF );if (sym) {
@@ -1388,6 +1402,8 @@ static int do_define(struct position pos, struct token *token, struct ident *namif (!ret) { sym->expansion = expansion; sym->arglist = arglist; + sym->vararg = macro_vararg >=0 ; + sym->fixed_args = macro_nargs - sym->vararg;if (token)/* Free the "define" token, but not the rest of the line */ __free_token (token); }
@@ -1396,6 +1412,9 @@ static int do_define(struct position pos, struct token *token, struct ident *nam sym->used_in =NULL ; sym->attr = attr; out: + macro_nargs =0 ; + macro_vararg =-1 ; + macro_funclike = false;return ret; }
@@ -1490,8 +1509,12 @@ static int do_handle_define(struct stream *stream, struct token **line, struct tif (match_op (expansion,'(' )) { arglist = expansion; expansion =parse_arguments (expansion); -if (!expansion) +if (!expansion) { + macro_nargs =0 ; + macro_vararg =-1 ;return 1 ; + } + macro_funclike = true; }else if (!eof_token (expansion)) {warning (expansion->pos,"no whitespace before object-like macro body" );
@@ -2075,8 +2098,9 @@ static void create_arglist(struct symbol *sym, int count) token =__alloc_token (0 );token_type (token) =TOKEN_ARG_COUNT ; - token->count.normal = count; sym->arglist = token; + sym->fixed_args = count; + sym->vararg =0 ; next = &token->next;while (count--) {
@@ -2300,7 +2324,7 @@ static int is_VA_ARGS_token(struct token *token)static void dump_macro (struct symbol *sym) { -int nargs = sym->arglist ? sym->arglist->count.normal :0 ; +int nargs = sym->fixed_args + sym->vararg;struct token *args[nargs];struct token *token;
symbol.h +1 -0
@@ -168,6 +168,7 @@ struct symbol {struct scope *used_in;void (*expand_simple)(struct token *);bool (*expand)(struct token *,struct arg *args); +int fixed_args, vararg; };struct /* NS_PREPROCESSOR */ {int (*handler)(struct stream *,struct token **,struct token *);
Signature · 1 line
2.47.3
PATCH 5/21 simplify collect_arguments() and fix error handling there
In reply to Al ViroThe current logics is too convoluted. We use collect_arg() to carve an argument out; it takes a pointer to previous token (either opening parenthesis or comma), finds how far does the argument extend, cuts the list at its end and returns the token that follows it (normally either closing parenthesis or the comma). collect_arg() is told whether we want a vararg argument or not - the difference is that normal arguments terminate on commas.
When macro has N non-vararg arguments and V (0 or 1) vararg ones, we want
* N calls of collect_arg() asking for non-vararg arguments;
all but the last one must be followed by commas. The last one may be followed either by comma or by closing parenthesis.
* If we have seen exactly N commas, call collect_arg() asking
to collect everything until the closing parenthesis. That will get us to the end of arguments.
The only potential gotcha is that there is a case when "exactly N commas" for non-vararg macro does _not_ mean excessive arguments - N = V = 0. Not hard to account for - in that case we must look at the chunk carved out by the last (and only) call of collect_arg(); that would be everything between the parentheses. If it's empty, we are fine, otherwise we've excessive arguments.
Rather than trying to fold all of that into a single loop, separate the handling of non-vararg arguments from the rest; the logics becomes simpler that way, especially around the error recovery.
As a side benefit the 'vararg' bit in struct argcount becomes unused and can be removed.
--- pre-process.c | 104 ++++++++++++++++++++++---------------------------- token.h | 1 - 2 files changed, 46 insertions(+), 59 deletions(-)
pre-process.c +46 -58
@@ -255,7 +255,7 @@ static void expand_list(struct token **list)static void preprocessor_line (struct stream *stream,struct token **line); -static struct token *collect_arg (struct token *prev,int vararg,const struct position *pos) +static struct token *collect_arg (struct token *prev,bool vararg,const struct position *pos) {struct stream *stream = input_streams + prev->pos.stream;struct token **p = &prev->next;
@@ -314,76 +314,66 @@ struct arg {static int collect_arguments (struct token *start,struct symbol *sym,struct arg *args,struct token *what) { +int fixed = sym->fixed_args; +bool vararg = sym->vararg;struct token *arglist = sym->arglist; -int wanted = sym->fixed_args + sym->vararg; -struct token *next =NULL ; -int count =0 ; +struct argcount *p; +struct token *next =NULL , *v =NULL ; +const char *err; +int commas; arglist = arglist->next;/* skip counter */ -if (!wanted) { - next =collect_arg (start,0 , &what->pos); -if (eof_token (next)) +for (commas =0 ; commas < fixed; commas++) { + next =collect_arg (start, false, &what->pos); +if (token_type (next) !=TOKEN_SPECIAL ) goto Eclosing; -if (!eof_token (start->next) || !match_op (next,')' )) { - count++; - goto Emany; - } - }else { -for (count =0 ; count < wanted; count++) { -struct argcount *p = &arglist->next->count; - next =collect_arg (start, p->vararg, &what->pos); -if (eof_token (next)) - goto Eclosing; -if (p->vararg && wanted ==1 &&eof_token (start->next)) -break ; - arglist = arglist->next->next; - args[count].arg = start->next; - args[count].n_normal = p->normal; - args[count].n_quoted = p->quoted; - args[count].n_str = p->str; -if (match_op (next,')' )) { - count++; -break ; - } - start = next; - } -if (count == wanted && !match_op (next,')' )) - goto Emany; -if (count == wanted -1 ) { -struct argcount *p = &arglist->next->count; -if (!p->vararg) + p = &arglist->next->count; + arglist = arglist->next->next; + args[commas].arg = start->next; + args[commas].n_normal = p->normal; + args[commas].n_quoted = p->quoted; + args[commas].n_str = p->str; +if (!match_op (next,',' )) { +if (commas < fixed -1 ) goto Efew; - args[count].arg =NULL ; - args[count].n_normal = p->normal; - args[count].n_quoted = p->quoted; - args[count].n_str = p->str; +break ; } -if (count < wanted -1 ) - goto Efew; + start = next; + } +if (commas == fixed) { + next =collect_arg (start, true, &what->pos); +if (token_type (next) !=TOKEN_SPECIAL ) + goto Eclosing; + v = start->next; +if (fixed ==0 &&eof_token (v)) + v =NULL ; + } +if (v && !vararg) + goto Eexcess; +if (vararg) { + p = &arglist->next->count; + args[fixed].arg = v; + args[fixed].n_normal = p->normal; + args[fixed].n_quoted = p->quoted; + args[fixed].n_str = p->str; } what->next = next->next;return 1 ; Efew: -sparse_error (what->pos,"macro \"%s\" requires %d arguments, but only %d given" , -show_token (what), wanted, count); + err ="too few arguments provided to" ; + next = next->next; goto out; -Emany: -while (match_op (next,',' )) { - next =collect_arg (next,0 , &what->pos); - count++; - } -if (eof_token (next)) - goto Eclosing; -sparse_error (what->pos,"macro \"%s\" passed %d arguments, but takes just %d" , -show_token (what), count, wanted); +Eexcess: + err ="too many arguments provided to" ; + next = next->next; goto out; Eclosing: -sparse_error (what->pos,"unterminated argument list invoking macro \"%s\"" , -show_token (what)); + err ="unterminated argument list invoking" ; out: - what->next = next->next; +sparse_error (what->pos,"%s macro \"%s\"" , err,show_ident (sym->ident)); + what->next = next;return 0 ; }
@@ -1107,7 +1097,7 @@ static inline void set_arg_count(struct token *token) {token_type (token) =TOKEN_ARG_COUNT ; token->count.normal = token->count.quoted = - token->count.str = token->count.vararg =0 ; + token->count.str =0 ; }static struct token *parse_arguments (struct token *list)
@@ -1148,7 +1138,6 @@ static struct token *parse_arguments(struct token *list)if (match_op (next->next,')' )) {set_arg_count (next); macro_vararg = macro_nargs -1 ; - next->count.vararg =1 ; next = next->next; arg->next->next = &eof_token_entry;return next->next;
@@ -1176,7 +1165,6 @@ static struct token *parse_arguments(struct token *list)return NULL ;set_arg_count (next); macro_vararg = macro_nargs -1 ; - next->count.vararg =1 ; next = next->next; arg->next->next = &eof_token_entry;return next;
token.h +0 -1
@@ -175,7 +175,6 @@ struct argcount { unsigned normal:10; unsigned quoted:10; unsigned str:10; - unsigned vararg:1; };/*
Signature · 1 line
2.47.3
PATCH 6/21 try_arg(): don't use arglist for argument name lookups
In reply to Al ViroJust store them into a global array and search there. That allows to get rid of mangling ... in the arglist along with the is_VA_ARGS_token() kludge. For now we still need to access the arglist in try_arg(), but that's going away as soon as we get rid of the use counters...
Added a check for duplicate argument names, while we are at it - we didn't do that.
--- pre-process.c | 90 ++++++++++++++-------------- validation/preprocessor/bad-args.c | 18 ++++++ validation/preprocessor/dump-macro.c | 9 +++ 3 files changed, 72 insertions(+), 45 deletions(-) create mode 100644 validation/preprocessor/bad-args.c create mode 100644 validation/preprocessor/dump-macro.c
pre-process.c +45 -45
@@ -1078,16 +1078,24 @@ static int token_list_different(struct token *list1, struct token *list2) } } +static struct ident *macro_arg_name[1024 ];static int macro_nargs =0 ;static int macro_vararg =-1 ;static bool macro_funclike = false;static bool macro_add_arg (struct position pos,struct ident *ident) { +for (int i =0 ; i < macro_nargs; i++) { +if (ident == macro_arg_name[i]) + goto Edup_arg; + }if (macro_nargs ==1024 ) goto Eargs; - macro_nargs++; + macro_arg_name[macro_nargs++] = ident;return true; +Edup_arg: +sparse_error (pos,"duplicate macro parameter \"%s\"" ,show_ident (ident)); +return false; Eargs:sparse_error (pos,"too many arguments in macro definition" );return false;
@@ -1157,8 +1165,6 @@ static struct token *parse_arguments(struct token *list)if (match_op (arg,SPECIAL_ELLIPSIS )) { next = arg->next; -token_type (arg) =TOKEN_IDENT ; - arg->ident = &__VA_ARGS___ident;if (!match_op (next,')' )) goto Enotclosed;if (!macro_add_arg (arg->pos, &__VA_ARGS___ident))
@@ -1198,41 +1204,41 @@ Eva_args:static int try_arg (struct token *token,enum token_type type,struct token *arglist) {struct ident *ident = token->ident; -int nr; +int nr, n;if (!macro_funclike ||token_type (token) !=TOKEN_IDENT )return 0 ; - arglist = arglist->next; +for (nr =0 ; nr < macro_nargs && macro_arg_name[nr] != ident; nr++) + ; -for (nr =0 ; !eof_token (arglist); nr++, arglist = arglist->next->next) { -if (arglist->ident == ident) { -struct argcount *count = &arglist->next->count; -int n; +if (nr == macro_nargs) +return 0 ; - token->argnum = nr; -token_type (token) = type; -switch (type) { -case TOKEN_MACRO_ARGUMENT : - n = ++count->normal; -break ; -case TOKEN_QUOTED_ARGUMENT : - n = ++count->quoted; -break ; -default : - n = ++count->str; - } -if (n) -return nr == macro_vararg ?2 :1 ; -/* -* XXX - need saner handling of that -* (>= 1024 instances of argument) -*/ -token_type (token) =TOKEN_ERROR ; -return -1 ; - } + arglist = arglist->next; +for (int i =0 ; i < nr; i++) + arglist = arglist->next->next; + + token->argnum = nr; +token_type (token) = type; +switch (type) { +case TOKEN_MACRO_ARGUMENT : + n = ++arglist->next->count.normal; +break ; +case TOKEN_QUOTED_ARGUMENT : + n = ++arglist->next->count.quoted; +break ; +default : + n = ++arglist->next->count.str; } -return 0 ; +if (n) +return nr == macro_vararg ?2 :1 ; +/* +* XXX - need saner handling of that +* (>= 1024 instances of argument) +*/ +token_type (token) =TOKEN_ERROR ; +return -1 ; }static struct token *handle_hash (struct token **p,struct token *arglist)
@@ -2304,16 +2310,10 @@ struct token * preprocess(struct token *token)return token; } -static int is_VA_ARGS_token (struct token *token) -{ -return (token_type (token) ==TOKEN_IDENT ) && - (token->ident == &__VA_ARGS___ident); -} -static void dump_macro (struct symbol *sym) {int nargs = sym->fixed_args + sym->vararg; -struct token *args[nargs]; +struct ident *args[nargs];struct token *token;printf ("#define %s" ,show_ident (sym->ident));
@@ -2325,13 +2325,13 @@ static void dump_macro(struct symbol *sym)for (; !eof_token (token); token = token->next) {if (token_type (token) ==TOKEN_ARG_COUNT )continue ; -if (is_VA_ARGS_token (token)) -printf ("%s..." , sep); -else -printf ("%s%s" , sep,show_token (token)); - args[narg++] = token; +printf ("%s%s" , sep,show_token (token)); +if (token_type (token) ==TOKEN_IDENT ) + args[narg++] = token->ident; sep ="," ; } +if (narg < nargs) + args[narg] = &__VA_ARGS___ident;putchar (')' ); }
@@ -2349,8 +2349,8 @@ static void dump_macro(struct symbol *sym)/* fall-through */ case TOKEN_QUOTED_ARGUMENT :case TOKEN_MACRO_ARGUMENT : - token = args[token->argnum]; -/* fall-through */ +printf ("%s" ,show_ident (args[token->argnum])); +break ;default :printf ("%s" ,show_token (token)); }
validation/preprocessor/bad-args.c new file +18 -0
@@ -0,0 +1,18 @@ +#define A(1) +#define B (__VA_ARGS__) +#define C (X ,Y ,X ) +/* +* check-name: macro arguments validation +* check-command: sparse -E $file +* +* check-output-start + + +* check-output-end +* +* check-error-start +preprocessor/bad-args.c:1:11: error: "1" may not appear in macro parameter list +preprocessor/bad-args.c:2:11: error: __VA_ARGS__ can only appear in the expansion of a C99 variadic macro +preprocessor/bad-args.c:3:15: error: duplicate macro parameter "X" +* check-error-end +*/
validation/preprocessor/dump-macro.c new file +9 -0
@@ -0,0 +1,9 @@ +#define A (X ,Y ,...) __VA_ARGS__,Y,X +/* +* check-name: -dM handling of varargs +* check-command: sparse -E -dM $file | tail -1 +* +* check-output-start +#define A(X,Y,...) __VA_ARGS__,Y,X +* check-output-end +*/
Signature · 1 line
2.47.3
PATCH 7/21 make expand_has_...() responsible for expanding its argument
In reply to Al ViroIf we want to make expansion of arguments on-demand, we need to adjust ->expand() calling conventions first, passing it unexpanded arguments. Switch create_arglist() to setting argcounts from normal=1 to quoted=1, provide a helper (first_arg()) that does actual expansion and make ->expand() instances use it. After that these fake arglists are used only for two things: they indicate that these macros are function-like and they short-circuit expand_arguments(). Once we switch to on-demand argument expansion, the second role will disappear and we can just use &eof_token_entry as ->arglist for those.
--- pre-process.c | 17 ++++++++++++----- validation/preprocessor/has-attribute.c | 3 +++ validation/preprocessor/has-builtin.c | 3 +++ 3 files changed, 18 insertions(+), 5 deletions(-)
pre-process.c +12 -5
@@ -2000,9 +2000,16 @@ static int handle_nondirective(struct stream *stream, struct token **line, strucreturn 1 ; } +static struct token *first_arg (struct arg *args) +{ +struct token *arg = args[0 ].arg; +expand_list (&arg); +return arg; +} +static bool expand_has_attribute (struct token *token,struct arg *args) { -struct token *arg = args[0 ].expanded; +struct token *arg =first_arg (args);struct symbol *sym;if (token_type (arg) !=TOKEN_IDENT ) {
@@ -2017,7 +2024,7 @@ static bool expand_has_attribute(struct token *token, struct arg *args)static bool expand_has_builtin (struct token *token,struct arg *args) { -struct token *arg = args[0 ].expanded; +struct token *arg =first_arg (args);struct symbol *sym;if (token_type (arg) !=TOKEN_IDENT ) {
@@ -2032,7 +2039,7 @@ static bool expand_has_builtin(struct token *token, struct arg *args)static bool expand_has_extension (struct token *token,struct arg *args) { -struct token *arg = args[0 ].expanded; +struct token *arg =first_arg (args);struct ident *ident;bool val = false;
@@ -2057,7 +2064,7 @@ static bool expand_has_extension(struct token *token, struct arg *args)static bool expand_has_feature (struct token *token,struct arg *args) { -struct token *arg = args[0 ].expanded; +struct token *arg =first_arg (args);struct ident *ident;bool val = false;
@@ -2103,7 +2110,7 @@ static void create_arglist(struct symbol *sym, int count)token_type (id) =TOKEN_IDENT ; uses =__alloc_token (0 );token_type (uses) =TOKEN_ARG_COUNT ; - uses->count.normal =1 ; + uses->count.quoted =1 ; *next = id; id->next = uses;
validation/preprocessor/has-attribute.c +3 -0
@@ -6,6 +6,8 @@ __has_attribute()??? Quesako?#endif 123 __has_attribute(nothinx) def +#define A packed +456 __has_attribute(A)#if __has_attribute (nothinx)#error "not a attribute!"
@@ -49,6 +51,7 @@ __has_attribute()??? Quesako?"has __has_attribute(), yeah!" 123 0 def +456 1"ok gcc" "ok gcc ignore" "ok sparse specific"
validation/preprocessor/has-builtin.c +3 -0
@@ -28,6 +28,8 @@ constant_p#endif 123 __has_builtin(abc) def +#define A __builtin_constant_p +456 __has_builtin(A)/* * check-name: has-builtin
@@ -39,5 +41,6 @@ constant_pabs constant_p 123 0 def +456 1 * check-output-end */
Signature · 1 line
2.47.3
PATCH 8/21 preparing to change argument number encoding for TOKEN_..._ARGUMENT
In reply to Al ViroWe want to steal some bits from TOKEN_..._ARGUMENT; it's not a problem, seeing that payload is a 32bit number and we are *not* going to support many millions of arguments in macros. For now, wrap the accesses into an inline helper (argnum(token)), to reduce the amount of noise in subsequent patches.
--- pre-process.c | 23 ++++++++++++++--------- token.h | 4 ++++ 2 files changed, 18 insertions(+), 9 deletions(-)
pre-process.c +14 -9
@@ -624,11 +624,16 @@ static struct token **copy(struct token **where, struct token *list)return where; } +static inline int argnum (const struct token *arg) +{ +return arg->argnum >>ARGNUM_BITS_STOLEN ; +} +static int handle_kludge (const struct token **p,struct arg *args) {const struct token *t = (*p)->next->next;while (1 ) { -struct arg *v = &args[t->argnum]; +struct arg *v = &args[argnum (t)];if (token_type (t->next) !=TOKEN_CONCAT ) {if (v->arg) {/* ignore the first ## */
@@ -681,13 +686,13 @@ static struct token **substitute(struct token **list, const struct token *body,break ;case TOKEN_STR_ARGUMENT : - arg = args[body->argnum].str; - count = &args[body->argnum].n_str; + arg = args[argnum (body)].str; + count = &args[argnum (body)].n_str; goto copy_arg;case TOKEN_QUOTED_ARGUMENT : - arg = args[body->argnum].arg; - count = &args[body->argnum].n_quoted; + arg = args[argnum (body)].arg; + count = &args[argnum (body)].n_quoted;if (!arg ||eof_token (arg)) {if (state == Concat) state = Normal;
@@ -698,8 +703,8 @@ static struct token **substitute(struct token **list, const struct token *body, goto copy_arg;case TOKEN_MACRO_ARGUMENT : - arg = args[body->argnum].expanded; - count = &args[body->argnum].n_normal; + arg = args[argnum (body)].expanded; + count = &args[argnum (body)].n_normal;if (eof_token (arg)) { state = Normal;continue ;
@@ -1219,7 +1224,7 @@ static int try_arg(struct token *token, enum token_type type, struct token *arglfor (int i =0 ; i < nr; i++) arglist = arglist->next->next; - token->argnum = nr; + token->argnum = nr <<ARGNUM_BITS_STOLEN ;token_type (token) = type;switch (type) {case TOKEN_MACRO_ARGUMENT :
@@ -2356,7 +2361,7 @@ static void dump_macro(struct symbol *sym)/* fall-through */ case TOKEN_QUOTED_ARGUMENT :case TOKEN_MACRO_ARGUMENT : -printf ("%s" ,show_ident (args[token->argnum])); +printf ("%s" ,show_ident (args[argnum (token)]));break ;default :printf ("%s" ,show_token (token));
token.h +4 -0
@@ -177,6 +177,10 @@ struct argcount { unsigned str:10; }; +enum { +ARGNUM_BITS_STOLEN +}; +/* * This is a very common data structure, it should be kept * as small as humanly possible. Big (rare) types go as
Signature · 1 line
2.47.3
PATCH 9/21 steal 2 bits from argnum for argument kind
In reply to Al ViroWe have 3 separate token types (TOKEN_{MACRO,QUOTED,STR}_ARGUMENT), with fairly similar handling at expansion time. Let's steal two bits from ->argnum and use them to represent the kind of occurrence; that simplifies substitute() and allows for better code generation there.
The object we use to store the argument state at expansion time (struct arg) is already a structure with 3 pointers to token lists (unexpanded, expanded and stringified forms of the argument) and 3 integer counters - the number of remaining occurrencies of each kind. Gather those into 3-element arrays indexed by the kind; counts will be gone soon, token lists will remain.
--- pre-process.c | 106 +++++++++++++++++++++----------------------------- token.h | 14 +++++-- 2 files changed, 55 insertions(+), 65 deletions(-)
pre-process.c +44 -62
@@ -304,12 +304,8 @@ static struct token *collect_arg(struct token *prev, bool vararg, const struct p*/ struct arg { -struct token *arg; -struct token *expanded; -struct token *str; -int n_normal; -int n_quoted; -int n_str; +struct token *arg[3 ]; +int count[3 ]; };static int collect_arguments (struct token *start,struct symbol *sym,struct arg *args,struct token *what)
@@ -330,10 +326,10 @@ static int collect_arguments(struct token *start, struct symbol *sym, struct arg goto Eclosing; p = &arglist->next->count; arglist = arglist->next->next; - args[commas].arg = start->next; - args[commas].n_normal = p->normal; - args[commas].n_quoted = p->quoted; - args[commas].n_str = p->str; + args[commas].arg[ARG_QUOTED ] = start->next; + args[commas].count[ARG_NORMAL ] = p->normal; + args[commas].count[ARG_QUOTED ] = p->quoted; + args[commas].count[ARG_STR ] = p->str;if (!match_op (next,',' )) {if (commas < fixed -1 ) goto Efew;
@@ -353,10 +349,10 @@ static int collect_arguments(struct token *start, struct symbol *sym, struct arg goto Eexcess;if (vararg) { p = &arglist->next->count; - args[fixed].arg = v; - args[fixed].n_normal = p->normal; - args[fixed].n_quoted = p->quoted; - args[fixed].n_str = p->str; + args[fixed].arg[ARG_QUOTED ] = v; + args[fixed].count[ARG_NORMAL ] = p->normal; + args[fixed].count[ARG_QUOTED ] = p->quoted; + args[fixed].count[ARG_STR ] = p->str; } what->next = next->next;return 1 ;
@@ -440,21 +436,21 @@ static void expand_arguments(int count, struct arg *args) {int i;for (i =0 ; i < count; i++) { -struct token *arg = args[i].arg; +struct token *arg = args[i].arg[ARG_QUOTED ];if (!arg) arg = &eof_token_entry; -if (args[i].n_str) - args[i].str =stringify (arg); -if (args[i].n_normal) { -if (!args[i].n_quoted) { - args[i].expanded = arg; - args[i].arg =NULL ; +if (args[i].count[ARG_STR ]) + args[i].arg[ARG_STR ] =stringify (arg); +if (args[i].count[ARG_NORMAL ]) { +if (!args[i].count[ARG_QUOTED ]) { + args[i].arg[ARG_NORMAL ] = arg; + args[i].arg[ARG_QUOTED ] =NULL ; }else if (eof_token (arg)) { - args[i].expanded = arg; + args[i].arg[ARG_NORMAL ] = arg; }else { - args[i].expanded =dup_list (arg); + args[i].arg[ARG_NORMAL ] =dup_list (arg); } -expand_list (&args[i].expanded); +expand_list (&args[i].arg[ARG_NORMAL ]); } } }
@@ -629,13 +625,18 @@ static inline int argnum(const struct token *arg)return arg->argnum >>ARGNUM_BITS_STOLEN ; } +static inline enum arg_kind argkind (const struct token *arg) +{ +return arg->argnum &ARGNUM_KIND_MASK ; +} +static int handle_kludge (const struct token **p,struct arg *args) {const struct token *t = (*p)->next->next;while (1 ) { -struct arg *v = &args[argnum (t)]; +struct token *v = args[argnum (t)].arg[ARG_QUOTED ];if (token_type (t->next) !=TOKEN_CONCAT ) { -if (v->arg) { +if (v) {/* ignore the first ## */ *p = (*p)->next;return 0 ;
@@ -644,7 +645,7 @@ static int handle_kludge(const struct token **p, struct arg *args) *p = t;return 1 ; } -if (v->arg && !eof_token (v->arg)) +if (v && !eof_token (v))return 0 ;/* no magic */ t = t->next->next; }
@@ -685,14 +686,9 @@ static struct token **substitute(struct token **list, const struct token *body, tail = &added->next;break ; -case TOKEN_STR_ARGUMENT : - arg = args[argnum (body)].str; - count = &args[argnum (body)].n_str; - goto copy_arg; - -case TOKEN_QUOTED_ARGUMENT : - arg = args[argnum (body)].arg; - count = &args[argnum (body)].n_quoted; +case TOKEN_MACRO_ARGUMENT : + arg = args[argnum (body)].arg[argkind (body)]; + count = &args[argnum (body)].count[argkind (body)];if (!arg ||eof_token (arg)) {if (state == Concat) state = Normal;
@@ -700,16 +696,6 @@ static struct token **substitute(struct token **list, const struct token *body, state = Placeholder;continue ; } - goto copy_arg; - -case TOKEN_MACRO_ARGUMENT : - arg = args[argnum (body)].expanded; - count = &args[argnum (body)].n_normal; -if (eof_token (arg)) { - state = Normal; -continue ; - } - copy_arg:if (!--*count) tail =move_into (&added, arg);else
@@ -1040,8 +1026,6 @@ static int token_different(struct token *t1, struct token *t2) different = t1->special != t2->special;break ;case TOKEN_MACRO_ARGUMENT : -case TOKEN_QUOTED_ARGUMENT : -case TOKEN_STR_ARGUMENT : different = t1->argnum != t2->argnum;break ; case TOKEN_CHAR_EMBEDDED_0 ... TOKEN_CHAR_EMBEDDED_3:
@@ -1206,7 +1190,7 @@ Eva_args:return NULL ; } -static int try_arg (struct token *token,enum token_type type,struct token *arglist) +static int try_arg (struct token *token,enum arg_kind kind,struct token *arglist) {struct ident *ident = token->ident;int nr, n;
@@ -1224,13 +1208,13 @@ static int try_arg(struct token *token, enum token_type type, struct token *arglfor (int i =0 ; i < nr; i++) arglist = arglist->next->next; - token->argnum = nr <<ARGNUM_BITS_STOLEN ; -token_type (token) = type; -switch (type) { -case TOKEN_MACRO_ARGUMENT : + token->argnum = (nr <<ARGNUM_BITS_STOLEN ) | kind; +token_type (token) =TOKEN_MACRO_ARGUMENT ; +switch (kind) { +case ARG_NORMAL : n = ++arglist->next->count.normal;break ; -case TOKEN_QUOTED_ARGUMENT : +case ARG_QUOTED : n = ++arglist->next->count.quoted;break ;default :
@@ -1251,7 +1235,7 @@ static struct token *handle_hash(struct token **p, struct token *arglist)struct token *token = *p;if (macro_funclike) {struct token *next = token->next; -if (!try_arg (next,TOKEN_STR_ARGUMENT , arglist)) +if (!try_arg (next,ARG_STR , arglist)) goto Equote; next->pos.whitespace = token->pos.whitespace;__free_token (token);
@@ -1273,7 +1257,7 @@ static struct token *handle_hashhash(struct token *token, struct token *arglist)struct token *concat;int state =match_op (token,',' ); -try_arg (token,TOKEN_QUOTED_ARGUMENT , arglist); +try_arg (token,ARG_QUOTED , arglist);while (1 ) {struct token *t;
@@ -1297,7 +1281,7 @@ static struct token *handle_hashhash(struct token *token, struct token *arglist)return NULL ; } - is_arg =try_arg (t,TOKEN_QUOTED_ARGUMENT , arglist); + is_arg =try_arg (t,ARG_QUOTED , arglist);if (state ==1 && is_arg) { state = is_arg;
@@ -1339,7 +1323,7 @@ static struct token *parse_expansion(struct token *expansion, struct token *arglif (!token)return NULL ; }else { -try_arg (token,TOKEN_MACRO_ARGUMENT , arglist); +try_arg (token,ARG_NORMAL , arglist); }if (token_type (token) ==TOKEN_ERROR ) goto Earg;
@@ -2007,7 +1991,7 @@ static int handle_nondirective(struct stream *stream, struct token **line, strucstatic struct token *first_arg (struct arg *args) { -struct token *arg = args[0 ].arg; +struct token *arg = args[0 ].arg[ARG_QUOTED ];expand_list (&arg);return arg; }
@@ -2356,11 +2340,9 @@ static void dump_macro(struct symbol *sym)case TOKEN_CONCAT :printf ("##" );break ; -case TOKEN_STR_ARGUMENT : -printf ("#" ); -/* fall-through */ -case TOKEN_QUOTED_ARGUMENT :case TOKEN_MACRO_ARGUMENT : +if (argkind (token) ==ARG_STR ) +printf ("#" );printf ("%s" ,show_ident (args[argnum (token)]));break ;default :
token.h +11 -3
@@ -100,8 +100,6 @@ enum token_type {TOKEN_STREAMBEGIN ,TOKEN_STREAMEND ,TOKEN_MACRO_ARGUMENT , -TOKEN_STR_ARGUMENT , -TOKEN_QUOTED_ARGUMENT ,TOKEN_CONCAT ,TOKEN_GNU_KLUDGE , TOKEN_UNTAINT,
@@ -177,8 +175,18 @@ struct argcount { unsigned str:10; }; +enum arg_kind { +ARG_QUOTED =0 , +ARG_NORMAL =1 , +ARG_STR =2 , +}; + +enum { +ARGNUM_BITS_STOLEN =2 +}; +enum { -ARGNUM_BITS_STOLEN +ARGNUM_KIND_MASK =3 };/*
Signature · 1 line
2.47.3
PATCH 10/21 on-demand argument expansion
In reply to Al ViroInstead of calculating expanded and stringified forms of arguments before we get to interpolating them into the body, do that on demand.
There are several subtle points involved:
* array of arguments ('args' in collect_arguments() and friends)
needs to be explicitly zeroed; then we can easily see whether we'd already expanded or stringified the sucker. Better done as an explicit memset(), and it's better off in collect_arguments() than in expand() itself - that way we don't need to bother with that for macros that don't have arguments in the first place. And yes, doing that as an empty initializer in expand() where that VLA is declared does result in a measurable slowdown...
* anti-recursion rules do not apply to argument expansion;
something like
#define A(x) x + 1 A(A(1))
should result in x + 1 + 1, not A(1) + 1. If expansion is done before we mark 'A' and call substitute() that happens automatically; if we delay it until substitute() runs into the first normal instance of an argument, we need to remove the mark for duration of that expansion. Not a problem, fortunately, since the set of marked symbols at the time we get to TOKEN_MACRO_ARGUMENT will be the same as it used to be at the time we enter substitute() - arguments can't contain any TOKEN_UNTAINT (collect_arg() would eat all of those) and any taint added during expand_list() will come with matching TOKEN_UNTAINT inserted into the list. All such TOKEN_UNTAINT will be consumed before expand_list() returns, restoring the original conditions. All we need to do is to remove the taint from macro being substituted just before expanding an argument and restore it right after that - it will do the right thing. It makes sense to shift setting the taint from the caller of substitute() where it's currently done into the very beginning of substitute() itself, while we are at it.
* instead of using counters to determine if this form of argument
is not needed after this place just mark the last place where given form is needed when we are parsing the body - it's easy enough to do. The only subtlety here is that unexpanded argument is needed to calculate an expanded form, so in
#define A(x) foo_##x = x
we can't cannibalize the unexpanded form of x until the second instance of x in the body. Rules for unexpanded form are
1) it's needed for any unexpanded occurrence (obviously)
2) it's needed for the first expanded occurrence
3) it's needed for the first stringified occurrence
Fortunately, we don't need nothing non-trivial at #define time - no separate passes, etc. Note that in real world most of the macros seen in given compile unit are never expanded in it, so we need to keep the handling of #define light - trading the overhead at expansion time for overhead at definition time is a bad idea.
* since the counters are gone, we no longer need to pass arglist
all over the place; parsing side gets an array of struct arg_state, which is where we keep the information about argument occurrences through the parsing. Expansion side doesn't need arglist anymore - the last place that used to need it was collect_arguments(), and only to copy the counters. No more of that...
--- pre-process.c | 159 ++++++++++++++++++++++++-------------------------- token.h | 8 ++- 2 files changed, 82 insertions(+), 85 deletions(-)
pre-process.c +76 -83
@@ -305,31 +305,23 @@ static struct token *collect_arg(struct token *prev, bool vararg, const struct pstruct arg {struct token *arg[3 ]; -int count[3 ]; };static int collect_arguments (struct token *start,struct symbol *sym,struct arg *args,struct token *what) {int fixed = sym->fixed_args;bool vararg = sym->vararg; -struct token *arglist = sym->arglist; -struct argcount *p;struct token *next =NULL , *v =NULL ;const char *err;int commas; - arglist = arglist->next;/* skip counter */ +memset (args,0 ,sizeof (struct arg ) * (fixed +1 ));for (commas =0 ; commas < fixed; commas++) { next =collect_arg (start, false, &what->pos);if (token_type (next) !=TOKEN_SPECIAL ) goto Eclosing; - p = &arglist->next->count; - arglist = arglist->next->next; args[commas].arg[ARG_QUOTED ] = start->next; - args[commas].count[ARG_NORMAL ] = p->normal; - args[commas].count[ARG_QUOTED ] = p->quoted; - args[commas].count[ARG_STR ] = p->str;if (!match_op (next,',' )) {if (commas < fixed -1 ) goto Efew;
@@ -347,13 +339,8 @@ static int collect_arguments(struct token *start, struct symbol *sym, struct arg }if (v && !vararg) goto Eexcess; -if (vararg) { - p = &arglist->next->count; +if (vararg) args[fixed].arg[ARG_QUOTED ] = v; - args[fixed].count[ARG_NORMAL ] = p->normal; - args[fixed].count[ARG_QUOTED ] = p->quoted; - args[fixed].count[ARG_STR ] = p->str; - } what->next = next->next;return 1 ;
@@ -432,29 +419,6 @@ static struct token *stringify(struct token *arg)return token; } -static void expand_arguments (int count,struct arg *args) -{ -int i; -for (i =0 ; i < count; i++) { -struct token *arg = args[i].arg[ARG_QUOTED ]; -if (!arg) - arg = &eof_token_entry; -if (args[i].count[ARG_STR ]) - args[i].arg[ARG_STR ] =stringify (arg); -if (args[i].count[ARG_NORMAL ]) { -if (!args[i].count[ARG_QUOTED ]) { - args[i].arg[ARG_NORMAL ] = arg; - args[i].arg[ARG_QUOTED ] =NULL ; - }else if (eof_token (arg)) { - args[i].arg[ARG_NORMAL ] = arg; - }else { - args[i].arg[ARG_NORMAL ] =dup_list (arg); - } -expand_list (&args[i].arg[ARG_NORMAL ]); - } - } -} -/* * Possibly valid combinations: * - ident + ident -> ident
@@ -651,11 +615,38 @@ static int handle_kludge(const struct token **p, struct arg *args) } } +static struct token *do_argument (const struct token *body, +struct arg *args, +struct ident *expanding) +{ +struct token *arg = args[argnum (body)].arg[argkind (body)]; +if (arg) +return arg; + arg = args[argnum (body)].arg[ARG_QUOTED ]; +if (!arg) + arg = &eof_token_entry; +if (argkind (body) ==ARG_NORMAL ) { +if (!eof_token (arg)) { +if (!(body->argnum & (1 <<ARGNUM_CONSUME_EXPAND ))) + arg =dup_list (arg); + expanding->tainted =0 ; +expand_list (&arg); + expanding->tainted =1 ; + } +return args[argnum (body)].arg[ARG_NORMAL ] = arg; + } +if (argkind (body) ==ARG_STR ) +return args[argnum (body)].arg[ARG_STR ] =stringify (arg); +return arg;// ARG_QUOTED +} +static struct token **substitute (struct token **list,const struct token *body,struct arg *args) {struct position *base_pos = &(*list)->pos; -int *count;enum {Normal, Placeholder, Concat} state = Normal; +struct ident *expanding = (*list)->ident; + + expanding->tainted =1 ;for (; !eof_token (body); body = body->next) {struct token *added, *arg;
@@ -687,8 +678,7 @@ static struct token **substitute(struct token **list, const struct token *body,break ;case TOKEN_MACRO_ARGUMENT : - arg = args[argnum (body)].arg[argkind (body)]; - count = &args[argnum (body)].count[argkind (body)]; + arg =do_argument (body, args, expanding);if (!arg ||eof_token (arg)) {if (state == Concat) state = Normal;
@@ -696,7 +686,7 @@ static struct token **substitute(struct token **list, const struct token *body, state = Placeholder;continue ; } -if (!--*count) +if (body->argnum & (1 <<ARGNUM_CONSUME )) tail =move_into (&added, arg);else tail =copy (&added, arg);
@@ -755,14 +745,11 @@ static int expand(struct token **list, struct symbol *sym)return 1 ;if (!collect_arguments (token->next, sym, args, token))return 1 ; -expand_arguments (nargs, args); }if (sym->expand)return sym->expand (token, args) ?0 :1 ; - expanding->tainted =1 ; - last = token->next; tail =substitute (list, expansion, args);/*
@@ -1093,8 +1080,6 @@ Eargs:static inline void set_arg_count (struct token *token) {token_type (token) =TOKEN_ARG_COUNT ; - token->count.normal = token->count.quoted = - token->count.str =0 ; }static struct token *parse_arguments (struct token *list)
@@ -1190,10 +1175,16 @@ Eva_args:return NULL ; } -static int try_arg (struct token *token,enum arg_kind kind,struct token *arglist) +struct arg_state { +struct token *needs_raw; +struct token *needs_expanded; +struct token *needs_str; +}; + +static int try_arg (struct token *token,enum arg_kind kind,struct arg_state args[]) {struct ident *ident = token->ident; -int nr, n; +int nr;if (!macro_funclike ||token_type (token) !=TOKEN_IDENT )return 0 ;
@@ -1204,38 +1195,31 @@ static int try_arg(struct token *token, enum arg_kind kind, struct token *arglisif (nr == macro_nargs)return 0 ; - arglist = arglist->next; -for (int i =0 ; i < nr; i++) - arglist = arglist->next->next; - token->argnum = (nr <<ARGNUM_BITS_STOLEN ) | kind;token_type (token) =TOKEN_MACRO_ARGUMENT ;switch (kind) { -case ARG_NORMAL : - n = ++arglist->next->count.normal; -break ;case ARG_QUOTED : - n = ++arglist->next->count.quoted; + args[nr].needs_raw = token;break ; -default : - n = ++arglist->next->count.str; +case ARG_NORMAL : +if (!args[nr].needs_expanded) + args[nr].needs_raw = token; + args[nr].needs_expanded = token; +break ; +default :// ARG_STR +if (!args[nr].needs_str) + args[nr].needs_raw = token; + args[nr].needs_str = token; } -if (n) -return nr == macro_vararg ?2 :1 ; -/* -* XXX - need saner handling of that -* (>= 1024 instances of argument) -*/ -token_type (token) =TOKEN_ERROR ; -return -1 ; +return nr == macro_vararg ?2 :1 ; } -static struct token *handle_hash (struct token **p,struct token *arglist) +static struct token *handle_hash (struct token **p,struct arg_state args[]) {struct token *token = *p;if (macro_funclike) {struct token *next = token->next; -if (!try_arg (next,ARG_STR , arglist)) +if (!try_arg (next,ARG_STR , args)) goto Equote; next->pos.whitespace = token->pos.whitespace;__free_token (token);
@@ -1251,13 +1235,13 @@ Equote: }/* token->next is ## */ -static struct token *handle_hashhash (struct token *token,struct token *arglist) +static struct token *handle_hashhash (struct token *token,struct arg_state args[]) {struct token *last = token;struct token *concat;int state =match_op (token,',' ); -try_arg (token,ARG_QUOTED , arglist); +try_arg (token,ARG_QUOTED , args);while (1 ) {struct token *t;
@@ -1276,12 +1260,12 @@ static struct token *handle_hashhash(struct token *token, struct token *arglist) goto Econcat;if (match_op (t,'#' )) { - t =handle_hash (&concat->next, arglist); + t =handle_hash (&concat->next, args);if (!t)return NULL ; } - is_arg =try_arg (t,ARG_QUOTED , arglist); + is_arg =try_arg (t,ARG_QUOTED , args);if (state ==1 && is_arg) { state = is_arg;
@@ -1304,8 +1288,9 @@ Econcat:return NULL ; } -static struct token *parse_expansion (struct token *expansion,struct token *arglist,struct ident *name) +static struct token *parse_expansion (struct token *expansion,struct ident *name) { +struct arg_state args[macro_nargs] = {};struct token *token = expansion;struct token **p;
@@ -1314,19 +1299,30 @@ static struct token *parse_expansion(struct token *expansion, struct token *arglfor (p = &expansion; !eof_token (token); p = &token->next, token = *p) {if (match_op (token,'#' )) { - token =handle_hash (p, arglist); + token =handle_hash (p, args);if (!token)return NULL ; }if (match_op (token->next,SPECIAL_HASHHASH )) { - token =handle_hashhash (token, arglist); + token =handle_hashhash (token, args);if (!token)return NULL ; }else { -try_arg (token,ARG_NORMAL , arglist); +try_arg (token,ARG_NORMAL , args); + } + } +for (int i =0 ; i < macro_nargs; i++) { +if (args[i].needs_str) + args[i].needs_str->argnum |=1 <<ARGNUM_CONSUME ; +if (args[i].needs_expanded) + args[i].needs_expanded->argnum |=1 <<ARGNUM_CONSUME ; +if (args[i].needs_raw) { +struct token *p = args[i].needs_raw; +if (argkind (p) ==ARG_QUOTED ) + p->argnum |=1 <<ARGNUM_CONSUME ; +else if (argkind (p) ==ARG_NORMAL ) + p->argnum |=1 <<ARGNUM_CONSUME_EXPAND ; } -if (token_type (token) ==TOKEN_ERROR ) - goto Earg; } token =alloc_token (&expansion->pos);token_type (token) =TOKEN_UNTAINT ;
@@ -1338,9 +1334,6 @@ static struct token *parse_expansion(struct token *expansion, struct token *argl Econcat:sparse_error (token->pos,"'##' cannot appear at the ends of macro expansion" );return NULL ; -Earg: -sparse_error (token->pos,"too many instances of argument in body" ); -return NULL ; } static int do_define(struct position pos, struct token *token, struct ident *name,
@@ -1349,7 +1342,7 @@ static int do_define(struct position pos, struct token *token, struct ident *namstruct symbol *sym;int ret =1 ; - expansion =parse_expansion (expansion, arglist, name); + expansion =parse_expansion (expansion, name);if (!expansion) goto out;
token.h +6 -2
@@ -182,13 +182,17 @@ enum arg_kind { };enum { -ARGNUM_BITS_STOLEN =2 +ARGNUM_CONSUME =2 , +ARGNUM_CONSUME_EXPAND , +ARGNUM_BITS_STOLEN };enum { -ARGNUM_KIND_MASK =3 +ARGNUM_KIND_MASK = (1 <<ARGNUM_CONSUME ) -1 }; +// _Static_assert(ARGNUM_KIND_MASK >= ARG_STR) +/* * This is a very common data structure, it should be kept * as small as humanly possible. Big (rare) types go as
Signature · 1 line
2.47.3
PATCH 11/21 kill create_arglist()
In reply to Al Virowe don't need the fake arglist for __has_extension() and its ilk anymore; just set the ->arglist to &eof_token_entry to indicate that arguments are expected and set ->fixed_args and ->vararg to tell how much.
--- pre-process.c | 37 +++++-------------------------------- 1 file changed, 5 insertions(+), 32 deletions(-)
pre-process.c +5 -32
@@ -2071,36 +2071,6 @@ static bool expand_has_feature(struct token *token, struct arg *args)return 1 ; } -static void create_arglist (struct symbol *sym,int count) -{ -struct token *token; -struct token **next; - -if (!count) -return ; - - token =__alloc_token (0 ); -token_type (token) =TOKEN_ARG_COUNT ; - sym->arglist = token; - sym->fixed_args = count; - sym->vararg =0 ; - next = &token->next; - -while (count--) { -struct token *id, *uses; - id =__alloc_token (0 ); -token_type (id) =TOKEN_IDENT ; - uses =__alloc_token (0 ); -token_type (uses) =TOKEN_ARG_COUNT ; - uses->count.quoted =1 ; - - *next = id; - id->next = uses; - next = &uses->next; - } - *next = &eof_token_entry; -} -static void init_preprocessor (void ) {int i;
@@ -2172,8 +2142,11 @@ static void init_preprocessor(void)struct symbol *sym; sym =create_symbol (stream, dynamic[i].name,SYM_NODE ,NS_MACRO ); sym->expand_simple = dynamic[i].expand_simple; -if ((sym->expand = dynamic[i].expand) !=NULL ) -create_arglist (sym,1 ); +if ((sym->expand = dynamic[i].expand) !=NULL ) { + sym->fixed_args =1 ; + sym->vararg = false; + sym->arglist = &eof_token_entry; + } } counter_macro =0 ;
Signature · 1 line
2.47.3
PATCH 12/21 stop mangling arglist, get rid of TOKEN_ARG_COUNT
In reply to Al ViroNow it can be done - we no longer store the counters in arglist, so there's no reason to mangle it. Just have it return the pointer to closing ) on success and let the caller split the list at that point. Simplifies both the parse_arguments() and dump_macro() and fixes a bug in the latter - pre-C99 gcc vararg macros used to lose ... in -dM output. They did work correctly, but dump_macro() output had produced #define A(X,Y) instead of correct #define A(X,Y...) Testcase added.
--- pre-process.c | 47 +++++++--------------------- token.h | 9 ------ tokenize.c | 4 --- validation/preprocessor/dump-macro.c | 4 ++- 4 files changed, 15 insertions(+), 49 deletions(-)
pre-process.c +12 -35
@@ -1000,7 +1000,6 @@ static int token_different(struct token *t1, struct token *t2)case TOKEN_IDENT : different = t1->ident != t2->ident;break ; -case TOKEN_ARG_COUNT :case TOKEN_UNTAINT :case TOKEN_CONCAT :case TOKEN_GNU_KLUDGE :
@@ -1077,22 +1076,12 @@ Eargs:return false; } -static inline void set_arg_count (struct token *token) -{ -token_type (token) =TOKEN_ARG_COUNT ; -} -static struct token *parse_arguments (struct token *list) {struct token *arg = list->next, *next = list; -set_arg_count (list); - -if (match_op (arg,')' )) { - next = arg->next; - list->next = &eof_token_entry; -return next; - } +if (match_op (arg,')' )) +return arg;while (token_type (arg) ==TOKEN_IDENT ) {if (arg->ident == &__VA_ARGS___ident)
@@ -1102,26 +1091,18 @@ static struct token *parse_arguments(struct token *list) next = arg->next;if (match_op (next,',' )) { -set_arg_count (next); arg = next->next;continue ; } -if (match_op (next,')' )) { -set_arg_count (next); - next = next->next; - arg->next->next = &eof_token_entry; +if (match_op (next,')' ))return next; - }/* normal cases are finished here */ if (match_op (next,SPECIAL_ELLIPSIS )) {if (match_op (next->next,')' )) { -set_arg_count (next); macro_vararg = macro_nargs -1 ; - next = next->next; - arg->next->next = &eof_token_entry;return next->next; }
@@ -1143,10 +1124,7 @@ static struct token *parse_arguments(struct token *list) goto Enotclosed;if (!macro_add_arg (arg->pos, &__VA_ARGS___ident))return NULL ; -set_arg_count (next); macro_vararg = macro_nargs -1 ; - next = next->next; - arg->next->next = &eof_token_entry;return next; }
@@ -1483,14 +1461,19 @@ static int do_handle_define(struct stream *stream, struct token **line, struct t expansion = left->next;if (!expansion->pos.whitespace) {if (match_op (expansion,'(' )) { - arglist = expansion; - expansion =parse_arguments (expansion); -if (!expansion) { +struct token *last =parse_arguments (expansion); +if (!last) { macro_nargs =0 ; macro_vararg =-1 ;return 1 ; } +// last points to ) at the end of arguments, +// expansion starts right after that, +// everything up to that point is arglist. macro_funclike = true; + arglist = expansion; + expansion = last->next; + last->next = &eof_token_entry; }else if (!eof_token (expansion)) {warning (expansion->pos,"no whitespace before object-like macro body" );
@@ -2281,20 +2264,14 @@ static void dump_macro(struct symbol *sym)printf ("#define %s" ,show_ident (sym->ident)); token = sym->arglist;if (token) { -const char *sep ="" ;int narg =0 ; -putchar ('(' );for (; !eof_token (token); token = token->next) { -if (token_type (token) ==TOKEN_ARG_COUNT ) -continue ; -printf ("%s%s" , sep,show_token (token)); +printf ("%s" ,show_token (token));if (token_type (token) ==TOKEN_IDENT ) args[narg++] = token->ident; - sep ="," ; }if (narg < nargs) args[narg] = &__VA_ARGS___ident; -putchar (')' ); } token = sym->expansion;
token.h +0 -9
@@ -103,7 +103,6 @@ enum token_type {TOKEN_CONCAT ,TOKEN_GNU_KLUDGE ,TOKEN_UNTAINT , -TOKEN_ARG_COUNT ,TOKEN_IF ,TOKEN_SKIP_GROUPS , TOKEN_ELSE,
@@ -168,13 +167,6 @@ struct string {char data[]; }; -/* will fit into 32 bits */ -struct argcount { -unsigned normal:10 ; -unsigned quoted:10 ; -unsigned str:10 ; -}; -enum arg_kind {ARG_QUOTED =0 ,ARG_NORMAL =1 ,
@@ -207,7 +199,6 @@ struct token {unsigned int special;struct string *string;int argnum; -struct argcount count;char embedded[4 ]; }; };
tokenize.c +0 -4
@@ -241,10 +241,6 @@ const char *show_token(const struct token *token)sprintf (buffer,"<untaint>" );return buffer; -case TOKEN_ARG_COUNT : -sprintf (buffer,"<argcnt>" ); -return buffer; -default :sprintf (buffer,"unhandled token type '%d' " ,token_type (token));return buffer;
validation/preprocessor/dump-macro.c +3 -1
@@ -1,9 +1,11 @@#define A (X ,Y ,...) __VA_ARGS__,Y,X +#define B(X,Y...) Y/* * check-name: -dM handling of varargs -* check-command: sparse -E -dM $file | tail -1 +* check-command: sparse -E -dM $file | tail -2 * * check-output-start #define A(X,Y,...) __VA_ARGS__,Y,X +#define B(X,Y...) Y * check-output-end */
Signature · 1 line
2.47.3
PATCH 13/21 deal with ## on arguments separately
In reply to Al ViroAdding/concatenating the chunks to growing expansion is done in the end of loop body in substitute(); preceding switch leaves the data for it in two variables - 'added' is the first token of the next chunk and 'tail' points to the forward pointer in the last token of that chunk.
The only case when we might be adding more than one token is macro argument; forcing it to use the same path as everything else complicates things for no good reason, especially when it comes to concatenation.
Let the TOKEN_MACRO_ARGUMENT case deal with that stuff on its own. In case of concatenation let it merge the first token before copying/inserting the rest; that simplifies the common case and it simplifies the data flow for everyone since we don't need to bother with 'tail' anymore.
As a side benefit, merge() is no longer inlined, which reduces the spills.
That chunk could go after __VA_OPT__ handling, but having it done first simplifies the things for __VA_OPT__ (and especially for #__VA_OPT__()), so let's put that one first.
--- pre-process.c | 38 +++++++++++++++++++++++--------------- 1 file changed, 23 insertions(+), 15 deletions(-)
pre-process.c +23 -15
@@ -650,7 +650,7 @@ static struct token **substitute(struct token **list, const struct token *body,for (; !eof_token (body); body = body->next) {struct token *added, *arg; -struct token **tail; +struct token **inserted_at;const struct token *t;switch (token_type (body)) {
@@ -674,7 +674,6 @@ static struct token **substitute(struct token **list, const struct token *body, } added =dup_token (t, base_pos);token_type (added) =TOKEN_SPECIAL ; - tail = &added->next;break ;case TOKEN_MACRO_ARGUMENT :
@@ -686,13 +685,28 @@ static struct token **substitute(struct token **list, const struct token *body, state = Placeholder;continue ; } +if (state == Concat &&merge (containing_token (list), arg)) { + arg = arg->next; +if (eof_token (arg)) { +// merged the sole token in + state = Normal; +continue ; + } + inserted_at =NULL ; + }else { + inserted_at = list; + }if (body->argnum & (1 <<ARGNUM_CONSUME )) - tail =move_into (&added, arg); + list =move_into (list, arg);else - tail =copy (&added, arg); - added->pos.newline = body->pos.newline; - added->pos.whitespace = body->pos.whitespace; -break ; + list =copy (list, arg); +if (inserted_at) { +struct token *p = *inserted_at; + p->pos.whitespace = body->pos.whitespace; + p->pos.newline =0 ; + } + state = Normal; +continue ;case TOKEN_CONCAT :if (state == Placeholder)
@@ -703,7 +717,6 @@ static struct token **substitute(struct token **list, const struct token *body,default : added =dup_token (body, base_pos); - tail = &added->next;break ; }
@@ -711,17 +724,12 @@ static struct token **substitute(struct token **list, const struct token *body,* if we got to doing real concatenation, we already have * added something into the list, so containing_token() is OK. */ -if (state == Concat &&merge (containing_token (list), added)) { - *list = added->next; -if (tail != &added->next) - list = tail; - }else { +if (state != Concat || !merge (containing_token (list), added)) { *list = added; - list = tail; + list = &added->next; } state = Normal; } - *list = &eof_token_entry;return list; }
Signature · 1 line
2.47.3
PATCH 14/21 preparations for __VA_OPT__ support: reshuffle argument slot assignments
In reply to Al ViroMove the vararg to slot 0, with the non-vararg arguments in slots 1..fixed_args; for macros with vararg arguments leave slot 0 unused.
Rationale: handling of __VA_OPT__ at expansion time will need to locate the vararg; having it always in the same slot makes life easier.
--- pre-process.c | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-)
pre-process.c +18 -16
@@ -321,7 +321,7 @@ static int collect_arguments(struct token *start, struct symbol *sym, struct arg next =collect_arg (start, false, &what->pos);if (token_type (next) !=TOKEN_SPECIAL ) goto Eclosing; - args[commas].arg[ARG_QUOTED ] = start->next; + args[commas +1 ].arg[ARG_QUOTED ] = start->next;if (!match_op (next,',' )) {if (commas < fixed -1 ) goto Efew;
@@ -340,7 +340,7 @@ static int collect_arguments(struct token *start, struct symbol *sym, struct argif (v && !vararg) goto Eexcess;if (vararg) - args[fixed].arg[ARG_QUOTED ] = v; + args[0 ].arg[ARG_QUOTED ] = v; what->next = next->next;return 1 ;
@@ -740,8 +740,7 @@ static int expand(struct token **list, struct symbol *sym)struct ident *expanding = token->ident;struct token **tail;struct token *expansion = sym->expansion; -int nargs = sym->fixed_args + sym->vararg; -struct arg args[nargs]; +struct arg args[sym->fixed_args +1 ];if (expanding->tainted) { token->pos.noexpand =1 ;
@@ -1181,6 +1180,7 @@ static int try_arg(struct token *token, enum arg_kind kind, struct arg_state argif (nr == macro_nargs)return 0 ; + nr = nr == macro_vararg ?0 : nr +1 ; token->argnum = (nr <<ARGNUM_BITS_STOLEN ) | kind;token_type (token) =TOKEN_MACRO_ARGUMENT ;switch (kind) {
@@ -1197,7 +1197,7 @@ static int try_arg(struct token *token, enum arg_kind kind, struct arg_state arg args[nr].needs_raw = token; args[nr].needs_str = token; } -return nr == macro_vararg ?2 :1 ; +return nr ==0 ?2 :1 ; }static struct token *handle_hash (struct token **p,struct arg_state args[])
@@ -1276,7 +1276,8 @@ Econcat:static struct token *parse_expansion (struct token *expansion,struct ident *name) { -struct arg_state args[macro_nargs] = {}; +int slots = macro_nargs + (macro_vararg <0 ); +struct arg_state args[slots] = {};struct token *token = expansion;struct token **p;
@@ -1297,7 +1298,7 @@ static struct token *parse_expansion(struct token *expansion, struct ident *nametry_arg (token,ARG_NORMAL , args); } } -for (int i =0 ; i < macro_nargs; i++) { +for (int i =0 ; i < slots; i++) {if (args[i].needs_str) args[i].needs_str->argnum |=1 <<ARGNUM_CONSUME ;if (args[i].needs_expanded)
@@ -1975,7 +1976,7 @@ static int handle_nondirective(struct stream *stream, struct token **line, strucstatic struct token *first_arg (struct arg *args) { -struct token *arg = args[0 ].arg[ARG_QUOTED ]; +struct token *arg = args[1 ].arg[ARG_QUOTED ];expand_list (&arg);return arg; }
@@ -2265,21 +2266,22 @@ struct token * preprocess(struct token *token)static void dump_macro (struct symbol *sym) { -int nargs = sym->fixed_args + sym->vararg; -struct ident *args[nargs]; +int fixed_args = sym->fixed_args; +struct ident *args[fixed_args +1 ];struct token *token;printf ("#define %s" ,show_ident (sym->ident)); token = sym->arglist;if (token) { -int narg =0 ; -for (; !eof_token (token); token = token->next) { + args[0 ] = &__VA_ARGS___ident; +for (int n =1 ; !eof_token (token); token = token->next) {printf ("%s" ,show_token (token)); -if (token_type (token) ==TOKEN_IDENT ) - args[narg++] = token->ident; +if (token_type (token) ==TOKEN_IDENT ) { + args[n] = token->ident; +if (n++ == fixed_args) + n =0 ; + } } -if (narg < nargs) - args[narg] = &__VA_ARGS___ident; } token = sym->expansion;
Signature · 1 line
2.47.3
PATCH 15/21 pre-process.c: split try_arg()
In reply to Al Viromore __VA_OPT__ preparations - we want to split the "parse the possible variable" from the parts that are sensitive to the kind of variable access (in particular, to subsequent ## being or not being there). With __VA_OPT__ we'll have a possibility of relevant ## being a lot further ahead than the next token and we won't find it until we'd parsed the entire __VA_OPT__(.....).
We could check for __VA_OPT__ _before_ checking for arguments, but that ends up screwing code generation a lot, slowing down the normal case where we've not a single __VA_OPT__ in the input.
Replace try_arg() with two new primitives:
* check_arg() - returns 0 if the next token is not an argument;
if the token is an argument, it gets converted to TOKEN_MACRO_ARGUMENT and slot number + 1 is returned. That function gets only token and arg_state array - 'kind' is not known yet. At the moment 'args' is not needed, but it will be needed for __VA_OPT__ handling, so that argument stays. Note that unlike try_arg() we don't need a special return value to tell vararg from non-vararg argument - the slot number is sufficient now. It's a vararg if and only if it occupies slot 0, i.e. if check_arg() has returned 1.
* seen_arg() - gets called only for TOKEN_MACRO_ARGUMENT token,
does the rest of what try_arg() used to do. Returns void.
Calls of try_arg() are replaced with combinations of these two, the first try_arg() in handle_hashhash() lifted into the only caller of handle_hashhash() and its check_arg() folded with the one we do for non-## case there.
--- pre-process.c | 37 ++++++++++++++++++++++++++----------- 1 file changed, 26 insertions(+), 11 deletions(-)
pre-process.c +26 -11
@@ -1166,7 +1166,7 @@ struct arg_state {struct token *needs_str; }; -static int try_arg (struct token *token,enum arg_kind kind,struct arg_state args[]) +static int check_arg (struct token *token,struct arg_state args[]) {struct ident *ident = token->ident;int nr;
@@ -1181,8 +1181,14 @@ static int try_arg(struct token *token, enum arg_kind kind, struct arg_state argreturn 0 ; nr = nr == macro_vararg ?0 : nr +1 ; - token->argnum = (nr <<ARGNUM_BITS_STOLEN ) | kind; + token->argnum = nr <<ARGNUM_BITS_STOLEN ;token_type (token) =TOKEN_MACRO_ARGUMENT ; +return nr +1 ; +} + +static void seen_arg (struct token *token,enum arg_kind kind,struct arg_state args[],int nr) +{ + token->argnum |= kind;switch (kind) {case ARG_QUOTED : args[nr].needs_raw = token;
@@ -1197,7 +1203,6 @@ static int try_arg(struct token *token, enum arg_kind kind, struct arg_state arg args[nr].needs_raw = token; args[nr].needs_str = token; } -return nr ==0 ?2 :1 ; }static struct token *handle_hash (struct token **p,struct arg_state args[])
@@ -1205,8 +1210,12 @@ static struct token *handle_hash(struct token **p, struct arg_state args[])struct token *token = *p;if (macro_funclike) {struct token *next = token->next; -if (!try_arg (next,ARG_STR , args)) +int nr =check_arg (next, args); + +if (!nr) goto Equote; + +seen_arg (next,ARG_STR , args, nr -1 ); next->pos.whitespace = token->pos.whitespace;__free_token (token); token = *p = next;
@@ -1226,12 +1235,10 @@ static struct token *handle_hashhash(struct token *token, struct arg_state args[struct token *last = token;struct token *concat;int state =match_op (token,',' ); - -try_arg (token,ARG_QUOTED , args); +int nr;while (1 ) {struct token *t; -int is_arg;/* eat duplicate ## */ concat = token->next;
@@ -1251,10 +1258,13 @@ static struct token *handle_hashhash(struct token *token, struct arg_state args[return NULL ; } - is_arg =try_arg (t,ARG_QUOTED , args); + nr =check_arg (t, args); +if (nr >0 ) +seen_arg (t,ARG_QUOTED , args, nr -1 ); -if (state ==1 && is_arg) { - state = is_arg; +if (state ==1 && nr >0 ) { +if (nr ==1 ) + state =2 ; }else { last = t; state =match_op (t,',' );
@@ -1280,6 +1290,7 @@ static struct token *parse_expansion(struct token *expansion, struct ident *namestruct arg_state args[slots] = {};struct token *token = expansion;struct token **p; +int nr;if (match_op (token,SPECIAL_HASHHASH )) goto Econcat;
@@ -1290,12 +1301,16 @@ static struct token *parse_expansion(struct token *expansion, struct ident *nameif (!token)return NULL ; } + nr =check_arg (token, args);if (match_op (token->next,SPECIAL_HASHHASH )) { +if (nr >0 ) +seen_arg (token,ARG_QUOTED , args, nr -1 ); token =handle_hashhash (token, args);if (!token)return NULL ; }else { -try_arg (token,ARG_NORMAL , args); +if (nr >0 ) +seen_arg (token,ARG_NORMAL , args, nr -1 ); } }for (int i =0 ; i < slots; i++) {
Signature · 1 line
2.47.3
PATCH 16/21 __VA_OPT__: parsing
In reply to Al Virova-opt-replacement can occur in any place where a macro argument of a vararg macro might. It consists of identifier __VA_OPT__, followed by '(', a sequence of pp-tokens with balanced parentheses (body of that va-opt-replacement) and finally a ')'.
Body of va-opt-replacement may not contain __VA_OPT__ and may not begin or end with a ##.
At the expansion time va-opt-replacement is handled at the same stage as argument substitution. What happens depends upon the value of __VA_ARGS__
- if it would expand to an empty token sequence, each va-opt-replacement in the body is treated the same way as an occurrence of an empty argument (replaced by an empty string literal if preceded by a # operator and by placemarker token otherwise).
If __VA_ARGS__ does *not* expand to an empty token sequence, the body of va-opt-replacement is subjected to argument substitution and # processing, as if it had been the entire macro body. Leading and trailing whitespace is stripped from the result. If va-opt-replacement is not preceded by a # operator, the resulting list is substituted in its place. If it *is* preceded by a # operator, the resulting list is subjected to ## processing/placemarker removal and converted into a string literal token. That token is substituted in place of # va-opt-replacement combination.
All of that is followed by usual processing of remaining ## operators and placemarker removal (we are, of course, allowed to calculate the individual token concatenations earlier, provided that end result is the same).
For non-stringified instances it's _almost_ the same as if all va-opt-replacements had been replaced with their bodies in case when __VA_ARGS__ expands to non-empty sequence of tokens; the only difference is that ## next to va-opt-replacement does not suppress expansion of arguments inside; for example
#define FOO BAR #define A(X) X ## 1 // X is not expanded #define B(X,...) __VA_OPT__(X) ## 1 // X is expanded A(FOO) B(FOO,_) B(FOO) yields FOO1 BAR1 1
Any ## inside the va-opt-replacement still have the usual effect on the adjacent macro arguments.
In other words, for non-stringified __VA_OPT__ we can simply
* parse its body as if it had been an entire macro (with the
usual handling of arguments)
* when substitute() gets to va-opt-replacement, check if expansion
of __VA_ARGS__ is empty
* if it is, just do what we do when seeing an empty argument,
otherwise switch to taking tokens to interpret from the body of that va-opt-replacement until we reach its end, then proceed to interpret the rest of the body of our macro.
For stringified __VA_OPT__ we need to save the state of interpreter (body, list, state), switch to (body of va-opt-replacement, private list, Normal) and once we are done stringify the private list, restore the saved state and add the string token we've got to the main list, same as usual.
Note on whitespace handling: whitespace in front of the first token coming from va-opt-replacement is _not_ affected by whatever whitespace we might have between __VA_OPT__ and '(' or '(' and the body; only the whitespace preceding the __VA_OPT__ itself matters.
Representation:
* new token types: TOKEN_VA_OPT and TOKEN_VA_OPT_STR; va-opt-replacement and # va-opt-replacement resp. get converted to that, with the body + surrounding parentheses stripped from the list and reference to the opening parenthesis stored into ->va_opt_linkage of the converted __VA_OPT__ token.
Closing parenthesis is converted to TOKEN_VA_OPT; its ->next points to eof_token_entry to make it distinguishable from the normal TOKEN_VA_OPT and its ->va_opt_linkage points back to the originating TOKEN_VA_OPT or TOKEN_VA_OPT_STR - basically, that will serve as return instruction. We could add a separate token type for that, but that would only make things more inconvenient at expansion time.
Note that in all cases ->va_opt_linkage points to the token immediately preceding the ones we should proceed to; that will simplify life at expansion time.
This commit contains the parser side of the things. Substitution side is done in the next one.
* check_arg() taught to recognize and parse __VA_OPT__(...); returns -1 on failure and 0 (not an argument of macro) on success. Callers updated.
* dump_macro() and token_list_different() taught to handle those.
--- ident-list.h | 1 + pre-process.c | 233 ++++++++++++++++++----- token.h | 3 + validation/preprocessor/dump-macro.c | 4 +- validation/preprocessor/va_opt_compare.c | 28 +++ validation/preprocessor/va_opt_parse.c | 37 ++++ 6 files changed, 258 insertions(+), 48 deletions(-) create mode 100644 validation/preprocessor/va_opt_compare.c create mode 100644 validation/preprocessor/va_opt_parse.c
ident-list.h +1 -0
@@ -65,6 +65,7 @@ IDENT(c_generic_selections);IDENT (c_static_assert);__IDENT (pragma_ident,"__pragma__" ,0 );__IDENT (__VA_ARGS___ident,"__VA_ARGS__" ,0 ); +__IDENT (__VA_OPT___ident,"__VA_OPT__" ,0 );__IDENT (__func___ident,"__func__" ,0 );__IDENT (__FUNCTION___ident,"__FUNCTION__" ,0 );__IDENT (__PRETTY_FUNCTION___ident,"__PRETTY_FUNCTION__" ,0 );
pre-process.c +186 -47
343 lines not on this page · raw message
token.h +3 -0
@@ -102,6 +102,8 @@ enum token_type {TOKEN_MACRO_ARGUMENT ,TOKEN_CONCAT ,TOKEN_GNU_KLUDGE , +TOKEN_VA_OPT , +TOKEN_VA_OPT_STR ,TOKEN_UNTAINT ,TOKEN_IF , TOKEN_SKIP_GROUPS,
@@ -199,6 +201,7 @@ struct token {unsigned int special;struct string *string;int argnum; +struct token *va_opt_linkage;char embedded[4 ]; }; };
validation/preprocessor/dump-macro.c +3 -1
@@ -1,11 +1,13 @@#define A (X ,Y ,...) __VA_ARGS__,Y,X #define B(X,Y...) Y +#define C (...) __VA_OPT__(1 #__VA_ARGS__) #__VA_OPT__(1 __VA_ARGS__)/* * check-name: -dM handling of varargs -* check-command: sparse -E -dM $file | tail -2 +* check-command: sparse -E -dM $file | tail -3 * * check-output-start #define A(X,Y,...) __VA_ARGS__,Y,X #define B(X,Y...) Y +#define C(...) __VA_OPT__(1 #__VA_ARGS__) #__VA_OPT__(1 __VA_ARGS__) * check-output-end */
validation/preprocessor/va_opt_compare.c new file +28 -0
@@ -0,0 +1,28 @@ +#define OK1 (X ,...) __VA_OPT__(X =) +#define OK1 (X ,...) __VA_OPT__(X =) +#define OK2 (X ,...) #__VA_OPT__(X =) +#define OK2 (X ,...) #__VA_OPT__(X =) +#define BAD1 (X ,...) __VA_OPT__(X) +#define BAD1 (X ,...) __VA_OPT__(_) +#define BAD2 (X ,...) __VA_OPT__(,) +#define BAD2 (X ,...) , +#define BAD3 (X ,...) __VA_OPT__(,) +#define BAD3 (X ,...) #__VA_OPT__(,) +/* +* check-name: __VA_OPT__ comparison +* check-command: sparse -E $file +* +* check-output-start + + +* check-output-end +* +* check-error-start +preprocessor/va_opt_compare.c:6:9: warning: preprocessor token BAD1 redefined +preprocessor/va_opt_compare.c:5:9: this was the original definition +preprocessor/va_opt_compare.c:8:9: warning: preprocessor token BAD2 redefined +preprocessor/va_opt_compare.c:7:9: this was the original definition +preprocessor/va_opt_compare.c:10:9: warning: preprocessor token BAD3 redefined +preprocessor/va_opt_compare.c:9:9: this was the original definition +* check-error-end +*/
validation/preprocessor/va_opt_parse.c new file +37 -0
@@ -0,0 +1,37 @@ +#define A (__VA_OPT__) +#define B (X ) __VA_OPT__(_) +#define C (X ,...) __VA_OPT__(__VA_OPT__(_)) +#define D (X ,...) __VA_OPT__ +#define E (X ,...) __VA_OPT__(_ +#define OK (X ,...) __VA_OPT__() +#define OK2 (X ,...) __VA_OPT__(,(,,),) +#define F (X ,...) __VA_OPT__(,(,,,) +#define OK3 (X ,...) __VA_OPT__(,(,,),)) +#define G1 (...) __VA_OPT__(##) +#define G2 (...) __VA_OPT__(##,) +#define G3 (...) __VA_OPT__(,##) +#define H (...) __VA_OPT__(#1) +#define OK4 (X ,...) __VA_OPT__(__VA_ARGS__,#X) +#define OK5 (X ,...) #__VA_OPT__(__VA_ARGS__,#X) +/* +* check-name: __VA_OPT__ parsing +* check-command: sparse -E $file +* +* check-output-start + + +* check-output-end +* +* check-error-start +preprocessor/va_opt_parse.c:1:11: error: __VA_OPT__ can only appear in the expansion of a C99 variadic macro +preprocessor/va_opt_parse.c:2:14: error: __VA_OPT__ can only appear in the expansion of a C99 variadic macro +preprocessor/va_opt_parse.c:3:29: error: __VA_OPT__ may not appear in a __VA_OPT__ +preprocessor/va_opt_parse.c:4:18: error: unterminated __VA_OPT__ +preprocessor/va_opt_parse.c:5:18: error: unterminated __VA_OPT__ +preprocessor/va_opt_parse.c:8:18: error: unterminated __VA_OPT__ +preprocessor/va_opt_parse.c:10:28: error: '##' cannot appear at the ends of macro expansion +preprocessor/va_opt_parse.c:11:28: error: '##' cannot appear at the ends of macro expansion +preprocessor/va_opt_parse.c:12:29: error: '##' cannot appear at the ends of macro expansion +preprocessor/va_opt_parse.c:13:27: error: '#' is not followed by a macro parameter +* check-error-end +*/
Signature · 1 line
2.47.3
PATCH 17/21 expansion-time va_opt handling
In reply to Al ViroTeach the interpreter (== substitute()) to handle TOKEN_VA_OPT and TOKEN_VA_OPT_STR.
Two tricky parts, both related to calculating when an argument can be consumed. One is that in situation like
#define A(x,...) __VA_OPT__(x) foo_##x x
we might end up doing expansion of x either at the 1st occurrence (inside __VA_OPT__) or at the 1st one _not_ inside __VA_OPT__ (the 3rd one in in this example). So at parsing time we need to keep track of whether we'd already seen an unconditional use of expanded form and similarly for stringified one.
Another is that getting to the first __VA_OPT__ means that
we need to find out whether the expanded form of __VA_ARGS__ is empty. If there'd been a prior expanding occurrence of __VA_ARGS__, we are fine; if there hadn't, we need to make sure that unexpanded form survives at least until that point.
--- pre-process.c | 106 +++++++++++++++++++- validation/preprocessor/va_opt.c | 54 ++++++++++ validation/preprocessor/va_opt2.c | 34 +++++++ validation/preprocessor/va_opt_whitespace.c | 14 +++ 4 files changed, 204 insertions(+), 4 deletions(-) create mode 100644 validation/preprocessor/va_opt.c create mode 100644 validation/preprocessor/va_opt2.c create mode 100644 validation/preprocessor/va_opt_whitespace.c
pre-process.c +102 -4
@@ -419,6 +419,18 @@ static struct token *stringify(struct token *arg)return token; } +static struct token *empty_string (const struct position *pos) +{ +struct token *token =__alloc_token (0 ); +static struct string empty = {.immutable =1 , .length =1 , .data ="" }; + + token->pos = *pos; +token_type (token) =TOKEN_STRING ; + token->string = ∅ + token->next = &eof_token_entry; +return token; +} +/* * Possibly valid combinations: * - ident + ident -> ident
@@ -645,11 +657,28 @@ static bool is_end_va_opt(const struct token *token)return eof_token (token->next); } +static bool skip_va_opt (struct arg *args,struct ident *expanding) +{ +struct token *arg = args[0 ].arg[ARG_NORMAL ]; +if (arg) +return eof_token (arg); + arg = args[0 ].arg[ARG_QUOTED ]; +if (!arg ||eof_token (arg)) +return true; + arg =dup_list (arg); + expanding->tainted =0 ; +expand_list (&arg); + expanding->tainted =1 ; + args[0 ].arg[ARG_NORMAL ] = arg; +return eof_token (arg); +} +static struct token **substitute (struct token **list,const struct token *body,struct arg *args) {struct position *base_pos = &(*list)->pos; -enum {Normal, Placeholder, Concat} state = Normal; +enum {Normal, Placeholder, Concat} state = Normal, saved_state = Normal;struct ident *expanding = (*list)->ident; +struct token **saved_list =NULL , *va_opt_list; expanding->tainted =1 ;
@@ -720,6 +749,47 @@ static struct token **substitute(struct token **list, const struct token *body, state = Concat;continue ; +case TOKEN_VA_OPT : +// entering va_opt? +if (!is_end_va_opt (body)) { +if (skip_va_opt (args, expanding)) { +if (state == Concat) + state = Normal; +else + state = Placeholder; +continue ; + } + body = body->va_opt_linkage; +continue ; + } + body = body->va_opt_linkage; +// leaving va_opt? +if (token_type (body) ==TOKEN_VA_OPT ) +continue ; +// leaving #va_opt +if (list == &va_opt_list) { + added =empty_string (base_pos); + }else { + *list = &eof_token_entry; + added =stringify (va_opt_list); + } + list = saved_list; + state = saved_state; +break ; + +case TOKEN_VA_OPT_STR : +// entering #va_opt +if (!skip_va_opt (args, expanding)) { + saved_state = state; + state = Normal; + saved_list = list; + list = &va_opt_list; + body = body->va_opt_linkage; +continue ; + } + added =empty_string (base_pos); +break ; +default : added =dup_token (body, base_pos);break ;
@@ -1202,9 +1272,11 @@ struct arg_state {struct token *needs_raw;struct token *needs_expanded;struct token *needs_str; +bool seen_uncond_expand; +bool seen_uncond_str; }; -static bool in_va_opt; +static bool in_va_opt, seen_va_opt;static struct token **parse_body (struct token **list,struct arg_state args[]);
@@ -1221,6 +1293,23 @@ static int parse_va_opt(struct token *token, struct arg_state args[])if (!match_op (next,'(' )) goto Eunterminated; +if (!seen_va_opt) { +/* +* The first __VA_OPT__() will need an expanded __VA_ARGS__. +* if we had no prior expanded occurrences of __VA_ARGS__, +* we'll need its unexpanded form to survive until that point. +* Only the cannibalization of unexpended form needs to be +* prevented; cannibalization of expanded form doesn't matter. +* We only want to know if it's an empty list, i.e. equal to +* &eof_token_entry, and the pointer stored in struct args +* ->arg[ARG_NORMAL] doesn't change when we get to the last +* expanded occurrence of __VA_ARGS__ and consume the list +* it's pointing to. +*/ +if (!args[0 ].needs_expanded) + args[0 ].needs_raw = token; + seen_va_opt = true; + }token_type (token) =TOKEN_VA_OPT ; token->va_opt_linkage = next; next->next->pos.whitespace = token->pos.whitespace;
@@ -1292,13 +1381,19 @@ static void seen_arg(struct token *token, enum arg_kind kind, struct arg_state a args[nr].needs_raw = token;break ;case ARG_NORMAL : -if (!args[nr].needs_expanded) +if (!args[nr].seen_uncond_expand && + (!in_va_opt || !args[nr].needs_expanded)) { + args[nr].seen_uncond_expand = !in_va_opt; args[nr].needs_raw = token; + } args[nr].needs_expanded = token;break ;default :// ARG_STR -if (!args[nr].needs_str) +if (!args[nr].seen_uncond_str && + (!in_va_opt || !args[nr].needs_str)) { + args[nr].seen_uncond_str = !in_va_opt; args[nr].needs_raw = token; + } args[nr].needs_str = token; } }
@@ -1436,6 +1531,7 @@ static struct token *parse_expansion(struct token *expansion, struct ident *namestruct token *token; tail =parse_body (&expansion, args); + seen_va_opt = false;if (!tail)return NULL ;for (int i =0 ; i < slots; i++) {
@@ -1445,6 +1541,8 @@ static struct token *parse_expansion(struct token *expansion, struct ident *name args[i].needs_expanded->argnum |=1 <<ARGNUM_CONSUME ;if (args[i].needs_raw) {struct token *p = args[i].needs_raw; +if (token_type (p) !=TOKEN_MACRO_ARGUMENT ) +continue ;if (argkind (p) ==ARG_QUOTED ) p->argnum |=1 <<ARGNUM_CONSUME ;else if (argkind (p) ==ARG_NORMAL )
validation/preprocessor/va_opt.c new file +54 -0
54 lines not on this page · raw message
validation/preprocessor/va_opt2.c new file +34 -0
@@ -0,0 +1,34 @@ +#define B (X ) 1 +// don't screw unexpanded __VA_ARGS__ on prior __VA_OPT__ +#define A (...) __VA_OPT__(1) A##__VA_ARGS__ +A (B (_)) +// tests for skipping __VA_OPT__ don't care if expanded __VA_ARGS__ +// has been already consumed +#define C (...) [__VA_ARGS__ __VA_OPT__(1)] +C (_) +C () +// don't cannibalize unexpanded __VA_ARGS__ too early +#define E (X ) +#define D (...) A##__VA_ARGS__ R __VA_OPT__(1) +D (E (_)) +// check that parser clears seen_va_opt on failure exit +#define BAD (...) __VA_OPT__(,) #1 +#define F (...) A##__VA_ARGS__ R __VA_OPT__(1) +F (E (_)) +/* +* check-name: __VA_ARGS__ cannibalization with __VA_OPT__ +* check-command: sparse -E $file +* +* check-output-start + +1 AB(_) +[_ 1] +[] +AE(_) R +AE(_) R +* check-output-end +* +* check-error-start +preprocessor/va_opt2.c:15:32: error: '#' is not followed by a macro parameter +* check-error-end +*/
validation/preprocessor/va_opt_whitespace.c new file +14 -0
@@ -0,0 +1,14 @@ +#define A (X ,...) [__VA_OPT__( X)][ __VA_OPT__(X)] +A (1 ,_) +/* +* check-name: __VA_OPT__ whitespace +* check-command: sparse -E $file +* +* check-output-start + +[1][ 1] +* check-output-end +* +* check-error-start +* check-error-end +*/
Signature · 1 line
2.47.3
PATCH 18/21 merge(): saner handling of ->noexpand
In reply to Al ViroWe only care about noexpand for identifiers and solitary #; the latter can't occur in merge(), the former should just get ->noexpand set according to ->ident->tainted. That eliminates the last remaining possibility of having expand() run into a token that has tainted identifier - the regular noexpand check in the caller is sufficient now. Should've done that all way back in 2004...
--- pre-process.c | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-)
pre-process.c +1 -9
@@ -507,7 +507,7 @@ static int merge(struct token *left, struct token *right)switch (res) {case TOKEN_IDENT : left->ident =built_in_ident (buffer); - left->pos.noexpand =0 ; + left->pos.noexpand = left->ident->tainted;return 1 ;case TOKEN_NUMBER :
@@ -529,13 +529,11 @@ static int merge(struct token *left, struct token *right)case TOKEN_WIDE_CHAR :case TOKEN_WIDE_STRING :token_type (left) = res; - left->pos.noexpand =0 ; left->string = right->string;return 1 ; case TOKEN_WIDE_CHAR_EMBEDDED_0 ... TOKEN_WIDE_CHAR_EMBEDDED_3:token_type (left) = res; - left->pos.noexpand =0 ;memcpy (left->embedded, right->embedded,4 );return 1 ;
@@ -812,16 +810,10 @@ static int expand(struct token **list, struct symbol *sym) {struct token *last;struct token *token = *list; -struct ident *expanding = token->ident;struct token **tail;struct token *expansion = sym->expansion;struct arg args[sym->fixed_args +1 ]; -if (expanding->tainted) { - token->pos.noexpand =1 ; -return 1 ; - } -if (sym->arglist) {if (!match_op (scan_next (&token->next),'(' ))return 1 ;
Signature · 1 line
2.47.3
PATCH 19/21 simplify the calling conventions of collect_arguments()
In reply to Al ViroCurrently we call that only after having verified that macro name is followed by the (, with those two tokens passed as separate arguments. What's more, collect_arguments() already can tell the caller "don't expand that" if the arguments are malformed, so there's no reason not to move the check for opening parenthesis into collect_arguments() - that makes the calling conventions simpler and it does not incur any cost - collect_arguments() is going to be inlined into its sole caller anyway.
--- pre-process.c | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-)
pre-process.c +11 -13
@@ -307,16 +307,17 @@ struct arg {struct token *arg[3 ]; }; -static int collect_arguments (struct token *start,struct symbol *sym,struct arg *args,struct token *what) +static int collect_arguments (struct token *what,int fixed,bool vararg,struct arg *args) { -int fixed = sym->fixed_args; -bool vararg = sym->vararg; +struct token *start =scan_next (&what->next);struct token *next =NULL , *v =NULL ;const char *err;int commas;memset (args,0 ,sizeof (struct arg ) * (fixed +1 )); +if (!match_op (start,'(' )) +return 0 ;for (commas =0 ; commas < fixed; commas++) { next =collect_arg (start, false, &what->pos);if (token_type (next) !=TOKEN_SPECIAL )
@@ -355,7 +356,7 @@ Eexcess: Eclosing: err ="unterminated argument list invoking" ; out: -sparse_error (what->pos,"%s macro \"%s\"" , err,show_ident (sym->ident)); +sparse_error (what->pos,"%s macro \"%s\"" , err,show_ident (what->ident)); what->next = next;return 0 ; }
@@ -808,23 +809,20 @@ static struct token **substitute(struct token **list, const struct token *body,static int expand (struct token **list,struct symbol *sym) { -struct token *last; +struct token *next;struct token *token = *list;struct token **tail;struct token *expansion = sym->expansion;struct arg args[sym->fixed_args +1 ]; -if (sym->arglist) { -if (!match_op (scan_next (&token->next),'(' )) -return 1 ; -if (!collect_arguments (token->next, sym, args, token)) -return 1 ; - } +if (sym->arglist && + !collect_arguments (token, sym->fixed_args, sym->vararg, args)) +return 1 ;if (sym->expand)return sym->expand (token, args) ?0 :1 ; - last = token->next; + next = token->next; tail =substitute (list, expansion, args);/* * Note that it won't be eof - at least TOKEN_UNTAINT will be there.
@@ -834,7 +832,7 @@ static int expand(struct token **list, struct symbol *sym)*/ (*list)->pos.newline = token->pos.newline; (*list)->pos.whitespace = token->pos.whitespace; - *tail = last; + *tail = next;return 0 ; }
Signature · 1 line
2.47.3
PATCH 20/21 make expand_one_symbol() inline
In reply to Al Virobetter code generation that way...
--- pre-process.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
pre-process.c +1 -1
@@ -206,7 +206,7 @@ static void expand_include_level(struct token *token)replace_with_integer (token, include_level -1 ); } -static int expand_one_symbol (struct token **list) +static inline int expand_one_symbol (struct token **list) {struct token *token = *list;struct symbol *sym;
Signature · 1 line
2.47.3
PATCH 21/21 substitute(): convert switch() into cascade of ifs
In reply to Al ViroAgain, better code generation that way (and I'd like to use likely() here); it *is* in a very hot loop.
Reorder the TOKEN_... a bit (move TOKEN_UNTAINT up, so that it's less than TOKEN_MACRO_ARGUMENT) to get the default (and by far the most common case) via single comparison.
--- pre-process.c | 68 +++++++++++++++++++++++---------------------------- token.h | 3 ++- 2 files changed, 33 insertions(+), 38 deletions(-)
pre-process.c +31 -37
@@ -682,34 +682,14 @@ static struct token **substitute(struct token **list, const struct token *body, expanding->tainted =1 ;for (; !eof_token (body); body = body->next) { -struct token *added, *arg; -struct token **inserted_at; -const struct token *t; +struct token *added; -switch (token_type (body)) { -case TOKEN_GNU_KLUDGE : -/* -* GNU kludge: if we had <comma>##<vararg>, behaviour -* depends on whether we had enough arguments to have -* a vararg. If we did, ## is just ignored. Otherwise -* both , and ## are ignored. Worse, there can be -* an arbitrary number of ##<arg> in between; if all of -* those are empty, we act as if they hadn't been there, -* otherwise we act as if the kludge didn't exist. -*/ - t = body; -if (handle_kludge (&body, args)) { -if (state == Concat) - state = Normal; -else - state = Placeholder; -continue ; - } - added =dup_token (t, base_pos); -token_type (added) =TOKEN_SPECIAL ; -break ; +if (token_type (body) <=TOKEN_LAST_NORMAL ) { + added =dup_token (body, base_pos); + }else if (token_type (body) ==TOKEN_MACRO_ARGUMENT ) { +struct token **inserted_at; +struct token *arg; -case TOKEN_MACRO_ARGUMENT : arg =do_argument (body, args, expanding);if (!arg ||eof_token (arg)) {if (state == Concat)
@@ -740,15 +720,33 @@ static struct token **substitute(struct token **list, const struct token *body, } state = Normal;continue ; - -case TOKEN_CONCAT : + }else if (token_type (body) ==TOKEN_CONCAT ) {if (state == Placeholder) state = Normal;else state = Concat;continue ; - -case TOKEN_VA_OPT : + }else if (token_type (body) ==TOKEN_GNU_KLUDGE ) { +const struct token *t = body; +/* +* GNU kludge: if we had <comma>##<vararg>, behaviour +* depends on whether we had enough arguments to have +* a vararg. If we did, ## is just ignored. Otherwise +* both , and ## are ignored. Worse, there can be +* an arbitrary number of ##<arg> in between; if all of +* those are empty, we act as if they hadn't been there, +* otherwise we act as if the kludge didn't exist. +*/ +if (handle_kludge (&body, args)) { +if (state == Concat) + state = Normal; +else + state = Placeholder; +continue ; + } + added =dup_token (t, base_pos); +token_type (added) =TOKEN_SPECIAL ; + }else if (token_type (body) ==TOKEN_VA_OPT ) {// entering va_opt? if (!is_end_va_opt (body)) {if (skip_va_opt (args, expanding)) {
@@ -774,9 +772,7 @@ static struct token **substitute(struct token **list, const struct token *body, } list = saved_list; state = saved_state; -break ; - -case TOKEN_VA_OPT_STR : + }else if (token_type (body) ==TOKEN_VA_OPT_STR ) {// entering #va_opt if (!skip_va_opt (args, expanding)) { saved_state = state;
@@ -787,10 +783,8 @@ static struct token **substitute(struct token **list, const struct token *body,continue ; } added =empty_string (base_pos); -break ; - -default : - added =dup_token (body, base_pos); + }else { +sparse_error (body->pos,"bad token type(%d)" ,token_type (body));break ; }
token.h +2 -1
@@ -99,12 +99,13 @@ enum token_type {TOKEN_SPECIAL ,TOKEN_STREAMBEGIN ,TOKEN_STREAMEND , +TOKEN_UNTAINT , +TOKEN_LAST_NORMAL =TOKEN_UNTAINT ,TOKEN_MACRO_ARGUMENT ,TOKEN_CONCAT ,TOKEN_GNU_KLUDGE ,TOKEN_VA_OPT ,TOKEN_VA_OPT_STR , -TOKEN_UNTAINT ,TOKEN_IF ,TOKEN_SKIP_GROUPS , TOKEN_ELSE,
Signature · 1 line
2.47.3
Re: [RFC PATCH] pre-process: add __VA_OPT__ support
In reply to Al ViroI have tested that branch on a few trivial cases, and it looks good to me.
I did write a long rant about how I hate cpp tricks and wish we had a few simple extensions (__VA_COUNT__ would be the most simple one, because COUNT_ARGS() is disgusting), but it is what it is, and this makes things better. So I decided to just delete my rant.
Linus
Chris Li
maintainerRe: [RFC PATCH] pre-process: add __VA_OPT__ support
In reply to Al ViroQuoted 26 lines · Al Viro
Quoted 24 lines · Al Viro
Quoted 6 lines · Al Viro
NOTE:
substitute()is the second hottest loop in the entire thing; only tokenizer is hotter. And gcc is too enthusiastic about the inlining around that function, ending up with bad register spills, along with a bunch of stalls. Worse, decisions are sensitive to minor changes in places textually far away, making it a real bitch to deal with. Makes for fun reordering the commits in local queue... ;-/FWIW, looking at that thing again, I wonder if we would be better off with doing argument expansion on demand rather than doing it in
expand_arguments(). Should be doable with a bit of care - we'd need to mark the TOKEN_..._ARG with several bits to decide whether we want to duplicate or not, etc., but that's worth doing anyway - better than playing with the counters.Note, BTW, that collapsing TOKEN_..._ARG together, with "kind of argument" moved into bits stolen from ->argnum improves code generation - that switch by token type is _hot_ and it reducing the number of cases gives a measurable speedup. Sure, we don't want heavy work at #define time - most of the macros are never expanded at all, but AFAICS this kind of processing can be dealt with while parsing the body, with no extra passes needed, etc.
Quoted 7 lines
Quoted 1 line
I'm going down right now, will look into that tomorrow morning...
That turned out to be trickier than I hoped, but I've got something that works.
See
git://git.kernel.org/pub/scm/linux/kernel/git/viro/sparse.git#va_opt (or individual patches in followups)
Nice, I applied the patch at the sparse-dev repo:
https://git.kernel.org/pub/scm/devel/sparse/sparse-dev.git/
I will push to the stable repository and make a cut soon if no issues are reported.
Chris
Quoted 101 lines
__VA_OPT__supported, AFAICS behaviour matches C23.
* expansion and stringifying of arguments is full-lazy now -
done on demand and at most once.
* va-opt-replacement parsed at #define time, handled correctly
bydump_macro()(i.e. -dM), comparisons when redefining and at expansion time.
* arglist mangling is gone, so's the argcount kludge.
* it's no slower than it used to be prior to that series.I have local followups (tentative fixes for whitespace handling in preprocessor and optimizations in tokenizer), but let's deal with that one first.
Shortlog:
Al Viro (21):
splitcopy()into "need to copy" and "can move in place" cases expand and simplify the call ofdup_token()incopy()
moredup_token()optimizations
parsing #define: saner handling of argument count, part 1 simplifycollect_arguments()and fix error handling theretry_arg(): don't use arglist for argument name lookups
make expand_has_...() responsible for expanding its argument preparing to change argument number encoding for TOKEN_..._ARGUMENT steal 2 bits from argnum for argument kind
on-demand argument expansion
killcreate_arglist()
stop mangling arglist, get rid ofTOKEN_ARG_COUNT
deal with ## on arguments separately
preparations for__VA_OPT__support: reshuffle argument slot assignmentspre-process.c: splittry_arg()
__VA_OPT__: parsing
expansion-timeva_opthandling
merge(): saner handling of ->noexpand
simplify the calling conventions ofcollect_arguments()makeexpand_one_symbol()inline
substitute(): convertswitch()into cascade of ifsDiffstat:
ident-list.h | 1 + pre-process.c | 929 +++++++++++++++++----------- symbol.h | 1 + token.h | 32 +- tokenize.c | 4 - validation/preprocessor/bad-args.c | 18 + validation/preprocessor/dump-macro.c | 13 + validation/preprocessor/has-attribute.c | 3 + validation/preprocessor/has-builtin.c | 3 + validation/preprocessor/va_opt.c | 54 ++ validation/preprocessor/va_opt2.c | 34 + validation/preprocessor/va_opt_compare.c | 28 + validation/preprocessor/va_opt_parse.c | 37 ++ validation/preprocessor/va_opt_whitespace.c | 14 + 14 files changed, 797 insertions(+), 374 deletions(-) create mode 100644 validation/preprocessor/bad-args.c create mode 100644 validation/preprocessor/dump-macro.c create mode 100644 validation/preprocessor/va_opt.c create mode 100644 validation/preprocessor/va_opt2.c create mode 100644 validation/preprocessor/va_opt_compare.c create mode 100644 validation/preprocessor/va_opt_parse.c create mode 100644 validation/preprocessor/va_opt_whitespace.cPS: as for the interesting uses of
__VA_OPT__, consider this:
; cat >test.c <<'EOF'
// based on a fun trick from David Mazières
// see https://www.scs.stanford.edu/~dm/blog/va-opt.html for the entire story // No, it's not unbounded recursion - up to 256 (4^4) elements in__VA_ARGS__; // more with trivial modifications, just add more levels to EXPAND... #define PARENS ()
#define EXPAND(...) EXPAND4(EXPAND4(EXPAND4(EXPAND4(__VA_ARGS__)))) #define EXPAND4(...) EXPAND3(EXPAND3(EXPAND3(EXPAND3(__VA_ARGS__)))) #define EXPAND3(...) EXPAND2(EXPAND2(EXPAND2(EXPAND2(__VA_ARGS__)))) #define EXPAND2(...) EXPAND1(EXPAND1(EXPAND1(EXPAND1(__VA_ARGS__)))) #define EXPAND1(...)__VA_ARGS__
#defineFOR_EACH_PAIR(macro, ...)\
__VA_OPT__(EXPAND(FOR_EACH_PAIR_HELPER(macro, __VA_ARGS__)))
#defineFOR_EACH_PAIR_HELPER(macro, a1, a2, ...)\
macro(a1, a2)\
__VA_OPT__(FOR_EACH_PAIR_AGAIN PARENS (macro, __VA_ARGS__))
#defineFOR_EACH_PAIR_AGAIN()FOR_EACH_PAIR_HELPER
FOR_EACH_PAIR(F, t1, id1, t2, id2, t3, id3, t4, id4, t5, id5, t6, id6)EOF
; cpp -Etest.c
# 0 "test.c"
# 0 "<built-in>"
# 0 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 0 "<command-line>" 2
# 1 "test.c"
# 18 "test.c"F(t1, id1)F(t2, id2)F(t3, id3)F(t4, id4)F(t5, id5)F(t6, id6);and the same output from sparse, modulo the # ... lines - sparse -E doesn't produce those. Our (fairly brittle) analogue is
__MAPinlinux/syscalls.hand if nothing else, unlike__MAP()this thing does not need the number of pairs passed as explicit argument. Would be interesting to try unifying SYSCALL0..SYSCALL6 into a single macro that would bloody well _count_ the arguments...
Eric Zhang
Tested-byRe: [RFC PATCH] pre-process: add __VA_OPT__ support
In reply to Al Viro---
Quoted 2 lines · Al Viro
That turned out to be trickier than I hoped, but I've got something that works.
Nice! It is much cleaner than what I had in my RFC :) I've tested the branch against tests cases in my previous RFC and some new tests, no regression.
Re: [RFC PATCH] pre-process: add __VA_OPT__ support
In reply to Linus TorvaldsQuoted 6 lines · Linus Torvalds
I have tested that branch on a few trivial cases, and it looks good to me.
I did write a long rant about how I hate cpp tricks and wish we had a few simple extensions (
__VA_COUNT__would be the most simple one, becauseCOUNT_ARGS()is disgusting), but it is what it is, and this makes things better. So I decided to just delete my rant.
Speaking of rants: gcc code generation in general and around bitfields.
Example: in collect_arg() we have
next->pos.stream = pos->stream;
next->pos.line = pos->line;
next->pos.pos = pos->pos;
next->pos.newline = 0;
in a loop, pos is declared const struct position *. Generates the
following horror:
movzwl 2(%r12), %edx
movl (%r12), %ecx
leaq 8(%rax), %rbp
shrw $6, %dx
andl $1048512, %ecx
movzwl %dx, %edx
salq $22, %rdx
orq %rcx, %rdx
movl 4(%r12), %ecx
andl $2147483647, %ecx
salq $32, %rcx
orq %rcx, %rdx
movq (%rax), %rcx
andq %r14, %rcx
orq %rcx, %rdx
movq %rdx, (%rax)
r12 is 'pos', rax - 'next', r14 comes from
movabsq $-9223372036852678593, %r14
in the beginning of the function (0x800000000020003f). Note that
*everything* prior to the last 4 insns is equivalent to
rbp = &(struct token *)rax->next
rdx = *(u64 *)r12 & 0x7fffffffffc0xfffc0written in a really convoluted way.
OK, so it doesn't figure out it could bloody well calculate that rdx value once and store in some register (the same r12, for that matter). Let's make it simple for the damn thing - pass struct position instead of struct position *; what we get is
movq %r12, %rdx leaq 8(%rax), %rbp movabsq $9223372032559808512, %rcx andl $1048512, %edx andq %r12, %rcx orq %r14, %rdx orq %rcx, %rdx movabsq $-9223372036852678593, %rcx andq (%rax), %rcx orq %rcx, %rdx movq %rdx, (%rax) What the hell? No, really - it's rdx = r12; rbp = &(struct token *)rax->next; rcx = 0x7fffffff00000000; rdx &= 0xfffc0; rcx &= r12; rdx |= rcx; followed by rcx = 0x800000000020003f & *(u64 *)rax; rdx |= rcx; *(u64 *)rax = rdx; Leaving aside the utility of repeating the same calculation on each iteration of the loop, figuring out that (0x7fffffff00000000 & r12) | (0xfffc0 & r12) is equal to 0x7fffffffffc0fffc0 & r12
ought to be within the abilities of the damn compiler - and it *is* loading a 64bit constant into rcx as it is. What's more, it's not a preference to using 64bit constants with lower 32 bits clear - another movabsq in the same chunk is not of that form.
Perhaps it's an explicit store of 0 to ->newline that does it? Clearing pos.newline in the beginning and have
next->pos.newline = pos.newline;
instead of zeroing in the loop does not change anything (other than worse register allocation). Moving zeroing of pos.newline into the caller finally gets that calculation out of loop... and messes with the register allocation in the caller, which is inlined into expand(), along with substitute(), do_argument() and quite a few other things.
Granted, collect_arg() is not particularly hot, but... ouch. I really, really don't like the handling of bitfields ;-/
Re: [RFC PATCH] pre-process: add __VA_OPT__ support
Quoted 2 lines · Al Viro
Speaking of rants: gcc code generation in general and around bitfields.
Yeah. gcc handling of bitfields is a disaster. I made a gcc bugzilla about some of this many years ago (almost exactly 15 years ago):
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=48696
and things haven't really improved much since, afaik.
I suggested at the time that gcc should stop doing bitfields internally, and translate it all into shifts and masks and then doing all the normal optimizations on those. But that's not what it does - gcc keeps it as a "bitfield access" way too long in the optimization phases, and then does a really bad job of optimizing it all.
And yes, I made that bugzilla entry due to sparse, and that 'struct pos'.
Because it really triggers all kinds of horrendous gcc behavior.
I looked at clang at one point, and iirc it generated *much* better code, because I think it does tth esmart thing, which is to get rid of the notion of bitfields as quickly as possible, and then doing just regular integer optimizations.
(And the real problem with gcc is really that "byte write followed by word read", which is horribly horribly expensive because it causes a pipeline stall. So even when the code looks small, it's really really bad. Clang actually generates more instructions for the test-case in that bugzilla, but the code is ten times faster because it doesn't stall the pipeline)
Linus
Re: [RFC PATCH] pre-process: add __VA_OPT__ support
Quoted 4 lines · Linus Torvalds
I looked at clang at one point, and iirc it generated *much* better code, because I think it does tth esmart thing, which is to get rid of the notion of bitfields as quickly as possible, and then doing just regular integer optimizations.
FWIW, with the local tokenizer patches the single worst spot at the moment (both for clang and for gcc build) is this:
p = &hash_table[hash];
while ((ident = *p) != NULL) {
if (ident->len == (unsigned char) len) {
in create_hashed_ident(). This is from clang build, where
it's inlined into tokenize_stream():
0.14 │ mov (%rdx,%rcx,8),%rax
12.34 │ mov %r12d,%r15d
0.02 │ test %rax,%rax
0.43 │ ↓ je 33e
│ mov %rsp,%r14
0.29 │ ↓ jmp 319
│ nop
│310:┌─→mov 0x0(%r13),%rax
2.00 │ │ test %rax,%rax
0.07 │ │↓ je 345
0.00 │319:│ mov %rax,%r13
│ │if (ident->len == (unsigned char) len) {
0.19 │ ├──cmp %r12b,0x10(%rax)
16.86 │ └──jne 310
and this is gcc build, where it's not inlined, so the percentages are
several times higher (out of 5.9% vs. out of 17.1% on the profiles I'm
looking at):
│ p = &hash_table[hash]; ▒
0.77 │ mov (%rax,%rdx,8),%rbx ▒
│ while ((ident = *p) != NULL) { ▒
27.77 │ test %rbx,%rbx ◆
0.98 │ ↓ jne 3b ▒
│ ↓ jmp c2 ▒
│ nop ▒
│ ident_hit++; ▒
│ return ident; ▒
│ } ▒
│ next: ▒
│ //misses++; ▒
│ p = &ident->next; ▒
0.00 │30:┌─→mov (%rbx),%rax ▒
│ │while ((ident = *p) != NULL) { ▒
6.11 │ │ test %rax,%rax ▒
0.24 │ │↓ je 70 ▒
│ │ mov %rax,%rbx ▒
│ │if (ident->len == (unsigned char) len) { ▒
0.81 │3b:├──cmp %bpl,0x10(%rbx) ▒
50.82 │ └──jne 30 ▒Most of the accesses are to single-element chain; it's not walking the lists that hurts, it's the very first step. The profiles are for userland cycles; looking for stalled-cycles-frontend gives exact same hotspots. The next one is lookup_symbol(); there we also walk linked lists. The only difference is that lists are often longer than one entry... Not sure what can be done about either.
Re: [RFC PATCH] pre-process: add __VA_OPT__ support
In reply to Al ViroOn Mon, Mar 16, 2026 at 06:56:22AM +0000, Al Viro wrote:
... and here's are the whitespace fixes and a bunch of optimizations; I really wonder if we ought to simply switch to uint64_t for struct position contents and go for several helpers for accessing individual parts. Code generation with clang is reasonable, but gcc is bloody awful - I'm sick and tired of fighting it all the time ;-/ Anyway, I've spent way too much time in that rabbit hole. I've a few more sitting in the local queue (tokenizer optimizations, mostly), but that's a separate story and I'd rather leave that for later.
See git://git.kernel.org/pub/scm/linux/kernel/git/viro/sparse.git #whitespaces (or individual patches in followups); it's on top of #va_opt.
Re whitespace: there are several places where gcc and clang handling of that stuff differs. The origin of the headache is that historically preprocessor had been a text filter sitting in front of compiler - its output had been fed through tokenizer and quite a few things in the original ANSI C bear the resulting scars. By C99 times it mostly switched to working in terms of token stream, which simplified a lot of stuff. Unfortunately, what it's working with is not quite a list of tokens - it's tokens mixed with whitespace. By that point comments are replaced with spaces and implementation is allowed to collapse any sequence of whitespace other than newline into a single space character.
All operations on the stream are described in terms of replacing a token or a sequence of tokens with a sequence of tokens; what happens to possible whitespace is almost unspecified.
Some things are obvious and generally agreed upon:
* if we are replacing a sequence of tokens, all whitespace stuck
between them is removed. All whitespace before to the first or after the last affected token in left as-is.
* all whitespace stuck between the tokens in the replacement
sequence is inserted along with those tokens.
What is *not* obvious is what should be done to leading or trailing whitespace in the replacement sequence. Part of that is explicitly covered (e.g. macro body has no leading or trailing whitespace), but in some cases the things get iffy. Trivial example:
#define E
#define F E - E
#define S(X) #X
#define A(X) S([X])
char *s = A(F);
A(F) is a macro invocation; there's one argument - Ident(F). No whitespace anywhere. What should these 4 tokens be replaced with? We start with the replacement list of A - Ident(S),Punctuator('('),Punctuator('['),Ident(X), Punctuator(']'),Punctuator(')'). The only parameter (X) occurs only once and there's neither # nor ## operator in sight, so that occurrence gets replaced with the token sequence resulting from full expansion of the corresponding argument.
Ident(F) expands to Ident(E),whitespace,Punctuator('-'),whitespace,Ident(E), which, after expanding both instances of E turns into
whitespace,Punctuator('-'),whitespace
Fair enough, there's only one token in that, so there's no inter-token whitespace in sight. There is both leading and trailing whitespace, though.
One interpretation is that this one token is precisely what gets substituted, yielding S([-]) with no whitespace anywhere. That's an invocation of S with the sole argument being Punctuator('['),Punctuator('-),Punctuator(']'), and the end result is "[-]". This is what clang does.
Another way to handle that is to have the whitespace preceding and following Punctuator('-') in the expansion of F stuck to it when we are substituting the damn thing, yielding S([ - ]) (same tokens as in the first variant, but with whitespaces stuck before and after the minus). The end result in this interpretation is "[ - ]". This is what gcc goes for.
Unfortunately, gcc rules are convoluted and when you add __VA_OPT__ into the mix they get really nasty.
Example:
#define E
#define F E - E
#define S(X) #X
#define A(X,...) S([__VA_OPT__(X)])
char *s = A(F,_);
ends up with "[- ]" - the leading whitespace is stripped, the trailing one remains stuck to the token sequence. Mixing that with ## leads to outright bugs:
#define E
#define F1 E 1
#define A(X,...) 1##__VA_OPT__(X)
int m1 = A(F1,...);
expands into
int m1 = 11;
In other words, left concatenation works fine. However, adding the right-hand analogue
#define F2 sizeof m E
#define B(X,...) __VA_OPT__(X)##1
int m2 = B(F2,_);
which should result in
int m2 = sizeof m1;
does *not* work with gcc - it ends up with
int m2 = sizeof m 1;
with predictable objections from the parser. Note that it's *not* a matter of confusion re "do we expand the argument here?" - if that argument hadn't been expanded, we would've ended up with
int m2 = sizeof F21;
and resulting errors would've been different. With clang everything works as expected and I don't see any interpretation of the standard that would allow what gcc is doing. The trigger for that bug is their treatment of the trailing whitespace, AFAICS; leading whitespace is stripped here.
Note that the current mainline sparse doesn't match either gcc or clang semantics - it loses whitespaces in some cases where they definitely should be retained. That needs to be fixed; e.g.
#define E
#define S(X) #X
#define A(X) S(X)
char *s = A([1 E]);
ought to produce "[1 ]", not "[1]". Nothing subtle about that case...
IMO we are be better off with the clang approach; it is easy to describe and it matches the behaviour of gcc unless you step into the areas where gcc is rather random. We can always reconsider if/when gcc folks come up with something that looks consistent...
Shortlog:
Al Viro (6):
nextchar(): get rid of special[]
simplify the inlined side of nextchar() tokenize_stream(): don't bother with isspace()
TOKEN_DIRECTIVE: recognize directive-introducing # in tokenizer saner collect_arg() code generation
try to get whitespaces right
Diffstat:
pre-process.c | 169 ++++++++++++++++++-------------- token.h | 1 + tokenize.c | 91 +++++++++-------- validation/preprocessor/va_opt-concat.c | 24 +++++ validation/preprocessor/va_opt.c | 23 +++-- validation/preprocessor/va_opt2.c | 2 +- 6 files changed, 184 insertions(+), 126 deletions(-) create mode 100644 validation/preprocessor/va_opt-concat.c
PATCH 1/6 nextchar(): get rid of special[]
We want to hit the slow path on '\t', '\n', '\\' and '\r'. Doing that as series of checks is painful, but we don't need to be that precise - we almost never see control symbols outside of that set and the slow path will handle them just fine. And checking if character belongs to [\0-\017\\] is easy enough without bothering with storing the set as an array.
--- tokenize.c | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-)
tokenize.c +1 -4
@@ -441,10 +441,7 @@ static inline int nextchar(stream_t *stream)if (offset < stream->size) {int c = stream->buffer[offset++]; -static const char special[256 ] = { - ['\t' ] =1 , ['\r' ] =1 , ['\n' ] =1 , ['\\' ] =1 - }; -if (!special[c]) { +if (c >=' ' && c !='\\' ) { stream->offset = offset; stream->pos++;return c;
Signature · 1 line
2.47.3
PATCH 2/6 simplify the inlined side of nextchar()
* make sure that data stream->buffer + stream->size always points to '\0'. That is enough to send nextchar() towards the slow path without the need to check offset for overflow.
* replace stream->offset with stream->current - pointer to current location in buffer rather than offset in it.
* have the increments of stream->current and stream->pos done before we check whether we need to call nextchar_slow() (with nextchar_slow() adjusted to be called with incremented ->current and ->pos).
--- tokenize.c | 71 +++++++++++++++++++++++++++--------------------------- 1 file changed, 36 insertions(+), 35 deletions(-)
tokenize.c +36 -35
@@ -47,7 +47,8 @@ unsigned int tabstop = 8;#define BUFSIZE (8192) typedef struct { - int fd, offset, size; + unsigned char *current; + int fd, size; int pos, line, nr; int newline, whitespace; struct token **tokenlist;
@@ -351,31 +352,34 @@ static struct token * alloc_token(stream_t *stream)*/ static int nextchar_slow (stream_t *stream) { -int offset = stream->offset; +unsigned char *p = stream->current;// bumped by fast path int size = stream->size;int c; -int spliced =0 , had_cr, had_backslash; +bool spliced = false, had_cr, had_backslash; restart: - had_cr = had_backslash =0 ; + had_cr = had_backslash = false; repeat: -if (offset >= size) { +if (p > stream->buffer + size) {if (stream->fd <0 ) goto got_eof; size =read (stream->fd, stream->buffer,BUFSIZE );if (size <=0 ) goto got_eof; + stream->buffer[size] ='\0' ;// sentry stream->size = size; - stream->offset = offset =0 ; + stream->current = stream->buffer; + p = stream->buffer +1 ; } - c = stream->buffer[offset++]; + c = p[-1 ];if (had_cr) goto check_lf;if (c =='\r' ) { - had_cr =1 ; + had_cr = true; + p++; goto repeat; }
@@ -383,6 +387,7 @@ norm:if (!had_backslash) {switch (c) {case '\t' : + stream->pos--; stream->pos += tabstop - stream->pos % tabstop;break ;case '\n' :
@@ -391,38 +396,40 @@ norm: stream->newline =1 ;break ;case '\\' : - had_backslash =1 ; + had_backslash = true; stream->pos++; + p++; goto repeat; -default : - stream->pos++; } }else {if (c =='\n' ) { stream->line++; - stream->pos =0 ; - spliced =1 ; + stream->pos =1 ; + spliced = true; + p++; goto restart; } - offset--; c ='\\' ; + stream->pos--; + p--; } -out: - stream->offset = offset; + stream->current = p;return c; -check_lf: +check_lf:// CR+LF => LF, solitary CR => LF if (c !='\n' ) - offset--; + p--; c ='\n' ; goto norm; got_eof: -if (had_backslash) { - c ='\\' ; - goto out; - } + stream->pos--; + stream->buffer[0 ] ='\0' ;// sentry + stream->current = stream->buffer; + stream->size =0 ; +if (had_backslash) +return '\\' ;if (stream->pos & Wnewline_eof)warning (stream_pos (stream),"no newline at end of file" );else if (spliced)
@@ -437,16 +444,10 @@ got_eof:*/ static inline int nextchar (stream_t *stream) { -int offset = stream->offset; - -if (offset < stream->size) { -int c = stream->buffer[offset++]; -if (c >=' ' && c !='\\' ) { - stream->offset = offset; - stream->pos++; -return c; - } - } +int c = *stream->current++; + stream->pos++; +if (c !='\\' && c >=' ' ) +return c;return nextchar_slow (stream); }
@@ -972,9 +973,8 @@ static struct token *setup_stream(stream_t *stream, int idx, int fd, stream->token =NULL ; stream->fd = fd; - stream->offset =0 ; stream->size = buf_size; - stream->buffer = buf; + stream->current = stream->buffer = buf; begin =alloc_token (stream);token_type (begin) =TOKEN_STREAMBEGIN ;
@@ -1014,7 +1014,7 @@ struct token * tokenize(const struct position *pos, const char *name, int fd, st {struct token *begin, *end;stream_t stream; -unsigned char buffer[BUFSIZE ]; +unsigned char buffer[BUFSIZE +1 ];int idx; idx =init_stream (pos, name, fd, next_path);
@@ -1023,6 +1023,7 @@ struct token * tokenize(const struct position *pos, const char *name, int fd, streturn endtoken; } + buffer[0 ] ='\0' ; begin =setup_stream (&stream, idx, fd, buffer,0 ); end =tokenize_stream (&stream);if (endtoken)
Signature · 1 line
2.47.3
PATCH 3/6 tokenize_stream(): don't bother with isspace()
In reply to Al Virowe have a spare bit in cclass[]...
--- tokenize.c | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-)
tokenize.c +11 -4
@@ -496,9 +496,16 @@ enum { Dot =16 , ValidSecond =32 , Quote =64 , + Whitespace = 128, };static const char cclass[257 ] = { + [' ' +1 ] = Whitespace, + ['\t' +1 ] = Whitespace, + ['\n' +1 ] = Whitespace, + ['\v' +1 ] = Whitespace, + ['\r' +1 ] = Whitespace, + ['\f' +1 ] = Whitespace, ['0' +1 ...'9' +1 ] = Digit | Hex, ['A' +1 ...'D' +1 ] = Letter | Hex, ['E' + 1] = Letter | Hex | Exp, /* E<exp> */
@@ -986,16 +993,16 @@ static struct token *tokenize_stream(stream_t *stream) {int c =nextchar (stream);while (c !=EOF ) { -if (!isspace (c)) { +if (!(cclass[c +1 ] & Whitespace)) {struct token *token =alloc_token (stream); stream->token = token; stream->newline =0 ; stream->whitespace =0 ; c =get_one_token (c, stream); -continue ; + }else { + stream->whitespace =1 ; + c =nextchar (stream); } - stream->whitespace =1 ; - c =nextchar (stream); }return mark_eof (stream); }
Signature · 1 line
2.47.3
PATCH 4/6 TOKEN_DIRECTIVE: recognize directive-introducing # in tokenizer
In reply to Al Viro'#' acts as start of directive it had been the first token in its line at the beginning of phase 4. In other words, it must have come from the input stream rather than from macro expansion (# may be present in the body of object-like macro) and there must've been no token between it and beginning of the line *before* any macro expansion had been done (i.e. in
#define EMPTY EMPTY #include <stdlib.h>
the # in front of include is *not* a beginning of directive).
Currently we handle that by hijacking 'noexpand' flag to mark the instances of # coming from macro expansion and checking if the token we'd run into might be a directive-starting # in do_preprocess() and in collect_arg().
It's actually simpler and faster to recognize those in tokenizer. Just have get_one_special() check if it's about to return a TOKEN_SPECIAL[#] and if it's the first token in its line, return a token of new type (TOKEN_DIRECTIVE). Checks in the preprocessor get simpler and we get rid of 'noexpand' abuse - there's no way for TOKEN_DIRECTIVE to end up in the body of any macro.
--- pre-process.c | 22 ++++++++-------------- token.h | 1 + tokenize.c | 2 ++ 3 files changed, 11 insertions(+), 14 deletions(-)
pre-process.c +8 -14
@@ -263,12 +263,10 @@ static struct token *collect_arg(struct token *prev, bool vararg, const struct pint nesting =0 ;while (!eof_token (next =scan_next (p))) { -if (next->pos.newline &&match_op (next,'#' )) { -if (!next->pos.noexpand) { -preprocessor_line (stream, p); -__free_token (next);/* Free the '#' token */ -continue ; - } +if (token_type (next) ==TOKEN_DIRECTIVE ) { +preprocessor_line (stream, p); +__free_token (next);/* Free the '#' token */ +continue ; }switch (token_type (next)) {case TOKEN_STREAMEND :
@@ -1402,8 +1400,6 @@ static struct token *handle_hash(struct token **p, struct arg_state args[]) goto Equote;__free_token (token); token = *p = next; - }else { - token->pos.noexpand =1 ; }return token;
@@ -2427,12 +2423,10 @@ static void do_preprocess(struct token **list)while (!eof_token (next =scan_next (list))) {struct stream *stream = input_streams + next->pos.stream; -if (next->pos.newline &&match_op (next,'#' )) { -if (!next->pos.noexpand) { -preprocessor_line (stream, list); -__free_token (next);/* Free the '#' token */ -continue ; - } +if (token_type (next) ==TOKEN_DIRECTIVE ) { +preprocessor_line (stream, list); +__free_token (next);/* Free the '#' token */ +continue ; }switch (token_type (next)) {
token.h +1 -0
@@ -109,6 +109,7 @@ enum token_type {TOKEN_IF ,TOKEN_SKIP_GROUPS ,TOKEN_ELSE , + TOKEN_DIRECTIVE, };/* Combination tokens */
tokenize.c +2 -0
@@ -790,6 +790,8 @@ static int get_one_special(int c, stream_t *stream)/* Pass it on.. */ token = stream->token;token_type (token) =TOKEN_SPECIAL ; +if (value =='#' && token->pos.newline) +token_type (token) =TOKEN_DIRECTIVE ; token->special = value;add_token (stream);return next;
Signature · 1 line
2.47.3
PATCH 5/6 saner collect_arg() code generation
In reply to Al Viro1) gently coax gcc code generator away from screwing the bitfields handling it is so keen to do - pass struct position from the caller by value, with .newline already cleared (with inlined helper that does trimming), do *not* let collect_arg() see that it's always setting ->pos.newline to 0 (otherwise the FPOS tries to peel the damn thing apart, turning mask-then-or into a bleeding horror).
2) get rid of 'vararg' checks for commas by changing the way we keep track of nesting parentheses - instead of
number of '(' - number of ')'
use
2 * number of '(' - 2 * number of ')' + varargThat still recognizes the closing parenthesis of argument list (counter gets negative there, vararg or no vararg) and it does recognize an argument-terminating comma without having to look at 'vararg' - just check if counter is zero.
Reduces spills nicely.
3) do *not* use eof_token() as loop termination condition, compare token_type() with TOKEN_EOF instead. Yes, it's faster to compare the pointer with constant instead, but it is *not* going to match that unless we have an unterminated argument list and we are going to check for TOKEN_STREAM{BEGIN,END} immediately afterwards anyway, with the same "leave the loop now" on match, so these checks combine nicely.
--- pre-process.c | 44 ++++++++++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 18 deletions(-)
pre-process.c +26 -18
@@ -255,42 +255,41 @@ static void expand_list(struct token **list)static void preprocessor_line (struct stream *stream,struct token **line); -static struct token *collect_arg (struct token *prev,bool vararg,const struct position *pos) +static struct token *collect_arg (struct token *prev,bool vararg,struct position pos) {struct stream *stream = input_streams + prev->pos.stream;struct token **p = &prev->next;struct token *next; -int nesting =0 ; +int nesting = vararg; -while (!eof_token (next =scan_next (p))) { +while (1 ) { + next =scan_next (p); +if (token_type (next) ==TOKEN_STREAMBEGIN || +token_type (next) ==TOKEN_STREAMEND || +token_type (next) ==TOKEN_EOF ) +break ;if (token_type (next) ==TOKEN_DIRECTIVE ) {preprocessor_line (stream, p);__free_token (next);/* Free the '#' token */ continue ; } -switch (token_type (next)) { -case TOKEN_STREAMEND : -case TOKEN_STREAMBEGIN : - *p = &eof_token_entry; -return next; - }if (false_nesting) { *p = next->next;__free_token (next);continue ; }if (match_op (next,'(' )) { - nesting++; + nesting +=2 ; }else if (match_op (next,')' )) { -if (!nesting--) +if ((nesting -=2 ) <0 )break ; - }else if (match_op (next,',' ) && !nesting && !vararg) { + }else if (match_op (next,',' ) && !nesting) {break ; } - next->pos.stream = pos->stream; - next->pos.line = pos->line; - next->pos.pos = pos->pos; - next->pos.newline =0 ; + next->pos.stream = pos.stream; + next->pos.line = pos.line; + next->pos.pos = pos.pos; + next->pos.newline = pos.newline; p = &next->next; } *p = &eof_token_entry;
@@ -305,6 +304,15 @@ struct arg {struct token *arg[3 ]; }; +static inline struct position location (const struct position *p) +{ +return (struct position ) { + .stream = p->stream, + .line = p->line, + .pos = p->pos + }; +} +static int collect_arguments (struct token *what,int fixed,bool vararg,struct arg *args) {struct token *start =scan_next (&what->next);
@@ -317,7 +325,7 @@ static int collect_arguments(struct token *what, int fixed, bool vararg, structif (!match_op (start,'(' ))return 0 ;for (commas =0 ; commas < fixed; commas++) { - next =collect_arg (start, false, &what->pos); + next =collect_arg (start, false,location (&what->pos));if (token_type (next) !=TOKEN_SPECIAL ) goto Eclosing; args[commas +1 ].arg[ARG_QUOTED ] = start->next;
@@ -329,7 +337,7 @@ static int collect_arguments(struct token *what, int fixed, bool vararg, struct start = next; }if (commas == fixed) { - next =collect_arg (start, true, &what->pos); + next =collect_arg (start, true,location (&what->pos));if (token_type (next) !=TOKEN_SPECIAL ) goto Eclosing; v = start->next;
Signature · 1 line
2.47.3
PATCH 6/6 try to get whitespaces right
In reply to Al ViroPreprocessor started as a text filter - it took a stream of characters and produced a stream of characters, with the output fed to compiler. Semantics had been not _quite_ as bad as with Bourne shell, but it had been full of dark corners all the same.
By C99 times it had been replaced with something far better defined. Now it operates on stream of tokens, and the output stream is _not_ fed through the tokenizer again. Operations are defined in terms of manipulations with that stream of tokens, which avoids a lot of headache.
Unfortunately, it's not exactly a stream of tokens - it's a stream of tokens and whitespaces. Which is where the things get interesting. When the standard says "replace the tokens from <here> to <there> with the sequence of tokens obtained by <this>", the general understanding is that
* whatever whitespaces might've been between <here> and <there>
are removed
* any whitespaces prior to <here> and past <there> remain as-is
* any whitespaces between the tokens of the sequence we are
told to substitute go into the the result.
What's not agreed upon is what should be done to possible leading or trailing whitespaces in the sequence.
In a lot of cases it doesn't matter - subsequent phases care only about tokens. Moreover, '#' operator (which does care about whitespaces) is explicitly required to trim any leading and trailing whitespace. However, there are cases where it is observable and different implementations yield different results.
Currently sparse is prone to losing whitespace in many situations where it definitely shouldn't. This commit attempts to fix that; semantics I'm going for matches what clang is doing, namely "trim the leading and trailing whitespace off the sequence being substituted". I would consider doing what gcc does (and it does diverge from clang in some cases), but... it's full of interesting corner cases and downright broken around combining __VA_OPT__() with ##. When/if they decide what to do with that...
What this commit does is
* don't lose ->pos.{newline,whitespace} deposited on TOKEN_UNTAINT
tokens; when scan_next() finds and skips those, have it collect their ->pos.{whitespace,newline}. If we are not at the end of the list and eventually get to a normal token, add the collected flags to it. Turns out that the comment in expand() had been too pessimistic - it's _not_ terribly costly, provided that the slow case of scan_next() is uninlined.
* have substitute() keep better track of pending whitespace.
We still don't want to copy ## or placemaker tokens into the growing replacement list, only to go over it again and exclude those, etc., so we build the list incrementally; ## awaiting the second argument is still represented as part of state. It's just that in addition to
<tokens> <tokens>[placemaker] <tokens>[##] we need to distinguish <tokens>[whitespace][placemaker] <tokens>[whitespace][placemaker][##]
as possible states.
Note: gcc code generation for bitfields really, really stinks.
--- pre-process.c | 102 ++++++++++++++++++------------ validation/preprocessor/va_opt.c | 23 ++++--- validation/preprocessor/va_opt2.c | 2 +- 3 files changed, 75 insertions(+), 52 deletions(-)
pre-process.c +61 -41
@@ -91,17 +91,6 @@ static const char **dirafter_includepath = includepath + 3; stream->protect =NULL ; \ }while (0 ) -static struct token *alloc_token(struct position *pos) -{ -struct token *token =__alloc_token (0 ); - - token->pos.stream = pos->stream; - token->pos.line = pos->line; - token->pos.pos = pos->pos; - token->pos.whitespace =1 ; -return token; -} -/* Expand symbol 'sym' at '*list' */ static int expand(struct token **, struct symbol *);
@@ -231,19 +220,34 @@ static inline int expand_one_symbol(struct token **list) } } -static inline struct token *scan_next (struct token **where) +static struct token *skip_untaints (struct token *token) { -struct token *token = *where; -if (token_type (token) !=TOKEN_UNTAINT ) -return token; +bool whitespace = false, newline = false;do { token->ident->tainted =0 ; +if (token->pos.whitespace) + whitespace = true; +if (token->pos.newline) + newline = true; token = token->next; }while (token_type (token) ==TOKEN_UNTAINT ); - *where = token; +if (token_type (token) !=TOKEN_EOF ) { +if (whitespace) + token->pos.whitespace =1 ; +if (newline) + token->pos.newline =1 ; + }return token; } +static inline struct token *scan_next (struct token **where) +{ +struct token *token = *where; +if (token_type (token) !=TOKEN_UNTAINT ) +return token; +return *where =skip_untaints (token); +} +static void expand_list (struct token **list) {struct token *next;
@@ -678,10 +682,29 @@ static bool skip_va_opt(struct arg *args, struct ident *expanding)return eof_token (arg); } +enum expansion_state { + Placemarker,// <tokens>Empty + Normal,// <tokens> + Concat,// <tokens> ## + Whitespace,// <tokens> Empty + Concat_White// <tokens> Empty ## +}; + +static enum expansion_state add_empty (enum expansion_state state, +const struct token *body) +{ +if (state < Concat) +return !body->pos.whitespace ? Placemarker : Whitespace; +else if (state == Concat) +return Normal; +else +return Whitespace; +} +static struct token **substitute (struct token **list,const struct token *body,struct arg *args) {struct position *base_pos = &(*list)->pos; -enum {Normal, Placeholder, Concat} state = Normal, saved_state = Normal; +enum expansion_state state = Normal, saved_state = Normal;struct ident *expanding = (*list)->ident;struct token **saved_list =NULL , *va_opt_list;
@@ -698,10 +721,7 @@ static struct token **substitute(struct token **list, const struct token *body, arg =do_argument (body, args, expanding);if (!arg ||eof_token (arg)) { -if (state == Concat) - state = Normal; -else - state = Placeholder; + state =add_empty (state, body);continue ; }if (state == Concat &&merge (containing_token (list), arg)) {
@@ -721,16 +741,18 @@ static struct token **substitute(struct token **list, const struct token *body, list =copy (list, arg);if (inserted_at) {struct token *p = *inserted_at; - p->pos.whitespace = body->pos.whitespace; + p->pos.whitespace =0 ; p->pos.newline =0 ; +if (body->pos.whitespace || state > Concat) + p->pos.whitespace =1 ; } state = Normal;continue ; }else if (token_type (body) ==TOKEN_CONCAT ) { -if (state == Placeholder) - state = Normal; -else - state = Concat; + state++;// Placemarker -> Normal +// Normal -> Concat +// White -> Concat_White +// impossible in Concat and Concat_White continue ; }else if (token_type (body) ==TOKEN_GNU_KLUDGE ) {const struct token *t = body;
@@ -744,10 +766,7 @@ static struct token **substitute(struct token **list, const struct token *body,* otherwise we act as if the kludge didn't exist. */ if (handle_kludge (&body, args)) { -if (state == Concat) - state = Normal; -else - state = Placeholder; + state =add_empty (state, body);continue ; } added =dup_token (t, base_pos);
@@ -756,10 +775,7 @@ static struct token **substitute(struct token **list, const struct token *body,// entering va_opt? if (!is_end_va_opt (body)) {if (skip_va_opt (args, expanding)) { -if (state == Concat) - state = Normal; -else - state = Placeholder; + state =add_empty (state, body);continue ; } body = body->va_opt_linkage;
@@ -801,6 +817,8 @@ static struct token **substitute(struct token **list, const struct token *body,if (state != Concat || !merge (containing_token (list), added)) { *list = added; list = &added->next; +if (state > Concat) + added->pos.whitespace =1 ; } state = Normal; }
@@ -826,12 +844,14 @@ static int expand(struct token **list, struct symbol *sym) tail =substitute (list, expansion, args);/* * Note that it won't be eof - at least TOKEN_UNTAINT will be there. -* We still can lose the newline flag if the sucker expands to nothing, -* but the price of dealing with that is probably too high (we'd need -* to collect the flags during scan_next()) +* We still can lose the whitespace information in the end of list, +* but that's deliberate - we match clang behaviour here. */ - (*list)->pos.newline = token->pos.newline; - (*list)->pos.whitespace = token->pos.whitespace; +struct position pos = (*list)->pos; +struct position pos2 = token->pos; + pos.newline = pos2.newline; + pos.whitespace = pos2.whitespace; + (*list)->pos = pos; *tail = next;return 0 ;
@@ -1537,8 +1557,8 @@ static struct token *parse_expansion(struct token *expansion, struct ident *name p->argnum |=1 <<ARGNUM_CONSUME_EXPAND ; } } - token =alloc_token (&expansion->pos); -token_type (token) =TOKEN_UNTAINT ; + token =__alloc_token (0 ); + token->pos = (struct position ){.type =TOKEN_UNTAINT }; token->ident = name; token->next = &eof_token_entry; *tail = token;
validation/preprocessor/va_opt.c +13 -10
@@ -1,3 +1,6 @@ +// Examples from C23 draft. Several are slightly incorrect - the common +// problem is that whitespace before a vanishing __VA_OPT__ (or an empty +// argument, for that matter) does *not* disappear. #define LPAREN () (#define G (Q ) 42#define F (R ,X , ...) __VA_OPT__(G R X) )
@@ -9,12 +12,12 @@ int x = F(LPAREN(), 0, <:-); // replaced by int x = 42;#define SDEF (sname, ...) S sname __VA_OPT__(= { __VA_ARGS__ })#define EMP F(a, b, c) // replaced by f(0, a, b, c) -F() // replaced by f(0) -F(EMP) // replaced by f(0) +F() // replaced by f(0) [wrong] +F(EMP) // replaced by f(0) [wrong] G(a, b, c) // replaced by f(0, a, b, c) -G(a, ) // replaced by f(0, a) -G(a) // replaced by f(0, a) -SDEF(foo); // replaced by S foo; +G(a, ) // replaced by f(0, a) [wrong] +G(a) // replaced by f(0, a) [wrong] +SDEF(foo); // replaced by S foo; [wrong]SDEF (bar,1 ,2 );// replaced by S bar = { 1, 2 }; // may not appear at the beginning of a replacement // list (6.10.5.3)
@@ -36,12 +39,12 @@ H5C(H5A()) // replaced by abint x =42 ; f(0 , a, b, c) -f(0) -f(0) +f(0 ) +f(0 ) f(0, a , b, c) -f(0, a) -f(0, a) -S foo; +f(0, a ) +f(0, a ) +S foo ;S bar = {1 ,2 }; ab, c, d""
validation/preprocessor/va_opt2.c +1 -1
@@ -23,7 +23,7 @@ F(E(_)) 1 AB(_) [_ 1] -[] +[ ] AE(_) R AE(_) R * check-output-end
Signature · 1 line
2.47.3
Re: [RFC PATCH] pre-process: add __VA_OPT__ support
In reply to Al ViroQuoted 10 lines · Al Viro
On Mon, Mar 16, 2026 at 06:56:22AM +0000, Al Viro wrote:
... and here's are the whitespace fixes and a bunch of optimizations; I really wonder if we ought to simply switch to
uint64_tfor struct position contents and go for several helpers for accessing individual parts. Code generation with clang is reasonable, but gcc is bloody awful - I'm sick and tired of fighting it all the time ;-/ Anyway, I've spent way too much time in that rabbit hole. I've a few more sitting in the local queue (tokenizer optimizations, mostly), but that's a separate story and I'd rather leave that for later.
Sigh... whitespace handling (6/6) had been too convoluted and ended up with breakage due to a missed case. Untangled, fixed and force-pushed into the same branch, with more testcases and hopefully better explanation of what was's going on with the machinery in substitute(). Ends up being faster, at that... Replacement for #6 below; comments and review would be welcome.
[PATCH 6/6] try to get whitespaces right
Preprocessor started as a text filter - it took a stream of characters and produced a stream of characters, with the output fed to compiler. Semantics had been not _quite_ as bad as with Bourne shell, but it had been full of dark corners all the same.
By C99 times it had been replaced with something far better defined. Now it operates on stream of tokens, and the output stream is _not_ fed through the tokenizer again. Operations are defined in terms of manipulations with that stream of tokens, which avoids a lot of headache.
Unfortunately, it's not exactly a stream of tokens - it's a stream of tokens and whitespaces. Which is where the things get interesting. When the standard says "replace the tokens from <here> to <there> with the sequence of tokens obtained by <this>", the general understanding is that
* whatever whitespaces might've been between <here> and <there>
are removed
* any whitespaces prior to <here> and past <there> remain as-is
* any whitespaces between the tokens of the sequence we are
told to substitute go into the the result.
What's not agreed upon is what should be done to possible leading or trailing whitespaces in the sequence.
In a lot of cases it doesn't matter - subsequent phases care only about tokens. Moreover, '#' operator (which does care about whitespaces) is explicitly required to trim any leading and trailing whitespace. However, there are cases where it is observable and different implementations yield different results.
Currently sparse is prone to losing whitespace in many situations where it definitely shouldn't. This commit attempts to fix that; semantics I'm going for matches what clang is doing, namely "trim the leading and trailing whitespace off the sequence being substituted". I would consider doing what gcc does (and it does diverge from clang in some cases), but... it's full of interesting corner cases and downright broken around combining __VA_OPT__() with ##. When/if they decide what to do with that...
What this commit does is
* don't lose ->pos.{newline,whitespace} deposited on TOKEN_UNTAINT
tokens; when scan_next() finds and skips those, have it collect their ->pos.{whitespace,newline}. If we are not at the end of the list and eventually get to a normal token, add the collected flags to it. Turns out that the comment in expand() had been too pessimistic - it's _not_ terribly costly, provided that the slow case of scan_next() is uninlined.
* have substitute() keep better track of pending whitespace.
The tricky part is the logics related to placemarkers and concatenation; see the comments in front of substitute() for details.
Note: gcc code generation for bitfields really, really stinks.
---
pre-process.c +134 -49
@@ -91,17 +91,6 @@ static const char **dirafter_includepath = includepath + 3; stream->protect =NULL ; \ }while (0 ) -static struct token *alloc_token(struct position *pos) -{ -struct token *token =__alloc_token (0 ); - - token->pos.stream = pos->stream; - token->pos.line = pos->line; - token->pos.pos = pos->pos; - token->pos.whitespace =1 ; -return token; -} -/* Expand symbol 'sym' at '*list' */ static int expand(struct token **, struct symbol *);
@@ -231,19 +220,34 @@ static inline int expand_one_symbol(struct token **list) } } -static inline struct token *scan_next (struct token **where) +static struct token *skip_untaints (struct token *token) { -struct token *token = *where; -if (token_type (token) !=TOKEN_UNTAINT ) -return token; +bool whitespace = false, newline = false;do { token->ident->tainted =0 ; +if (token->pos.whitespace) + whitespace = true; +if (token->pos.newline) + newline = true; token = token->next; }while (token_type (token) ==TOKEN_UNTAINT ); - *where = token; +if (token_type (token) !=TOKEN_EOF ) { +if (whitespace) + token->pos.whitespace =1 ; +if (newline) + token->pos.newline =1 ; + }return token; } +static inline struct token *scan_next (struct token **where) +{ +struct token *token = *where; +if (token_type (token) !=TOKEN_UNTAINT ) +return token; +return *where =skip_untaints (token); +} +static void expand_list (struct token **list) {struct token *next;
@@ -678,10 +682,94 @@ static bool skip_va_opt(struct arg *args, struct ident *expanding)return eof_token (arg); } +/* +* substitute(): handle macro expansion. +* Notionally we should +* Copy the body of macro +* Replace the occurrences of parameters within it with actual +* arguments, placemarker tokens, stringified forms of actual +* arguments or with results of their full expansion, depending +* upon the context. +* Remove all occurrences of ## operator, merging the tokens that +* precede and follow those. Placemarkers are neutral elements +* wrt merge. +* Remove all remaining placemarkers. +* Naive implementation would involve walking the list many times, which +* is obviously costly. Fortunately, it's possible to do everything in +* one pass. Since we have already determined the context for all +* occurrences of parameters back when we processed the defintion, the +* only tricky part is in handling of ## operators. We evaluate them +* in left-to-right order (standard explicitly leaves implementation free +* to choose any, but left-to-right is the usual variant). Another +* unspecified thing is what to do if body of a macro has two adjacent +* ## operators without any tokens in between; interpretation varies +* between the implementations and we follow gcc here - treat those as +* a single ##. +* That results in a nice property - if all ## to the left of some token +* have already been processed, all tokens to the left of that one are +* not going to be affected by the remaining ##. Moreover, any placemarkers +* to the left of that token are going to quietly disappear. +* That allows to build the list iteratively, with the part already +* constructed containing neither parameters, nor ##, nor placemarkers - +* only whitespace and normal tokens. Consider the next tokens (possibly +* with preceding whitespace) coming from body or from argument substitution. +* Since concatenation consumes adjacent whitespace, we can ignore the +* preceding whitespace for ##. +* Let's denote whitespace as w, placemarker as P, ## as C and any other +* token as T. Rules: +* <list> T: <list, T> +* <list> wT: <list, wT> +* <list> C T merge T into the last token of list +* <list> C wT merge T into the last token of list (## consumes whitespace) +* <list> C P <list> (placemarker is the right neutral) +* <list> C wP <list> +* <list> P T: <list, T> (we can remove that placemarker immediately) +* <list> P wT: <list, wT> +* <list> P P: <list> P +* <list> P wP: <list> wP +* <list> wP T: <list, wT> +* <list> wP wT: <list, wT> +* <list> wP P: <list> wP +* <list> wP wP: <list> wP +* <list> P C T: <list, T> (placemarker is the left neutral) +* <list> P C wT: <list, T> +* <list> P C P: <list> P +* <list> P C wP: <list> P +* <list> wP C T: <list, wT> +* <list> wP C wT: <list, wT> +* <list> wP C P: <list> wP +* <list> wP C wP: <list> wP +* In other words, the next step is determined by at most 3 following tokens. +* So we need to keep track of at most two tokens past the already constructed +* list and there are only 6 possible sequences for those: +* empty, P, wP, C, P C, wP C. +* In other words, we need to keep track of the already built list + already +* observed suffix from the set above. Rules above are easy to express in +* those terms - incoming token is either acted upon or added to the suffix. +* Note that suffix always matches w?P?( C)?, so it can be encoded as a simple +* bitmap; we get better code generation that way. +*/ +enum { + Placemarker =1 , + Whitespace =2 , + Concat =4 , +}; + +static int placemarker (int suffix,const struct token *body) +{ +// if suffix ends with C, strip it off +if (suffix & Concat) +return suffix & ~Concat; +// ... otherwise add P or wP to the suffix +if (body->pos.whitespace) + suffix |= Whitespace; +return suffix | Placemarker; +} +static struct token **substitute (struct token **list,const struct token *body,struct arg *args) {struct position *base_pos = &(*list)->pos; -enum {Normal, Placeholder, Concat} state = Normal, saved_state = Normal; +int suffix =0 , saved_suffix =0 ;struct ident *expanding = (*list)->ident;struct token **saved_list =NULL , *va_opt_list;
@@ -698,17 +786,14 @@ static struct token **substitute(struct token **list, const struct token *body, arg =do_argument (body, args, expanding);if (!arg ||eof_token (arg)) { -if (state == Concat) - state = Normal; -else - state = Placeholder; + suffix =placemarker (suffix, body);continue ; } -if (state == Concat &&merge (containing_token (list), arg)) { +if (suffix == Concat &&merge (containing_token (list), arg)) { arg = arg->next;if (eof_token (arg)) {// merged the sole token in - state = Normal; + suffix =0 ;continue ; } inserted_at =NULL ;
@@ -721,16 +806,16 @@ static struct token **substitute(struct token **list, const struct token *body, list =copy (list, arg);if (inserted_at) {struct token *p = *inserted_at; - p->pos.whitespace = body->pos.whitespace; + p->pos.whitespace =0 ; p->pos.newline =0 ; +if (suffix & Whitespace || + (!(suffix & Concat) && body->pos.whitespace)) + p->pos.whitespace =1 ; } - state = Normal; + suffix =0 ;continue ; }else if (token_type (body) ==TOKEN_CONCAT ) { -if (state == Placeholder) - state = Normal; -else - state = Concat; + suffix |= Concat;continue ; }else if (token_type (body) ==TOKEN_GNU_KLUDGE ) {const struct token *t = body;
@@ -744,10 +829,7 @@ static struct token **substitute(struct token **list, const struct token *body,* otherwise we act as if the kludge didn't exist. */ if (handle_kludge (&body, args)) { -if (state == Concat) - state = Normal; -else - state = Placeholder; + suffix =placemarker (suffix, body);continue ; } added =dup_token (t, base_pos);
@@ -756,10 +838,7 @@ static struct token **substitute(struct token **list, const struct token *body,// entering va_opt? if (!is_end_va_opt (body)) {if (skip_va_opt (args, expanding)) { -if (state == Concat) - state = Normal; -else - state = Placeholder; + suffix =placemarker (suffix, body);continue ; } body = body->va_opt_linkage;
@@ -777,12 +856,12 @@ static struct token **substitute(struct token **list, const struct token *body, added =stringify (va_opt_list); } list = saved_list; - state = saved_state; + suffix = saved_suffix; }else if (token_type (body) ==TOKEN_VA_OPT_STR ) {// entering #va_opt if (!skip_va_opt (args, expanding)) { - saved_state = state; - state = Normal; + saved_suffix = suffix; + suffix =0 ; saved_list = list; list = &va_opt_list; body = body->va_opt_linkage;
@@ -798,11 +877,15 @@ static struct token **substitute(struct token **list, const struct token *body,* if we got to doing real concatenation, we already have * added something into the list, so containing_token() is OK. */ -if (state != Concat || !merge (containing_token (list), added)) { +if (suffix != Concat || !merge (containing_token (list), added)) { *list = added; list = &added->next; +if (suffix & Concat) + added->pos.whitespace =0 ; +if (suffix & Whitespace) + added->pos.whitespace =1 ; } - state = Normal; + suffix =0 ; }return list; }
@@ -826,12 +909,14 @@ static int expand(struct token **list, struct symbol *sym) tail =substitute (list, expansion, args);/* * Note that it won't be eof - at least TOKEN_UNTAINT will be there. -* We still can lose the newline flag if the sucker expands to nothing, -* but the price of dealing with that is probably too high (we'd need -* to collect the flags during scan_next()) +* We still can lose the whitespace information in the end of list, +* but that's deliberate - we match clang behaviour here. */ - (*list)->pos.newline = token->pos.newline; - (*list)->pos.whitespace = token->pos.whitespace; +struct position pos = (*list)->pos; +struct position pos2 = token->pos; + pos.newline = pos2.newline; + pos.whitespace = pos2.whitespace; + (*list)->pos = pos; *tail = next;return 0 ;
@@ -1537,8 +1622,8 @@ static struct token *parse_expansion(struct token *expansion, struct ident *name p->argnum |=1 <<ARGNUM_CONSUME_EXPAND ; } } - token =alloc_token (&expansion->pos); -token_type (token) =TOKEN_UNTAINT ; + token =__alloc_token (0 ); + token->pos = (struct position ){.type =TOKEN_UNTAINT }; token->ident = name; token->next = &eof_token_entry; *tail = token;
validation/preprocessor/va_opt-concat.c new file +24 -0
@@ -0,0 +1,24 @@ +// gcc bug; left concat works there, right concat doesn't +// it's not just gcc -E spewing garbage - try to compile that +// with gcc -c and watch the fireworks. +#define E +#define F1 E 1 E +#define A (X ,...) 1##__VA_OPT__(X) +int m1 = A(F1,...); // left concatenation - int m1 = 11; + +#define F2 sizeof m E +#define B (X ,...) __VA_OPT__(X)##1 +int m2 =B (F2 ,_);// right concatenation - int m2 = sizeof m1; +/* +* check-name: __VA_OPT__ interplay with ## +* check-command: sparse -E $file +* +* check-output-start + +int m1 = 11; +int m2 = sizeof m1; +* check-output-end +* +* check-error-start +* check-error-end +*/
validation/preprocessor/va_opt.c +13 -10
@@ -1,3 +1,6 @@ +// Examples from C23 draft. Several are slightly incorrect - the common +// problem is that whitespace before a vanishing __VA_OPT__ (or an empty +// argument, for that matter) does *not* disappear. #define LPAREN () (#define G (Q ) 42#define F (R ,X , ...) __VA_OPT__(G R X) )
@@ -9,12 +12,12 @@ int x = F(LPAREN(), 0, <:-); // replaced by int x = 42;#define SDEF (sname, ...) S sname __VA_OPT__(= { __VA_ARGS__ })#define EMP F(a, b, c) // replaced by f(0, a, b, c) -F() // replaced by f(0) -F(EMP) // replaced by f(0) +F() // replaced by f(0) [wrong] +F(EMP) // replaced by f(0) [wrong] G(a, b, c) // replaced by f(0, a, b, c) -G(a, ) // replaced by f(0, a) -G(a) // replaced by f(0, a) -SDEF(foo); // replaced by S foo; +G(a, ) // replaced by f(0, a) [wrong] +G(a) // replaced by f(0, a) [wrong] +SDEF(foo); // replaced by S foo; [wrong]SDEF (bar,1 ,2 );// replaced by S bar = { 1, 2 }; // may not appear at the beginning of a replacement // list (6.10.5.3)
@@ -36,12 +39,12 @@ H5C(H5A()) // replaced by abint x =42 ; f(0 , a, b, c) -f(0) -f(0) +f(0 ) +f(0 ) f(0, a , b, c) -f(0, a) -f(0, a) -S foo; +f(0, a ) +f(0, a ) +S foo ;S bar = {1 ,2 }; ab, c, d""
validation/preprocessor/va_opt2.c +1 -1
@@ -23,7 +23,7 @@ F(E(_)) 1 AB(_) [_ 1] -[] +[ ] AE(_) R AE(_) R * check-output-end
validation/preprocessor/whitespace.c new file +100 -0
100 lines not on this page · raw message
Re: [RFC PATCH] pre-process: add __VA_OPT__ support
Quoted 3 lines · Al Viro
Sigh... whitespace handling (6/6) had been too convoluted and ended up with breakage due to a missed case.
I'm impressed that you are trying to get this right, even though clearly nobody really will ever be able to depend on it.
I suspect this part of the patch is more likely to actually be something that somebody may actually want some day:
+// We ought to add __builtin_strcmp() support to constant expressions; +// what's more, "foo"[0] should also be recognized as one... +// Sloppy length check for now...
because yeah, we've actually depended on the compiler just figuring some of those kinds of build-time optimizations out before to remove dead code etc.
Linus
Re: [RFC PATCH] pre-process: add __VA_OPT__ support
Quoted 10 lines · Linus Torvalds
I suspect this part of the patch is more likely to actually be something that somebody may actually want some day:
+// We ought to add
__builtin_strcmp()support to constant expressions; +// what's more, "foo"[0] should also be recognized as one... +// Sloppy length check for now...because yeah, we've actually depended on the compiler just figuring some of those kinds of build-time optimizations out before to remove dead code etc.
Something like delta below ought to take care of __builtin_strcmp(); figuring out the things like "ab"[1] being equal to 'b' is something I'd rather leave for later - at the very least after I resurrect and repost the busy-wait in shrink_dcache_parent() patchset. I've really spent way too much of the last couple of months on digging in sparse ;-/
As for the whitespace handling in preprocessor, I suspect that it'll end up with several bug reports for gcc and a DR for ISO C folks re clarifying that part of 6.10; not until summer, probably...
builtin.c +44 -1
@@ -631,6 +631,49 @@ static struct symbol_op strlen_op = { .expand = expand_strlen, }; +static int evaluate_strcmp (struct expression *expr) +{ +struct expression *arg; +bool non_const = false; + + FOR_EACH_PTR(expr->args, arg) { +if (arg && arg->type ==EXPR_SYMBOL ) + arg = arg->symbol->initializer; +if (!arg || arg->type !=EXPR_STRING || !arg->string->length) + non_const = true; + }END_FOR_EACH_PTR (arg); +if (!non_const) + expr->flags |=CEF_ICE ; +return 1 ; +} + +static int expand_strcmp (struct expression *expr,int cost) +{ +struct expression *arg; +const char *v[2 ]; +int n =0 ; + + FOR_EACH_PTR(expr->args, arg) { +if (!arg) +return UNSAFE ; +if (arg->type ==EXPR_SYMBOL ) + arg = arg->symbol->initializer; +if (!arg || arg->type !=EXPR_STRING || !arg->string->length) +return UNSAFE ; + v[n++] = arg->string->data; + }END_FOR_EACH_PTR (arg); + expr->flags |=CEF_SET_ICE ; + expr->type =EXPR_VALUE ; + expr->value =strcmp (v[0 ], v[1 ]); + expr->taint =0 ; +return 0 ; +} + +static struct symbol_op strcmp_op = { + .evaluate = evaluate_strcmp, + .expand = expand_strcmp, +}; +/* * Builtin functions */
@@ -806,7 +849,7 @@ static const struct builtin_fn builtins_common[] = { { "__builtin_strcasestr", &string_ctype, 0, { &const_string_ctype, &const_string_ctype }}, { "__builtin_strcat", &string_ctype, 0, { &string_ctype, &const_string_ctype }}, { "__builtin_strchr", &string_ctype, 0, { &const_string_ctype, &int_ctype }}, - { "__builtin_strcmp", &int_ctype, 0, { &const_string_ctype, &const_string_ctype }}, + { "__builtin_strcmp", &int_ctype, 0, { &const_string_ctype, &const_string_ctype }, .op = &strcmp_op}, { "__builtin_strcpy", &string_ctype, 0, { &string_ctype, &const_string_ctype }}, { "__builtin_strcspn", size_t_ctype, 0, { &const_string_ctype, &const_string_ctype }}, { "__builtin_strdup", &string_ctype, 0, { &const_string_ctype }},
validation/preprocessor/whitespace.c +0 -14
@@ -1,23 +1,9 @@#define S (X ) #X -#if notyet#define EXPECT (X ,Y ) _Static_assert(__builtin_strcmp(S(X),Y) == 0, \ #X " => " S(X) ", " Y "expected");#define Y (M ) EXPECT(M(,]),"[ ]")#define N (M ) EXPECT(M(,]),"[]") -#else - -// We ought to add __builtin_strcmp() support to constant expressions; -// what's more, "foo"[0] should also be recognized as one... -// Sloppy length check for now... - -#define __Y (X ) _Static_assert(__builtin_strlen(S(X)) == 3, \ - #X " => " S(X) ", [ ] expected"); -#define Y (M ) __Y(M(,])) -#define __N (X ) _Static_assert(__builtin_strlen(S(X)) == 2, \ - #X " => " S(X) ", [] expected"); -#define N (M ) __N(M(,])) -#endif #define T1 (X ,R ) [] // T#define A1 (X ,R ) [R // A
Re: [RFC PATCH] pre-process: add __VA_OPT__ support
Quoted 5 lines · Al Viro
Something like delta below ought to take care of
__builtin_strcmp(); figuring out the things like "ab"[1] being equal to 'b' is something I'd rather leave for later - at the very least after I resurrect and repost the busy-wait inshrink_dcache_parent()patchset. I've really spent way too much of the last couple of months on digging in sparse ;-/
BTW, gcc doesn't accept a trick allowed by clang (as well as by sparse with this patch):
#define splat() ({ \
_Static_assert(__builtin_strcmp(__func__, "foo") == 0, \
"use only in foo()"); \
something(); \
})gcc does not realize that __func__ is a constant array with known contents. Oh, well...
Re: [PATCH 16/21] __VA_OPT__: parsing
In reply to Al Viropre-process.c static struct token *parse_expansion(struct token *expansion, struct ident *name · line 1434
Quoted 4 lines · Al Viro
pre-process.c +4
-0+static struct token *parse_expansion (struct token *expansion,struct ident *name) +{ +int slots = macro_nargs + (macro_vararg <0 ); +struct arg_state args[slots] = {};
^^^^^^^^^^^^^^^^
Hi Al,
gcc-11 and gcc-12 don't allow variable length arrays with an initializer. The compile fails with:
pre-process.c: In function ‘parse_expansion’:
pre-process.c:1513:16: error: variable-sized object may not be initialized
1513 | struct arg_state args[slots] = {};
| ^~~~~~~~~make: *** [Makefile:263: pre-process.o] Error 1
make: *** Waiting for unfinished jobs....
It works in gcc-13 and later.
regards,
dan carpenter